vj-codegen 0.1.0

LLVM code generator of the vj SystemVerilog simulator.
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
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
//! The AOT backend -- `AotBackend::emit_object` writes one real ELF/Mach-O
//! `.o` per `inkwell::module::Module` via `inkwell::targets::TargetMachine`,
//! and `AotBackend::link` shells out to the system linker (`cc`) to merge
//! that object against `sv-sim-runtime`'s staticlib into one real, loadable
//! `.so`, immediately probing the result with `libloading`.
//!
//! **Reconciled at the wave-B integration merge** from two independently
//! built halves (docs/LEDGER.md "AOT backend"): wave-A codegen Task 25
//! (`docs/superpowers/plans/2026-09-23-wave-A-codegen.md`, ledger CG-010,
//! CG-011, CG-012, CG-063, CG-126, CG-140) built `AotBackend::for_host`'s
//! own target-machine construction/validation and `AotBackend::triple`;
//! A2-part2 Task 4 (`docs/superpowers/plans/2026-09-26-wave-A2-process-
//! kernels.md`; ledger CG-127, RT-003) built the real `link`/
//! [`AotKernelHandle`]/[`emit_process_count_fn`] semantics the spec needs.
//! This file keeps both: the struct, `for_host`, and `triple` below are
//! Task 25's; `link`'s body, `AotKernelHandle`, and `emit_process_count_fn`
//! are Task 4's; `emit_object` is Task 25's (fixed target machine, no
//! per-call re-derivation, CG-012) but returns [`CodegenError`] (Task 4's
//! error type for this whole backend, per that type's own doc comment) so
//! both halves speak one error type.
//!
//! **CG-010/CG-011 ("one lowering, two backends"):** this file never lowers
//! anything itself. It is handed an already-lowered, already-verified
//! `Module` -- the SAME `Module` type `crate::orc::JitBackend::
//! add_module_from_bitcode` consumes (via bitcode serialization) -- and only
//! turns it into machine code. `crate::func::lower_function`/`crate::
//! session::lower_instance_body`/`crate::process_lower::lower_kernel_fn*`
//! remain the sole IR-emission path; this backend and `orc::JitBackend` are
//! two consumers of that one path's output, never a second lowering.
//!
//! **CG-012:** `AotBackend::for_host` owns exactly the target-machine setup
//! (triple/CPU/features/`TargetMachine`) this backend needs, built once at
//! construction time; `AotBackend::emit_object`/`link` re-derive nothing per
//! call.
//!
//! **CG-063/CG-127/RT-003:** `emit_object` is the "every worker emits its
//! own `.o` file independently" half; `link` is the separate, explicit merge
//! step against `sv-sim-runtime`'s staticlib (ARCHITECTURE ยง9's own
//! build-topology note: "the system linker or a bundled lld/mold"), then
//! immediately probes the result with `libloading` -- `dlsym`-ing
//! `sim_abi_version`/`sim_process_count` and calling each once -- so a `.so`
//! that links but is not genuinely loadable/callable is a
//! [`CodegenError::Load`], never silently reported `Ok`.
//!
//! **CG-140:** `AotBackend::for_host` does not merely check a capability
//! flag (`Target::has_target_machine`, which only reports whether ANY
//! `TargetMachine` can be constructed at all) -- it goes on to actually emit
//! a real object buffer from a trivial throwaway module via
//! [`verify_target_machine_emits_objects`], the same real
//! `TargetMachine::write_to_memory_buffer` codepath `emit_object` itself
//! uses, and fails loudly (naming the host triple and the underlying LLVM
//! error) if that does not genuinely work. A pinned `llvm-sys` "prebuilt"
//! that shipped a JIT-only or reduced target-list build -- the exact risk
//! CG-140 names -- would either fail `Target::from_triple`/
//! `has_target_machine` or fail this real emission attempt; either way
//! `AotBackend::for_host` returns `Err` rather than a backend that silently
//! produces garbage/empty objects later.
//!
//! **What `link` can and cannot prove yet (verified-live note, matching this
//! plan's own established partial-closure pattern for CG-101-105/PR-122/
//! RT-003/CG-127):** ARCHITECTURE ยง5 names NINE frozen entry points a
//! compiled kernel's `.so` exports (`sv_sim_abi::entry`). Of those,
//! `sim_process_count` is genuinely real as of this task ([`emit_process_count_fn`]
//! bakes it as a per-design compile-time constant -- process count is a
//! static property of a compiled design, never scheduler state, so it needs
//! no live `Engine` to answer correctly) and `sim_abi_version` (a tenth,
//! version-only, design-INDEPENDENT symbol -- `sv_sim_abi::version`) is real
//! permanently, from `sv-sim-runtime::aot_exports`. The other eight
//! (`sim_init`/`sim_settle`/`sim_eval_region`/`sim_commit_nba`/`sim_save`/
//! `sim_restore`/`sim_step_time`/`sim_final`) have no real exported body
//! anywhere in this tree yet -- Task 5 (CG-161/CG-162/CG-165, "ABI
//! entry-point exports for the .so/reload story") is what makes
//! `sched::control::abi_entry_point_map`'s documentation-as-data table real,
//! forwarding calls, not this task. `link` below never dlsyms those eight,
//! and this crate's own tests never claim they work.
//!
//! Every AOT object this backend emits uses `RelocMode::PIC` unconditionally
//! (never a caller-selectable option): `link` always produces a `.so`
//! (CG-063's own "into one .so" acceptance), and a shared object's code must
//! be position-independent -- there is no non-PIC path this crate exposes,
//! so there is nothing to select.
use std::path::{Path, PathBuf};
use std::process::Command;

use inkwell::AddressSpace;
use inkwell::OptimizationLevel;
use inkwell::context::Context;
use inkwell::module::{Linkage, Module};
use inkwell::targets::{
    CodeModel, FileType, InitializationConfig, RelocMode, Target, TargetMachine, TargetTriple,
};
use inkwell::values::FunctionValue;

use crate::error::CodegenError;

/// CG-127's real return type (`docs/design/codegen.md` ยง9's `SvKernelTable`
/// draft is superseded by ARCHITECTURE ยง5's frozen, simpler ABI -- this is
/// the real return type, holding exactly the two fields a linked `.so` can
/// genuinely report about itself right after linking) -- everything a
/// caller can learn about a just-linked `.so` without driving it through a
/// live `Engine`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AotKernelHandle {
    pub abi_version: u32,
    pub process_count: u32,
}

/// The AOT backend, alongside [`crate::orc::JitBackend`] -- an alternate
/// consumer of the exact same lowered `Module` a plan produces
/// (`crate::process_lower::lower_kernel_fn`/`lower_kernel_fn_with_repr`),
/// taking a compile-then-link path to a real, loadable artifact instead of
/// an in-process JIT.
pub struct AotBackend {
    target_machine: TargetMachine,
}

impl AotBackend {
    /// Builds one `AotBackend` targeting the machine this process is
    /// actually running on -- host triple, host CPU, host CPU features
    /// (`TargetMachine::get_host_cpu_name`/`get_host_cpu_features`, the same
    /// pair `orc::JitBackend`'s underlying ORC v2 `LLJIT` uses by default for
    /// its own JIT target-machine, so an AOT-compiled `.o` and a JIT-compiled
    /// module target machine-code-identical CPU features -- load-bearing for
    /// `tests/aot_backend.rs`'s `jit_and_aot_produce_bit_identical_results`).
    ///
    /// Fails loudly (never returns a backend that will later silently
    /// misbehave) if:
    /// - native target initialization fails;
    /// - the host triple cannot be resolved to a `Target` at all;
    /// - CG-140: that `Target` reports no `TargetMachine` support, or a
    ///   constructed `TargetMachine` cannot actually emit a real object
    ///   buffer for a trivial probe module.
    pub fn for_host() -> Result<Self, CodegenError> {
        Target::initialize_native(&InitializationConfig::default())
            .map_err(|e| CodegenError::ObjectEmission(format!("native target init: {e}")))?;

        let triple = TargetMachine::get_default_triple();
        let target = Target::from_triple(&triple).map_err(|e| {
            CodegenError::ObjectEmission(format!(
                "failed to resolve a Target for host triple {:?}: {e}",
                triple.as_str()
            ))
        })?;

        // CG-140, first (cheap) leg of the check: a Target reporting no
        // TargetMachine support at all cannot possibly emit objects.
        if !target.has_target_machine() {
            return Err(CodegenError::ObjectEmission(format!(
                "CG-140: host target {:?} has no TargetMachine (codegen backend) registered \
                 in this pinned llvm-sys build -- object emission is impossible (a JIT-only \
                 or reduced target-list prebuilt?)",
                triple.as_str()
            )));
        }

        let cpu = TargetMachine::get_host_cpu_name();
        let features = TargetMachine::get_host_cpu_features();
        let target_machine = target
            .create_target_machine(
                &triple,
                cpu.to_str().unwrap_or(""),
                features.to_str().unwrap_or(""),
                OptimizationLevel::Default,
                RelocMode::PIC,
                CodeModel::Default,
            )
            .ok_or_else(|| {
                CodegenError::ObjectEmission(format!(
                    "Target::create_target_machine returned None for host triple {:?}",
                    triple.as_str()
                ))
            })?;

        // CG-140, second (real) leg of the check: actually emit an object
        // buffer, not merely inspect a capability flag.
        verify_target_machine_emits_objects(&target_machine)?;

        Ok(AotBackend { target_machine })
    }

    /// The `TargetTriple` this backend's `TargetMachine` was built for --
    /// exposed for diagnostics/tests only (e.g. so a caller can name it in
    /// an error message), never re-derived by any other method on this
    /// type.
    pub fn triple(&self) -> TargetTriple {
        self.target_machine.get_triple()
    }

    /// CG-126's exact signature shape: writes a real, relocatable object
    /// file (ELF on Linux) for `module` to `path`, using this backend's
    /// fixed host `TargetMachine` -- no per-call target reconfiguration
    /// (CG-012). Position-independent (`RelocMode::PIC`, baked in at
    /// `for_host` construction time), since this object's only sanctioned
    /// destination is [`Self::link`]'s `-shared` output.
    ///
    /// `module` is never mutated or consumed: this is the same live `Module`
    /// value a caller may still hand to `JitBackend::add_module_from_bitcode`
    /// afterwards (via `Module::write_bitcode_to_memory`), which is exactly
    /// what proves CG-010's "one lowering, two backends" in
    /// `tests/aot_backend.rs`'s `jit_and_aot_produce_bit_identical_results`.
    pub fn emit_object(&self, module: &Module, path: &Path) -> Result<(), CodegenError> {
        self.target_machine
            .write_to_file(module, FileType::Object, path)
            .map_err(|e| CodegenError::ObjectEmission(format!("{path:?}: {e}")))
    }

    /// Links `objects` plus `runtime_rlib` (`sv-sim-runtime` built as a
    /// `staticlib` -- see that crate's own `Cargo.toml` `[lib]` section)
    /// into a real shared object at `out_so`, via the system linker
    /// (`cc -shared`, ARCHITECTURE ยง9's own build-topology note: "the
    /// system linker or a bundled lld/mold"), then immediately probes the
    /// result with `libloading` -- `dlsym`-ing `sim_abi_version`/
    /// `sim_process_count` and calling each once -- so a `.so` that links
    /// but is not genuinely loadable/callable is a [`CodegenError::Load`],
    /// never silently reported `Ok` (this crate's own "no gate that cannot
    /// fail" posture: a `.so` missing either symbol, or that fails to
    /// `dlopen` at all, makes this function fail, not just `link` produce a
    /// file nobody checked).
    ///
    /// **`--whole-archive` around `runtime_rlib` (integration-merge fix):**
    /// `sim_abi_version` (`aot_exports.rs`) is a design-INDEPENDENT symbol
    /// that ARCHITECTURE ยง5 requires every compiled `.so` to export
    /// unconditionally -- "the loader calls this FIRST, before trusting any
    /// other symbol". A plain static link only pulls the object-file(s) of
    /// `runtime_rlib` that resolve a symbol `objects` actually REFERENCES;
    /// whether `sim_abi_version` happens to sit in the same rustc codegen
    /// unit as an accessor function `objects` does call is an unrelated
    /// implementation detail this crate has no business depending on (it
    /// held only by incidental codegen-unit bundling before this fix, as
    /// this file's own `tests/aot_backend.rs` fixtures with no accessor
    /// calls at all exposed: `dlsym sim_abi_version` failed for them even
    /// though the link itself "succeeded"). `--whole-archive` forces every
    /// object in `runtime_rlib` into `out_so` regardless of what `objects`
    /// references, so `sim_abi_version` is always present -- this is
    /// exactly the "no gate that cannot fail" posture this function's own
    /// post-link probe already claims, now actually true unconditionally,
    /// not only for callers whose kernel happens to reference an accessor.
    pub fn link(
        &self,
        objects: &[PathBuf],
        runtime_rlib: &Path,
        out_so: &Path,
    ) -> Result<AotKernelHandle, CodegenError> {
        self.link_exporting(objects, runtime_rlib, out_so, None)
    }

    /// [`Self::link`] for a whole-design `.so`: the dynamic symbol table is
    /// cut to `exports` (glob patterns, e.g. `sim_*`) by a version script, so
    /// the runtime's own symbols stay private to the library. Every link also
    /// binds the library's references to its own definitions (`-Bsymbolic`),
    /// so a copy of the runtime in the process that loads it (`sv-sim`'s own)
    /// can never interpose on the one inside.
    pub fn link_exporting(
        &self,
        objects: &[PathBuf],
        runtime_rlib: &Path,
        out_so: &Path,
        exports: Option<&[&str]>,
    ) -> Result<AotKernelHandle, CodegenError> {
        if objects.is_empty() {
            return Err(CodegenError::Link(
                "link: at least one object file is required".to_string(),
            ));
        }
        let mut cmd = Command::new("cc");
        cmd.arg("-shared").arg("-fPIC").arg("-o").arg(out_so);
        cmd.arg("-Wl,-Bsymbolic");
        // A design that calls DPI-C leaves those functions undefined: they come
        // from the libraries `run-aot` loads after this one, so they bind at
        // their first call, not at load (a distro `cc` may default to `-z now`).
        cmd.arg("-Wl,-z,lazy");
        let script = exports.map(|_| out_so.with_extension("map"));
        if let (Some(path), Some(patterns)) = (&script, exports) {
            let mut text = String::from("{\n  global:\n");
            for p in patterns {
                text.push_str(&format!("    {p};\n"));
            }
            text.push_str("  local:\n    *;\n};\n");
            std::fs::write(path, text).map_err(|e| {
                CodegenError::Link(format!("cannot write the version script {path:?}: {e}"))
            })?;
            cmd.arg(format!("-Wl,--version-script={}", path.display()));
        }
        for obj in objects {
            cmd.arg(obj);
        }
        cmd.arg("-Wl,--whole-archive")
            .arg(runtime_rlib)
            .arg("-Wl,--no-whole-archive");
        // `runtime_rlib` is a Rust `staticlib`, which transitively needs
        // libc/libm/libpthread/libdl -- linked explicitly rather than
        // relying on the host `cc`'s own defaults, so a link failure here
        // is never mistaken for RT-003's own "zero slang references"
        // property (a partially-unresolved link failing for a missing libc
        // symbol would be a false negative on a completely different
        // question).
        cmd.arg("-lpthread").arg("-ldl").arg("-lm");
        let output = cmd
            .output()
            .map_err(|e| CodegenError::Link(format!("failed to spawn `cc`: {e}")))?;
        if let Some(path) = &script {
            let _ = std::fs::remove_file(path);
        }
        if !output.status.success() {
            return Err(CodegenError::Link(format!(
                "`cc -shared` exited with {:?}: {}",
                output.status.code(),
                String::from_utf8_lossy(&output.stderr)
            )));
        }

        // SAFETY: `out_so` was just produced, above, by this same function
        // from this workspace's own compiled object(s) plus its own runtime
        // staticlib -- never an arbitrary/untrusted path. Loading it runs
        // its ordinary dynamic-loader initialization (relocations,
        // `.init_array`), the standard, accepted cost of loading any freshly
        // compiled code; this probe closes the library again (`lib` is
        // dropped at the end of this scope) rather than keeping it mapped --
        // a caller that needs to keep driving the `.so` afterward
        // (`sv-sim-bin::aot_loader::load_aot_kernel`) opens its own, separate
        // `libloading::Library` on the same path.
        let lib = unsafe { libloading::Library::new(out_so) }
            .map_err(|e| CodegenError::Load(format!("dlopen {}: {e}", out_so.display())))?;
        let abi_version: u32 = unsafe {
            let sym: libloading::Symbol<extern "C" fn() -> u32> = lib
                .get(sv_sim_abi::version::SIM_ABI_VERSION_SYMBOL.as_bytes())
                .map_err(|e| CodegenError::Load(format!("dlsym sim_abi_version: {e}")))?;
            sym()
        };
        let process_count: u32 = unsafe {
            let sym: libloading::Symbol<extern "C" fn(sv_sim_abi::SimHandle) -> u32> = lib
                .get(sv_sim_abi::entry::SIM_PROCESS_COUNT_SYMBOL.as_bytes())
                .map_err(|e| CodegenError::Load(format!("dlsym sim_process_count: {e}")))?;
            // `sim_process_count`'s own body (`emit_process_count_fn` below)
            // ignores its `SimHandle` argument entirely (it is a static,
            // per-design compile-time constant, never scheduler state) --
            // a null handle is exactly as valid a call as any other here.
            sym(sv_sim_abi::SimHandle(std::ptr::null_mut()))
        };

        Ok(AotKernelHandle {
            abi_version,
            process_count,
        })
    }

    /// `build-aot --exe`: links `objects` (the design's own object, which
    /// must already contain a real `main` -- [`emit_main_fn`] puts one
    /// there) plus `runtime_rlib` into a standalone, position-independent
    /// EXECUTABLE at `out_exe` (never `-shared`): no host process, no
    /// `.so`, no `libloading`. `-Bsymbolic`/the version script in
    /// [`Self::link_exporting`] are both `.so`-only concerns (symbol
    /// interposition between a library and its host process) that do not
    /// exist for a standalone binary, so neither is passed here.
    ///
    /// Verified, not merely linked -- but, unlike [`Self::link_exporting`]'s
    /// `dlopen`-and-call probe (which only ever calls two PURE accessors,
    /// `sim_abi_version`/`sim_process_count`), this never actually RUNS the
    /// produced binary: an executable's only behaviour IS running the whole
    /// design (`main` is nothing but `return sv_sim_aot_main(argc, argv);`),
    /// which may need plusargs, read real files, or simply take a long time
    /// -- none of which belongs inside a `build` step as a side effect the
    /// caller never asked for. Instead this reads `out_exe`'s own ELF header
    /// ([`elf_header_is_a_valid_executable`]) and fails loudly
    /// (`CodegenError::Load`) if `cc` produced something that links but
    /// is not genuinely a loadable `ET_EXEC`/`ET_DYN` (PIE) binary.
    pub fn link_exe(
        &self,
        objects: &[PathBuf],
        runtime_rlib: &Path,
        out_exe: &Path,
    ) -> Result<(), CodegenError> {
        if objects.is_empty() {
            return Err(CodegenError::Link(
                "link_exe: at least one object file is required".to_string(),
            ));
        }
        let mut cmd = Command::new("cc");
        cmd.arg("-o").arg(out_exe);
        for obj in objects {
            cmd.arg(obj);
        }
        cmd.arg("-Wl,--whole-archive")
            .arg(runtime_rlib)
            .arg("-Wl,--no-whole-archive");
        // Exported, so a VPI library the executable `dlopen`s at run time
        // (`--vpi LIB`, IEEE 1800-2023 36.9) resolves its `vpi_*` calls
        // against the executable's own definitions.
        cmd.arg("-Wl,--export-dynamic");
        cmd.arg("-lpthread").arg("-ldl").arg("-lm");
        let output = cmd
            .output()
            .map_err(|e| CodegenError::Link(format!("failed to spawn `cc`: {e}")))?;
        if !output.status.success() {
            return Err(CodegenError::Link(format!(
                "`cc` exited with {:?}: {}",
                output.status.code(),
                String::from_utf8_lossy(&output.stderr)
            )));
        }

        let bytes = std::fs::read(out_exe)
            .map_err(|e| CodegenError::Load(format!("reading {}: {e}", out_exe.display())))?;
        if !elf_header_is_a_valid_executable(&bytes) {
            return Err(CodegenError::Load(format!(
                "{} was linked but its ELF header is not a valid ET_EXEC/ET_DYN executable",
                out_exe.display()
            )));
        }
        Ok(())
    }
}

/// `bytes`' ELF header says this is a real executable: the `\x7fELF` magic,
/// a 64-bit (`EI_CLASS` = 2) little-endian (`EI_DATA` = 1) header long
/// enough to hold `e_type`, and `e_type` (offset 16, a `u16`) is `ET_EXEC`
/// (2) or `ET_DYN` (3 -- a position-independent executable, `cc`'s default
/// on every host this backend targets, since [`AotBackend::for_host`]'s own
/// objects are always `RelocMode::PIC`). Never executes `bytes`.
fn elf_header_is_a_valid_executable(bytes: &[u8]) -> bool {
    const ET_EXEC: u16 = 2;
    const ET_DYN: u16 = 3;
    bytes.len() >= 18
        && bytes[0..4] == [0x7f, b'E', b'L', b'F']
        && bytes[4] == 2 // ELFCLASS64
        && bytes[5] == 1 // ELFDATA2LSB
        && matches!(u16::from_le_bytes([bytes[16], bytes[17]]), ET_EXEC | ET_DYN)
}

/// CG-140's load-bearing check: builds one trivial throwaway `void @cg140_
/// probe_fn()` module on its own private `Context` and asks `tm` to emit it
/// as a real object buffer in memory (`TargetMachine::
/// write_to_memory_buffer`, the exact underlying LLVM call `emit_object`
/// itself uses via `write_to_file`) -- a genuine end-to-end exercise of
/// object-file emission, not merely a capability-flag read, so a `llvm-sys`
/// prebuilt that advertises `TargetMachine` support but is actually missing
/// the AsmPrinter/object-emission backend components for this triple still
/// gets caught here rather than surfacing later as an obscure `emit_object`
/// failure on a real design.
fn verify_target_machine_emits_objects(tm: &TargetMachine) -> Result<(), CodegenError> {
    let ctx = Context::create();
    let probe_module = ctx.create_module("cg140_probe");
    let void_fn_ty = ctx.void_type().fn_type(&[], false);
    let f = probe_module.add_function("cg140_probe_fn", void_fn_ty, None);
    let builder = ctx.create_builder();
    let entry = ctx.append_basic_block(f, "entry");
    builder.position_at_end(entry);
    builder.build_return(None).map_err(|e| {
        CodegenError::ObjectEmission(format!(
            "CG-140 probe module failed to build its own trivial body: {e}"
        ))
    })?;
    probe_module.verify().map_err(|e| {
        CodegenError::ObjectEmission(format!(
            "CG-140 probe module unexpectedly failed LLVM verify: {e}"
        ))
    })?;

    tm.write_to_memory_buffer(&probe_module, FileType::Object)
        .map(|_buf| ())
        .map_err(|e| {
            CodegenError::ObjectEmission(format!(
                "CG-140: this build's pinned llvm-sys/LLVM prebuilt does not actually support \
                 object-file emission for host triple {:?} (a JIT-only or reduced target-list \
                 build?): {e}",
                tm.get_triple().as_str()
            ))
        })
}

/// Task 4's own codegen addition (not part of `crate::process_lower`'s
/// existing `emit_process_table`, though it shares that function's module):
/// emits the real `sim_process_count` ABI entry point
/// (`sv_sim_abi::entry::SIM_PROCESS_COUNT_SYMBOL`) as
/// `extern "C" fn(SimHandle) -> u32`, its body a single `ret i32 <count>` --
/// `count` is `plans.len()` at the call site below, baked as an LLVM
/// constant. Ignoring the `SimHandle` argument is correct, not a shortcut:
/// unlike the other eight ARCHITECTURE ยง5 entry points (Task 5's own scope,
/// see this module's doc comment), a compiled design's process COUNT is a
/// static property fixed at compile time, never something that varies by
/// which live simulation instance is asking.
pub fn emit_process_count_fn<'ctx>(
    ctx: &'ctx Context,
    module: &Module<'ctx>,
    count: u32,
) -> FunctionValue<'ctx> {
    let ptr_ty = ctx.ptr_type(AddressSpace::default());
    let i32_ty = ctx.i32_type();
    let fn_ty = i32_ty.fn_type(&[ptr_ty.into()], false);
    let f = module.add_function(
        sv_sim_abi::entry::SIM_PROCESS_COUNT_SYMBOL,
        fn_ty,
        Some(Linkage::External),
    );
    let entry = ctx.append_basic_block(f, "entry");
    let builder = ctx.create_builder();
    builder.position_at_end(entry);
    let ret = i32_ty.const_int(u64::from(count), false);
    builder
        .build_return(Some(&ret))
        .expect("a single `ret i32 <const>` in a fresh entry block always builds");
    f
}

/// Symbol of the encoded design image's accessor (`extern "C" fn() -> *const u8`).
pub const DESIGN_IMAGE_PTR_SYMBOL: &str = "sv_sim_design_image_ptr";
/// Symbol of the encoded design image's length accessor (`extern "C" fn() -> u64`).
pub const DESIGN_IMAGE_LEN_SYMBOL: &str = "sv_sim_design_image_len";
/// The function-pointer table, one entry per `DesignImage::symbols` name.
pub const SYMBOL_TABLE_SYMBOL: &str = "SV_SIM_SYMBOL_TABLE";
/// `u32` entry count of [`SYMBOL_TABLE_SYMBOL`].
pub const SYMBOL_COUNT_SYMBOL: &str = "SV_SIM_SYMBOL_COUNT";
/// The runner-side hook a load-time constructor hands the image to.
pub const AOT_REGISTER_SYMBOL: &str = "sv_sim_aot_register";

/// Embeds a design image in `module`: its bytes behind
/// [`DESIGN_IMAGE_PTR_SYMBOL`]/[`DESIGN_IMAGE_LEN_SYMBOL`], a function-pointer
/// table ([`SYMBOL_TABLE_SYMBOL`]) resolving `symbols` (index-aligned with the
/// image's symbol list), and an `llvm.global_ctors` constructor that calls
/// [`AOT_REGISTER_SYMBOL`]`(image, len, table, count)` when the `.so` loads, so
/// the runner needs no link-time reference to the object it is linked with.
///
/// Fails, naming the symbol, if `symbols` names a function the module lacks.
pub fn emit_image_globals<'ctx>(
    ctx: &'ctx Context,
    module: &Module<'ctx>,
    image_bytes: &[u8],
    symbols: &[String],
) -> Result<(), crate::error::LoweringError> {
    let ptr_ty = ctx.ptr_type(AddressSpace::default());
    let i32_ty = ctx.i32_type();
    let i64_ty = ctx.i64_type();
    let builder = ctx.create_builder();
    let fail = |m: String| crate::error::LoweringError {
        message: m,
        at: "aot::emit_image_globals".to_string(),
    };

    // The image bytes.
    let data = ctx.const_string(image_bytes, false);
    let image_global = module.add_global(data.get_type(), None, "SV_SIM_DESIGN_IMAGE");
    image_global.set_initializer(&data);
    image_global.set_constant(true);
    image_global.set_linkage(Linkage::Internal);
    let image_ptr = image_global.as_pointer_value();

    let ptr_fn = module.add_function(
        DESIGN_IMAGE_PTR_SYMBOL,
        ptr_ty.fn_type(&[], false),
        Some(Linkage::External),
    );
    builder.position_at_end(ctx.append_basic_block(ptr_fn, "entry"));
    builder
        .build_return(Some(&image_ptr))
        .map_err(|e| fail(e.to_string()))?;
    let len_fn = module.add_function(
        DESIGN_IMAGE_LEN_SYMBOL,
        i64_ty.fn_type(&[], false),
        Some(Linkage::External),
    );
    builder.position_at_end(ctx.append_basic_block(len_fn, "entry"));
    builder
        .build_return(Some(&i64_ty.const_int(image_bytes.len() as u64, false)))
        .map_err(|e| fail(e.to_string()))?;

    // The kernel table.
    let mut entries = Vec::with_capacity(symbols.len());
    for name in symbols {
        let f = module.get_function(name).ok_or_else(|| {
            fail(format!(
                "the image names kernel `{name}`, which was not lowered"
            ))
        })?;
        entries.push(f.as_global_value().as_pointer_value());
    }
    let table = ptr_ty.const_array(&entries);
    let table_global = module.add_global(table.get_type(), None, SYMBOL_TABLE_SYMBOL);
    table_global.set_initializer(&table);
    table_global.set_constant(true);
    table_global.set_linkage(Linkage::External);
    let count_global = module.add_global(i32_ty, None, SYMBOL_COUNT_SYMBOL);
    count_global.set_initializer(&i32_ty.const_int(symbols.len() as u64, false));
    count_global.set_constant(true);
    count_global.set_linkage(Linkage::External);

    // The load-time registration.
    let register = module.add_function(
        AOT_REGISTER_SYMBOL,
        ctx.void_type().fn_type(
            &[ptr_ty.into(), i64_ty.into(), ptr_ty.into(), i32_ty.into()],
            false,
        ),
        Some(Linkage::External),
    );
    let ctor = module.add_function(
        "sv_sim_aot_ctor",
        ctx.void_type().fn_type(&[], false),
        Some(Linkage::Internal),
    );
    builder.position_at_end(ctx.append_basic_block(ctor, "entry"));
    builder
        .build_call(
            register,
            &[
                image_ptr.into(),
                i64_ty.const_int(image_bytes.len() as u64, false).into(),
                table_global.as_pointer_value().into(),
                i32_ty.const_int(symbols.len() as u64, false).into(),
            ],
            "",
        )
        .map_err(|e| fail(e.to_string()))?;
    builder
        .build_return(None)
        .map_err(|e| fail(e.to_string()))?;
    let entry_ty = ctx.struct_type(&[i32_ty.into(), ptr_ty.into(), ptr_ty.into()], false);
    let entry = ctx.const_struct(
        &[
            i32_ty.const_int(65535, false).into(),
            ctor.as_global_value().as_pointer_value().into(),
            ptr_ty.const_null().into(),
        ],
        false,
    );
    let ctors = entry_ty.const_array(&[entry]);
    let ctors_global = module.add_global(ctors.get_type(), None, "llvm.global_ctors");
    ctors_global.set_initializer(&ctors);
    ctors_global.set_linkage(Linkage::Appending);
    Ok(())
}

/// M6 (`build-aot --exe`): the "3-line `main`" the plan names -- declares
/// `sv_sim_aot_main` (defined by `sv-sim-aot`, the runtime archive this
/// object is later linked against, exactly like every other `sv_rt_*`/
/// `sim_*` symbol this crate's lowering already emits calls to without a
/// local definition) and defines a real C `main(argc, argv)` that forwards
/// straight to it, so `cc`'s own CRT startup (`_start` -> `__libc_start_main`
/// -> `main`) is the only driver code the resulting binary needs -- no
/// `sv-sim` host process, no `libloading`/`dlopen`, at all.
///
/// Added to the SAME module `compile_design_to_object` is about to emit as
/// this design's one object file (never a second object/module): `main`
/// and the design's kernels end up in one `.o`, linked once against the
/// runtime archive, by [`AotBackend::link_exe`].
pub fn emit_main_fn<'ctx>(ctx: &'ctx Context, module: &Module<'ctx>) -> FunctionValue<'ctx> {
    let ptr_ty = ctx.ptr_type(AddressSpace::default());
    let i32_ty = ctx.i32_type();
    let aot_main = module.add_function(
        "sv_sim_aot_main",
        i32_ty.fn_type(&[i32_ty.into(), ptr_ty.into()], false),
        Some(Linkage::External),
    );
    let main_fn = module.add_function(
        "main",
        i32_ty.fn_type(&[i32_ty.into(), ptr_ty.into()], false),
        Some(Linkage::External),
    );
    let builder = ctx.create_builder();
    let entry = ctx.append_basic_block(main_fn, "entry");
    builder.position_at_end(entry);
    let argc = main_fn.get_nth_param(0).expect("main has an argc param");
    let argv = main_fn.get_nth_param(1).expect("main has an argv param");
    let ret = builder
        .build_call(aot_main, &[argc.into(), argv.into()], "code")
        .expect("a two-argument call to an external fn of matching type always builds")
        .try_as_basic_value()
        .unwrap_basic();
    builder
        .build_return(Some(&ret))
        .expect("returning the call's own i32 result always builds");
    main_fn
}

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

    /// `AotBackend::for_host` itself IS the CG-140 build-time check
    /// (`verify_target_machine_emits_objects` runs unconditionally inside
    /// it) -- this test just re-states that acceptance directly, so a
    /// future refactor that accidentally skips the check on some path still
    /// gets caught by a test that names CG-140 explicitly, not only by
    /// `tests/aot_backend.rs`'s own copy of the same assertion.
    #[test]
    fn for_host_runs_the_cg140_object_emission_check() {
        AotBackend::for_host()
            .expect("AotBackend::for_host must succeed and must have verified real object emission on this host (CG-140)");
    }

    #[test]
    fn link_with_no_objects_is_a_loud_error_not_a_panic_or_silent_noop() {
        let backend = AotBackend::for_host().expect("AotBackend::for_host");
        let dir = std::env::temp_dir();
        // `objects` is checked before `runtime_rlib` is ever touched, so a
        // placeholder (non-existent) rlib path is fine here.
        let err = backend
            .link(
                &[],
                &dir.join("cg063_link_empty_probe.rlib"),
                &dir.join("cg063_link_empty_probe.so"),
            )
            .expect_err("link with zero objects must be an Err, never Ok or a panic");
        let msg = err.to_string();
        assert!(
            msg.contains("at least one object file"),
            "error message should name the actual problem, got: {msg}"
        );
    }
}