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
// Copyright (c) 2016-2021 Fabian Schuiki

//! Expression lvalue lowering to MIR.

use crate::crate_prelude::*;
use crate::{
    hir::HirNode,
    mir::{
        lower,
        lower::rvalue::{adjust_indexing, compute_indexing},
        lvalue::*,
        rvalue::RvalueKind,
    },
    syntax::ast::BasicNode,
    ty::{SbvType, UnpackedType},
    typeck::{CastOp, CastType},
    ParamEnv,
};
use num::ToPrimitive;

/// An internal builder for lvalue lowering.
pub struct Builder<'a, C> {
    /// The context to lower into.
    pub cx: &'a C,
    /// The span of the expression being lowered.
    pub span: Span,
    /// The expression being lowered.
    pub expr: NodeId,
    /// The parametrization of the expression being lowered.
    pub env: ParamEnv,
}

impl<'a, C: Context<'a>> Builder<'_, C> {
    /// Create a new builder for a different node.
    #[allow(dead_code)]
    pub fn with(&self, expr: NodeId) -> Self {
        Builder {
            cx: self.cx,
            span: self.cx.span(expr),
            expr,
            env: self.env,
        }
    }

    /// Intern an MIR node.
    pub fn build(&self, ty: &'a UnpackedType<'a>, kind: LvalueKind<'a>) -> &'a Lvalue<'a> {
        self.cx.arena().alloc_mir_lvalue(Lvalue {
            id: self.cx.alloc_id(self.span),
            origin: self.expr,
            env: self.env,
            span: self.span,
            ty,
            kind: kind,
        })
    }

    /// Create an error node.
    ///
    /// This is usually called when something goes wrong during MIR construction
    /// and a marker node is needed to indicate that part of the MIR is invalid.
    pub fn error(&self) -> &'a Lvalue<'a> {
        self.build(UnpackedType::make_error(), LvalueKind::Error)
    }
}

/// Lower an expression to an lvalue in the MIR.
#[moore_derive::query]
pub fn mir_lvalue<'a>(
    cx: &impl Context<'a>,
    expr_id: NodeId,
    env: ParamEnv,
) -> &'a mir::Lvalue<'a> {
    let span = cx.span(expr_id);
    let builder = Builder {
        cx,
        span,
        expr: expr_id,
        env,
    };

    // Try to extract the expr HIR for this node. Handle a few special cases
    // where the node is not technically an expression, but can be used as a
    // lvalue.
    let hir = match cx.hir_of(expr_id) {
        Ok(HirNode::Expr(x)) => x,
        Ok(x) => bug_span!(span, cx, "no lvalue for {:?}", x),
        Err(_) => return builder.error(),
    };

    // Determine the cast type.
    let cast = cx.cast_type(expr_id, env).unwrap();

    // Lower the expression.
    let lvalue = lower_expr_inner(&builder, hir, cast.init).unwrap_or_else(|_| builder.error());
    if lvalue.is_error() {
        return lvalue;
    }
    assert_span!(
        lvalue.ty.is_identical(cast.init),
        hir.span,
        cx,
        "lvalue lowering produced type `{}`, expected `{}`",
        lvalue.ty,
        cast.init
    );

    // Lower the casts.
    lower_cast(&builder, lvalue, cast)
}

/// Lower an expression to an rvalue in the MIR.
///
/// May return an error if any of the database queries break.
fn lower_expr_inner<'a>(
    builder: &Builder<'_, impl Context<'a>>,
    hir: &'a hir::Expr<'a>,
    ty: &'a UnpackedType<'a>,
) -> Result<&'a Lvalue<'a>> {
    let expr_id = hir.id;
    let cx = builder.cx;
    let span = cx.span(expr_id);
    let env = builder.env;
    if ty.is_error() {
        return Err(());
    }

    // Match on the various forms.
    match hir.kind {
        // Identifiers and scoped identifiers we simply resolve and try to lower
        // the resolved node to an MIR node.
        hir::ExprKind::Ident(..) | hir::ExprKind::Scope(..) => {
            let binding = cx.resolve_node(expr_id, env)?;
            return match cx.hir_of(binding)? {
                HirNode::GenvarDecl(decl) => Ok(builder.build(ty, LvalueKind::Genvar(decl.id))),
                HirNode::VarDecl(decl) => Ok(builder.build(ty, LvalueKind::Var(decl.id))),
                HirNode::IntPort(port) if ty.resolve_full().core.get_interface().is_some() => {
                    Ok(builder.build(ty, LvalueKind::Intf(port.id)))
                }
                HirNode::IntPort(port) => Ok(builder.build(ty, LvalueKind::Port(port.id))),
                HirNode::Inst(inst) if ty.resolve_full().core.get_interface().is_some() => {
                    Ok(builder.build(ty, LvalueKind::Intf(inst.id)))
                }
                x => {
                    cx.emit(
                        DiagBuilder2::error(format!(
                            "{} cannot be used as the target of an assignment",
                            x.desc_full()
                        ))
                        .span(span),
                    );
                    Err(())
                }
            };
        }

        hir::ExprKind::Index(target, mode) => {
            // Compute the indexing parameters.
            let (base, length) = compute_indexing(cx, builder.expr, env, mode)?;

            // Lower the indexee and make sure it can be indexed into.
            let target = cx.mir_lvalue(target, env);
            assert_span!(
                target.ty.dims().next().is_some(),
                target.span,
                cx,
                "cannot index into `{}`; should be handled by typeck",
                target.ty
            );

            // Offset the indexing base by the dimension base, e.g. for accesses
            // such as `x[1]` into `logic [2:1] x`, which essentially accesses
            // element 0.
            let target_dim = target.ty.dims().next().unwrap();
            let rvalue_builder = lower::rvalue::Builder {
                cx,
                span: base.span,
                expr: base.id,
                env: base.env,
            };
            let base = adjust_indexing(&rvalue_builder, base, target_dim);

            // Build the cast lvalue.
            return Ok(builder.build(
                ty,
                LvalueKind::Index {
                    value: target,
                    base,
                    length,
                },
            ));
        }

        hir::ExprKind::Field(target, name) => {
            let target_ty = cx.self_determined_type(target, env);
            let value = cx.mir_lvalue(target, env);
            if let Some(intf) = target_ty.and_then(|ty| ty.get_interface()) {
                let def = cx.resolve_hierarchical_or_error(name, intf.ast)?;
                // Distinguish `intf.modport` and `intf.signal`.
                if def.node.as_all().is_modport_name() {
                    return Ok(builder.build(ty, value.kind.clone()));
                } else {
                    return Ok(builder.build(ty, LvalueKind::IntfSignal(value, def.node.id())));
                }
            } else {
                let (field, _) = cx.resolve_field_access(expr_id, env)?;
                return Ok(builder.build(ty, LvalueKind::Member { value, field }));
            }
        }

        hir::ExprKind::Concat(repeat, ref exprs) => {
            // Compute the SBVT for each expression and lower it to MIR,
            // implicitly casting to the SBVT.
            let exprs = exprs
                .iter()
                .map(|&expr| {
                    let value = builder.cx.mir_lvalue(expr, env);
                    assert_span!(
                        value.ty.coalesces_to_llhd_scalar(),
                        value.span,
                        builder.cx,
                        "type `{}` does not coalesce to LLHD scalar",
                        value.ty
                    );
                    Ok((value.ty.get_bit_size().unwrap(), value))
                })
                .collect::<Result<Vec<_>>>()?;

            // Compute the result type of the concatenation.
            let final_ty = builder.cx.need_self_determined_type(hir.id, env);
            if final_ty.is_error() {
                return Err(());
            }
            let domain = final_ty.domain();
            let concat_width = exprs.iter().map(|(w, _)| w).sum();
            let concat_ty =
                SbvType::new(domain, ty::Sign::Unsigned, concat_width).to_unpacked(builder.cx);

            // Assemble the concatenation.
            let concat = builder.build(
                concat_ty,
                LvalueKind::Concat(exprs.into_iter().map(|(_, v)| v).collect()),
            );

            // If a repetition is present, apply that.
            let repeat = if let Some(repeat) = repeat {
                let count = builder
                    .cx
                    .constant_int_value_of(repeat, env)?
                    .to_usize()
                    .unwrap();
                builder.build(final_ty, LvalueKind::Repeat(count, concat))
            } else {
                concat
            };
            return Ok(repeat);
        }

        _ => (),
    }

    // Show an error informing the user that the given expression cannot be
    // assigned to.
    error!("{:#?}", hir);
    cx.emit(DiagBuilder2::error(format!("{} cannot be assigned to", hir.desc_full())).span(span));
    Err(())
}

/// Generate the nodes necessary for a cast operation.
fn lower_cast<'a>(
    builder: &Builder<'_, impl Context<'a>>,
    mut value: &'a Lvalue<'a>,
    to: CastType<'a>,
) -> &'a Lvalue<'a> {
    // Don't bother with errors.
    if value.is_error() {
        return value;
    }
    if to.is_error() {
        return builder.error();
    }
    assert_type!(
        value.ty,
        to.init,
        value.span,
        builder.cx,
        "lvalue type `{}` does not match initial type of cast `{}`",
        value.ty,
        to
    );
    trace!(
        "Lowering cast to `{}` from `{}` of `{}` (line {})",
        to,
        value.ty,
        value.span.extract(),
        value.span.begin().human_line()
    );

    // Lower each cast individually.
    for &(op, to) in &to.casts {
        debug!("- {:?} from `{}` to `{}`", op, value.ty, to);
        match op {
            CastOp::PackSBVT => {
                assert_span!(to.is_simple_bit_vector(), value.span, builder.cx);
                value = pack_simple_bit_vector(builder, value);
            }
            CastOp::PickModport => {
                value = builder.build(to, value.kind.clone());
            }
            _ => {
                bug_span!(
                    value.span,
                    builder.cx,
                    "lvalue lowering of cast to `{}` not yet supported: {:?}",
                    to,
                    op
                );
            }
        }
        if !value.ty.is_identical(to) {
            error!(
                "Cast {:?} should have produced `{}`, but value is `{}`",
                op, to, value.ty
            );
        }
    }

    // Check that the casts have actually produced the expected output type.
    assert_type!(
        value.ty,
        to.ty,
        value.span,
        builder.cx,
        "lvalue type `{}` does not match final cast type `{}` after lower_cast",
        value.ty,
        to.ty
    );
    value
}

/// Generate the nodes necessary to pack a value to its corresponding simple bit
/// vector type.
fn pack_simple_bit_vector<'a>(
    builder: &Builder<'_, impl Context<'a>>,
    value: &'a Lvalue<'a>,
) -> &'a Lvalue<'a> {
    if value.is_error() {
        return value;
    }
    let to = value
        .ty
        .simple_bit_vector(builder.cx, value.span)
        .forget()
        .to_unpacked(builder.cx);
    if value.ty.coalesces_to_llhd_scalar() {
        builder.build(to, LvalueKind::Transmute(value))
    } else if let Some(dim) = value.ty.outermost_dim() {
        pack_array(builder, value, dim, to)
    } else if let Some(strukt) = value.ty.get_struct() {
        pack_struct(builder, value, strukt, to)
    } else {
        bug_span!(
            value.span,
            builder.cx,
            "cannot pack a `{}` as SBVT",
            value.ty
        );
    }
}

/// Pack a struct as a simple bit vector.
fn pack_struct<'a>(
    builder: &Builder<'_, impl Context<'a>>,
    value: &'a Lvalue<'a>,
    strukt: &'a ty::StructType<'a>,
    to: &'a UnpackedType<'a>,
) -> &'a Lvalue<'a> {
    // Pack each of the fields.
    let mut packed_fields = vec![];
    for (i, field) in strukt.members.iter().enumerate() {
        let field_value = builder.build(field.ty, LvalueKind::Member { value, field: i });
        let field_value = pack_simple_bit_vector(builder, field_value);
        packed_fields.push(field_value);
    }

    // Concatenate the fields.
    builder.build(to, LvalueKind::Concat(packed_fields))
}

/// Pack an array as a simple bit vector.
fn pack_array<'a>(
    builder: &Builder<'_, impl Context<'a>>,
    value: &'a Lvalue<'a>,
    dim: ty::Dim<'a>,
    to: &'a UnpackedType<'a>,
) -> &'a Lvalue<'a> {
    // Determine the length of the array.
    let length = match dim.get_size() {
        Some(x) => x,
        None => bug_span!(
            builder.span,
            builder.cx,
            "pack array with invalid input dimension `{}`",
            dim
        ),
    };

    // Determine the element type.
    let elem_ty = value.ty.pop_dim(builder.cx).unwrap();

    // Catch the trivial case where the core type now is just an integer bit
    // vector type, which is already in the right form.
    if elem_ty.dims().next().is_none() {
        if let Some(ty::PackedCore::IntVec(_)) = elem_ty.get_packed().map(|x| &x.core) {
            return builder.build(to, LvalueKind::Transmute(value));
        }
    }

    // Cast each element.
    let mut packed_elements = vec![];
    let int_ty =
        SbvType::new(ty::Domain::TwoValued, ty::Sign::Unsigned, 32).to_unpacked(builder.cx);
    for i in (0..length).rev() {
        let rvalue_builder = lower::rvalue::Builder {
            cx: builder.cx,
            span: builder.span,
            expr: builder.expr,
            env: builder.env,
        };
        let i = rvalue_builder.build(
            int_ty,
            RvalueKind::Const(
                rvalue_builder
                    .cx
                    .intern_value(value::make_int(int_ty, i.into())),
            ),
        );
        let elem = builder.build(
            elem_ty,
            LvalueKind::Index {
                value,
                base: i,
                length: 0,
            },
        );
        let elem = pack_simple_bit_vector(builder, elem);
        packed_elements.push(elem);
    }

    // Concatenate the elements.
    builder.build(to, LvalueKind::Concat(packed_elements))
}