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
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
//! Event handles (LRM 1800-2023 15.5.2 - 15.5.5): assignment, merging,
//! `null`, comparison, event arguments of tasks, and automatic (local)
//! `event` variables and arrays.
//!
//! An instance body that uses any of those keeps every event in the event
//! pool (`sv_sim_sim::state::event_pool`, its layout and the meaning of its
//! rows). Here, an event expression resolves to an object id -- a row of the
//! pool -- through its handle: a static event variable's handle cell, or the
//! 64-bit id an automatic `event` variable holds in its process frame. The
//! trigger, the wait, `.triggered` and `->>` then act on that row exactly as
//! they do on an element of an event array ([`crate::arrays::EventElem`]).

use crate::types::TypeWidth;
use inkwell::IntPredicate;
use inkwell::values::{IntValue, PointerValue};
use sv_lang::Symbol;
use sv_lang::kinds::ExpressionKind;
use sv_sim_sim::state::EVENT_CELL_WIDTH;
use sv_sim_sim::state::event_pool::{DYNAMIC_ROWS, event_count, pool_key, pool_of_key, static_key};
use sv_sim_sim::symid::SymbolUid;

use crate::arrays::{Backing, EventElem};
use crate::error::LoweringError;
use crate::expr::{LowerCtx, LoweredValue, MemorySignalInfo};
use crate::ops::OpBuilder;
use crate::types::int_type;
use crate::value::PackedValue;

/// The pool memory of the body being lowered, when it has one.
pub(crate) fn pool_info(cx: &LowerCtx<'_, '_, '_>) -> Option<MemorySignalInfo> {
    cx.mem_signals.get(&pool_key()).copied()
}

/// The static event variable that event expression `e` names through a
/// hierarchical reference (`s.ev`, `s.ea[i]`), if it does.
pub(crate) fn hierarchical_event_var<'d>(e: &sv_lang::Expression<'d>) -> Option<Symbol<'d>> {
    let mut e = *e;
    loop {
        if e.kind() == ExpressionKind::Conversion
            && let Some(inner) = e.conversion_operand()
        {
            e = inner;
        } else if e.kind() == ExpressionKind::ElementSelect
            && let Some(base) = e.select_value()
        {
            e = base;
        } else {
            break;
        }
    }
    (e.kind() == ExpressionKind::HierarchicalValue)
        .then(|| e.referenced_symbol())
        .flatten()
}

/// The pool event expression `e` lives in: the pool of the instance that owns
/// the event when `e` names it hierarchically (`s.ev`; registered beside this
/// body's signals when `s` keeps its events in a pool, run.rs), else this
/// body's own pool. Object ids are rows of ONE pool, so a handle read from one
/// pool is never stored into another ([`same_pool`]).
pub(crate) fn pool_for(
    cx: &LowerCtx<'_, '_, '_>,
    e: &sv_lang::Expression<'_>,
) -> Option<MemorySignalInfo> {
    if let Some(var) = hierarchical_event_var(e)
        && let Some(p) = cx.mem_signals.get(&pool_of_key(&var.uid()))
    {
        return Some(*p);
    }
    pool_info(cx)
}

/// `h` names an object of the pool `pool`; an id of another pool is
/// meaningless in it, so storing or passing one is refused by name.
fn same_pool(
    cx: &LowerCtx<'_, '_, '_>,
    h: &EventElem<'_>,
    pool: &MemorySignalInfo,
    what: &str,
) -> Result<(), LoweringError> {
    if h.info.slot == pool.slot {
        return Ok(());
    }
    Err(LoweringError::unsupported_at(
        &format!(
            "{what}: the event handle belongs to the event pool of another instance (an event \
             of one instance cannot be assigned, passed or stored by another, LRM 1800-2023 \
             15.5.5)"
        ),
        &cx.fn_sym,
    ))
}

/// The pool entry of static event variable `sym`: `lower_index` is the id of
/// its first event.
fn static_entry(cx: &LowerCtx<'_, '_, '_>, sym: &Symbol<'_>) -> Option<MemorySignalInfo> {
    cx.mem_signals.get(&static_key(&sym.uid())).copied()
}

/// The backing of a static event array `sym`: its range of the pool.
pub(crate) fn static_array_backing(
    cx: &LowerCtx<'_, '_, '_>,
    sym: &Symbol<'_>,
) -> Option<MemorySignalInfo> {
    static_entry(cx, sym)
}

fn i64c<'ctx>(cx: &LowerCtx<'ctx, '_, '_>, v: u64) -> IntValue<'ctx> {
    cx.ctx.i64_type().const_int(v, false)
}

/// The low 64 bits of pool row `row`'s cell.
fn load_cell_low<'ctx>(
    cx: &LowerCtx<'ctx, '_, '_>,
    pool: &MemorySignalInfo,
    row: IntValue<'ctx>,
) -> Result<IntValue<'ctx>, LoweringError> {
    let cell = crate::arrays::load_raw(cx, Backing::Memory(*pool), row, EVENT_CELL_WIDTH)?;
    Ok(cx
        .b
        .build_int_truncate(cell, cx.ctx.i64_type(), "ev_cell_lo")
        .unwrap())
}

/// Stores the 64-bit `value` to pool row `row`, the rest of the cell zero.
fn store_cell_low<'ctx>(
    cx: &LowerCtx<'ctx, '_, '_>,
    pool: &MemorySignalInfo,
    row: IntValue<'ctx>,
    value: IntValue<'ctx>,
) -> Result<(), LoweringError> {
    let packed = int_type(cx.ctx, EVENT_CELL_WIDTH * 2);
    let v = cx.b.build_int_z_extend(value, packed, "ev_cell_v").unwrap();
    crate::arrays::store_raw(cx, Backing::Memory(*pool), row, v, EVENT_CELL_WIDTH)
}

fn op<'a, 'ctx>(cx: &'a LowerCtx<'ctx, '_, '_>) -> OpBuilder<'a, 'ctx> {
    OpBuilder {
        ctx: cx.ctx,
        b: &cx.b,
    }
}

/// The 64-bit id in the frame handle at `ptr` (a scalar variable, or one row
/// of a local array).
pub(crate) fn frame_load<'ctx>(
    cx: &LowerCtx<'ctx, '_, '_>,
    ptr: PointerValue<'ctx>,
) -> IntValue<'ctx> {
    let op = op(cx);
    let raw =
        cx.b.build_load(op.packed_type(64, cx.repr), ptr, "ev_handle")
            .unwrap()
            .into_int_value();
    op.lane_val(PackedValue {
        llvm: raw,
        width: 64,
        repr: cx.repr,
        signed: false,
    })
}

/// Stores `id` into the frame handle at `ptr`.
pub(crate) fn frame_store<'ctx>(
    cx: &LowerCtx<'ctx, '_, '_>,
    ptr: PointerValue<'ctx>,
    id: IntValue<'ctx>,
) {
    let op = op(cx);
    let v = op.pack(id, op.i_n(64).const_zero(), 64, cx.repr, false);
    cx.b.build_store(ptr, v.llvm).unwrap();
}

/// The object a static event's handle names: its handle cell, 0 meaning the
/// event itself, all ones `null`.
fn static_target<'ctx>(
    cx: &LowerCtx<'ctx, '_, '_>,
    pool: &MemorySignalInfo,
    own: IntValue<'ctx>,
) -> Result<IntValue<'ctx>, LoweringError> {
    let i64t = cx.ctx.i64_type();
    let row =
        cx.b.build_int_add(own, i64c(cx, pool.lower_index as u64), "ev_hcell_row")
            .unwrap();
    let cell = load_cell_low(cx, pool, row)?;
    let is_self =
        cx.b.build_int_compare(IntPredicate::EQ, cell, i64t.const_zero(), "ev_is_self")
            .unwrap();
    let is_null =
        cx.b.build_int_compare(IntPredicate::EQ, cell, i64t.const_all_ones(), "ev_is_null")
            .unwrap();
    let other =
        cx.b.build_select(is_null, i64t.const_zero(), cell, "ev_other")
            .unwrap()
            .into_int_value();
    Ok(cx
        .b
        .build_select(is_self, own, other, "ev_target")
        .unwrap()
        .into_int_value())
}

/// An event expression's object, ready for the per-element machinery: the
/// pool row (0 for `null`, an unknown or out-of-range index) and whether it
/// names an event at all.
fn element<'ctx>(
    cx: &LowerCtx<'ctx, '_, '_>,
    pool: MemorySignalInfo,
    id: IntValue<'ctx>,
    ok: IntValue<'ctx>,
) -> EventElem<'ctx> {
    let i64t = cx.ctx.i64_type();
    let non_null =
        cx.b.build_int_compare(IntPredicate::NE, id, i64t.const_zero(), "ev_non_null")
            .unwrap();
    let valid = cx.b.build_and(ok, non_null, "ev_named").unwrap();
    let row =
        cx.b.build_select(valid, id, i64t.const_zero(), "ev_row")
            .unwrap()
            .into_int_value();
    EventElem {
        info: pool,
        row,
        valid,
    }
}

/// Resolves event expression `e` -- a named event, an element of an event
/// array, an event handle variable, `null` -- to the object it names. `None`
/// when the body has no event pool or `e` is not an event expression.
pub(crate) fn resolve_handle<'ctx, 'd>(
    cx: &LowerCtx<'ctx, 'd, '_>,
    e: sv_lang::Expression<'d>,
) -> Result<Option<EventElem<'ctx>>, LoweringError> {
    let mut e = e;
    while e.kind() == ExpressionKind::Conversion
        && let Some(inner) = e.conversion_operand()
    {
        e = inner;
    }
    let Some(pool) = pool_for(cx, &e) else {
        return Ok(None);
    };
    let all = cx.ctx.bool_type().const_all_ones();
    if e.kind() == ExpressionKind::NullLiteral {
        return Ok(Some(element(cx, pool, i64c(cx, 0), all)));
    }
    if !e.expr_type().is_some_and(|t| t.is_event()) {
        return Ok(None);
    }
    let (id, ok) = if sv_sim_sim::symid::is_value_name(e.kind()) {
        let sym = e
            .referenced_symbol()
            .ok_or_else(|| LoweringError::unsupported_at("an unresolved event name", &cx.fn_sym))?;
        if let Some(st) = static_entry(cx, &sym) {
            (
                static_target(cx, &pool, i64c(cx, st.lower_index as u64))?,
                all,
            )
        } else if let Some(&(ptr, 64, _)) = cx.locals.get(&sym.uid()) {
            (frame_load(cx, ptr), all)
        } else {
            return Err(LoweringError::unsupported_at(
                "an event that is neither an event of this module nor a local event handle \
                 (a hierarchical reference to an event, LRM 1800-2023 15.5, is unsupported \
                 where events are assigned, compared or passed)",
                &sym,
            ));
        }
    } else if e.kind() == ExpressionKind::ElementSelect {
        let Some((r, shape)) = crate::arrays::resolve_array_ref(cx, e)? else {
            return Err(LoweringError::unsupported_at(
                "an element of an event array that is not a module-level or local array",
                &cx.fn_sym,
            ));
        };
        if !shape.dims.is_empty() {
            return Err(LoweringError::unsupported_at(
                "a sub-array of an event array used as an event",
                &cx.fn_sym,
            ));
        }
        match r.backing {
            Backing::Memory(info) => {
                let own =
                    cx.b.build_int_add(i64c(cx, info.lower_index as u64), r.base, "ev_own")
                        .unwrap();
                (static_target(cx, &pool, own)?, r.valid)
            }
            Backing::Local(base) => {
                let p = crate::arrays::local_row_ptr(cx, base, r.base, 64);
                (frame_load(cx, p), r.valid)
            }
        }
    } else {
        return Err(LoweringError::unsupported_at(
            &format!(
                "an event expression of kind {:?} (only event names, event array elements, \
                 and `null` are supported)",
                e.kind()
            ),
            &cx.fn_sym,
        ));
    };
    Ok(Some(element(cx, pool, id, ok)))
}

/// Makes event expression `lhs` -- a named event, an event array element, a
/// handle variable -- name the object `rhs` names (LRM 15.5.5.1: the events
/// merge; `null` clears it).
pub(crate) fn assign_handle<'ctx, 'd>(
    cx: &LowerCtx<'ctx, 'd, '_>,
    lhs: sv_lang::Expression<'d>,
    rhs: &EventElem<'ctx>,
) -> Result<(), LoweringError> {
    let pool = pool_for(cx, &lhs).expect("an event assignment resolved a handle");
    same_pool(cx, rhs, &pool, "an event assignment")?;
    let id = rhs.row;
    if sv_sim_sim::symid::is_value_name(lhs.kind()) {
        let sym = lhs
            .referenced_symbol()
            .ok_or_else(|| LoweringError::unsupported_at("an unresolved event name", &cx.fn_sym))?;
        return assign_symbol(cx, &pool, &sym, id);
    }
    if lhs.kind() != ExpressionKind::ElementSelect {
        return Err(LoweringError::unsupported_at(
            "an event assignment target that is not an event, an event array element or a \
             handle variable",
            &cx.fn_sym,
        ));
    }
    let Some((r, shape)) = crate::arrays::resolve_array_ref(cx, lhs)? else {
        return Err(LoweringError::unsupported_at(
            "an element of an event array that is not a module-level or local array",
            &cx.fn_sym,
        ));
    };
    if !shape.dims.is_empty() {
        return Err(LoweringError::unsupported_at(
            "an assignment to a sub-array of an event array",
            &cx.fn_sym,
        ));
    }
    crate::arrays::when_valid(cx, r.valid, || match r.backing {
        Backing::Memory(info) => {
            let own =
                cx.b.build_int_add(i64c(cx, info.lower_index as u64), r.base, "ev_own")
                    .unwrap();
            store_static_handle(cx, &pool, own, id)
        }
        Backing::Local(base) => {
            let p = crate::arrays::local_row_ptr(cx, base, r.base, 64);
            frame_store(cx, p, id);
            Ok(())
        }
    })
}

/// Makes event variable `sym` (static, or a frame handle) name object `id`
/// (0 = `null`).
pub(crate) fn assign_symbol<'ctx>(
    cx: &LowerCtx<'ctx, '_, '_>,
    pool: &MemorySignalInfo,
    sym: &Symbol<'_>,
    id: IntValue<'ctx>,
) -> Result<(), LoweringError> {
    if let Some(st) = static_entry(cx, sym) {
        return store_static_handle(cx, pool, i64c(cx, st.lower_index as u64), id);
    }
    if let Some(&(ptr, 64, _)) = cx.locals.get(&sym.uid()) {
        frame_store(cx, ptr, id);
        return Ok(());
    }
    Err(LoweringError::unsupported_at(
        "an assignment to an event that is neither an event of this module nor a local event \
         handle",
        sym,
    ))
}

/// Writes static event `own`'s handle cell: `id`, or all ones for `null`.
fn store_static_handle<'ctx>(
    cx: &LowerCtx<'ctx, '_, '_>,
    pool: &MemorySignalInfo,
    own: IntValue<'ctx>,
    id: IntValue<'ctx>,
) -> Result<(), LoweringError> {
    let i64t = cx.ctx.i64_type();
    let is_null =
        cx.b.build_int_compare(IntPredicate::EQ, id, i64t.const_zero(), "ev_assign_null")
            .unwrap();
    let cell =
        cx.b.build_select(is_null, i64t.const_all_ones(), id, "ev_hcell")
            .unwrap()
            .into_int_value();
    let row =
        cx.b.build_int_add(own, i64c(cx, pool.lower_index as u64), "ev_hcell_row")
            .unwrap();
    store_cell_low(cx, pool, row, cell)
}

/// `lhs = rhs` of event type (LRM 15.5.5.1): the value of the expression is
/// never used (an event has no value).
pub(crate) fn lower_event_assignment<'ctx, 'd>(
    cx: &LowerCtx<'ctx, 'd, '_>,
    lhs: sv_lang::Expression<'d>,
    rhs: sv_lang::Expression<'d>,
) -> Result<LoweredValue<'ctx>, LoweringError> {
    if let Some(v) = crate::class_events::lower_assignment(cx, lhs, rhs)? {
        return Ok(v);
    }
    let h = resolve_handle(cx, rhs)?.ok_or_else(|| {
        LoweringError::unsupported_at(
            "an event assignment whose source is not an event expression",
            &cx.fn_sym,
        )
    })?;
    assign_handle(cx, lhs, &h)?;
    let op = op(cx);
    Ok(LoweredValue::Packed(op.pack(
        cx.ctx.bool_type().const_zero(),
        cx.ctx.bool_type().const_zero(),
        1,
        cx.repr,
        false,
    )))
}

/// `a == b`, `a != b` (and `===`, `!==`) of events (LRM 15.5.5.2, 15.5.5.3):
/// true iff both name the same event or are both `null`. `None` when neither
/// operand is an event.
pub(crate) fn lower_event_equality<'ctx, 'd>(
    cx: &LowerCtx<'ctx, 'd, '_>,
    e: sv_lang::Expression<'d>,
    negate: bool,
) -> Result<Option<LoweredValue<'ctx>>, LoweringError> {
    let (Some(l), Some(r)) = (e.left(), e.right()) else {
        return Ok(None);
    };
    let is_event = |x: sv_lang::Expression<'d>| x.expr_type().is_some_and(|t| t.is_event());
    if !is_event(l) && !is_event(r) {
        return Ok(None);
    }
    if let Some(v) = crate::class_events::lower_equality(cx, l, r, negate)? {
        return Ok(Some(v));
    }
    let (Some(a), Some(b)) = (resolve_handle(cx, l)?, resolve_handle(cx, r)?) else {
        return Err(LoweringError::unsupported_at(
            "an event comparison with an operand that is not an event expression",
            &cx.fn_sym,
        ));
    };
    let mut same =
        cx.b.build_int_compare(IntPredicate::EQ, a.row, b.row, "ev_same")
            .unwrap();
    if a.info.slot != b.info.slot {
        // Two pools hold different objects: equal only as two `null`s.
        let zero = i64c(cx, 0);
        let a0 =
            cx.b.build_int_compare(IntPredicate::EQ, a.row, zero, "ev_a0")
                .unwrap();
        let b0 =
            cx.b.build_int_compare(IntPredicate::EQ, b.row, zero, "ev_b0")
                .unwrap();
        same = cx.b.build_and(a0, b0, "ev_both_null").unwrap();
    }
    if negate {
        same = cx.b.build_not(same, "ev_differ").unwrap();
    }
    let op = op(cx);
    Ok(Some(LoweredValue::Packed(op.pack(
        same,
        cx.ctx.bool_type().const_zero(),
        1,
        cx.repr,
        false,
    ))))
}

/// An event in a Boolean context (`if (e)`, `!e`, `e ? a : b`): true iff it is
/// not `null` (LRM 15.5.5.3). `e` is the conversion node; `None` when its
/// operand is not an event.
pub(crate) fn lower_event_truth<'ctx, 'd>(
    cx: &LowerCtx<'ctx, 'd, '_>,
    e: sv_lang::Expression<'d>,
) -> Result<Option<LoweredValue<'ctx>>, LoweringError> {
    let Some(operand) = e.conversion_operand() else {
        return Ok(None);
    };
    if !operand.expr_type().is_some_and(|t| t.is_event())
        || e.expr_type().is_some_and(|t| t.is_event())
    {
        return Ok(None);
    }
    let non_null = if let Some(nn) = crate::class_events::lower_non_null(cx, operand)? {
        nn
    } else {
        let Some(h) = resolve_handle(cx, operand)? else {
            return Err(LoweringError::unsupported_at(
                "an event used as a Boolean outside the event pool",
                &cx.fn_sym,
            ));
        };
        cx.b.build_int_compare(IntPredicate::NE, h.row, i64c(cx, 0), "ev_nonnull")
            .unwrap()
    };
    let to_w = e.expr_type().map_or(1, |t| t.value_width());
    let op = op(cx);
    let bit =
        cx.b.build_int_z_extend_or_bit_cast(non_null, op.i_n(to_w), "ev_bool")
            .unwrap();
    Ok(Some(LoweredValue::Packed(op.pack(
        bit,
        op.i_n(to_w).const_zero(),
        to_w,
        cx.repr,
        false,
    ))))
}

/// [`lower_event_truth`] for a condition: the i1 "is not null" of an event
/// expression (possibly under conversions), `None` for any other expression.
pub(crate) fn lower_event_condition<'ctx, 'd>(
    cx: &LowerCtx<'ctx, 'd, '_>,
    e: sv_lang::Expression<'d>,
) -> Result<Option<IntValue<'ctx>>, LoweringError> {
    let mut inner = e;
    while inner.kind() == ExpressionKind::Conversion
        && let Some(x) = inner.conversion_operand()
    {
        inner = x;
    }
    if !inner.expr_type().is_some_and(|t| t.is_event()) {
        return Ok(None);
    }
    if let Some(nn) = crate::class_events::lower_non_null(cx, inner)? {
        return Ok(Some(nn));
    }
    let Some(h) = resolve_handle(cx, inner)? else {
        return Err(LoweringError::unsupported_at(
            "an event used as a Boolean outside the event pool",
            &cx.fn_sym,
        ));
    };
    Ok(Some(
        cx.b.build_int_compare(IntPredicate::NE, h.row, i64c(cx, 0), "ev_nonnull")
            .unwrap(),
    ))
}

/// A new event object for an automatic declaration: the id of the next
/// unused dynamic row of the pool.
fn alloc_event<'ctx>(
    cx: &LowerCtx<'ctx, '_, '_>,
    pool: &MemorySignalInfo,
) -> Result<IntValue<'ctx>, LoweringError> {
    let i64t = cx.ctx.i64_type();
    let used = load_cell_low(cx, pool, i64c(cx, 0))?;
    let cap = i64c(cx, u64::from(DYNAMIC_ROWS));
    let full =
        cx.b.build_int_compare(IntPredicate::UGE, used, cap, "ev_pool_full")
            .unwrap();
    // Never a silent reuse of a live event: the pool is used up, so the
    // process ends with a fatal error.
    crate::stmt_shared::fatal_if(
        cx,
        full,
        sv_lang::SourceLoc::default(),
        &format!(
            "too many local events: more than {DYNAMIC_ROWS} automatic event declarations \
             executed (the event pool of this module is exhausted)"
        ),
    )?;
    let n = used;
    let next =
        cx.b.build_int_add(n, i64t.const_int(1, false), "ev_alloc_next")
            .unwrap();
    store_cell_low(cx, pool, i64c(cx, 0), next)?;
    let base = i64c(cx, 2 * pool.lower_index as u64 + 1);
    Ok(cx.b.build_int_add(base, n, "ev_alloc_id").unwrap())
}

/// `var` is an event (or an event array) variable of a body with an event
/// pool: its declaration is [`init_event_var`], not an ordinary variable's.
pub(crate) fn is_pool_event_var(cx: &LowerCtx<'_, '_, '_>, var: &Symbol<'_>) -> bool {
    pool_info(cx).is_some() && var.value_type().as_ref().and_then(event_count).is_some()
}

/// Declares event variable `var` (an automatic block or task local, or a
/// static one): a new event object for each automatic event, the named
/// object for an initializer (`event e = other;`, `= null`).
pub(crate) fn init_event_var<'d>(
    cx: &LowerCtx<'_, 'd, '_>,
    var: &Symbol<'d>,
) -> Result<(), LoweringError> {
    let pool = pool_info(cx).expect("an event declaration of a body with an event pool");
    let ty = var.value_type().expect("an event variable has a type");
    let count = event_count(&ty).expect("an event variable holds events");
    let scalar = !ty.is_unpacked_array();
    if let Some(st) = static_entry(cx, var) {
        // A static event is one object for the whole run; only an
        // initializer names another.
        if let Some(init) = var.initializer() {
            if !scalar {
                return Err(LoweringError::unsupported_at(
                    "an initializer on an event array",
                    var,
                ));
            }
            let h = resolve_handle(cx, init)?.ok_or_else(|| {
                LoweringError::unsupported_at("an event initializer that is not an event", var)
            })?;
            store_static_handle(cx, &pool, i64c(cx, st.lower_index as u64), h.row)?;
        }
        return Ok(());
    }
    let &(ptr, _, _) = cx
        .locals
        .get(&var.uid())
        .ok_or_else(|| LoweringError::unsupported_at("a local event has no frame slot", var))?;
    if scalar {
        let id = match var.initializer() {
            Some(init) => {
                resolve_handle(cx, init)?
                    .ok_or_else(|| {
                        LoweringError::unsupported_at(
                            "an event initializer that is not an event",
                            var,
                        )
                    })?
                    .row
            }
            None => alloc_event(cx, &pool)?,
        };
        frame_store(cx, ptr, id);
        return Ok(());
    }
    if var.initializer().is_some() {
        return Err(LoweringError::unsupported_at(
            "an initializer on an event array",
            var,
        ));
    }
    // One new object per element.
    let unit = cx.ctx.bool_type().const_zero();
    crate::arrays::row_loop(cx, u64::from(count), unit, |k, acc| {
        let id = alloc_event(cx, &pool)?;
        let p = crate::arrays::local_row_ptr(cx, ptr, k, 64);
        frame_store(cx, p, id);
        Ok(acc)
    })?;
    Ok(())
}

/// Copies the objects of event array `actual` into (`to_formal`) or out of
/// the local frame array `formal_ptr` row by row (LRM 1800-2023 15.5.5.1:
/// handles are passed, so both arrays name the same events; 7.4 arrays are
/// copied element-wise). `actual` is a whole event array or a slice of one,
/// module-level (pool range) or local.
fn copy_event_array<'ctx, 'd>(
    cx: &LowerCtx<'ctx, 'd, '_>,
    pool: &MemorySignalInfo,
    formal: &Symbol<'d>,
    formal_ptr: PointerValue<'ctx>,
    actual: sv_lang::Expression<'d>,
    to_formal: bool,
) -> Result<(), LoweringError> {
    let count = formal
        .value_type()
        .as_ref()
        .and_then(event_count)
        .expect("an event array formal holds events");
    let Some((r, _)) = crate::arrays::array_target(cx, actual)? else {
        return Err(LoweringError::unsupported_at(
            "an event array argument whose actual is not a module-level or local event array",
            formal,
        ));
    };
    if pool_for(cx, &actual).is_some_and(|p| p.slot != pool.slot) {
        return Err(LoweringError::unsupported_at(
            "an event array argument whose actual is an event array of another instance",
            formal,
        ));
    }
    let i64t = cx.ctx.i64_type();
    let unit = cx.ctx.bool_type().const_zero();
    crate::arrays::row_loop(cx, u64::from(count), unit, |k, acc| {
        let row = cx.b.build_int_add(r.base, k, "ev_arg_row").unwrap();
        let formal_row = crate::arrays::local_row_ptr(cx, formal_ptr, k, 64);
        if to_formal {
            let id = match r.backing {
                Backing::Memory(info) => {
                    let own =
                        cx.b.build_int_add(i64c(cx, info.lower_index as u64), row, "ev_own")
                            .unwrap();
                    static_target(cx, pool, own)?
                }
                Backing::Local(base) => {
                    frame_load(cx, crate::arrays::local_row_ptr(cx, base, row, 64))
                }
            };
            // An element selected through an unknown or out-of-range index
            // is `null` (0).
            let id =
                cx.b.build_select(r.valid, id, i64t.const_zero(), "ev_arg_id")
                    .unwrap()
                    .into_int_value();
            frame_store(cx, formal_row, id);
        } else {
            let id = frame_load(cx, formal_row);
            crate::arrays::when_valid(cx, r.valid, || match r.backing {
                Backing::Memory(info) => {
                    let own =
                        cx.b.build_int_add(i64c(cx, info.lower_index as u64), row, "ev_own")
                            .unwrap();
                    store_static_handle(cx, pool, own, id)
                }
                Backing::Local(base) => {
                    frame_store(cx, crate::arrays::local_row_ptr(cx, base, row, 64), id);
                    Ok(())
                }
            })?;
        }
        Ok(acc)
    })?;
    Ok(())
}

/// Binds event formal `formal` of an inlined task to the event `actual`
/// names (LRM 15.5.5.1: the handle is passed, so both name one event).
pub(crate) fn bind_event_formal<'ctx, 'd>(
    cx: &LowerCtx<'ctx, 'd, '_>,
    formal: &Symbol<'d>,
    actual: sv_lang::Expression<'d>,
) -> Result<(), LoweringError> {
    let Some(pool) = pool_info(cx) else {
        return Err(LoweringError::unsupported_at(
            "an event formal in a module with no event pool (internal)",
            formal,
        ));
    };
    if formal.value_type().is_some_and(|t| t.is_unpacked_array()) {
        if let Some(&(ptr, _, _)) = cx.locals.get(&formal.uid()) {
            return copy_event_array(cx, &pool, formal, ptr, actual, true);
        }
        return Err(LoweringError::unsupported_at(
            "an event array as a task argument",
            formal,
        ));
    }
    let h = resolve_handle(cx, actual)?.ok_or_else(|| {
        LoweringError::unsupported_at(
            "an event argument whose actual is not an event expression",
            formal,
        )
    })?;
    same_pool(cx, &h, &pool, "an event argument")?;
    assign_symbol(cx, &pool, formal, h.row)
}

/// `formal` is an event (or an event array) formal argument.
pub(crate) fn is_event_formal(formal: &Symbol<'_>) -> bool {
    formal.value_type().as_ref().and_then(event_count).is_some()
}

/// The copy-back of an `output`/`inout`/`ref` event formal of an inlined
/// task: event expression `actual` names the object the formal names when
/// the task returns (LRM 1800-2023 15.5.5.1: assigning an event merges, so
/// processes waiting on the actual's old object stay on it). `false` when
/// `formal` is not an event.
pub(crate) fn copy_out_formal<'ctx, 'd>(
    cx: &LowerCtx<'ctx, 'd, '_>,
    formal: &Symbol<'d>,
    actual: sv_lang::Expression<'d>,
) -> Result<bool, LoweringError> {
    if !formal.value_type().is_some_and(|t| t.is_event()) && !is_event_formal(formal) {
        return Ok(false);
    }
    if formal.value_type().is_some_and(|t| t.is_unpacked_array()) {
        if let (Some(pool), Some(&(ptr, _, _))) = (pool_info(cx), cx.locals.get(&formal.uid())) {
            copy_event_array(cx, &pool, formal, ptr, actual, false)?;
            return Ok(true);
        }
        return Err(LoweringError::unsupported_at(
            "an event array as a task argument",
            formal,
        ));
    }
    let id = if let Some(&(ptr, 64, _)) = cx.locals.get(&formal.uid()) {
        frame_load(cx, ptr)
    } else if let (Some(pool), Some(st)) = (pool_info(cx), static_entry(cx, formal)) {
        // A static task's formal is the instance's own event.
        static_target(cx, &pool, i64c(cx, st.lower_index as u64))?
    } else {
        return Err(LoweringError::unsupported_at(
            "an event formal has no frame handle (internal)",
            formal,
        ));
    };
    // Module events (pool rows) and class events (runtime ids) are two id
    // spaces that never mix: refuse rather than store the wrong kind of id.
    let class_formal = crate::class_events::is_class_method_local(formal);
    if class_formal != crate::class_events::is_class_event(actual) {
        return Err(LoweringError::unsupported_at(
            "an event argument whose formal and actual are not both class events or both \
             module events (a module event cannot be passed back as a class event, LRM \
             1800-2023 15.5)",
            formal,
        ));
    }
    if class_formal {
        crate::class_events::store_id(cx, actual, id)?;
        return Ok(true);
    }
    let Some(pool) = pool_info(cx) else {
        return Err(LoweringError::unsupported_at(
            "an event formal in a module with no event pool (internal)",
            formal,
        ));
    };
    let all = cx.ctx.bool_type().const_all_ones();
    assign_handle(cx, actual, &element(cx, pool, id, all))?;
    Ok(true)
}