CIRCT 22.0.0git
Loading...
Searching...
No Matches
Expressions.cpp
Go to the documentation of this file.
1//===- Expressions.cpp - Slang expression conversion ----------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
10#include "slang/ast/EvalContext.h"
11#include "slang/ast/SystemSubroutine.h"
12#include "slang/syntax/AllSyntax.h"
13#include "llvm/ADT/ScopeExit.h"
14
15using namespace circt;
16using namespace ImportVerilog;
17using moore::Domain;
18
19/// Convert a Slang `SVInt` to a CIRCT `FVInt`.
20static FVInt convertSVIntToFVInt(const slang::SVInt &svint) {
21 if (svint.hasUnknown()) {
22 unsigned numWords = svint.getNumWords() / 2;
23 auto value = ArrayRef<uint64_t>(svint.getRawPtr(), numWords);
24 auto unknown = ArrayRef<uint64_t>(svint.getRawPtr() + numWords, numWords);
25 return FVInt(APInt(svint.getBitWidth(), value),
26 APInt(svint.getBitWidth(), unknown));
27 }
28 auto value = ArrayRef<uint64_t>(svint.getRawPtr(), svint.getNumWords());
29 return FVInt(APInt(svint.getBitWidth(), value));
30}
31
32/// Map an index into an array, with bounds `range`, to a bit offset of the
33/// underlying bit storage. This is a dynamic version of
34/// `slang::ConstantRange::translateIndex`.
35static Value getSelectIndex(Context &context, Location loc, Value index,
36 const slang::ConstantRange &range) {
37 auto &builder = context.builder;
38 auto indexType = cast<moore::UnpackedType>(index.getType());
39
40 // Compute offset first so we know if it is negative.
41 auto lo = range.lower();
42 auto hi = range.upper();
43 auto offset = range.isLittleEndian() ? lo : hi;
44
45 // If any bound is negative we need a signed index type.
46 const bool needSigned = (lo < 0) || (hi < 0);
47
48 // Magnitude over full range, not just the chosen offset.
49 const uint64_t maxAbs = std::max<uint64_t>(std::abs(lo), std::abs(hi));
50
51 // Bits needed from the range:
52 // - unsigned: ceil(log2(maxAbs + 1)) (ensure at least 1)
53 // - signed: ceil(log2(maxAbs)) + 1 sign bit (ensure at least 2 when neg)
54 unsigned want = needSigned
55 ? (llvm::Log2_64_Ceil(std::max<uint64_t>(1, maxAbs)) + 1)
56 : std::max<unsigned>(1, llvm::Log2_64_Ceil(maxAbs + 1));
57
58 // Keep at least as wide as the incoming index.
59 const unsigned bw = std::max<unsigned>(want, indexType.getBitSize().value());
60
61 auto intType =
62 moore::IntType::get(index.getContext(), bw, indexType.getDomain());
63 index = context.materializeConversion(intType, index, needSigned, loc);
64
65 if (offset == 0) {
66 if (range.isLittleEndian())
67 return index;
68 else
69 return moore::NegOp::create(builder, loc, index);
70 }
71
72 auto offsetConst =
73 moore::ConstantOp::create(builder, loc, intType, offset, needSigned);
74 if (range.isLittleEndian())
75 return moore::SubOp::create(builder, loc, index, offsetConst);
76 else
77 return moore::SubOp::create(builder, loc, offsetConst, index);
78}
79
80/// Get the currently active timescale as an integer number of femtoseconds.
82 static_assert(int(slang::TimeUnit::Seconds) == 0);
83 static_assert(int(slang::TimeUnit::Milliseconds) == 1);
84 static_assert(int(slang::TimeUnit::Microseconds) == 2);
85 static_assert(int(slang::TimeUnit::Nanoseconds) == 3);
86 static_assert(int(slang::TimeUnit::Picoseconds) == 4);
87 static_assert(int(slang::TimeUnit::Femtoseconds) == 5);
88
89 static_assert(int(slang::TimeScaleMagnitude::One) == 1);
90 static_assert(int(slang::TimeScaleMagnitude::Ten) == 10);
91 static_assert(int(slang::TimeScaleMagnitude::Hundred) == 100);
92
93 auto exp = static_cast<unsigned>(context.timeScale.base.unit);
94 assert(exp <= 5);
95 exp = 5 - exp;
96 auto scale = static_cast<uint64_t>(context.timeScale.base.magnitude);
97 while (exp-- > 0)
98 scale *= 1000;
99 return scale;
100}
101
103 const slang::ast::ClassPropertySymbol &expr) {
104 auto loc = context.convertLocation(expr.location);
105 auto builder = context.builder;
106
107 auto type = context.convertType(expr.getType());
108 // Get the scope's implicit this variable
109 mlir::Value instRef = context.getImplicitThisRef();
110 if (!instRef) {
111 mlir::emitError(loc) << "class property '" << expr.name
112 << "' referenced without an implicit 'this'";
113 return {};
114 }
115
116 auto fieldSym = mlir::FlatSymbolRefAttr::get(builder.getContext(), expr.name);
117 auto fieldTy = cast<moore::UnpackedType>(type);
118 auto fieldRefTy = moore::RefType::get(fieldTy);
119
120 moore::ClassHandleType classTy =
121 cast<moore::ClassHandleType>(instRef.getType());
122
123 auto targetClassHandle =
124 context.getAncestorClassWithProperty(classTy, expr.name, loc);
125 if (!targetClassHandle)
126 return {};
127
128 auto upcastRef = context.materializeConversion(targetClassHandle, instRef,
129 false, instRef.getLoc());
130 if (!upcastRef)
131 return {};
132
133 Value fieldRef = moore::ClassPropertyRefOp::create(builder, loc, fieldRefTy,
134 upcastRef, fieldSym);
135 return fieldRef;
136}
137
138namespace {
139/// A visitor handling expressions that can be lowered as lvalue and rvalue.
140struct ExprVisitor {
141 Context &context;
142 Location loc;
143 OpBuilder &builder;
144 bool isLvalue;
145
146 ExprVisitor(Context &context, Location loc, bool isLvalue)
147 : context(context), loc(loc), builder(context.builder),
148 isLvalue(isLvalue) {}
149
150 /// Convert an expression either as an lvalue or rvalue, depending on whether
151 /// this is an lvalue or rvalue visitor. This is useful for projections such
152 /// as `a[i]`, where you want `a` as an lvalue if you want `a[i]` as an
153 /// lvalue, or `a` as an rvalue if you want `a[i]` as an rvalue.
154 Value convertLvalueOrRvalueExpression(const slang::ast::Expression &expr) {
155 if (isLvalue)
156 return context.convertLvalueExpression(expr);
157 return context.convertRvalueExpression(expr);
158 }
159
160 /// Handle single bit selections.
161 Value visit(const slang::ast::ElementSelectExpression &expr) {
162 auto type = context.convertType(*expr.type);
163 auto value = convertLvalueOrRvalueExpression(expr.value());
164 if (!type || !value)
165 return {};
166
167 // We only support indexing into a few select types for now.
168 auto derefType = value.getType();
169 if (isLvalue)
170 derefType = cast<moore::RefType>(derefType).getNestedType();
171 if (!isa<moore::IntType, moore::ArrayType, moore::UnpackedArrayType>(
172 derefType)) {
173 mlir::emitError(loc) << "unsupported expression: element select into "
174 << expr.value().type->toString() << "\n";
175 return {};
176 }
177
178 auto resultType =
179 isLvalue ? moore::RefType::get(cast<moore::UnpackedType>(type)) : type;
180 auto range = expr.value().type->getFixedRange();
181 if (auto *constValue = expr.selector().getConstant();
182 constValue && constValue->isInteger()) {
183 assert(!constValue->hasUnknown());
184 assert(constValue->size() <= 32);
185
186 auto lowBit = constValue->integer().as<uint32_t>().value();
187 if (isLvalue)
188 return moore::ExtractRefOp::create(builder, loc, resultType, value,
189 range.translateIndex(lowBit));
190 else
191 return moore::ExtractOp::create(builder, loc, resultType, value,
192 range.translateIndex(lowBit));
193 }
194
195 auto lowBit = context.convertRvalueExpression(expr.selector());
196 if (!lowBit)
197 return {};
198 lowBit = getSelectIndex(context, loc, lowBit, range);
199 if (isLvalue)
200 return moore::DynExtractRefOp::create(builder, loc, resultType, value,
201 lowBit);
202 else
203 return moore::DynExtractOp::create(builder, loc, resultType, value,
204 lowBit);
205 }
206
207 /// Handle range bit selections.
208 Value visit(const slang::ast::RangeSelectExpression &expr) {
209 auto type = context.convertType(*expr.type);
210 auto value = convertLvalueOrRvalueExpression(expr.value());
211 if (!type || !value)
212 return {};
213
214 std::optional<int32_t> constLeft;
215 std::optional<int32_t> constRight;
216 if (auto *constant = expr.left().getConstant())
217 constLeft = constant->integer().as<int32_t>();
218 if (auto *constant = expr.right().getConstant())
219 constRight = constant->integer().as<int32_t>();
220
221 // We currently require the right-hand-side of the range to be constant.
222 // This catches things like `[42:$]` which we don't support at the moment.
223 if (!constRight) {
224 mlir::emitError(loc)
225 << "unsupported expression: range select with non-constant bounds";
226 return {};
227 }
228
229 // We need to determine the right bound of the range. This is the address of
230 // the least significant bit of the underlying bit storage, which is the
231 // offset we want to pass to the extract op.
232 //
233 // The arrays [6:2] and [2:6] both have 5 bits worth of underlying storage.
234 // The left and right bound of the range only determine the addressing
235 // scheme of the storage bits:
236 //
237 // Storage bits: 4 3 2 1 0 <-- extract op works on storage bits
238 // [6:2] indices: 6 5 4 3 2 ("little endian" in Slang terms)
239 // [2:6] indices: 2 3 4 5 6 ("big endian" in Slang terms)
240 //
241 // Before we can extract, we need to map the range select left and right
242 // bounds from these indices to actual bit positions in the storage.
243
244 Value offsetDyn;
245 int32_t offsetConst = 0;
246 auto range = expr.value().type->getFixedRange();
247
248 using slang::ast::RangeSelectionKind;
249 if (expr.getSelectionKind() == RangeSelectionKind::Simple) {
250 // For a constant range [a:b], we want the offset of the lowest storage
251 // bit from which we are starting the extract. For a range [5:3] this is
252 // bit index 3; for a range [3:5] this is bit index 5. Both of these are
253 // later translated map to bit offset 1 (see bit indices above).
254 assert(constRight && "constness checked in slang");
255 offsetConst = *constRight;
256 } else {
257 // For an indexed range [a+:b] or [a-:b], determining the lowest storage
258 // bit is a bit more complicated. We start out with the base index `a`.
259 // This is the lower *index* of the range, but not the lower *storage bit
260 // position*.
261 //
262 // The range [a+:b] expands to [a+b-1:a] for a [6:2] range, or [a:a+b-1]
263 // for a [2:6] range. The range [a-:b] expands to [a:a-b+1] for a [6:2]
264 // range, or [a-b+1:a] for a [2:6] range.
265 if (constLeft) {
266 offsetConst = *constLeft;
267 } else {
268 offsetDyn = context.convertRvalueExpression(expr.left());
269 if (!offsetDyn)
270 return {};
271 }
272
273 // For a [a-:b] select on [2:6] and a [a+:b] select on [6:2], the range
274 // expands to [a-b+1:a] and [a+b-1:a]. In this case, the right bound which
275 // corresponds to the lower *storage bit offset*, is just `a` and there's
276 // no further tweaking to do.
277 int32_t offsetAdd = 0;
278
279 // For a [a-:b] select on [6:2], the range expands to [a:a-b+1]. We
280 // therefore have to take the `a` from above and adjust it by `-b+1` to
281 // arrive at the right bound.
282 if (expr.getSelectionKind() == RangeSelectionKind::IndexedDown &&
283 range.isLittleEndian()) {
284 assert(constRight && "constness checked in slang");
285 offsetAdd = 1 - *constRight;
286 }
287
288 // For a [a+:b] select on [2:6], the range expands to [a:a+b-1]. We
289 // therefore have to take the `a` from above and adjust it by `+b-1` to
290 // arrive at the right bound.
291 if (expr.getSelectionKind() == RangeSelectionKind::IndexedUp &&
292 !range.isLittleEndian()) {
293 assert(constRight && "constness checked in slang");
294 offsetAdd = *constRight - 1;
295 }
296
297 // Adjust the offset such that it matches the right bound of the range.
298 if (offsetAdd != 0) {
299 if (offsetDyn)
300 offsetDyn = moore::AddOp::create(
301 builder, loc, offsetDyn,
302 moore::ConstantOp::create(
303 builder, loc, cast<moore::IntType>(offsetDyn.getType()),
304 offsetAdd,
305 /*isSigned=*/offsetAdd < 0));
306 else
307 offsetConst += offsetAdd;
308 }
309 }
310
311 // Create a dynamic or constant extract. Use `getSelectIndex` and
312 // `ConstantRange::translateIndex` to map from the bit indices provided by
313 // the user to the actual storage bit position. Since `offset*` corresponds
314 // to the right bound of the range, which provides the index of the least
315 // significant selected storage bit, we get the bit offset at which we want
316 // to start extracting.
317 auto resultType =
318 isLvalue ? moore::RefType::get(cast<moore::UnpackedType>(type)) : type;
319
320 if (offsetDyn) {
321 offsetDyn = getSelectIndex(context, loc, offsetDyn, range);
322 if (isLvalue) {
323 return moore::DynExtractRefOp::create(builder, loc, resultType, value,
324 offsetDyn);
325 } else {
326 return moore::DynExtractOp::create(builder, loc, resultType, value,
327 offsetDyn);
328 }
329 } else {
330 offsetConst = range.translateIndex(offsetConst);
331 if (isLvalue) {
332 return moore::ExtractRefOp::create(builder, loc, resultType, value,
333 offsetConst);
334 } else {
335 return moore::ExtractOp::create(builder, loc, resultType, value,
336 offsetConst);
337 }
338 }
339 }
340
341 /// Handle concatenations.
342 Value visit(const slang::ast::ConcatenationExpression &expr) {
343 SmallVector<Value> operands;
344 for (auto *operand : expr.operands()) {
345 // Handle empty replications like `{0{...}}` which may occur within
346 // concatenations. Slang assigns them a `void` type which we can check for
347 // here.
348 if (operand->type->isVoid())
349 continue;
350 auto value = convertLvalueOrRvalueExpression(*operand);
351 if (!value)
352 return {};
353 if (!isLvalue)
354 value = context.convertToSimpleBitVector(value);
355 if (!value)
356 return {};
357 operands.push_back(value);
358 }
359 if (isLvalue)
360 return moore::ConcatRefOp::create(builder, loc, operands);
361 else
362 return moore::ConcatOp::create(builder, loc, operands);
363 }
364
365 /// Handle member accesses.
366 Value visit(const slang::ast::MemberAccessExpression &expr) {
367 auto type = context.convertType(*expr.type);
368 if (!type)
369 return {};
370
371 auto *valueType = expr.value().type.get();
372 auto memberName = builder.getStringAttr(expr.member.name);
373
374 // Handle structs.
375 if (valueType->isStruct()) {
376 auto resultType =
377 isLvalue ? moore::RefType::get(cast<moore::UnpackedType>(type))
378 : type;
379 auto value = convertLvalueOrRvalueExpression(expr.value());
380 if (!value)
381 return {};
382
383 if (isLvalue)
384 return moore::StructExtractRefOp::create(builder, loc, resultType,
385 memberName, value);
386 return moore::StructExtractOp::create(builder, loc, resultType,
387 memberName, value);
388 }
389
390 // Handle unions.
391 if (valueType->isPackedUnion() || valueType->isUnpackedUnion()) {
392 auto resultType =
393 isLvalue ? moore::RefType::get(cast<moore::UnpackedType>(type))
394 : type;
395 auto value = convertLvalueOrRvalueExpression(expr.value());
396 if (!value)
397 return {};
398
399 if (isLvalue)
400 return moore::UnionExtractRefOp::create(builder, loc, resultType,
401 memberName, value);
402 return moore::UnionExtractOp::create(builder, loc, type, memberName,
403 value);
404 }
405
406 // Handle classes.
407 if (valueType->isClass()) {
408 auto valTy = context.convertType(*valueType);
409 if (!valTy)
410 return {};
411 auto targetTy = cast<moore::ClassHandleType>(valTy);
412
413 // We need to pick the closest ancestor that declares a property with the
414 // relevant name. System Verilog explicitly enforces lexical shadowing, as
415 // shown in IEEE 1800-2023 Section 8.14 "Overridden members".
416 auto upcastTargetTy =
417 context.getAncestorClassWithProperty(targetTy, expr.member.name, loc);
418 if (!upcastTargetTy)
419 return {};
420
421 // Convert the class handle to the required target type for property
422 // shadowing purposes.
423 Value baseVal =
424 context.convertRvalueExpression(expr.value(), upcastTargetTy);
425 if (!baseVal)
426 return {};
427
428 // @field and result type !moore.ref<T>.
429 auto fieldSym =
430 mlir::FlatSymbolRefAttr::get(builder.getContext(), expr.member.name);
431 auto fieldRefTy = moore::RefType::get(cast<moore::UnpackedType>(type));
432
433 // Produce a ref to the class property from the (possibly upcast) handle.
434 Value fieldRef = moore::ClassPropertyRefOp::create(
435 builder, loc, fieldRefTy, baseVal, fieldSym);
436
437 // If we need an RValue, read the reference, otherwise return
438 return isLvalue ? fieldRef
439 : moore::ReadOp::create(builder, loc, fieldRef);
440 }
441
442 mlir::emitError(loc, "expression of type ")
443 << valueType->toString() << " has no member fields";
444 return {};
445 }
446};
447} // namespace
448
449//===----------------------------------------------------------------------===//
450// Rvalue Conversion
451//===----------------------------------------------------------------------===//
452
453// NOLINTBEGIN(misc-no-recursion)
454namespace {
455struct RvalueExprVisitor : public ExprVisitor {
456 RvalueExprVisitor(Context &context, Location loc)
457 : ExprVisitor(context, loc, /*isLvalue=*/false) {}
458 using ExprVisitor::visit;
459
460 // Handle references to the left-hand side of a parent assignment.
461 Value visit(const slang::ast::LValueReferenceExpression &expr) {
462 assert(!context.lvalueStack.empty() && "parent assignments push lvalue");
463 auto lvalue = context.lvalueStack.back();
464 return moore::ReadOp::create(builder, loc, lvalue);
465 }
466
467 // Handle named values, such as references to declared variables.
468 Value visit(const slang::ast::NamedValueExpression &expr) {
469 // Handle local variables.
470 if (auto value = context.valueSymbols.lookup(&expr.symbol)) {
471 if (isa<moore::RefType>(value.getType())) {
472 auto readOp = moore::ReadOp::create(builder, loc, value);
473 if (context.rvalueReadCallback)
474 context.rvalueReadCallback(readOp);
475 value = readOp.getResult();
476 }
477 return value;
478 }
479
480 // Handle global variables.
481 if (auto globalOp = context.globalVariables.lookup(&expr.symbol)) {
482 auto value = moore::GetGlobalVariableOp::create(builder, loc, globalOp);
483 return moore::ReadOp::create(builder, loc, value);
484 }
485
486 // We're reading a class property.
487 if (auto *const property =
488 expr.symbol.as_if<slang::ast::ClassPropertySymbol>()) {
489 auto fieldRef = visitClassProperty(context, *property);
490 return moore::ReadOp::create(builder, loc, fieldRef).getResult();
491 }
492
493 // Try to materialize constant values directly.
494 auto constant = context.evaluateConstant(expr);
495 if (auto value = context.materializeConstant(constant, *expr.type, loc))
496 return value;
497
498 // Otherwise some other part of ImportVerilog should have added an MLIR
499 // value for this expression's symbol to the `context.valueSymbols` table.
500 auto d = mlir::emitError(loc, "unknown name `") << expr.symbol.name << "`";
501 d.attachNote(context.convertLocation(expr.symbol.location))
502 << "no rvalue generated for " << slang::ast::toString(expr.symbol.kind);
503 return {};
504 }
505
506 // Handle hierarchical values, such as `x = Top.sub.var`.
507 Value visit(const slang::ast::HierarchicalValueExpression &expr) {
508 auto hierLoc = context.convertLocation(expr.symbol.location);
509 if (auto value = context.valueSymbols.lookup(&expr.symbol)) {
510 if (isa<moore::RefType>(value.getType())) {
511 auto readOp = moore::ReadOp::create(builder, hierLoc, value);
512 if (context.rvalueReadCallback)
513 context.rvalueReadCallback(readOp);
514 value = readOp.getResult();
515 }
516 return value;
517 }
518
519 // Emit an error for those hierarchical values not recorded in the
520 // `valueSymbols`.
521 auto d = mlir::emitError(loc, "unknown hierarchical name `")
522 << expr.symbol.name << "`";
523 d.attachNote(hierLoc) << "no rvalue generated for "
524 << slang::ast::toString(expr.symbol.kind);
525 return {};
526 }
527
528 // Handle type conversions (explicit and implicit).
529 Value visit(const slang::ast::ConversionExpression &expr) {
530 auto type = context.convertType(*expr.type);
531 if (!type)
532 return {};
533 return context.convertRvalueExpression(expr.operand(), type);
534 }
535
536 // Handle blocking and non-blocking assignments.
537 Value visit(const slang::ast::AssignmentExpression &expr) {
538 auto lhs = context.convertLvalueExpression(expr.left());
539 if (!lhs)
540 return {};
541
542 // Determine the right-hand side value of the assignment.
543 context.lvalueStack.push_back(lhs);
544 auto rhs = context.convertRvalueExpression(
545 expr.right(), cast<moore::RefType>(lhs.getType()).getNestedType());
546 context.lvalueStack.pop_back();
547 if (!rhs)
548 return {};
549
550 // If this is a blocking assignment, we can insert the delay/wait ops of the
551 // optional timing control directly in between computing the RHS and
552 // executing the assignment.
553 if (!expr.isNonBlocking()) {
554 if (expr.timingControl)
555 if (failed(context.convertTimingControl(*expr.timingControl)))
556 return {};
557 auto assignOp = moore::BlockingAssignOp::create(builder, loc, lhs, rhs);
558 if (context.variableAssignCallback)
559 context.variableAssignCallback(assignOp);
560 return rhs;
561 }
562
563 // For non-blocking assignments, we only support time delays for now.
564 if (expr.timingControl) {
565 // Handle regular time delays.
566 if (auto *ctrl = expr.timingControl->as_if<slang::ast::DelayControl>()) {
567 auto delay = context.convertRvalueExpression(
568 ctrl->expr, moore::TimeType::get(builder.getContext()));
569 if (!delay)
570 return {};
571 auto assignOp = moore::DelayedNonBlockingAssignOp::create(
572 builder, loc, lhs, rhs, delay);
573 if (context.variableAssignCallback)
574 context.variableAssignCallback(assignOp);
575 return rhs;
576 }
577
578 // All other timing controls are not supported.
579 auto loc = context.convertLocation(expr.timingControl->sourceRange);
580 mlir::emitError(loc)
581 << "unsupported non-blocking assignment timing control: "
582 << slang::ast::toString(expr.timingControl->kind);
583 return {};
584 }
585 auto assignOp = moore::NonBlockingAssignOp::create(builder, loc, lhs, rhs);
586 if (context.variableAssignCallback)
587 context.variableAssignCallback(assignOp);
588 return rhs;
589 }
590
591 // Helper function to convert an argument to a simple bit vector type, pass it
592 // to a reduction op, and optionally invert the result.
593 template <class ConcreteOp>
594 Value createReduction(Value arg, bool invert) {
595 arg = context.convertToSimpleBitVector(arg);
596 if (!arg)
597 return {};
598 Value result = ConcreteOp::create(builder, loc, arg);
599 if (invert)
600 result = moore::NotOp::create(builder, loc, result);
601 return result;
602 }
603
604 // Helper function to create pre and post increments and decrements.
605 Value createIncrement(Value arg, bool isInc, bool isPost) {
606 auto preValue = moore::ReadOp::create(builder, loc, arg);
607 Value postValue;
608 // Catch the special case where a signed 1 bit value (i1) is incremented,
609 // as +1 can not be expressed as a signed 1 bit value. For any 1-bit number
610 // negating is equivalent to incrementing.
611 if (moore::isIntType(preValue.getType(), 1)) {
612 postValue = moore::NotOp::create(builder, loc, preValue).getResult();
613 } else {
614
615 auto one = moore::ConstantOp::create(
616 builder, loc, cast<moore::IntType>(preValue.getType()), 1);
617 postValue =
618 isInc ? moore::AddOp::create(builder, loc, preValue, one).getResult()
619 : moore::SubOp::create(builder, loc, preValue, one).getResult();
620 auto assignOp =
621 moore::BlockingAssignOp::create(builder, loc, arg, postValue);
622 if (context.variableAssignCallback)
623 context.variableAssignCallback(assignOp);
624 }
625
626 if (isPost)
627 return preValue;
628 return postValue;
629 }
630
631 // Helper function to create pre and post increments and decrements.
632 Value createRealIncrement(Value arg, bool isInc, bool isPost) {
633 auto preValue = moore::ReadOp::create(builder, loc, arg);
634 Value postValue;
635
636 auto ty = preValue.getType();
637 moore::RealType realTy = llvm::dyn_cast<moore::RealType>(ty);
638 if (!realTy)
639 return {};
640
641 FloatAttr oneAttr;
642 if (realTy.getWidth() == moore::RealWidth::f32) {
643 oneAttr = builder.getFloatAttr(builder.getF32Type(), 1.0);
644 } else if (realTy.getWidth() == moore::RealWidth::f64) {
645 oneAttr = builder.getFloatAttr(builder.getF64Type(), 1.0);
646 } else {
647 mlir::emitError(loc) << "cannot construct increment for " << realTy;
648 return {};
649 }
650 auto one = moore::ConstantRealOp::create(builder, loc, oneAttr);
651
652 postValue =
653 isInc
654 ? moore::AddRealOp::create(builder, loc, preValue, one).getResult()
655 : moore::SubRealOp::create(builder, loc, preValue, one).getResult();
656 auto assignOp =
657 moore::BlockingAssignOp::create(builder, loc, arg, postValue);
658
659 if (context.variableAssignCallback)
660 context.variableAssignCallback(assignOp);
661
662 if (isPost)
663 return preValue;
664 return postValue;
665 }
666
667 Value visitRealUOp(const slang::ast::UnaryExpression &expr) {
668 Type opFTy = context.convertType(*expr.operand().type);
669
670 using slang::ast::UnaryOperator;
671 Value arg;
672 if (expr.op == UnaryOperator::Preincrement ||
673 expr.op == UnaryOperator::Predecrement ||
674 expr.op == UnaryOperator::Postincrement ||
675 expr.op == UnaryOperator::Postdecrement)
676 arg = context.convertLvalueExpression(expr.operand());
677 else
678 arg = context.convertRvalueExpression(expr.operand(), opFTy);
679 if (!arg)
680 return {};
681
682 switch (expr.op) {
683 // `+a` is simply `a`
684 case UnaryOperator::Plus:
685 return arg;
686 case UnaryOperator::Minus:
687 return moore::NegRealOp::create(builder, loc, arg);
688
689 case UnaryOperator::Preincrement:
690 return createRealIncrement(arg, true, false);
691 case UnaryOperator::Predecrement:
692 return createRealIncrement(arg, false, false);
693 case UnaryOperator::Postincrement:
694 return createRealIncrement(arg, true, true);
695 case UnaryOperator::Postdecrement:
696 return createRealIncrement(arg, false, true);
697
698 case UnaryOperator::LogicalNot:
699 arg = context.convertToBool(arg);
700 if (!arg)
701 return {};
702 return moore::NotOp::create(builder, loc, arg);
703
704 default:
705 mlir::emitError(loc) << "Unary operator " << slang::ast::toString(expr.op)
706 << " not supported with real values!\n";
707 return {};
708 }
709 }
710
711 // Handle unary operators.
712 Value visit(const slang::ast::UnaryExpression &expr) {
713 // First check whether we need real or integral BOps
714 const auto *floatType =
715 expr.operand().type->as_if<slang::ast::FloatingType>();
716 // If op is real-typed, treat as real BOp.
717 if (floatType)
718 return visitRealUOp(expr);
719
720 using slang::ast::UnaryOperator;
721 Value arg;
722 if (expr.op == UnaryOperator::Preincrement ||
723 expr.op == UnaryOperator::Predecrement ||
724 expr.op == UnaryOperator::Postincrement ||
725 expr.op == UnaryOperator::Postdecrement)
726 arg = context.convertLvalueExpression(expr.operand());
727 else
728 arg = context.convertRvalueExpression(expr.operand());
729 if (!arg)
730 return {};
731
732 switch (expr.op) {
733 // `+a` is simply `a`, but converted to a simple bit vector type since
734 // this is technically an arithmetic operation.
735 case UnaryOperator::Plus:
736 return context.convertToSimpleBitVector(arg);
737
738 case UnaryOperator::Minus:
739 arg = context.convertToSimpleBitVector(arg);
740 if (!arg)
741 return {};
742 return moore::NegOp::create(builder, loc, arg);
743
744 case UnaryOperator::BitwiseNot:
745 arg = context.convertToSimpleBitVector(arg);
746 if (!arg)
747 return {};
748 return moore::NotOp::create(builder, loc, arg);
749
750 case UnaryOperator::BitwiseAnd:
751 return createReduction<moore::ReduceAndOp>(arg, false);
752 case UnaryOperator::BitwiseOr:
753 return createReduction<moore::ReduceOrOp>(arg, false);
754 case UnaryOperator::BitwiseXor:
755 return createReduction<moore::ReduceXorOp>(arg, false);
756 case UnaryOperator::BitwiseNand:
757 return createReduction<moore::ReduceAndOp>(arg, true);
758 case UnaryOperator::BitwiseNor:
759 return createReduction<moore::ReduceOrOp>(arg, true);
760 case UnaryOperator::BitwiseXnor:
761 return createReduction<moore::ReduceXorOp>(arg, true);
762
763 case UnaryOperator::LogicalNot:
764 arg = context.convertToBool(arg);
765 if (!arg)
766 return {};
767 return moore::NotOp::create(builder, loc, arg);
768
769 case UnaryOperator::Preincrement:
770 return createIncrement(arg, true, false);
771 case UnaryOperator::Predecrement:
772 return createIncrement(arg, false, false);
773 case UnaryOperator::Postincrement:
774 return createIncrement(arg, true, true);
775 case UnaryOperator::Postdecrement:
776 return createIncrement(arg, false, true);
777 }
778
779 mlir::emitError(loc, "unsupported unary operator");
780 return {};
781 }
782
783 /// Handles logical operators (§11.4.7), assuming lhs/rhs are rvalues already.
784 Value buildLogicalBOp(slang::ast::BinaryOperator op, Value lhs, Value rhs,
785 std::optional<Domain> domain = std::nullopt) {
786 using slang::ast::BinaryOperator;
787 // TODO: These should short-circuit; RHS should be in a separate block.
788
789 if (domain) {
790 lhs = context.convertToBool(lhs, domain.value());
791 rhs = context.convertToBool(rhs, domain.value());
792 } else {
793 lhs = context.convertToBool(lhs);
794 rhs = context.convertToBool(rhs);
795 }
796
797 if (!lhs || !rhs)
798 return {};
799
800 switch (op) {
801 case BinaryOperator::LogicalAnd:
802 return moore::AndOp::create(builder, loc, lhs, rhs);
803
804 case BinaryOperator::LogicalOr:
805 return moore::OrOp::create(builder, loc, lhs, rhs);
806
807 case BinaryOperator::LogicalImplication: {
808 // (lhs -> rhs) == (!lhs || rhs)
809 auto notLHS = moore::NotOp::create(builder, loc, lhs);
810 return moore::OrOp::create(builder, loc, notLHS, rhs);
811 }
812
813 case BinaryOperator::LogicalEquivalence: {
814 // (lhs <-> rhs) == (lhs && rhs) || (!lhs && !rhs)
815 auto notLHS = moore::NotOp::create(builder, loc, lhs);
816 auto notRHS = moore::NotOp::create(builder, loc, rhs);
817 auto both = moore::AndOp::create(builder, loc, lhs, rhs);
818 auto notBoth = moore::AndOp::create(builder, loc, notLHS, notRHS);
819 return moore::OrOp::create(builder, loc, both, notBoth);
820 }
821
822 default:
823 llvm_unreachable("not a logical BinaryOperator");
824 }
825 }
826
827 Value visitRealBOp(const slang::ast::BinaryExpression &expr) {
828 // Convert operands to the chosen target type.
829 auto lhs = context.convertRvalueExpression(expr.left());
830 if (!lhs)
831 return {};
832 auto rhs = context.convertRvalueExpression(expr.right());
833 if (!rhs)
834 return {};
835
836 using slang::ast::BinaryOperator;
837 switch (expr.op) {
838 case BinaryOperator::Add:
839 return moore::AddRealOp::create(builder, loc, lhs, rhs);
840 case BinaryOperator::Subtract:
841 return moore::SubRealOp::create(builder, loc, lhs, rhs);
842 case BinaryOperator::Multiply:
843 return moore::MulRealOp::create(builder, loc, lhs, rhs);
844 case BinaryOperator::Divide:
845 return moore::DivRealOp::create(builder, loc, lhs, rhs);
846 case BinaryOperator::Power:
847 return moore::PowRealOp::create(builder, loc, lhs, rhs);
848
849 case BinaryOperator::Equality:
850 return moore::EqRealOp::create(builder, loc, lhs, rhs);
851 case BinaryOperator::Inequality:
852 return moore::NeRealOp::create(builder, loc, lhs, rhs);
853
854 case BinaryOperator::GreaterThan:
855 return moore::FgtOp::create(builder, loc, lhs, rhs);
856 case BinaryOperator::LessThan:
857 return moore::FltOp::create(builder, loc, lhs, rhs);
858 case BinaryOperator::GreaterThanEqual:
859 return moore::FgeOp::create(builder, loc, lhs, rhs);
860 case BinaryOperator::LessThanEqual:
861 return moore::FleOp::create(builder, loc, lhs, rhs);
862
863 case BinaryOperator::LogicalAnd:
864 case BinaryOperator::LogicalOr:
865 case BinaryOperator::LogicalImplication:
866 case BinaryOperator::LogicalEquivalence:
867 return buildLogicalBOp(expr.op, lhs, rhs);
868
869 default:
870 mlir::emitError(loc) << "Binary operator "
871 << slang::ast::toString(expr.op)
872 << " not supported with real valued operands!\n";
873 return {};
874 }
875 }
876
877 // Helper function to convert two arguments to a simple bit vector type and
878 // pass them into a binary op.
879 template <class ConcreteOp>
880 Value createBinary(Value lhs, Value rhs) {
881 lhs = context.convertToSimpleBitVector(lhs);
882 if (!lhs)
883 return {};
884 rhs = context.convertToSimpleBitVector(rhs);
885 if (!rhs)
886 return {};
887 return ConcreteOp::create(builder, loc, lhs, rhs);
888 }
889
890 // Handle binary operators.
891 Value visit(const slang::ast::BinaryExpression &expr) {
892 // First check whether we need real or integral BOps
893 const auto *rhsFloatType =
894 expr.right().type->as_if<slang::ast::FloatingType>();
895 const auto *lhsFloatType =
896 expr.left().type->as_if<slang::ast::FloatingType>();
897
898 // If either arg is real-typed, treat as real BOp.
899 if (rhsFloatType || lhsFloatType)
900 return visitRealBOp(expr);
901
902 auto lhs = context.convertRvalueExpression(expr.left());
903 if (!lhs)
904 return {};
905 auto rhs = context.convertRvalueExpression(expr.right());
906 if (!rhs)
907 return {};
908
909 // Determine the domain of the result.
910 Domain domain = Domain::TwoValued;
911 if (expr.type->isFourState() || expr.left().type->isFourState() ||
912 expr.right().type->isFourState())
913 domain = Domain::FourValued;
914
915 using slang::ast::BinaryOperator;
916 switch (expr.op) {
917 case BinaryOperator::Add:
918 return createBinary<moore::AddOp>(lhs, rhs);
919 case BinaryOperator::Subtract:
920 return createBinary<moore::SubOp>(lhs, rhs);
921 case BinaryOperator::Multiply:
922 return createBinary<moore::MulOp>(lhs, rhs);
923 case BinaryOperator::Divide:
924 if (expr.type->isSigned())
925 return createBinary<moore::DivSOp>(lhs, rhs);
926 else
927 return createBinary<moore::DivUOp>(lhs, rhs);
928 case BinaryOperator::Mod:
929 if (expr.type->isSigned())
930 return createBinary<moore::ModSOp>(lhs, rhs);
931 else
932 return createBinary<moore::ModUOp>(lhs, rhs);
933 case BinaryOperator::Power: {
934 // Slang casts the LHS and result of the `**` operator to a four-valued
935 // type, since the operator can return X even for two-valued inputs. To
936 // maintain uniform types across operands and results, cast the RHS to
937 // that four-valued type as well.
938 auto rhsCast = context.materializeConversion(
939 lhs.getType(), rhs, expr.right().type->isSigned(), rhs.getLoc());
940 if (expr.type->isSigned())
941 return createBinary<moore::PowSOp>(lhs, rhsCast);
942 else
943 return createBinary<moore::PowUOp>(lhs, rhsCast);
944 }
945
946 case BinaryOperator::BinaryAnd:
947 return createBinary<moore::AndOp>(lhs, rhs);
948 case BinaryOperator::BinaryOr:
949 return createBinary<moore::OrOp>(lhs, rhs);
950 case BinaryOperator::BinaryXor:
951 return createBinary<moore::XorOp>(lhs, rhs);
952 case BinaryOperator::BinaryXnor: {
953 auto result = createBinary<moore::XorOp>(lhs, rhs);
954 if (!result)
955 return {};
956 return moore::NotOp::create(builder, loc, result);
957 }
958
959 case BinaryOperator::Equality:
960 if (isa<moore::UnpackedArrayType>(lhs.getType()))
961 return moore::UArrayCmpOp::create(
962 builder, loc, moore::UArrayCmpPredicate::eq, lhs, rhs);
963 else if (isa<moore::StringType>(lhs.getType()))
964 return moore::StringCmpOp::create(
965 builder, loc, moore::StringCmpPredicate::eq, lhs, rhs);
966 else
967 return createBinary<moore::EqOp>(lhs, rhs);
968 case BinaryOperator::Inequality:
969 if (isa<moore::UnpackedArrayType>(lhs.getType()))
970 return moore::UArrayCmpOp::create(
971 builder, loc, moore::UArrayCmpPredicate::ne, lhs, rhs);
972 else if (isa<moore::StringType>(lhs.getType()))
973 return moore::StringCmpOp::create(
974 builder, loc, moore::StringCmpPredicate::ne, lhs, rhs);
975 else
976 return createBinary<moore::NeOp>(lhs, rhs);
977 case BinaryOperator::CaseEquality:
978 return createBinary<moore::CaseEqOp>(lhs, rhs);
979 case BinaryOperator::CaseInequality:
980 return createBinary<moore::CaseNeOp>(lhs, rhs);
981 case BinaryOperator::WildcardEquality:
982 return createBinary<moore::WildcardEqOp>(lhs, rhs);
983 case BinaryOperator::WildcardInequality:
984 return createBinary<moore::WildcardNeOp>(lhs, rhs);
985
986 case BinaryOperator::GreaterThanEqual:
987 if (expr.left().type->isSigned())
988 return createBinary<moore::SgeOp>(lhs, rhs);
989 else if (isa<moore::StringType>(lhs.getType()))
990 return moore::StringCmpOp::create(
991 builder, loc, moore::StringCmpPredicate::ge, lhs, rhs);
992 else
993 return createBinary<moore::UgeOp>(lhs, rhs);
994 case BinaryOperator::GreaterThan:
995 if (expr.left().type->isSigned())
996 return createBinary<moore::SgtOp>(lhs, rhs);
997 else if (isa<moore::StringType>(lhs.getType()))
998 return moore::StringCmpOp::create(
999 builder, loc, moore::StringCmpPredicate::gt, lhs, rhs);
1000 else
1001 return createBinary<moore::UgtOp>(lhs, rhs);
1002 case BinaryOperator::LessThanEqual:
1003 if (expr.left().type->isSigned())
1004 return createBinary<moore::SleOp>(lhs, rhs);
1005 else if (isa<moore::StringType>(lhs.getType()))
1006 return moore::StringCmpOp::create(
1007 builder, loc, moore::StringCmpPredicate::le, lhs, rhs);
1008 else
1009 return createBinary<moore::UleOp>(lhs, rhs);
1010 case BinaryOperator::LessThan:
1011 if (expr.left().type->isSigned())
1012 return createBinary<moore::SltOp>(lhs, rhs);
1013 else if (isa<moore::StringType>(lhs.getType()))
1014 return moore::StringCmpOp::create(
1015 builder, loc, moore::StringCmpPredicate::lt, lhs, rhs);
1016 else
1017 return createBinary<moore::UltOp>(lhs, rhs);
1018
1019 case BinaryOperator::LogicalAnd:
1020 case BinaryOperator::LogicalOr:
1021 case BinaryOperator::LogicalImplication:
1022 case BinaryOperator::LogicalEquivalence:
1023 return buildLogicalBOp(expr.op, lhs, rhs, domain);
1024
1025 case BinaryOperator::LogicalShiftLeft:
1026 return createBinary<moore::ShlOp>(lhs, rhs);
1027 case BinaryOperator::LogicalShiftRight:
1028 return createBinary<moore::ShrOp>(lhs, rhs);
1029 case BinaryOperator::ArithmeticShiftLeft:
1030 return createBinary<moore::ShlOp>(lhs, rhs);
1031 case BinaryOperator::ArithmeticShiftRight: {
1032 // The `>>>` operator is an arithmetic right shift if the LHS operand is
1033 // signed, or a logical right shift if the operand is unsigned.
1034 lhs = context.convertToSimpleBitVector(lhs);
1035 rhs = context.convertToSimpleBitVector(rhs);
1036 if (!lhs || !rhs)
1037 return {};
1038 if (expr.type->isSigned())
1039 return moore::AShrOp::create(builder, loc, lhs, rhs);
1040 return moore::ShrOp::create(builder, loc, lhs, rhs);
1041 }
1042 }
1043
1044 mlir::emitError(loc, "unsupported binary operator");
1045 return {};
1046 }
1047
1048 // Handle `'0`, `'1`, `'x`, and `'z` literals.
1049 Value visit(const slang::ast::UnbasedUnsizedIntegerLiteral &expr) {
1050 return context.materializeSVInt(expr.getValue(), *expr.type, loc);
1051 }
1052
1053 // Handle integer literals.
1054 Value visit(const slang::ast::IntegerLiteral &expr) {
1055 return context.materializeSVInt(expr.getValue(), *expr.type, loc);
1056 }
1057
1058 // Handle time literals.
1059 Value visit(const slang::ast::TimeLiteral &expr) {
1060 // The time literal is expressed in the current time scale. Determine the
1061 // conversion factor to convert the literal from the current time scale into
1062 // femtoseconds, and round the scaled value to femtoseconds.
1063 double scale = getTimeScaleInFemtoseconds(context);
1064 double value = std::round(expr.getValue() * scale);
1065 assert(value >= 0.0);
1066
1067 // Check that the value does not exceed what we can represent in the IR.
1068 // Casting the maximum uint64 value to double changes its value from
1069 // 18446744073709551615 to 18446744073709551616, which makes the comparison
1070 // overestimate the largest number we can represent. To avoid this, round
1071 // the maximum value down to the closest number that only has the front 53
1072 // bits set. This matches the mantissa of a double, plus the implicit
1073 // leading 1, ensuring that we can accurately represent the limit.
1074 static constexpr uint64_t limit =
1075 (std::numeric_limits<uint64_t>::max() >> 11) << 11;
1076 if (value > limit) {
1077 mlir::emitError(loc) << "time value is larger than " << limit << " fs";
1078 return {};
1079 }
1080
1081 return moore::ConstantTimeOp::create(builder, loc,
1082 static_cast<uint64_t>(value));
1083 }
1084
1085 // Handle replications.
1086 Value visit(const slang::ast::ReplicationExpression &expr) {
1087 auto type = context.convertType(*expr.type);
1088 auto value = context.convertRvalueExpression(expr.concat());
1089 if (!value)
1090 return {};
1091 return moore::ReplicateOp::create(builder, loc, type, value);
1092 }
1093
1094 // Handle set membership operator.
1095 Value visit(const slang::ast::InsideExpression &expr) {
1096 auto lhs = context.convertToSimpleBitVector(
1097 context.convertRvalueExpression(expr.left()));
1098 if (!lhs)
1099 return {};
1100 // All conditions for determining whether it is inside.
1101 SmallVector<Value> conditions;
1102
1103 // Traverse open range list.
1104 for (const auto *listExpr : expr.rangeList()) {
1105 Value cond;
1106 // The open range list on the right-hand side of the inside operator is a
1107 // comma-separated list of expressions or ranges.
1108 if (const auto *openRange =
1109 listExpr->as_if<slang::ast::ValueRangeExpression>()) {
1110 // Handle ranges.
1111 auto lowBound = context.convertToSimpleBitVector(
1112 context.convertRvalueExpression(openRange->left()));
1113 auto highBound = context.convertToSimpleBitVector(
1114 context.convertRvalueExpression(openRange->right()));
1115 if (!lowBound || !highBound)
1116 return {};
1117 Value leftValue, rightValue;
1118 // Determine if the expression on the left-hand side is inclusively
1119 // within the range.
1120 if (openRange->left().type->isSigned() ||
1121 expr.left().type->isSigned()) {
1122 leftValue = moore::SgeOp::create(builder, loc, lhs, lowBound);
1123 } else {
1124 leftValue = moore::UgeOp::create(builder, loc, lhs, lowBound);
1125 }
1126 if (openRange->right().type->isSigned() ||
1127 expr.left().type->isSigned()) {
1128 rightValue = moore::SleOp::create(builder, loc, lhs, highBound);
1129 } else {
1130 rightValue = moore::UleOp::create(builder, loc, lhs, highBound);
1131 }
1132 cond = moore::AndOp::create(builder, loc, leftValue, rightValue);
1133 } else {
1134 // Handle expressions.
1135 if (!listExpr->type->isIntegral()) {
1136 if (listExpr->type->isUnpackedArray()) {
1137 mlir::emitError(
1138 loc, "unpacked arrays in 'inside' expressions not supported");
1139 return {};
1140 }
1141 mlir::emitError(
1142 loc, "only simple bit vectors supported in 'inside' expressions");
1143 return {};
1144 }
1145
1146 auto value = context.convertToSimpleBitVector(
1147 context.convertRvalueExpression(*listExpr));
1148 if (!value)
1149 return {};
1150 cond = moore::WildcardEqOp::create(builder, loc, lhs, value);
1151 }
1152 conditions.push_back(cond);
1153 }
1154
1155 // Calculate the final result by `or` op.
1156 auto result = conditions.back();
1157 conditions.pop_back();
1158 while (!conditions.empty()) {
1159 result = moore::OrOp::create(builder, loc, conditions.back(), result);
1160 conditions.pop_back();
1161 }
1162 return result;
1163 }
1164
1165 // Handle conditional operator `?:`.
1166 Value visit(const slang::ast::ConditionalExpression &expr) {
1167 auto type = context.convertType(*expr.type);
1168
1169 // Handle condition.
1170 if (expr.conditions.size() > 1) {
1171 mlir::emitError(loc)
1172 << "unsupported conditional expression with more than one condition";
1173 return {};
1174 }
1175 const auto &cond = expr.conditions[0];
1176 if (cond.pattern) {
1177 mlir::emitError(loc) << "unsupported conditional expression with pattern";
1178 return {};
1179 }
1180 auto value =
1181 context.convertToBool(context.convertRvalueExpression(*cond.expr));
1182 if (!value)
1183 return {};
1184 auto conditionalOp =
1185 moore::ConditionalOp::create(builder, loc, type, value);
1186
1187 // Create blocks for true region and false region.
1188 auto &trueBlock = conditionalOp.getTrueRegion().emplaceBlock();
1189 auto &falseBlock = conditionalOp.getFalseRegion().emplaceBlock();
1190
1191 OpBuilder::InsertionGuard g(builder);
1192
1193 // Handle left expression.
1194 builder.setInsertionPointToStart(&trueBlock);
1195 auto trueValue = context.convertRvalueExpression(expr.left(), type);
1196 if (!trueValue)
1197 return {};
1198 moore::YieldOp::create(builder, loc, trueValue);
1199
1200 // Handle right expression.
1201 builder.setInsertionPointToStart(&falseBlock);
1202 auto falseValue = context.convertRvalueExpression(expr.right(), type);
1203 if (!falseValue)
1204 return {};
1205 moore::YieldOp::create(builder, loc, falseValue);
1206
1207 return conditionalOp.getResult();
1208 }
1209
1210 /// Handle calls.
1211 Value visit(const slang::ast::CallExpression &expr) {
1212 // Try to materialize constant values directly.
1213 auto constant = context.evaluateConstant(expr);
1214 if (auto value = context.materializeConstant(constant, *expr.type, loc))
1215 return value;
1216
1217 return std::visit(
1218 [&](auto &subroutine) { return visitCall(expr, subroutine); },
1219 expr.subroutine);
1220 }
1221
1222 /// Get both the actual `this` argument of a method call and the required
1223 /// class type.
1224 std::pair<Value, moore::ClassHandleType>
1225 getMethodReceiverTypeHandle(const slang::ast::CallExpression &expr) {
1226
1227 moore::ClassHandleType handleTy;
1228 Value thisRef;
1229
1230 // Qualified call: t.m(...), extract from thisClass.
1231 if (const slang::ast::Expression *recvExpr = expr.thisClass()) {
1232 thisRef = context.convertRvalueExpression(*recvExpr);
1233 if (!thisRef)
1234 return {};
1235 } else {
1236 // Unqualified call inside a method body: try using implicit %this.
1237 thisRef = context.getImplicitThisRef();
1238 if (!thisRef) {
1239 mlir::emitError(loc) << "method '" << expr.getSubroutineName()
1240 << "' called without an object";
1241 return {};
1242 }
1243 }
1244 handleTy = cast<moore::ClassHandleType>(thisRef.getType());
1245 return {thisRef, handleTy};
1246 }
1247
1248 /// Build a method call including implicit this argument.
1249 mlir::CallOpInterface
1250 buildMethodCall(const slang::ast::SubroutineSymbol *subroutine,
1251 FunctionLowering *lowering,
1252 moore::ClassHandleType actualHandleTy, Value actualThisRef,
1253 SmallVector<Value> &arguments,
1254 SmallVector<Type> &resultTypes) {
1255
1256 // Get the expected receiver type from the lowered method
1257 auto funcTy = lowering->op.getFunctionType();
1258 auto expected0 = funcTy.getInput(0);
1259 auto expectedHdlTy = cast<moore::ClassHandleType>(expected0);
1260
1261 // Upcast the handle as necessary.
1262 auto implicitThisRef = context.materializeConversion(
1263 expectedHdlTy, actualThisRef, false, actualThisRef.getLoc());
1264
1265 // Build an argument list where the this reference is the first argument.
1266 SmallVector<Value> explicitArguments;
1267 explicitArguments.reserve(arguments.size() + 1);
1268 explicitArguments.push_back(implicitThisRef);
1269 explicitArguments.append(arguments.begin(), arguments.end());
1270
1271 // Method call: choose direct vs virtual.
1272 const bool isVirtual =
1273 (subroutine->flags & slang::ast::MethodFlags::Virtual) != 0;
1274
1275 if (!isVirtual) {
1276 auto calleeSym = lowering->op.getSymName();
1277 // Direct (non-virtual) call -> moore.class.call
1278 return mlir::func::CallOp::create(builder, loc, resultTypes, calleeSym,
1279 explicitArguments);
1280 }
1281
1282 auto funcName = subroutine->name;
1283 auto method = moore::VTableLoadMethodOp::create(
1284 builder, loc, funcTy, actualThisRef,
1285 SymbolRefAttr::get(context.getContext(), funcName));
1286 return mlir::func::CallIndirectOp::create(builder, loc, method,
1287 explicitArguments);
1288 }
1289
1290 /// Handle subroutine calls.
1291 Value visitCall(const slang::ast::CallExpression &expr,
1292 const slang::ast::SubroutineSymbol *subroutine) {
1293
1294 const bool isMethod = (subroutine->thisVar != nullptr);
1295
1296 auto *lowering = context.declareFunction(*subroutine);
1297 if (!lowering)
1298 return {};
1299 auto convertedFunction = context.convertFunction(*subroutine);
1300 if (failed(convertedFunction))
1301 return {};
1302
1303 // Convert the call arguments. Input arguments are converted to an rvalue.
1304 // All other arguments are converted to lvalues and passed into the function
1305 // by reference.
1306 SmallVector<Value> arguments;
1307 for (auto [callArg, declArg] :
1308 llvm::zip(expr.arguments(), subroutine->getArguments())) {
1309
1310 // Unpack the `<expr> = EmptyArgument` pattern emitted by Slang for output
1311 // and inout arguments.
1312 auto *expr = callArg;
1313 if (const auto *assign = expr->as_if<slang::ast::AssignmentExpression>())
1314 expr = &assign->left();
1315
1316 Value value;
1317 if (declArg->direction == slang::ast::ArgumentDirection::In)
1318 value = context.convertRvalueExpression(*expr);
1319 else
1320 value = context.convertLvalueExpression(*expr);
1321 if (!value)
1322 return {};
1323 arguments.push_back(value);
1324 }
1325
1326 if (!lowering->isConverting && !lowering->captures.empty()) {
1327 auto materializeCaptureAtCall = [&](Value cap) -> Value {
1328 // Captures are expected to be moore::RefType.
1329 auto refTy = dyn_cast<moore::RefType>(cap.getType());
1330 if (!refTy) {
1331 lowering->op.emitError(
1332 "expected captured value to be moore::RefType");
1333 return {};
1334 }
1335
1336 // Expected case: the capture stems from a variable of any parent
1337 // scope. We need to walk up, since definition might be a couple regions
1338 // up.
1339 Region *capRegion = [&]() -> Region * {
1340 if (auto ba = dyn_cast<BlockArgument>(cap))
1341 return ba.getOwner()->getParent();
1342 if (auto *def = cap.getDefiningOp())
1343 return def->getParentRegion();
1344 return nullptr;
1345 }();
1346
1347 Region *callRegion =
1348 builder.getBlock() ? builder.getBlock()->getParent() : nullptr;
1349
1350 for (Region *r = callRegion; r; r = r->getParentRegion()) {
1351 if (r == capRegion) {
1352 // Safe to use the SSA value directly here.
1353 return cap;
1354 }
1355 }
1356
1357 // Otherwise we can’t legally rematerialize this capture here.
1358 lowering->op.emitError()
1359 << "cannot materialize captured ref at call site; non-symbol "
1360 << "source: "
1361 << (cap.getDefiningOp()
1362 ? cap.getDefiningOp()->getName().getStringRef()
1363 : "<block-arg>");
1364 return {};
1365 };
1366
1367 for (Value cap : lowering->captures) {
1368 Value mat = materializeCaptureAtCall(cap);
1369 if (!mat)
1370 return {};
1371 arguments.push_back(mat);
1372 }
1373 }
1374
1375 // Determine result types from the declared/converted func op.
1376 SmallVector<Type> resultTypes(
1377 lowering->op.getFunctionType().getResults().begin(),
1378 lowering->op.getFunctionType().getResults().end());
1379
1380 mlir::CallOpInterface callOp;
1381 if (isMethod) {
1382 // Class functions -> build func.call / func.indirect_call with implicit
1383 // this argument
1384 auto [thisRef, tyHandle] = getMethodReceiverTypeHandle(expr);
1385 callOp = buildMethodCall(subroutine, lowering, tyHandle, thisRef,
1386 arguments, resultTypes);
1387 } else {
1388 // Free function -> func.call
1389 callOp =
1390 mlir::func::CallOp::create(builder, loc, lowering->op, arguments);
1391 }
1392
1393 auto result = resultTypes.size() > 0 ? callOp->getOpResult(0) : Value{};
1394 // For calls to void functions we need to have a value to return from this
1395 // function. Create a dummy `unrealized_conversion_cast`, which will get
1396 // deleted again later on.
1397 if (resultTypes.size() == 0)
1398 return mlir::UnrealizedConversionCastOp::create(
1399 builder, loc, moore::VoidType::get(context.getContext()),
1400 ValueRange{})
1401 .getResult(0);
1402
1403 return result;
1404 }
1405
1406 /// Handle system calls.
1407 Value visitCall(const slang::ast::CallExpression &expr,
1408 const slang::ast::CallExpression::SystemCallInfo &info) {
1409 const auto &subroutine = *info.subroutine;
1410
1411 // $rose, $fell, $stable, $changed, and $past are only valid in
1412 // the context of properties and assertions. Those are treated in the
1413 // LTLDialect; treat them there instead.
1414 bool isAssertionCall =
1415 llvm::StringSwitch<bool>(subroutine.name)
1416 .Cases({"$rose", "$fell", "$stable", "$past"}, true)
1417 .Default(false);
1418
1419 if (isAssertionCall)
1420 return context.convertAssertionCallExpression(expr, info, loc);
1421
1422 auto args = expr.arguments();
1423
1424 FailureOr<Value> result;
1425 Value value;
1426 Value value2;
1427
1428 // $sformatf() and $sformat look like system tasks, but we handle string
1429 // formatting differently from expression evaluation, so handle them
1430 // separately.
1431 // According to IEEE 1800-2023 Section 21.3.3 "Formatting data to a
1432 // string" $sformatf works just like the string formatting but returns
1433 // a StringType.
1434 if (!subroutine.name.compare("$sformatf")) {
1435 // Create the FormatString
1436 auto fmtValue = context.convertFormatString(
1437 expr.arguments(), loc, moore::IntFormat::Decimal, false);
1438 if (failed(fmtValue))
1439 return {};
1440 return fmtValue.value();
1441 }
1442
1443 // Call the conversion function with the appropriate arity. These return one
1444 // of the following:
1445 //
1446 // - `failure()` if the system call was recognized but some error occurred
1447 // - `Value{}` if the system call was not recognized
1448 // - non-null `Value` result otherwise
1449 switch (args.size()) {
1450 case (0):
1451 result = context.convertSystemCallArity0(subroutine, loc);
1452 break;
1453
1454 case (1):
1455 value = context.convertRvalueExpression(*args[0]);
1456 if (!value)
1457 return {};
1458 result = context.convertSystemCallArity1(subroutine, loc, value);
1459 break;
1460
1461 case (2):
1462 value = context.convertRvalueExpression(*args[0]);
1463 value2 = context.convertRvalueExpression(*args[1]);
1464 if (!value || !value2)
1465 return {};
1466 result = context.convertSystemCallArity2(subroutine, loc, value, value2);
1467 break;
1468
1469 default:
1470 break;
1471 }
1472
1473 // If we have recognized the system call but the conversion has encountered
1474 // and already reported an error, simply return the usual null `Value` to
1475 // indicate failure.
1476 if (failed(result))
1477 return {};
1478
1479 // If we have recognized the system call and got a non-null `Value` result,
1480 // return that.
1481 if (*result)
1482 return *result;
1483
1484 // Otherwise we didn't recognize the system call.
1485 mlir::emitError(loc) << "unsupported system call `" << subroutine.name
1486 << "`";
1487 return {};
1488 }
1489
1490 /// Handle string literals.
1491 Value visit(const slang::ast::StringLiteral &expr) {
1492 auto type = context.convertType(*expr.type);
1493 return moore::ConstantStringOp::create(builder, loc, type, expr.getValue());
1494 }
1495
1496 /// Handle real literals.
1497 Value visit(const slang::ast::RealLiteral &expr) {
1498 auto fTy = mlir::Float64Type::get(context.getContext());
1499 auto attr = mlir::FloatAttr::get(fTy, expr.getValue());
1500 return moore::ConstantRealOp::create(builder, loc, attr).getResult();
1501 }
1502
1503 /// Helper function to convert RValues at creation of a new Struct, Array or
1504 /// Int.
1505 FailureOr<SmallVector<Value>>
1506 convertElements(const slang::ast::AssignmentPatternExpressionBase &expr,
1507 std::variant<Type, ArrayRef<Type>> expectedTypes,
1508 unsigned replCount) {
1509 const auto &elts = expr.elements();
1510 const size_t elementCount = elts.size();
1511
1512 // Inspect the variant.
1513 const bool hasBroadcast =
1514 std::holds_alternative<Type>(expectedTypes) &&
1515 static_cast<bool>(std::get<Type>(expectedTypes)); // non-null Type
1516
1517 const bool hasPerElem =
1518 std::holds_alternative<ArrayRef<Type>>(expectedTypes) &&
1519 !std::get<ArrayRef<Type>>(expectedTypes).empty();
1520
1521 // If per-element types are provided, enforce arity.
1522 if (hasPerElem) {
1523 auto types = std::get<ArrayRef<Type>>(expectedTypes);
1524 if (types.size() != elementCount) {
1525 mlir::emitError(loc)
1526 << "assignment pattern arity mismatch: expected " << types.size()
1527 << " elements, got " << elementCount;
1528 return failure();
1529 }
1530 }
1531
1532 SmallVector<Value> converted;
1533 converted.reserve(elementCount * std::max(1u, replCount));
1534
1535 // Convert each element heuristically, no type is expected
1536 if (!hasBroadcast && !hasPerElem) {
1537 // No expected type info.
1538 for (const auto *elementExpr : elts) {
1539 Value v = context.convertRvalueExpression(*elementExpr);
1540 if (!v)
1541 return failure();
1542 converted.push_back(v);
1543 }
1544 } else if (hasBroadcast) {
1545 // Same expected type for all elements.
1546 Type want = std::get<Type>(expectedTypes);
1547 for (const auto *elementExpr : elts) {
1548 Value v = want ? context.convertRvalueExpression(*elementExpr, want)
1549 : context.convertRvalueExpression(*elementExpr);
1550 if (!v)
1551 return failure();
1552 converted.push_back(v);
1553 }
1554 } else { // hasPerElem, individual type is expected for each element
1555 auto types = std::get<ArrayRef<Type>>(expectedTypes);
1556 for (size_t i = 0; i < elementCount; ++i) {
1557 Type want = types[i];
1558 const auto *elementExpr = elts[i];
1559 Value v = want ? context.convertRvalueExpression(*elementExpr, want)
1560 : context.convertRvalueExpression(*elementExpr);
1561 if (!v)
1562 return failure();
1563 converted.push_back(v);
1564 }
1565 }
1566
1567 for (unsigned i = 1; i < replCount; ++i)
1568 converted.append(converted.begin(), converted.begin() + elementCount);
1569
1570 return converted;
1571 }
1572
1573 /// Handle assignment patterns.
1574 Value visitAssignmentPattern(
1575 const slang::ast::AssignmentPatternExpressionBase &expr,
1576 unsigned replCount = 1) {
1577 auto type = context.convertType(*expr.type);
1578 const auto &elts = expr.elements();
1579
1580 // Handle integers.
1581 if (auto intType = dyn_cast<moore::IntType>(type)) {
1582 auto elements = convertElements(expr, {}, replCount);
1583
1584 if (failed(elements))
1585 return {};
1586
1587 assert(intType.getWidth() == elements->size());
1588 std::reverse(elements->begin(), elements->end());
1589 return moore::ConcatOp::create(builder, loc, intType, *elements);
1590 }
1591
1592 // Handle packed structs.
1593 if (auto structType = dyn_cast<moore::StructType>(type)) {
1594 SmallVector<Type> expectedTy;
1595 expectedTy.reserve(structType.getMembers().size());
1596 for (auto member : structType.getMembers())
1597 expectedTy.push_back(member.type);
1598
1599 FailureOr<SmallVector<Value>> elements;
1600 if (expectedTy.size() == elts.size())
1601 elements = convertElements(expr, expectedTy, replCount);
1602 else
1603 elements = convertElements(expr, {}, replCount);
1604
1605 if (failed(elements))
1606 return {};
1607
1608 assert(structType.getMembers().size() == elements->size());
1609 return moore::StructCreateOp::create(builder, loc, structType, *elements);
1610 }
1611
1612 // Handle unpacked structs.
1613 if (auto structType = dyn_cast<moore::UnpackedStructType>(type)) {
1614 SmallVector<Type> expectedTy;
1615 expectedTy.reserve(structType.getMembers().size());
1616 for (auto member : structType.getMembers())
1617 expectedTy.push_back(member.type);
1618
1619 FailureOr<SmallVector<Value>> elements;
1620 if (expectedTy.size() == elts.size())
1621 elements = convertElements(expr, expectedTy, replCount);
1622 else
1623 elements = convertElements(expr, {}, replCount);
1624
1625 if (failed(elements))
1626 return {};
1627
1628 assert(structType.getMembers().size() == elements->size());
1629
1630 return moore::StructCreateOp::create(builder, loc, structType, *elements);
1631 }
1632
1633 // Handle packed arrays.
1634 if (auto arrayType = dyn_cast<moore::ArrayType>(type)) {
1635 auto elements =
1636 convertElements(expr, arrayType.getElementType(), replCount);
1637
1638 if (failed(elements))
1639 return {};
1640
1641 assert(arrayType.getSize() == elements->size());
1642 return moore::ArrayCreateOp::create(builder, loc, arrayType, *elements);
1643 }
1644
1645 // Handle unpacked arrays.
1646 if (auto arrayType = dyn_cast<moore::UnpackedArrayType>(type)) {
1647 auto elements =
1648 convertElements(expr, arrayType.getElementType(), replCount);
1649
1650 if (failed(elements))
1651 return {};
1652
1653 assert(arrayType.getSize() == elements->size());
1654 return moore::ArrayCreateOp::create(builder, loc, arrayType, *elements);
1655 }
1656
1657 mlir::emitError(loc) << "unsupported assignment pattern with type " << type;
1658 return {};
1659 }
1660
1661 Value visit(const slang::ast::SimpleAssignmentPatternExpression &expr) {
1662 return visitAssignmentPattern(expr);
1663 }
1664
1665 Value visit(const slang::ast::StructuredAssignmentPatternExpression &expr) {
1666 return visitAssignmentPattern(expr);
1667 }
1668
1669 Value visit(const slang::ast::ReplicatedAssignmentPatternExpression &expr) {
1670 auto count =
1671 context.evaluateConstant(expr.count()).integer().as<unsigned>();
1672 assert(count && "Slang guarantees constant non-zero replication count");
1673 return visitAssignmentPattern(expr, *count);
1674 }
1675
1676 Value visit(const slang::ast::StreamingConcatenationExpression &expr) {
1677 SmallVector<Value> operands;
1678 for (auto stream : expr.streams()) {
1679 auto operandLoc = context.convertLocation(stream.operand->sourceRange);
1680 if (!stream.constantWithWidth.has_value() && stream.withExpr) {
1681 mlir::emitError(operandLoc)
1682 << "Moore only support streaming "
1683 "concatenation with fixed size 'with expression'";
1684 return {};
1685 }
1686 Value value;
1687 if (stream.constantWithWidth.has_value()) {
1688 value = context.convertRvalueExpression(*stream.withExpr);
1689 auto type = cast<moore::UnpackedType>(value.getType());
1690 auto intType = moore::IntType::get(
1691 context.getContext(), type.getBitSize().value(), type.getDomain());
1692 // Do not care if it's signed, because we will not do expansion.
1693 value = context.materializeConversion(intType, value, false, loc);
1694 } else {
1695 value = context.convertRvalueExpression(*stream.operand);
1696 }
1697
1698 value = context.convertToSimpleBitVector(value);
1699 if (!value)
1700 return {};
1701 operands.push_back(value);
1702 }
1703 Value value;
1704
1705 if (operands.size() == 1) {
1706 // There must be at least one element, otherwise slang will report an
1707 // error.
1708 value = operands.front();
1709 } else {
1710 value = moore::ConcatOp::create(builder, loc, operands).getResult();
1711 }
1712
1713 if (expr.getSliceSize() == 0) {
1714 return value;
1715 }
1716
1717 auto type = cast<moore::IntType>(value.getType());
1718 SmallVector<Value> slicedOperands;
1719 auto iterMax = type.getWidth() / expr.getSliceSize();
1720 auto remainSize = type.getWidth() % expr.getSliceSize();
1721
1722 for (size_t i = 0; i < iterMax; i++) {
1723 auto extractResultType = moore::IntType::get(
1724 context.getContext(), expr.getSliceSize(), type.getDomain());
1725
1726 auto extracted = moore::ExtractOp::create(builder, loc, extractResultType,
1727 value, i * expr.getSliceSize());
1728 slicedOperands.push_back(extracted);
1729 }
1730 // Handle other wire
1731 if (remainSize) {
1732 auto extractResultType = moore::IntType::get(
1733 context.getContext(), remainSize, type.getDomain());
1734
1735 auto extracted =
1736 moore::ExtractOp::create(builder, loc, extractResultType, value,
1737 iterMax * expr.getSliceSize());
1738 slicedOperands.push_back(extracted);
1739 }
1740
1741 return moore::ConcatOp::create(builder, loc, slicedOperands);
1742 }
1743
1744 Value visit(const slang::ast::AssertionInstanceExpression &expr) {
1745 return context.convertAssertionExpression(expr.body, loc);
1746 }
1747
1748 // A new class expression can stand for one of two things:
1749 // 1) A call to the `new` method (ctor) of a class made outside the scope of
1750 // the class
1751 // 2) A call to the `super.new` method, i.e. the constructor of the base
1752 // class, within the scope of a class, more specifically, within the new
1753 // method override of a class.
1754 // In the first case we should emit an allocation and a call to the ctor if it
1755 // exists (it's optional in System Verilog), in the second case we should emit
1756 // a call to the parent's ctor (System Verilog only has single inheritance, so
1757 // super is always unambiguous), but no allocation, as the child class' new
1758 // invocation already allocated space for both its own and its parent's
1759 // properties.
1760 Value visit(const slang::ast::NewClassExpression &expr) {
1761 auto type = context.convertType(*expr.type);
1762 auto classTy = dyn_cast<moore::ClassHandleType>(type);
1763 Value newObj;
1764
1765 // We are calling new from within a new function, and it's pointing to
1766 // super. Check the implicit this ref to figure out the super class type.
1767 // Do not allocate a new object.
1768 if (!classTy && expr.isSuperClass) {
1769 newObj = context.getImplicitThisRef();
1770 if (!newObj || !newObj.getType() ||
1771 !isa<moore::ClassHandleType>(newObj.getType())) {
1772 mlir::emitError(loc) << "implicit this ref was not set while "
1773 "converting new class function";
1774 return {};
1775 }
1776 auto thisType = cast<moore::ClassHandleType>(newObj.getType());
1777 auto classDecl =
1778 cast<moore::ClassDeclOp>(*context.symbolTable.lookupNearestSymbolFrom(
1779 context.intoModuleOp, thisType.getClassSym()));
1780 auto baseClassSym = classDecl.getBase();
1781 classTy = circt::moore::ClassHandleType::get(context.getContext(),
1782 baseClassSym.value());
1783 } else {
1784 // We are calling from outside a class; allocate space for the object.
1785 newObj = moore::ClassNewOp::create(builder, loc, classTy, {});
1786 }
1787
1788 const auto *constructor = expr.constructorCall();
1789 // If there's no ctor, we are done.
1790 if (!constructor)
1791 return newObj;
1792
1793 if (const auto *callConstructor =
1794 constructor->as_if<slang::ast::CallExpression>())
1795 if (const auto *subroutine =
1796 std::get_if<const slang::ast::SubroutineSymbol *>(
1797 &callConstructor->subroutine)) {
1798 // Bit paranoid, but virtually free checks that new is a class method
1799 // and the subroutine has already been converted.
1800 if (!(*subroutine)->thisVar) {
1801 mlir::emitError(loc) << "Expected subroutine called by new to use an "
1802 "implicit this reference";
1803 return {};
1804 }
1805 if (failed(context.convertFunction(**subroutine)))
1806 return {};
1807 // Pass the newObj as the implicit this argument of the ctor.
1808 auto savedThis = context.currentThisRef;
1809 context.currentThisRef = newObj;
1810 auto restoreThis =
1811 llvm::make_scope_exit([&] { context.currentThisRef = savedThis; });
1812 // Emit a call to ctor
1813 if (!visitCall(*callConstructor, *subroutine))
1814 return {};
1815 // Return new handle
1816 return newObj;
1817 }
1818 return {};
1819 }
1820
1821 /// Emit an error for all other expressions.
1822 template <typename T>
1823 Value visit(T &&node) {
1824 mlir::emitError(loc, "unsupported expression: ")
1825 << slang::ast::toString(node.kind);
1826 return {};
1827 }
1828
1829 Value visitInvalid(const slang::ast::Expression &expr) {
1830 mlir::emitError(loc, "invalid expression");
1831 return {};
1832 }
1833};
1834} // namespace
1835
1836//===----------------------------------------------------------------------===//
1837// Lvalue Conversion
1838//===----------------------------------------------------------------------===//
1839
1840namespace {
1841struct LvalueExprVisitor : public ExprVisitor {
1842 LvalueExprVisitor(Context &context, Location loc)
1843 : ExprVisitor(context, loc, /*isLvalue=*/true) {}
1844 using ExprVisitor::visit;
1845
1846 // Handle named values, such as references to declared variables.
1847 Value visit(const slang::ast::NamedValueExpression &expr) {
1848 // Handle local variables.
1849 if (auto value = context.valueSymbols.lookup(&expr.symbol))
1850 return value;
1851
1852 // Handle global variables.
1853 if (auto globalOp = context.globalVariables.lookup(&expr.symbol))
1854 return moore::GetGlobalVariableOp::create(builder, loc, globalOp);
1855
1856 if (auto *const property =
1857 expr.symbol.as_if<slang::ast::ClassPropertySymbol>()) {
1858 return visitClassProperty(context, *property);
1859 }
1860
1861 auto d = mlir::emitError(loc, "unknown name `") << expr.symbol.name << "`";
1862 d.attachNote(context.convertLocation(expr.symbol.location))
1863 << "no lvalue generated for " << slang::ast::toString(expr.symbol.kind);
1864 return {};
1865 }
1866
1867 // Handle hierarchical values, such as `Top.sub.var = x`.
1868 Value visit(const slang::ast::HierarchicalValueExpression &expr) {
1869 // Handle local variables.
1870 if (auto value = context.valueSymbols.lookup(&expr.symbol))
1871 return value;
1872
1873 // Handle global variables.
1874 if (auto globalOp = context.globalVariables.lookup(&expr.symbol))
1875 return moore::GetGlobalVariableOp::create(builder, loc, globalOp);
1876
1877 // Emit an error for those hierarchical values not recorded in the
1878 // `valueSymbols`.
1879 auto d = mlir::emitError(loc, "unknown hierarchical name `")
1880 << expr.symbol.name << "`";
1881 d.attachNote(context.convertLocation(expr.symbol.location))
1882 << "no lvalue generated for " << slang::ast::toString(expr.symbol.kind);
1883 return {};
1884 }
1885
1886 Value visit(const slang::ast::StreamingConcatenationExpression &expr) {
1887 SmallVector<Value> operands;
1888 for (auto stream : expr.streams()) {
1889 auto operandLoc = context.convertLocation(stream.operand->sourceRange);
1890 if (!stream.constantWithWidth.has_value() && stream.withExpr) {
1891 mlir::emitError(operandLoc)
1892 << "Moore only support streaming "
1893 "concatenation with fixed size 'with expression'";
1894 return {};
1895 }
1896 Value value;
1897 if (stream.constantWithWidth.has_value()) {
1898 value = context.convertLvalueExpression(*stream.withExpr);
1899 auto type = cast<moore::UnpackedType>(
1900 cast<moore::RefType>(value.getType()).getNestedType());
1901 auto intType = moore::RefType::get(moore::IntType::get(
1902 context.getContext(), type.getBitSize().value(), type.getDomain()));
1903 // Do not care if it's signed, because we will not do expansion.
1904 value = context.materializeConversion(intType, value, false, loc);
1905 } else {
1906 value = context.convertLvalueExpression(*stream.operand);
1907 }
1908
1909 if (!value)
1910 return {};
1911 operands.push_back(value);
1912 }
1913 Value value;
1914 if (operands.size() == 1) {
1915 // There must be at least one element, otherwise slang will report an
1916 // error.
1917 value = operands.front();
1918 } else {
1919 value = moore::ConcatRefOp::create(builder, loc, operands).getResult();
1920 }
1921
1922 if (expr.getSliceSize() == 0) {
1923 return value;
1924 }
1925
1926 auto type = cast<moore::IntType>(
1927 cast<moore::RefType>(value.getType()).getNestedType());
1928 SmallVector<Value> slicedOperands;
1929 auto widthSum = type.getWidth();
1930 auto domain = type.getDomain();
1931 auto iterMax = widthSum / expr.getSliceSize();
1932 auto remainSize = widthSum % expr.getSliceSize();
1933
1934 for (size_t i = 0; i < iterMax; i++) {
1935 auto extractResultType = moore::RefType::get(moore::IntType::get(
1936 context.getContext(), expr.getSliceSize(), domain));
1937
1938 auto extracted = moore::ExtractRefOp::create(
1939 builder, loc, extractResultType, value, i * expr.getSliceSize());
1940 slicedOperands.push_back(extracted);
1941 }
1942 // Handle other wire
1943 if (remainSize) {
1944 auto extractResultType = moore::RefType::get(
1945 moore::IntType::get(context.getContext(), remainSize, domain));
1946
1947 auto extracted =
1948 moore::ExtractRefOp::create(builder, loc, extractResultType, value,
1949 iterMax * expr.getSliceSize());
1950 slicedOperands.push_back(extracted);
1951 }
1952
1953 return moore::ConcatRefOp::create(builder, loc, slicedOperands);
1954 }
1955
1956 /// Emit an error for all other expressions.
1957 template <typename T>
1958 Value visit(T &&node) {
1959 return context.convertRvalueExpression(node);
1960 }
1961
1962 Value visitInvalid(const slang::ast::Expression &expr) {
1963 mlir::emitError(loc, "invalid expression");
1964 return {};
1965 }
1966};
1967} // namespace
1968
1969//===----------------------------------------------------------------------===//
1970// Entry Points
1971//===----------------------------------------------------------------------===//
1972
1973Value Context::convertRvalueExpression(const slang::ast::Expression &expr,
1974 Type requiredType) {
1975 auto loc = convertLocation(expr.sourceRange);
1976 auto value = expr.visit(RvalueExprVisitor(*this, loc));
1977 if (value && requiredType)
1978 value =
1979 materializeConversion(requiredType, value, expr.type->isSigned(), loc);
1980 return value;
1981}
1982
1983Value Context::convertLvalueExpression(const slang::ast::Expression &expr) {
1984 auto loc = convertLocation(expr.sourceRange);
1985 return expr.visit(LvalueExprVisitor(*this, loc));
1986}
1987// NOLINTEND(misc-no-recursion)
1988
1989/// Helper function to convert a value to its "truthy" boolean value.
1990Value Context::convertToBool(Value value) {
1991 if (!value)
1992 return {};
1993 if (auto type = dyn_cast_or_null<moore::IntType>(value.getType()))
1994 if (type.getBitSize() == 1)
1995 return value;
1996 if (auto type = dyn_cast_or_null<moore::UnpackedType>(value.getType()))
1997 return moore::BoolCastOp::create(builder, value.getLoc(), value);
1998 mlir::emitError(value.getLoc(), "expression of type ")
1999 << value.getType() << " cannot be cast to a boolean";
2000 return {};
2001}
2002
2003/// Materialize a Slang real literal as a constant op.
2004Value Context::materializeSVReal(const slang::ConstantValue &svreal,
2005 const slang::ast::Type &astType,
2006 Location loc) {
2007 const auto *floatType = astType.as_if<slang::ast::FloatingType>();
2008 assert(floatType);
2009
2010 FloatAttr attr;
2011 if (svreal.isShortReal() &&
2012 floatType->floatKind == slang::ast::FloatingType::ShortReal) {
2013 attr = FloatAttr::get(builder.getF32Type(), svreal.shortReal().v);
2014 } else if (svreal.isReal() &&
2015 floatType->floatKind == slang::ast::FloatingType::Real) {
2016 attr = FloatAttr::get(builder.getF64Type(), svreal.real().v);
2017 } else {
2018 mlir::emitError(loc) << "invalid real constant";
2019 return {};
2020 }
2021
2022 return moore::ConstantRealOp::create(builder, loc, attr);
2023}
2024
2025/// Materialize a Slang string literal as a literal string constant op.
2026Value Context::materializeString(const slang::ConstantValue &stringLiteral,
2027 const slang::ast::Type &astType,
2028 Location loc) {
2029 slang::ConstantValue intVal = stringLiteral.convertToInt();
2030 auto effectiveWidth = intVal.getEffectiveWidth();
2031 if (!effectiveWidth)
2032 return {};
2033
2034 auto intTy = moore::IntType::getInt(getContext(), effectiveWidth.value());
2035
2036 if (astType.isString()) {
2037 auto immInt = moore::ConstantStringOp::create(builder, loc, intTy,
2038 stringLiteral.toString())
2039 .getResult();
2040 return moore::IntToStringOp::create(builder, loc, immInt).getResult();
2041 }
2042 return {};
2043}
2044
2045/// Materialize a Slang integer literal as a constant op.
2046Value Context::materializeSVInt(const slang::SVInt &svint,
2047 const slang::ast::Type &astType, Location loc) {
2048 auto type = convertType(astType);
2049 if (!type)
2050 return {};
2051
2052 bool typeIsFourValued = false;
2053 if (auto unpackedType = dyn_cast<moore::UnpackedType>(type))
2054 typeIsFourValued = unpackedType.getDomain() == moore::Domain::FourValued;
2055
2056 auto fvint = convertSVIntToFVInt(svint);
2057 auto intType = moore::IntType::get(getContext(), fvint.getBitWidth(),
2058 fvint.hasUnknown() || typeIsFourValued
2061 auto result = moore::ConstantOp::create(builder, loc, intType, fvint);
2062 return materializeConversion(type, result, astType.isSigned(), loc);
2063}
2064
2066 const slang::ConstantValue &constant,
2067 const slang::ast::FixedSizeUnpackedArrayType &astType, Location loc) {
2068
2069 auto type = convertType(astType);
2070 if (!type)
2071 return {};
2072
2073 // Check whether underlying type is an integer, if so, get bit width
2074 unsigned bitWidth;
2075 if (astType.elementType.isIntegral())
2076 bitWidth = astType.elementType.getBitWidth();
2077 else
2078 return {};
2079
2080 bool typeIsFourValued = false;
2081
2082 // Check whether the underlying type is four-valued
2083 if (auto unpackedType = dyn_cast<moore::UnpackedType>(type))
2084 typeIsFourValued = unpackedType.getDomain() == moore::Domain::FourValued;
2085 else
2086 return {};
2087
2088 auto domain =
2090
2091 // Construct the integer type this is an unpacked array of; if possible keep
2092 // it two-valued, unless any entry is four-valued or the underlying type is
2093 // four-valued
2094 auto intType = moore::IntType::get(getContext(), bitWidth, domain);
2095 // Construct the full array type from intType
2096 auto arrType = moore::UnpackedArrayType::get(
2097 getContext(), constant.elements().size(), intType);
2098
2099 llvm::SmallVector<mlir::Value> elemVals;
2100 moore::ConstantOp constOp;
2101
2102 mlir::OpBuilder::InsertionGuard guard(builder);
2103
2104 // Add one ConstantOp for every element in the array
2105 for (auto elem : constant.elements()) {
2106 FVInt fvInt = convertSVIntToFVInt(elem.integer());
2107 constOp = moore::ConstantOp::create(builder, loc, intType, fvInt);
2108 elemVals.push_back(constOp.getResult());
2109 }
2110
2111 // Take the result of each ConstantOp and concatenate them into an array (of
2112 // constant values).
2113 auto arrayOp = moore::ArrayCreateOp::create(builder, loc, arrType, elemVals);
2114
2115 return arrayOp.getResult();
2116}
2117
2118Value Context::materializeConstant(const slang::ConstantValue &constant,
2119 const slang::ast::Type &type, Location loc) {
2120
2121 if (auto *arr = type.as_if<slang::ast::FixedSizeUnpackedArrayType>())
2122 return materializeFixedSizeUnpackedArrayType(constant, *arr, loc);
2123 if (constant.isInteger())
2124 return materializeSVInt(constant.integer(), type, loc);
2125 if (constant.isReal() || constant.isShortReal())
2126 return materializeSVReal(constant, type, loc);
2127 if (constant.isString())
2128 return materializeString(constant, type, loc);
2129
2130 return {};
2131}
2132
2133slang::ConstantValue
2134Context::evaluateConstant(const slang::ast::Expression &expr) {
2135 using slang::ast::EvalFlags;
2136 slang::ast::EvalContext evalContext(
2137 slang::ast::ASTContext(compilation.getRoot(),
2138 slang::ast::LookupLocation::max),
2139 EvalFlags::CacheResults | EvalFlags::SpecparamsAllowed);
2140 return expr.eval(evalContext);
2141}
2142
2143/// Helper function to convert a value to its "truthy" boolean value and
2144/// convert it to the given domain.
2145Value Context::convertToBool(Value value, Domain domain) {
2146 value = convertToBool(value);
2147 if (!value)
2148 return {};
2149 auto type = moore::IntType::get(getContext(), 1, domain);
2150 return materializeConversion(type, value, false, value.getLoc());
2151}
2152
2154 if (!value)
2155 return {};
2156 if (isa<moore::IntType>(value.getType()))
2157 return value;
2158
2159 // Some operations in Slang's AST, for example bitwise or `|`, don't cast
2160 // packed struct/array operands to simple bit vectors but directly operate
2161 // on the struct/array. Since the corresponding IR ops operate only on
2162 // simple bit vectors, insert a conversion in this case.
2163 if (auto packed = dyn_cast<moore::PackedType>(value.getType()))
2164 if (auto sbvType = packed.getSimpleBitVector())
2165 return materializeConversion(sbvType, value, false, value.getLoc());
2166
2167 mlir::emitError(value.getLoc()) << "expression of type " << value.getType()
2168 << " cannot be cast to a simple bit vector";
2169 return {};
2170}
2171
2172/// Create the necessary operations to convert from a `PackedType` to the
2173/// corresponding simple bit vector `IntType`. This will apply special handling
2174/// to time values, which requires scaling by the local timescale.
2176 Location loc) {
2177 if (isa<moore::IntType>(value.getType()))
2178 return value;
2179
2180 auto &builder = context.builder;
2181 auto packedType = cast<moore::PackedType>(value.getType());
2182 auto intType = packedType.getSimpleBitVector();
2183 assert(intType);
2184
2185 // If we are converting from a time to an integer, divide the integer by the
2186 // timescale.
2187 if (isa<moore::TimeType>(packedType) &&
2189 value = builder.createOrFold<moore::TimeToLogicOp>(loc, value);
2190 auto scale = moore::ConstantOp::create(builder, loc, intType,
2192 return builder.createOrFold<moore::DivUOp>(loc, value, scale);
2193 }
2194
2195 // If this is an aggregate type, make sure that it does not contain any
2196 // `TimeType` fields. These require special conversion to ensure that the
2197 // local timescale is in effect.
2198 if (packedType.containsTimeType()) {
2199 mlir::emitError(loc) << "unsupported conversion: " << packedType
2200 << " cannot be converted to " << intType
2201 << "; contains a time type";
2202 return {};
2203 }
2204
2205 // Otherwise create a simple `PackedToSBVOp` for the conversion.
2206 return builder.createOrFold<moore::PackedToSBVOp>(loc, value);
2207}
2208
2209/// Create the necessary operations to convert from a simple bit vector
2210/// `IntType` to an equivalent `PackedType`. This will apply special handling to
2211/// time values, which requires scaling by the local timescale.
2213 moore::PackedType packedType,
2214 Value value, Location loc) {
2215 if (value.getType() == packedType)
2216 return value;
2217
2218 auto &builder = context.builder;
2219 auto intType = cast<moore::IntType>(value.getType());
2220 assert(intType && intType == packedType.getSimpleBitVector());
2221
2222 // If we are converting from an integer to a time, multiply the integer by the
2223 // timescale.
2224 if (isa<moore::TimeType>(packedType) &&
2226 auto scale = moore::ConstantOp::create(builder, loc, intType,
2228 value = builder.createOrFold<moore::MulOp>(loc, value, scale);
2229 return builder.createOrFold<moore::LogicToTimeOp>(loc, value);
2230 }
2231
2232 // If this is an aggregate type, make sure that it does not contain any
2233 // `TimeType` fields. These require special conversion to ensure that the
2234 // local timescale is in effect.
2235 if (packedType.containsTimeType()) {
2236 mlir::emitError(loc) << "unsupported conversion: " << intType
2237 << " cannot be converted to " << packedType
2238 << "; contains a time type";
2239 return {};
2240 }
2241
2242 // Otherwise create a simple `PackedToSBVOp` for the conversion.
2243 return builder.createOrFold<moore::SBVToPackedOp>(loc, packedType, value);
2244}
2245
2246/// Check whether the actual handle is a subclass of another handle type
2247/// and return a properly upcast version if so.
2248static mlir::Value maybeUpcastHandle(Context &context, mlir::Value actualHandle,
2249 moore::ClassHandleType expectedHandleTy) {
2250 auto loc = actualHandle.getLoc();
2251
2252 auto actualTy = actualHandle.getType();
2253 auto actualHandleTy = dyn_cast<moore::ClassHandleType>(actualTy);
2254 if (!actualHandleTy) {
2255 mlir::emitError(loc) << "expected a !moore.class<...> value, got "
2256 << actualTy;
2257 return {};
2258 }
2259
2260 // Fast path: already the expected handle type.
2261 if (actualHandleTy == expectedHandleTy)
2262 return actualHandle;
2263
2264 if (!context.isClassDerivedFrom(actualHandleTy, expectedHandleTy)) {
2265 mlir::emitError(loc)
2266 << "receiver class " << actualHandleTy.getClassSym()
2267 << " is not the same as, or derived from, expected base class "
2268 << expectedHandleTy.getClassSym().getRootReference();
2269 return {};
2270 }
2271
2272 // Only implicit upcasting is allowed - down casting should never be implicit.
2273 auto casted = moore::ClassUpcastOp::create(context.builder, loc,
2274 expectedHandleTy, actualHandle)
2275 .getResult();
2276 return casted;
2277}
2278
2279Value Context::materializeConversion(Type type, Value value, bool isSigned,
2280 Location loc) {
2281 // Nothing to do if the types are already equal.
2282 if (type == value.getType())
2283 return value;
2284
2285 // Handle packed types which can be converted to a simple bit vector. This
2286 // allows us to perform resizing and domain casting on that bit vector.
2287 auto dstPacked = dyn_cast<moore::PackedType>(type);
2288 auto srcPacked = dyn_cast<moore::PackedType>(value.getType());
2289 auto dstInt = dstPacked ? dstPacked.getSimpleBitVector() : moore::IntType();
2290 auto srcInt = srcPacked ? srcPacked.getSimpleBitVector() : moore::IntType();
2291
2292 if (dstInt && srcInt) {
2293 // Convert the value to a simple bit vector if it isn't one already.
2294 value = materializePackedToSBVConversion(*this, value, loc);
2295 if (!value)
2296 return {};
2297
2298 // Create truncation or sign/zero extension ops depending on the source and
2299 // destination width.
2300 auto resizedType = moore::IntType::get(
2301 value.getContext(), dstInt.getWidth(), srcPacked.getDomain());
2302 if (dstInt.getWidth() < srcInt.getWidth()) {
2303 value = builder.createOrFold<moore::TruncOp>(loc, resizedType, value);
2304 } else if (dstInt.getWidth() > srcInt.getWidth()) {
2305 if (isSigned)
2306 value = builder.createOrFold<moore::SExtOp>(loc, resizedType, value);
2307 else
2308 value = builder.createOrFold<moore::ZExtOp>(loc, resizedType, value);
2309 }
2310
2311 // Convert the domain if needed.
2312 if (dstInt.getDomain() != srcInt.getDomain()) {
2313 if (dstInt.getDomain() == moore::Domain::TwoValued)
2314 value = builder.createOrFold<moore::LogicToIntOp>(loc, value);
2315 else if (dstInt.getDomain() == moore::Domain::FourValued)
2316 value = builder.createOrFold<moore::IntToLogicOp>(loc, value);
2317 }
2318
2319 // Convert the value from a simple bit vector back to the packed type.
2320 value = materializeSBVToPackedConversion(*this, dstPacked, value, loc);
2321 if (!value)
2322 return {};
2323
2324 assert(value.getType() == type);
2325 return value;
2326 }
2327
2328 // Convert from FormatStringType to StringType
2329 if (isa<moore::StringType>(type) &&
2330 isa<moore::FormatStringType>(value.getType())) {
2331 return builder.createOrFold<moore::FormatStringToStringOp>(loc, value);
2332 }
2333
2334 // Convert from StringType to FormatStringType
2335 if (isa<moore::FormatStringType>(type) &&
2336 isa<moore::StringType>(value.getType())) {
2337 return builder.createOrFold<moore::FormatStringOp>(loc, value);
2338 }
2339
2340 // Handle Real To Int conversion
2341 if (isa<moore::IntType>(type) && isa<moore::RealType>(value.getType())) {
2342 auto twoValInt = builder.createOrFold<moore::RealToIntOp>(
2343 loc, dyn_cast<moore::IntType>(type).getTwoValued(), value);
2344
2345 if (dyn_cast<moore::IntType>(type).getDomain() == moore::Domain::FourValued)
2346 return materializePackedToSBVConversion(*this, twoValInt, loc);
2347 return twoValInt;
2348 }
2349
2350 // Handle Int to Real conversion
2351 if (isa<moore::RealType>(type) && isa<moore::IntType>(value.getType())) {
2352 Value twoValInt;
2353 // Check if int needs to be converted to two-valued first
2354 if (dyn_cast<moore::IntType>(value.getType()).getDomain() ==
2356 twoValInt = value;
2357 else
2358 twoValInt = materializeConversion(
2359 dyn_cast<moore::IntType>(value.getType()).getTwoValued(), value, true,
2360 loc);
2361
2362 if (isSigned)
2363 return builder.createOrFold<moore::SIntToRealOp>(loc, type, twoValInt);
2364 return builder.createOrFold<moore::UIntToRealOp>(loc, type, twoValInt);
2365 }
2366
2367 if (isa<moore::ClassHandleType>(type) &&
2368 isa<moore::ClassHandleType>(value.getType()))
2369 return maybeUpcastHandle(*this, value, cast<moore::ClassHandleType>(type));
2370
2371 // TODO: Handle other conversions with dedicated ops.
2372 if (value.getType() != type)
2373 value = moore::ConversionOp::create(builder, loc, type, value);
2374 return value;
2375}
2376
2377FailureOr<Value>
2378Context::convertSystemCallArity0(const slang::ast::SystemSubroutine &subroutine,
2379 Location loc) {
2380
2381 auto systemCallRes =
2382 llvm::StringSwitch<std::function<FailureOr<Value>()>>(subroutine.name)
2383 .Case("$urandom",
2384 [&]() -> Value {
2385 return moore::UrandomBIOp::create(builder, loc, nullptr);
2386 })
2387 .Case("$random",
2388 [&]() -> Value {
2389 return moore::RandomBIOp::create(builder, loc, nullptr);
2390 })
2391 .Case(
2392 "$time",
2393 [&]() -> Value { return moore::TimeBIOp::create(builder, loc); })
2394 .Case(
2395 "$stime",
2396 [&]() -> Value { return moore::TimeBIOp::create(builder, loc); })
2397 .Case(
2398 "$realtime",
2399 [&]() -> Value { return moore::TimeBIOp::create(builder, loc); })
2400 .Default([&]() -> Value { return {}; });
2401 return systemCallRes();
2402}
2403
2404FailureOr<Value>
2405Context::convertSystemCallArity1(const slang::ast::SystemSubroutine &subroutine,
2406 Location loc, Value value) {
2407 auto systemCallRes =
2408 llvm::StringSwitch<std::function<FailureOr<Value>()>>(subroutine.name)
2409 // Signed and unsigned system functions.
2410 .Case("$signed", [&]() { return value; })
2411 .Case("$unsigned", [&]() { return value; })
2412
2413 // Math functions in SystemVerilog.
2414 .Case("$clog2",
2415 [&]() -> FailureOr<Value> {
2416 value = convertToSimpleBitVector(value);
2417 if (!value)
2418 return failure();
2419 return (Value)moore::Clog2BIOp::create(builder, loc, value);
2420 })
2421 .Case("$ln",
2422 [&]() -> Value {
2423 return moore::LnBIOp::create(builder, loc, value);
2424 })
2425 .Case("$log10",
2426 [&]() -> Value {
2427 return moore::Log10BIOp::create(builder, loc, value);
2428 })
2429 .Case("$sin",
2430 [&]() -> Value {
2431 return moore::SinBIOp::create(builder, loc, value);
2432 })
2433 .Case("$cos",
2434 [&]() -> Value {
2435 return moore::CosBIOp::create(builder, loc, value);
2436 })
2437 .Case("$tan",
2438 [&]() -> Value {
2439 return moore::TanBIOp::create(builder, loc, value);
2440 })
2441 .Case("$exp",
2442 [&]() -> Value {
2443 return moore::ExpBIOp::create(builder, loc, value);
2444 })
2445 .Case("$sqrt",
2446 [&]() -> Value {
2447 return moore::SqrtBIOp::create(builder, loc, value);
2448 })
2449 .Case("$floor",
2450 [&]() -> Value {
2451 return moore::FloorBIOp::create(builder, loc, value);
2452 })
2453 .Case("$ceil",
2454 [&]() -> Value {
2455 return moore::CeilBIOp::create(builder, loc, value);
2456 })
2457 .Case("$asin",
2458 [&]() -> Value {
2459 return moore::AsinBIOp::create(builder, loc, value);
2460 })
2461 .Case("$acos",
2462 [&]() -> Value {
2463 return moore::AcosBIOp::create(builder, loc, value);
2464 })
2465 .Case("$atan",
2466 [&]() -> Value {
2467 return moore::AtanBIOp::create(builder, loc, value);
2468 })
2469 .Case("$sinh",
2470 [&]() -> Value {
2471 return moore::SinhBIOp::create(builder, loc, value);
2472 })
2473 .Case("$cosh",
2474 [&]() -> Value {
2475 return moore::CoshBIOp::create(builder, loc, value);
2476 })
2477 .Case("$tanh",
2478 [&]() -> Value {
2479 return moore::TanhBIOp::create(builder, loc, value);
2480 })
2481 .Case("$asinh",
2482 [&]() -> Value {
2483 return moore::AsinhBIOp::create(builder, loc, value);
2484 })
2485 .Case("$acosh",
2486 [&]() -> Value {
2487 return moore::AcoshBIOp::create(builder, loc, value);
2488 })
2489 .Case("$atanh",
2490 [&]() -> Value {
2491 return moore::AtanhBIOp::create(builder, loc, value);
2492 })
2493 .Case("$urandom",
2494 [&]() -> Value {
2495 return moore::UrandomBIOp::create(builder, loc, value);
2496 })
2497 .Case("$random",
2498 [&]() -> Value {
2499 return moore::RandomBIOp::create(builder, loc, value);
2500 })
2501 .Case("$realtobits",
2502 [&]() -> Value {
2503 return moore::RealtobitsBIOp::create(builder, loc, value);
2504 })
2505 .Case("$bitstoreal",
2506 [&]() -> Value {
2507 return moore::BitstorealBIOp::create(builder, loc, value);
2508 })
2509 .Case("$shortrealtobits",
2510 [&]() -> Value {
2511 return moore::ShortrealtobitsBIOp::create(builder, loc,
2512 value);
2513 })
2514 .Case("$bitstoshortreal",
2515 [&]() -> Value {
2516 return moore::BitstoshortrealBIOp::create(builder, loc,
2517 value);
2518 })
2519 .Case("len",
2520 [&]() -> Value {
2521 if (isa<moore::StringType>(value.getType()))
2522 return moore::StringLenOp::create(builder, loc, value);
2523 return {};
2524 })
2525 .Case("toupper",
2526 [&]() -> Value {
2527 return moore::StringToUpperOp::create(builder, loc, value);
2528 })
2529 .Case("tolower",
2530 [&]() -> Value {
2531 return moore::StringToLowerOp::create(builder, loc, value);
2532 })
2533 .Default([&]() -> Value { return {}; });
2534 return systemCallRes();
2535}
2536
2537FailureOr<Value>
2538Context::convertSystemCallArity2(const slang::ast::SystemSubroutine &subroutine,
2539 Location loc, Value value1, Value value2) {
2540 auto systemCallRes =
2541 llvm::StringSwitch<std::function<FailureOr<Value>()>>(subroutine.name)
2542 .Case("getc",
2543 [&]() -> Value {
2544 return moore::StringGetCOp::create(builder, loc, value1,
2545 value2);
2546 })
2547 .Default([&]() -> Value { return {}; });
2548 return systemCallRes();
2549}
2550
2551// Resolve any (possibly nested) SymbolRefAttr to an op from the root.
2552static mlir::Operation *resolve(Context &context, mlir::SymbolRefAttr sym) {
2553 return context.symbolTable.lookupNearestSymbolFrom(context.intoModuleOp, sym);
2554}
2555
2556bool Context::isClassDerivedFrom(const moore::ClassHandleType &actualTy,
2557 const moore::ClassHandleType &baseTy) {
2558 if (!actualTy || !baseTy)
2559 return false;
2560
2561 mlir::SymbolRefAttr actualSym = actualTy.getClassSym();
2562 mlir::SymbolRefAttr baseSym = baseTy.getClassSym();
2563
2564 if (actualSym == baseSym)
2565 return true;
2566
2567 auto *op = resolve(*this, actualSym);
2568 auto decl = llvm::dyn_cast_or_null<moore::ClassDeclOp>(op);
2569 // Walk up the inheritance chain via ClassDeclOp::$base (SymbolRefAttr).
2570 while (decl) {
2571 mlir::SymbolRefAttr curBase = decl.getBaseAttr();
2572 if (!curBase)
2573 break;
2574 if (curBase == baseSym)
2575 return true;
2576 decl = llvm::dyn_cast_or_null<moore::ClassDeclOp>(resolve(*this, curBase));
2577 }
2578 return false;
2579}
2580
2581moore::ClassHandleType
2582Context::getAncestorClassWithProperty(const moore::ClassHandleType &actualTy,
2583 llvm::StringRef fieldName, Location loc) {
2584 // Start at the actual class symbol.
2585 mlir::SymbolRefAttr classSym = actualTy.getClassSym();
2586
2587 while (classSym) {
2588 // Resolve the class declaration from the root symbol table owner.
2589 auto *op = resolve(*this, classSym);
2590 auto decl = llvm::dyn_cast_or_null<moore::ClassDeclOp>(op);
2591 if (!decl)
2592 break;
2593
2594 // Scan the class body for a property with the requested symbol name.
2595 for (auto &block : decl.getBody()) {
2596 for (auto &opInBlock : block) {
2597 if (auto prop =
2598 llvm::dyn_cast<moore::ClassPropertyDeclOp>(&opInBlock)) {
2599 if (prop.getSymName() == fieldName) {
2600 // Found a declaring ancestor: return its handle type.
2601 return moore::ClassHandleType::get(actualTy.getContext(), classSym);
2602 }
2603 }
2604 }
2605 }
2606
2607 // Not found here—climb to the base class (if any) and continue.
2608 classSym = decl.getBaseAttr(); // may be null; loop ends if so
2609 }
2610
2611 // No ancestor declares that property.
2612 mlir::emitError(loc) << "unknown property `" << fieldName << "`";
2613 return {};
2614}
assert(baseType &&"element must be base type")
static std::unique_ptr< Context > context
static Value materializeSBVToPackedConversion(Context &context, moore::PackedType packedType, Value value, Location loc)
Create the necessary operations to convert from a simple bit vector IntType to an equivalent PackedTy...
static mlir::Value maybeUpcastHandle(Context &context, mlir::Value actualHandle, moore::ClassHandleType expectedHandleTy)
Check whether the actual handle is a subclass of another handle type and return a properly upcast ver...
static mlir::Operation * resolve(Context &context, mlir::SymbolRefAttr sym)
static Value visitClassProperty(Context &context, const slang::ast::ClassPropertySymbol &expr)
static uint64_t getTimeScaleInFemtoseconds(Context &context)
Get the currently active timescale as an integer number of femtoseconds.
static Value materializePackedToSBVConversion(Context &context, Value value, Location loc)
Create the necessary operations to convert from a PackedType to the corresponding simple bit vector I...
static Value getSelectIndex(Context &context, Location loc, Value index, const slang::ConstantRange &range)
Map an index into an array, with bounds range, to a bit offset of the underlying bit storage.
static FVInt convertSVIntToFVInt(const slang::SVInt &svint)
Convert a Slang SVInt to a CIRCT FVInt.
Four-valued arbitrary precision integers.
Definition FVInt.h:37
A packed SystemVerilog type.
Definition MooreTypes.h:153
bool containsTimeType() const
Check if this is a TimeType, or an aggregate that contains a nested TimeType.
IntType getSimpleBitVector() const
Get the simple bit vector type equivalent to this packed type.
void info(Twine message)
Definition LSPUtils.cpp:20
Domain
The number of values each bit of a type can assume.
Definition MooreTypes.h:49
@ FourValued
Four-valued types such as logic or integer.
@ TwoValued
Two-valued types such as bit or int.
bool isIntType(Type type, unsigned width)
Check if a type is an IntType type of the given width.
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
A helper class to facilitate the conversion from a Slang AST to MLIR operations.
Value materializeConversion(Type type, Value value, bool isSigned, Location loc)
Helper function to insert the necessary operations to cast a value from one type to another.
Value convertLvalueExpression(const slang::ast::Expression &expr)
Value materializeConstant(const slang::ConstantValue &constant, const slang::ast::Type &type, Location loc)
Helper function to materialize a ConstantValue as an SSA value.
slang::ConstantValue evaluateConstant(const slang::ast::Expression &expr)
Evaluate the constant value of an expression.
slang::ast::Compilation & compilation
OpBuilder builder
The builder used to create IR operations.
Value materializeFixedSizeUnpackedArrayType(const slang::ConstantValue &constant, const slang::ast::FixedSizeUnpackedArrayType &astType, Location loc)
Helper function to materialize an unpacked array of SVInts as an SSA value.
bool isClassDerivedFrom(const moore::ClassHandleType &actualTy, const moore::ClassHandleType &baseTy)
Checks whether one class (actualTy) is derived from another class (baseTy).
Type convertType(const slang::ast::Type &type, LocationAttr loc={})
Convert a slang type into an MLIR type.
Definition Types.cpp:196
Value materializeSVInt(const slang::SVInt &svint, const slang::ast::Type &type, Location loc)
Helper function to materialize an SVInt as an SSA value.
Value materializeSVReal(const slang::ConstantValue &svreal, const slang::ast::Type &type, Location loc)
Helper function to materialize a real value as an SSA value.
Value convertToBool(Value value)
Helper function to convert a value to its "truthy" boolean value.
moore::ClassHandleType getAncestorClassWithProperty(const moore::ClassHandleType &actualTy, StringRef fieldName, Location loc)
Tries to find the closest base class of actualTy that carries a property with name fieldName.
Value convertRvalueExpression(const slang::ast::Expression &expr, Type requiredType={})
FailureOr< Value > convertSystemCallArity0(const slang::ast::SystemSubroutine &subroutine, Location loc)
Convert system function calls only have arity-0.
Value convertToSimpleBitVector(Value value)
Helper function to convert a value to its simple bit vector representation, if it has one.
Value materializeString(const slang::ConstantValue &string, const slang::ast::Type &astType, Location loc)
Helper function to materialize a string as an SSA value.
FailureOr< Value > convertSystemCallArity1(const slang::ast::SystemSubroutine &subroutine, Location loc, Value value)
Convert system function calls only have arity-1.
MLIRContext * getContext()
Return the MLIR context.
FailureOr< Value > convertSystemCallArity2(const slang::ast::SystemSubroutine &subroutine, Location loc, Value value1, Value value2)
Convert system function calls with arity-2.
Location convertLocation(slang::SourceLocation loc)
Convert a slang SourceLocation into an MLIR Location.