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
//! `event` properties, locals and formals of classes (LRM 1800-2023 15.5).
//!
//! A module's `event` is a state cell (or a row of its event pool,
//! [`crate::events`]), which compiled class code cannot reach: a class method
//! has no instance handle. A CLASS event is instead a runtime object
//! (`vj_sim::sched::class_event`): the value of an `event` property, local
//! or formal is its 64-bit id (`0` = `null`), and `@e`, `-> e` and `.triggered`
//! are `sv_rt_semaphore` calls (`SemaphoreOp::Event*`). Which space an event
//! expression is in is [`vj_sim::process::cfg::is_class_event_expr`]; the
//! two never mix (assigning a module event to a class one is refused by name).
//!
//! Limits, all refused by name: `@(a or b)`/edge/`iff` on one; an event array in a class.

use inkwell::IntPredicate;
use inkwell::values::IntValue;
use sv_lang::Symbol;
use sv_lang::kinds::ExpressionKind;
use vj_runtime::semaphore_rt::SemaphoreOp;
use vj_sim::symid::SymbolUid;

use crate::error::LoweringError;
use crate::expr::{LowerCtx, LoweredValue};
use crate::ops::OpBuilder;

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

/// Strips conversions.
fn strip<'d>(mut e: sv_lang::Expression<'d>) -> sv_lang::Expression<'d> {
    while e.kind() == ExpressionKind::Conversion
        && let Some(inner) = e.conversion_operand()
    {
        e = inner;
    }
    e
}

/// `e` is a class event ([`vj_sim::process::cfg::is_class_event_expr`]).
pub(crate) fn is_class_event(e: sv_lang::Expression<'_>) -> bool {
    vj_sim::process::cfg::is_class_event_expr(&e)
}

/// Whether `e` is `null` (under conversions).
fn is_null(e: sv_lang::Expression<'_>) -> bool {
    strip(e).kind() == ExpressionKind::NullLiteral
}

/// A new-event-id / trigger / wait / triggered call.
fn call<'ctx>(cx: &LowerCtx<'ctx, '_, '_>, op: SemaphoreOp, id: IntValue<'ctx>) -> IntValue<'ctx> {
    crate::classes::semaphore_call(cx, op, id, cx.ctx.i64_type().const_zero())
}

/// A fresh event object's id.
pub(crate) fn new_event<'ctx>(cx: &LowerCtx<'ctx, '_, '_>) -> IntValue<'ctx> {
    call(cx, SemaphoreOp::EventNew, cx.ctx.i64_type().const_zero())
}

/// The object handle, slot and name of an `event` property named by
/// `e` (a `static` one lives in its class's singleton); `None` when `e` is not
/// a property.
fn property<'ctx, 'd>(
    cx: &LowerCtx<'ctx, 'd, '_>,
    e: sv_lang::Expression<'d>,
) -> Result<Option<(IntValue<'ctx>, vj_sim::objects::FieldSlot, String)>, LoweringError> {
    let member = if e.kind() == ExpressionKind::MemberAccess {
        e.member_symbol()
    } else if matches!(
        e.kind(),
        ExpressionKind::NamedValue | ExpressionKind::HierarchicalValue
    ) {
        e.referenced_symbol()
    } else {
        None
    };
    let Some(member) = member else {
        return Ok(None);
    };
    if crate::classes::is_static_field(&member) {
        // One event per class specialization (LRM 8.9), held by the class's
        // static singleton like every other static property.
        let (h, slot, _) = crate::classes::static_location(cx, &member)?;
        return Ok(Some((h, slot, member.name().to_owned())));
    }
    if !crate::classes::is_instance_field(&member) {
        return Ok(None);
    }
    let h = if e.kind() == ExpressionKind::MemberAccess {
        let base = e.operand().ok_or_else(|| {
            LoweringError::unsupported_at("member-access event missing base", &cx.fn_sym)
        })?;
        crate::classes::receiver_handle(cx, base)?
    } else {
        crate::classes::current_this_handle(cx)?
    };
    let (slot, _) = crate::classes::member_slot_and_type(&member)?;
    Ok(Some((h, slot, member.name().to_owned())))
}

/// The 64-bit id class-event expression `e` holds.
fn load_id<'ctx, 'd>(
    cx: &LowerCtx<'ctx, 'd, '_>,
    e: sv_lang::Expression<'d>,
) -> Result<IntValue<'ctx>, LoweringError> {
    let e = strip(e);
    if let Some((h, slot, name)) = property(cx, e)? {
        let (pv, live) = crate::classes::field_get_call(cx, h, slot, 64, false);
        crate::classes::report_dead_handle_access(cx, live, e.source_range().start, &name, "read")?;
        return Ok(op(cx).lane_val(pv));
    }
    let sym = e
        .referenced_symbol()
        .ok_or_else(|| LoweringError::unsupported_at("an unresolved class event", &cx.fn_sym))?;
    match cx.locals.get(&sym.uid()) {
        Some(&(ptr, 64, _)) => Ok(crate::events::frame_load(cx, ptr)),
        _ => Err(LoweringError::unsupported_at(
            "a class event that is neither a property nor a local/formal of its method",
            &sym,
        )),
    }
}

/// The id `e` names, where `e` is a class event or `null`. Any other event
/// (a module's) is refused: the two spaces do not mix.
pub(crate) fn id_of<'ctx, 'd>(
    cx: &LowerCtx<'ctx, 'd, '_>,
    e: sv_lang::Expression<'d>,
) -> Result<IntValue<'ctx>, LoweringError> {
    if is_null(e) {
        return Ok(cx.ctx.i64_type().const_zero());
    }
    if !is_class_event(e) {
        return Err(LoweringError::unsupported_at(
            "a class event used together with an event that is not a class event (a module \
             event cannot be assigned to, compared with or passed as a class event, LRM \
             1800-2023 15.5)",
            &cx.fn_sym,
        ));
    }
    load_id(cx, e)
}

/// Stores `id` as the value of class-event expression `lhs`.
pub(crate) fn store_id<'ctx, 'd>(
    cx: &LowerCtx<'ctx, 'd, '_>,
    lhs: sv_lang::Expression<'d>,
    id: IntValue<'ctx>,
) -> Result<(), LoweringError> {
    let lhs = strip(lhs);
    if let Some((h, slot, name)) = property(cx, lhs)? {
        let v = op(cx).pack(id, op(cx).i_n(64).const_zero(), 64, cx.repr, false);
        let live = crate::classes::field_set_call(cx, h, slot, v);
        return crate::classes::report_dead_handle_access(
            cx,
            live,
            lhs.source_range().start,
            &name,
            "write",
        );
    }
    let sym = lhs
        .referenced_symbol()
        .ok_or_else(|| LoweringError::unsupported_at("an unresolved class event", &cx.fn_sym))?;
    match cx.locals.get(&sym.uid()) {
        Some(&(ptr, 64, _)) => {
            crate::events::frame_store(cx, ptr, id);
            Ok(())
        }
        _ => Err(LoweringError::unsupported_at(
            "an assignment to a class event that is neither a property nor a local/formal of \
             its method",
            &sym,
        )),
    }
}

/// `lhs = rhs` where `lhs` is a class event (15.5.5.1: both then name one
/// object; `= null` clears it). `None` when `lhs` is not a class event.
pub(crate) fn lower_assignment<'ctx, 'd>(
    cx: &LowerCtx<'ctx, 'd, '_>,
    lhs: sv_lang::Expression<'d>,
    rhs: sv_lang::Expression<'d>,
) -> Result<Option<LoweredValue<'ctx>>, LoweringError> {
    if !is_class_event(lhs) {
        // A module event assigned from a class event: refuse, never alias.
        if is_class_event(rhs) {
            return Err(LoweringError::unsupported_at(
                "a class event assigned to an event that is not a class event (LRM 1800-2023 \
                 15.5)",
                &cx.fn_sym,
            ));
        }
        return Ok(None);
    }
    let id = id_of(cx, rhs)?;
    store_id(cx, lhs, id)?;
    let o = op(cx);
    Ok(Some(LoweredValue::Packed(o.pack(
        cx.ctx.bool_type().const_zero(),
        cx.ctx.bool_type().const_zero(),
        1,
        cx.repr,
        false,
    ))))
}

/// `a == b` / `a != b` where either operand is a class event.
pub(crate) fn lower_equality<'ctx, 'd>(
    cx: &LowerCtx<'ctx, 'd, '_>,
    l: sv_lang::Expression<'d>,
    r: sv_lang::Expression<'d>,
    negate: bool,
) -> Result<Option<LoweredValue<'ctx>>, LoweringError> {
    if !is_class_event(l) && !is_class_event(r) {
        return Ok(None);
    }
    let a = id_of(cx, l)?;
    let b = id_of(cx, r)?;
    let pred = if negate {
        IntPredicate::NE
    } else {
        IntPredicate::EQ
    };
    let same = cx.b.build_int_compare(pred, a, b, "cev_cmp").unwrap();
    let o = op(cx);
    Ok(Some(LoweredValue::Packed(o.pack(
        same,
        cx.ctx.bool_type().const_zero(),
        1,
        cx.repr,
        false,
    ))))
}

/// The i1 "is not null" of class event `e`; `None` when `e` is not one.
pub(crate) fn lower_non_null<'ctx, 'd>(
    cx: &LowerCtx<'ctx, 'd, '_>,
    e: sv_lang::Expression<'d>,
) -> Result<Option<IntValue<'ctx>>, LoweringError> {
    if !is_class_event(e) {
        return Ok(None);
    }
    let id = load_id(cx, e)?;
    Ok(Some(
        cx.b.build_int_compare(
            IntPredicate::NE,
            id,
            cx.ctx.i64_type().const_zero(),
            "cev_nonnull",
        )
        .unwrap(),
    ))
}

/// `-> e` on a class event: `true` when `target` was one (and was lowered).
pub(crate) fn lower_trigger<'ctx, 'd>(
    cx: &LowerCtx<'ctx, 'd, '_>,
    target: sv_lang::Expression<'d>,
) -> Result<bool, LoweringError> {
    if !is_class_event(target) {
        return Ok(false);
    }
    let id = load_id(cx, target)?;
    call(cx, SemaphoreOp::EventTrigger, id);
    Ok(true)
}

/// `->> [#d] e` on a class event (LRM 1800-2023 15.5.1, 15.5.5.1): the trigger
/// is a nonblocking update, committed in the NBA region `delay` ticks from now.
/// `true` when `target` was a class event (and was lowered).
pub(crate) fn lower_trigger_nba<'ctx, 'd>(
    cx: &LowerCtx<'ctx, 'd, '_>,
    target: sv_lang::Expression<'d>,
    delay: IntValue<'ctx>,
) -> Result<bool, LoweringError> {
    if !is_class_event(target) {
        return Ok(false);
    }
    let id = load_id(cx, target)?;
    crate::classes::semaphore_call(cx, SemaphoreOp::EventTriggerNba, id, delay);
    Ok(true)
}

/// `e.triggered` on a class event.
pub(crate) fn lower_triggered<'ctx, 'd>(
    cx: &LowerCtx<'ctx, 'd, '_>,
    target: sv_lang::Expression<'d>,
) -> Result<Option<LoweredValue<'ctx>>, LoweringError> {
    if !is_class_event(target) {
        return Ok(None);
    }
    let id = load_id(cx, target)?;
    let r = call(cx, SemaphoreOp::EventTriggered, id);
    let bit =
        cx.b.build_int_truncate(r, cx.ctx.bool_type(), "cev_triggered")
            .unwrap();
    let o = op(cx);
    Ok(Some(LoweredValue::Packed(o.pack(
        bit,
        cx.ctx.bool_type().const_zero(),
        1,
        cx.repr,
        false,
    ))))
}

/// The leaf of `@e` on a class event (`process::cfg::walk_timed` pushed the
/// `Timed` statement and a by-request suspend after it): queues the running
/// process on the event's object. The guarded body is not part of the leaf.
pub(crate) fn lower_wait<'ctx, 'd>(
    cx: &LowerCtx<'ctx, 'd, '_>,
    stmt: &sv_lang::Statement<'d>,
) -> Result<(), LoweringError> {
    let tc = stmt.timing_control().ok_or_else(|| {
        LoweringError::unsupported_at("a class event wait with no event", &cx.fn_sym)
    })?;
    // `@e` or an `@(e1 or e2 ...)` list of class events (15.5, 9.4.2.1): the
    // process is queued on every term's event, the last call blocks it, and the
    // first trigger of any term wakes it (and drops it from the others).
    let terms = vj_sim::process::cfg::class_event_wait_terms(&tc)
        .map_err(|e| LoweringError::unsupported_at(&e.to_string(), &cx.fn_sym))?;
    if vj_sim::process::cfg::class_event_wait_is_mixed(&tc) {
        // `@(ce or sig ...)`: queue on every class term without blocking; the
        // suspend that follows is the signal wait (`walk_timed`).
        for sig in &terms {
            let id = load_id(cx, *sig)?;
            call(cx, SemaphoreOp::EventEnqueueDual, id);
        }
        return Ok(());
    }
    let Some((last, first)) = terms.split_last() else {
        return Err(LoweringError::unsupported_at(
            "a class event wait with no event",
            &cx.fn_sym,
        ));
    };
    for sig in first {
        let id = load_id(cx, *sig)?;
        call(cx, SemaphoreOp::EventEnqueue, id);
    }
    let id = load_id(cx, *last)?;
    call(cx, SemaphoreOp::EventWait, id);
    Ok(())
}

/// The resume of a mixed `@(class_event or signal ...)` wait: the process
/// leaves the class-event queues it is still on.
pub(crate) fn lower_leave(cx: &LowerCtx<'_, '_, '_>) {
    call(cx, SemaphoreOp::EventLeave, cx.ctx.i64_type().const_zero());
}

/// Declares class-event local `var`: a new event object, or the one its
/// initializer names. `false` when `var` is not a class-method `event`.
pub(crate) fn init_local<'ctx, 'd>(
    cx: &LowerCtx<'ctx, 'd, '_>,
    var: &Symbol<'d>,
) -> Result<bool, LoweringError> {
    if !var.value_type().is_some_and(|t| t.is_event()) || !is_class_method_local(var) {
        return Ok(false);
    }
    let &(ptr, _, _) = cx
        .locals
        .get(&var.uid())
        .ok_or_else(|| LoweringError::unsupported_at("a local event has no frame slot", var))?;
    let id = match var.initializer() {
        Some(init) => id_of(cx, init)?,
        None => new_event(cx),
    };
    crate::events::frame_store(cx, ptr, id);
    Ok(true)
}

/// `var` is declared inside a class method.
pub(crate) fn is_class_method_local(var: &Symbol<'_>) -> bool {
    let mut scope = var.parent();
    while let Some(s) = scope {
        if s.kind() == sv_lang::kinds::SymbolKind::Subroutine {
            return s.parent().is_some_and(|p| {
                matches!(
                    p.kind(),
                    sv_lang::kinds::SymbolKind::ClassType
                        | sv_lang::kinds::SymbolKind::GenericClassDef
                )
            });
        }
        scope = s.parent();
    }
    false
}

/// Binds the `input` event formal `formal` of an inlined class-method task to
/// the class event `actual` names (both then name one object, 15.5.5.1).
/// `false` when `formal` is not a class-method event.
pub(crate) fn bind_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_class_method_local(formal) {
        return Ok(false);
    }
    let &(ptr, _, _) = cx.locals.get(&formal.uid()).ok_or_else(|| {
        LoweringError::unsupported_at("an event formal has no frame slot", formal)
    })?;
    let id = id_of(cx, actual)?;
    crate::events::frame_store(cx, ptr, id);
    Ok(true)
}