vj-codegen 0.2.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
//! Task 22 (`docs/superpowers/plans/2026-09-23-wave-A-codegen.md`, ledger
//! CG-060, CG-092, CG-117, CG-118): the top-level `CodegenSession` entry
//! object and `lower_instance_body`/`lower_all_instance_bodies`, the
//! rayon-parallel fan-out that lowers one unique `InstanceBody` `Symbol` per
//! worker thread, each worker building its own `inkwell::Context`.
//!
//! **BINDING CORRECTION 3 (supersedes the plan's original "`LoweredUnit` owns
//! its own Context+Module, self-referential" design):** `inkwell::module::
//! Module<'ctx>` is **not** `Send` (only `Context` is). A `LoweredUnit`
//! returned from a rayon worker and gathered back on the calling thread must
//! therefore never carry a live `Module`/`Context` pair across that boundary
//! -- a `Mutex` only serializes *access*, it does not make a `!Send` value
//! legal to move between threads at all. The worker-side pipeline is instead:
//! create a fresh `Context` **inside** the worker closure, lower the body's
//! functions into a `Module` on that `Context`, verify (`FunctionValue::
//! verify` per function, inside `func::lower_function`; the whole `Module`
//! once more here), serialize the verified `Module` to LLVM bitcode
//! (`Module::write_bitcode_to_memory() -> MemoryBuffer<'static>`, copied out
//! to an owned `Vec<u8>`), then let the `Context`/`Module` drop before the
//! closure returns. `LoweredUnit` owns only that `Vec<u8>` (plus plain-data
//! metadata) -- `Vec<u8>`/`String`/`Vec<String>` are all `Send + 'static`, so
//! `LoweredUnit` crosses the rayon boundary safely with no unsafe code and no
//! `Mutex` (`loweredunit_is_send`, tests/session_parallel.rs, is the
//! compile-time proof). The collector (a future JIT backend, Task 24 --
//! itself revised by BINDING CORRECTION 4 to parse each blob into its own
//! fresh context on the consuming side -- or an AOT backend, Task 25) parses
//! each blob back into a live `Module` in **its own** `Context` when and
//! where it actually needs one; this file's own
//! `lower_instance_body_bitcode_reparses_into_populated_module`/
//! `n_workers_produce_n_independently_parseable_bitcode_blobs`/
//! `merged_bitcode_blobs_jit_and_run_correctly` tests (tests/
//! session_parallel.rs) exercise exactly that reparse step, the last two
//! using the existing legacy `Jit`/`ExecutionEngine` path (BINDING CORRECTION
//! 4: Task 24's `LLJIT`/`JITDylib` backend does not exist yet in this
//! track's tree at this task) rather than the not-yet-built Task 24 backend
//! the plan's literal text names.
//!
//! This is a deviation from CG-118's literal "returns a `LoweredUnit`
//! containing a populated `Module`" wording; the module *was* fully
//! populated and LLVM-verified before serialization, which is what CG-118's
//! acceptance is actually protecting against (an unpopulated/unverified
//! module) -- the substance of the acceptance still holds even though the
//! literal type shape changed.
//!
//! **Lowering-unit scope (this task's own, narrower than the whole-design
//! Deferred/A2-slice pipeline):** `lower_instance_body` lowers every direct
//! member of `body` that is a `SymbolKind::Subroutine` (a leaf `function
//! automatic`, this crate's existing `func::lower_function` P0 capability) --
//! exactly mirroring `module.rs::discover_processes`'s own established
//! pattern of filtering an `InstanceBody`'s direct `members()` down to the
//! one kind it cares about and silently skipping everything else (ports,
//! nets, variables, procedural blocks, instances -- each some OTHER
//! subsystem's own concern, not a silently-dropped construct THIS function
//! was asked to lower). A `Subroutine` member that fails to lower (e.g. a
//! `real`-typed argument, per `func::lower_function`'s own scope note)
//! propagates as a loud `LoweringError`, never silently skipped.
//!
//! **Review fix (r2), duplicate-name detection:** an earlier revision of
//! this file claimed the whole-module `module.verify()` call in
//! `lower_instance_body_in` would catch "duplicate names across two
//! Subroutine members in the same body". That claim was false: LLVM's
//! `Module::add_function` (invoked by `func::lower_function`) silently
//! disambiguates a same-named second function itself (e.g. a real duplicate
//! `f0` becomes the LLVM-level name `f0.1`) before either that function's
//! own per-function verify or the later whole-module verify ever runs, so
//! neither verify ever sees a conflict to reject. `lower_instance_body_in`
//! now detects a duplicate SV name among the `Subroutine` members it is
//! about to lower explicitly (before creating any LLVM function for it) and
//! returns a `LoweringError` naming the collision; `tests/
//! session_parallel.rs`'s `duplicate_subroutine_name_is_a_loud_lowering_
//! error` proves this returns `Err` rather than an `Ok(LoweredUnit)` with a
//! silently-renamed function.
use inkwell::context::Context;
use rayon::prelude::*;

use sv_lang::kinds::SymbolKind;
use sv_lang::{Design, Symbol};

use crate::error::LoweringError;
use crate::func::lower_function;
use crate::value::ValueRepr;

/// Task 29 (CG-068): what [`symbol_role`]'s exhaustive `match` over
/// `SymbolKind` classifies a direct `InstanceBody` member as, for
/// `lower_instance_body_in`'s member-walk below.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SymbolRole {
    /// A leaf `function`/`task` -- this crate's existing `func::
    /// lower_function` (Task 22's own scope) is the only member kind this
    /// pipeline actually lowers.
    Function,
    /// An `initial`/`always`/`always_ff`/`always_comb`/`always_latch`/
    /// `final` procedural block -- CPS process-lowering machinery, Deferred
    /// at this wave (ARCHITECTURE.md §6.4's "fork/join ... unresolved" open
    /// sub-problem's sibling; see the plan's Deferred section). A
    /// legitimate SV construct this lowering unit does not touch, never an
    /// error.
    ProceduralBlock,
    /// A plain net/variable/formal-argument/struct-field declaration --
    /// state storage, not itself code to lower; any USE of it is instead
    /// reached through `expr.rs::lower_expr`'s own `NamedValue` arm.
    Variable,
    /// Every other purely structural/declarative member kind this task has
    /// surveyed and confirmed carries no independent code for THIS
    /// leaf-function lowering unit to emit (ports, parameters, types,
    /// sub-module instances -- each its own separately-lowered
    /// `InstanceBody`, continuous assigns -- the netlist/driver subsystem's
    /// concern, generate-block containers, imports, attributes, ...) --
    /// mirrors `module.rs::discover_processes`'s own doc comment on exactly
    /// this "some OTHER subsystem's concern" distinction. Never an error.
    Structural,
}

/// Task 29 (CG-068): the crate's first genuine `match` over `SymbolKind`
/// (as opposed to `frontend.rs::find_function`'s plain `==` check) --
/// classifies one direct `InstanceBody` member for `lower_instance_body_in`'s
/// walk below. Every one of `sv_lang::kinds::SymbolKind`'s 101 named
/// variants (pinned, `kind_counts::SYMBOL_KIND_COUNT`) is listed in exactly
/// one arm below; the required-by-`#[non_exhaustive]` trailing wildcard
/// exists only for a future `sv-lang-kinds` variant beyond today's pinned
/// 101 (a version bump the `symbol_kind_count_matches_pinned_constant` test,
/// `tests/exhaustiveness.rs`, catches first) and, defensively, for
/// `Unknown` itself -- both end in a named [`LoweringError`], never a
/// silent default `Ok(SymbolRole::Structural)` (CG-066/067/068's shared
/// discipline, applied here to `SymbolKind`).
///
/// The deferred/unsupported bucket below (class/OOP, randomize/constraint,
/// functional coverage, SVA sequences/properties/clocking/checkers,
/// randsequence, gate primitives, `defparam` value overrides,
/// elaboration-time system tasks, anonymous `program` blocks, `alias`) is
/// every `SymbolKind` this crate has never validated a correct,
/// semantics-preserving way to silently skip -- per CG-070/CG-072, "we
/// haven't implemented this" must fail loudly, never silently produce wrong
/// codegen by pretending it was as harmless as a port or a type
/// declaration.
///
/// **`SpecifyBlock`/`Specparam`/`TimingPath`/`PulseStyle`/
/// `SystemTimingCheck` are deliberately NOT in that deferred bucket** (moved
/// out by `docs/superpowers/plans/2026-10-03-sdf.md` Task 1): this function
/// is dead on `run.rs`'s real pipeline (confirmed by that plan's own grep --
/// `lower_instance_body`/`lower_all_instance_bodies` have no call site in
/// `vj`), but it is still exercised by `tests/exhaustiveness.rs`'s
/// `symbol_kind_count_matches_pinned_constant`, so it must still classify
/// every kind correctly. These five kinds are declarative specify-block
/// content -- not executable statements, exactly like `ContinuousAssign`
/// below -- and are planned/registered as native Rust `CompiledProcess`es by
/// `vj`'s own `specify::plan`/`timingcheck::plan` (that plan's §1.3
/// decision 1), never by this crate's LLVM lowering. The sdf plan is the
/// owner of this classification going forward.
pub fn symbol_role(sym: &Symbol) -> Result<SymbolRole, LoweringError> {
    use SymbolKind::*;
    match sym.kind() {
        Subroutine => Ok(SymbolRole::Function),
        ProceduralBlock => Ok(SymbolRole::ProceduralBlock),
        Net | Variable | FormalArgument | Field => Ok(SymbolRole::Variable),

        // Pure bookkeeping/internal AST plumbing -- never real design
        // content of their own.
        Root | Definition | CompilationUnit | DeferredMember | TransparentMember
        | EmptyMember
        // Pure type declarations -- a variable/net that USES one of these
        // types is itself the `Variable`-role member carrying it; the type
        // declaration symbol alone contributes no code.
        | PredefinedIntegerType | ScalarType | FloatingType | EnumType | EnumValue
        | PackedArrayType | FixedSizeUnpackedArrayType | DynamicArrayType
        | DPIOpenArrayType | AssociativeArrayType | QueueType | PackedStructType
        | UnpackedStructType | PackedUnionType | UnpackedUnionType | VoidType
        | NullType | CHandleType | StringType | EventType | UnboundedType
        | TypeRefType | UntypedType | SequenceType | PropertyType
        | VirtualInterfaceType | TypeAlias | ErrorType | ForwardingTypedef | NetType
        // Already-resolved compile-time constants / generic parameters --
        // a USE reaches its folded value through the referencing
        // expression, not this declaration symbol.
        | Parameter | TypeParameter
        // Port-list declarations -- instance-connection wiring is a
        // separate (netlist) subsystem's concern, not this leaf-function
        // lowering unit's.
        | Port | MultiPort | InterfacePort | Modport | ModportPort
        | ModportClocking
        // Sub-instances -- each gets its OWN, separate
        // `lower_instance_body` call (that is the whole point of
        // `lower_all_instance_bodies`'s per-body fan-out); silently
        // skipping the `Instance`/`InstanceArray` symbol HERE is
        // non-duplication, not a dropped construct.
        | Instance | InstanceBody | InstanceArray
        // Package/import/attribute bookkeeping -- metadata only.
        | Package | ExplicitImport | WildcardImport | Attribute
        // Generate-elaboration bookkeeping -- slang has already resolved
        // generate constructs by the time a `Design` exists; this pipeline
        // never recurses into a `GenerateBlock`'s own nested members
        // either way (pre-existing scope, unchanged by this task).
        | Genvar | GenerateBlock | GenerateBlockArray
        // A named statement-block scoping container at the top level --
        // no independent lowering here.
        | StatementBlock
        // Continuous assigns are the netlist/driver-elaboration subsystem's
        // concern (ARCHITECTURE.md's own division of responsibility) --
        // pre-existing scope, unchanged by this task.
        | ContinuousAssign
        // Config blocks are pure post-elaboration metadata (config
        // resolution has already happened upstream in slang by the time a
        // `Design` exists).
        | ConfigBlock
        // `docs/superpowers/plans/2026-10-03-sdf.md` Task 1: a `specify
        // ... endspecify` block and its members (module-path declarations,
        // pulse-style/showcancelled declarations, system timing checks) and
        // a `specparam` declaration are declarative annotations on
        // existing drivers/checks, not executable statements -- exactly
        // like `ContinuousAssign` above (that symbol's own comment reads
        // "the netlist/driver-elaboration subsystem's concern"; the exact
        // same sentence now applies here). They are planned/registered as
        // native Rust `CompiledProcess`es by `vj`'s own
        // `specify::plan`/`timingcheck::plan` (sibling to
        // `primitives::plan`), never lowered to LLVM by this crate. The sdf
        // plan owns this classification going forward.
        | SpecifyBlock | Specparam | TimingPath | PulseStyle | SystemTimingCheck
        // A covergroup declaration (Clause 19) is compiled per instance into
        // kernels by `crate::covergroup`, never as executable statements.
        | CovergroupType
        // Constraints plan C1: a `constraint` block is declarative class-scope
        // metadata, never an executable member of an instance body; its
        // content is consumed by the constraint solver (`vj-sim::
        // constraints`), built once per class template from the block's own
        // bound tree rather than lowered to LLVM here. Structural, exactly
        // like the specify family just above.
        | ConstraintBlock => Ok(SymbolRole::Structural),

        // Everything below is a construct this crate has never validated a
        // correct lowering (or a correct "safe to ignore") for -- silently
        // treating any of these as `Structural` would risk exactly the
        // silent-miscompile CG-070/CG-072 forbid (most concretely:
        // `DefParam` can change a design's actual runtime behavior if
        // ignored, so it is deliberately NOT bucketed with the inert
        // declarations above; `Specparam`'s own equivalent risk is instead
        // covered by the `vj-sim`/`vj` specify/timing-check
        // subsystem now owning it, per the doc comment above).
        other @ (Unknown
        | ClassType
        | ClassProperty
        | ElabSystemTask
        | GenericClassDef
        | MethodPrototype
        | UninstantiatedDef
        | Iterator
        | PatternVar
        | DefParam
        | Primitive
        | PrimitivePort
        | PrimitiveInstance
        | Sequence
        | Property
        | AssertionPort
        | ClockingBlock
        | ClockVar
        | LocalAssertionVar
        | LetDecl
        | Checker
        | CheckerInstance
        | CheckerInstanceBody
        | RandSeqProduction
        | CovergroupBody
        | Coverpoint
        | CoverCross
        | CoverCrossBody
        | CoverageBin
        | AnonymousProgram
        | NetAlias) => Err(LoweringError::unsupported_at(
            &format!(
                "symbol kind {other:?} inside an instance body is out of this crate's \
                 scope (class/OOP, functional coverage, SVA, \
                 randsequence, gate-primitive instances, defparam value overrides, \
                 elaboration-time system tasks, and program blocks are all deferred -- \
                 see ARCHITECTURE.md §6.1/§7)"
            ),
            sym,
        )),
        // Defensive-only: a future `sv-lang-kinds` version bump beyond
        // today's pinned 101 variants (caught first by
        // `symbol_kind_count_matches_pinned_constant`, tests/
        // exhaustiveness.rs) -- never a silent `Ok(_)`.
        other => Err(LoweringError::unsupported_at(
            &format!("symbol kind {other:?} is outside the pinned SymbolKind::COUNT range"),
            sym,
        )),
    }
}

/// CG-117: the top-level entry object. Owns nothing thread-unsafe itself (a
/// `&'d Design` -- `Design` is `Send + Sync`, per `sv_lang::Design`'s own doc
/// comment -- plus two plain `Copy` scalars), so it can be constructed once
/// and shared *by reference* across worker threads with no `Mutex`/`Arc`
/// wrapper around the session itself (`session_is_shared_by_reference_
/// across_threads`, tests/session_parallel.rs, is the concrete proof: it
/// typechecks and runs only because `CodegenSession<'d>: Sync`).
pub struct CodegenSession<'d> {
    pub design: &'d Design,
    pub mode: ValueRepr,
    pub wide_threshold: u32,
}

impl<'d> CodegenSession<'d> {
    pub fn new(design: &'d Design, mode: ValueRepr, wide_threshold: u32) -> Self {
        CodegenSession {
            design,
            mode,
            wide_threshold,
        }
    }
}

/// CG-118's lowering-unit output, in BINDING CORRECTION 3's corrected shape:
/// `Send + 'static`, no `Module`/`Context`/LLVM-value field of any kind.
/// `def_name` is the `InstanceBody`'s own module-definition name (diagnostic/
/// bookkeeping only); `function_names` lists every LLVM function the module
/// actually defines, in lowering order, so a caller need not re-walk the
/// reparsed `Module` to discover what is in it.
#[derive(Debug, Clone)]
pub struct LoweredUnit {
    pub module_bitcode: Vec<u8>,
    pub def_name: String,
    pub function_names: Vec<String>,
}

/// CG-118: lowers one unique `InstanceBody` `Symbol` -- building its own
/// fresh `inkwell::Context` internally (CG-060's "one `Context` per
/// compile-worker thread" property, satisfied trivially here since this
/// function creates, uses, and drops exactly one `Context` entirely within
/// whichever single thread calls it; `lower_all_instance_bodies` below is
/// what actually calls this from more than one thread).
pub fn lower_instance_body<'d>(
    sess: &CodegenSession<'d>,
    body: Symbol<'d>,
) -> Result<LoweredUnit, LoweringError> {
    let ctx = Context::create();
    lower_instance_body_in(&ctx, sess, body)
}

/// The core of [`lower_instance_body`], factored out so
/// [`lower_all_instance_bodies_with_probe`] can create the `Context` itself
/// (to hand its pointer identity to a test probe) and still share this exact
/// lowering path -- there is only one place that walks `body`'s members and
/// serializes the result, never two divergent copies.
fn lower_instance_body_in<'d>(
    ctx: &Context,
    sess: &CodegenSession<'d>,
    body: Symbol<'d>,
) -> Result<LoweredUnit, LoweringError> {
    let def_name = body.name().to_string();
    let module = ctx.create_module(&def_name);

    // Review fix (r2): `module.verify()` below does NOT catch two
    // `SymbolKind::Subroutine` members sharing one SV name -- LLVM's
    // `Module::add_function` (called by `func::lower_function`) silently
    // disambiguates a name collision itself (e.g. a second `f0` becomes
    // `f0.1` at the LLVM level) before either that function's own
    // `FunctionValue::verify` or this whole-module `verify()` ever runs, so
    // both verifies trivially pass on a Module that is missing information:
    // the second declaration's *real* SV name has been silently lost, and a
    // caller resolving "f0" by name later gets only the first definition
    // with no error and no indication the second existed. Detect the
    // collision explicitly, at the SV-name level, before any LLVM function
    // is created for it, and fail loudly with a `LoweringError` naming the
    // duplicate -- this is what actually protects CG-118's "a genuinely
    // malformed design must never lower silently" acceptance; the
    // whole-module `verify()` retained below still catches other
    // cross-function structural issues it *can* see, but never this one.
    let mut seen_subroutine_names: std::collections::HashSet<&str> =
        std::collections::HashSet::new();

    let mut function_names = Vec::new();
    for member in vj_sim::netlist::module_items(&body) {
        // Task 29 (CG-068/CG-070/CG-072): route through the crate's
        // exhaustive `SymbolKind` dispatch instead of a bare `!=
        // SymbolKind::Subroutine` equality skip -- a genuinely-deferred
        // construct sitting directly in this body (`class`, `randomize`/
        // `constraint`, SVA, a gate-primitive instance, ...) now fails
        // loudly via `symbol_role`'s own `LoweringError`, rather than being
        // silently skipped indistinguishably from an ordinary port or net.
        match symbol_role(&member)? {
            SymbolRole::Function => {}
            SymbolRole::ProceduralBlock | SymbolRole::Variable | SymbolRole::Structural => {
                continue;
            }
        }
        let name = member.name();
        if !seen_subroutine_names.insert(name) {
            return Err(LoweringError {
                message: format!(
                    "duplicate function/task name '{name}' declared more than once in the same scope"
                ),
                at: member.hierarchical_path(),
            });
        }
        let f = lower_function(ctx, &module, sess.design, &member, sess.mode)?;
        function_names.push(f.get_name().to_string_lossy().into_owned());
    }

    // A whole-module structural verify on top of `lower_function`'s own
    // per-function `FunctionValue::verify` -- catches anything else only
    // visible once every function sharing this Module is present. (Review
    // fix (r2): duplicate Subroutine names are now caught explicitly above,
    // BEFORE this point, because LLVM's own `add_function` silently
    // disambiguates same-named functions rather than ever surfacing that as
    // a verify failure -- see the comment above the loop.) This remains the
    // rest of the "populated Module" half of CG-118's acceptance that
    // survives BINDING CORRECTION 3's shape change.
    if let Err(e) = module.verify() {
        return Err(LoweringError {
            message: format!("instance body module failed LLVM verify: {e}"),
            at: body.hierarchical_path(),
        });
    }

    let bitcode = module.write_bitcode_to_memory();
    let module_bitcode = bitcode.as_slice().to_vec();

    Ok(LoweredUnit {
        module_bitcode,
        def_name,
        function_names,
    })
}

/// CG-092: lowers every `Symbol` in `bodies` in parallel via `rayon`, each on
/// its own worker thread with its own fresh `Context` (never shared, never
/// pooled) -- riding plain `rayon::prelude::*` on the caller-supplied slice
/// rather than `sv_lang::Design::par_visit`/`par_visit_from` (see this file's
/// own module doc comment, and the `Cargo.toml` comment on the `rayon`
/// workspace dependency, for why: those two visit an entire design with a
/// `Fn(Symbol)` callback, not the "map a caller-owned `&[Symbol]` list to a
/// `Vec<Result<LoweredUnit, _>>`" shape this function needs).
pub fn lower_all_instance_bodies<'d>(
    sess: &CodegenSession<'d>,
    bodies: &[Symbol<'d>],
) -> Vec<Result<LoweredUnit, LoweringError>> {
    lower_all_instance_bodies_with_probe(sess, bodies, |_worker_context_ptr| {})
}

/// As [`lower_all_instance_bodies`], but also invokes `on_worker_context`
/// with each worker's freshly-created `Context`'s pointer identity (as a
/// `usize`) immediately after creating it and before using it for anything.
///
/// **Deviation from the plan's literal `lower_all_instance_bodies` signature
/// (not a new public name the plan itself lists, but a minimal, documented
/// addition):** CG-060's own acceptance ("running codegen with N rayon worker
/// threads never touches a Context from a thread other than the one that
/// created it") needs a way to OBSERVE that N genuinely distinct `Context`s
/// were created, one per worker -- but `LoweredUnit` deliberately carries no
/// `Context`-derived handle at all (BINDING CORRECTION 3), so there is
/// nothing in `lower_all_instance_bodies`'s own return value a test could
/// inspect for this. This probe hook is the seam: it never exposes a live
/// `&Context` outside the crate (which would immediately violate `Module<
/// 'ctx>`'s own `!Send` boundary the moment a caller tried to hold onto one
/// across the call) -- only its address, exactly enough to prove distinctness
/// (`each_worker_gets_its_own_context_never_shared`, tests/
/// session_parallel.rs) without weakening the "no Context ever crosses a
/// thread boundary" property this task exists to establish. `on_worker_
/// context` itself runs ON the worker thread that owns the `Context`, so it
/// must be `Sync` (rayon calls it from whichever thread happens to run each
/// closure).
pub fn lower_all_instance_bodies_with_probe<'d, F>(
    sess: &CodegenSession<'d>,
    bodies: &[Symbol<'d>],
    on_worker_context: F,
) -> Vec<Result<LoweredUnit, LoweringError>>
where
    F: Fn(usize) + Sync,
{
    bodies
        .par_iter()
        .map(|body| {
            let ctx = Context::create();
            on_worker_context(std::ptr::from_ref::<Context>(&ctx) as usize);
            lower_instance_body_in(&ctx, sess, *body)
        })
        .collect()
}