14#include "mlir/IR/Operation.h"
15#include "mlir/IR/Value.h"
16#include "slang/ast/EvalContext.h"
17#include "slang/ast/SystemSubroutine.h"
18#include "slang/ast/types/AllTypes.h"
19#include "slang/syntax/AllSyntax.h"
20#include "llvm/ADT/ScopeExit.h"
21#include "llvm/ADT/StringExtras.h"
22#include "llvm/Support/SaveAndRestore.h"
25using namespace ImportVerilog;
30 if (svint.hasUnknown()) {
31 unsigned numWords = svint.getNumWords() / 2;
32 auto value = ArrayRef<uint64_t>(svint.getRawPtr(), numWords);
33 auto unknown = ArrayRef<uint64_t>(svint.getRawPtr() + numWords, numWords);
34 return FVInt(APInt(svint.getBitWidth(), value),
35 APInt(svint.getBitWidth(), unknown));
37 auto value = ArrayRef<uint64_t>(svint.getRawPtr(), svint.getNumWords());
38 return FVInt(APInt(svint.getBitWidth(), value));
43static Value
getIsUnknown(OpBuilder &builder, Location loc, Value value,
44 moore::IntType valTy, MLIRContext *ctx) {
46 if (valTy.getWidth() > 1) {
47 auto mooreI1Type = moore::IntType::get(ctx, 1, valTy.getDomain());
48 bitVal = moore::ReduceXorOp::create(builder, loc, mooreI1Type, value);
50 auto xType = moore::IntType::get(ctx, 1, moore::Domain::FourValued);
53 return moore::CaseEqOp::create(builder, loc, bitVal, xConst).getResult();
59 moore::IntType valTy) {
60 if (valTy.getDomain() == moore::Domain::FourValued)
61 value = builder.createOrFold<moore::LogicToIntOp>(loc, value);
62 return builder.createOrFold<moore::ToBuiltinIntOp>(loc, value);
69 const slang::ConstantRange &range) {
70 auto &builder =
context.builder;
71 auto indexType = cast<moore::UnpackedType>(index.getType());
74 auto lo = range.lower();
75 auto hi = range.upper();
76 auto offset = range.isLittleEndian() ? lo : hi;
79 const bool needSigned = (lo < 0) || (hi < 0);
82 const uint64_t maxAbs = std::max<uint64_t>(std::abs(lo), std::abs(hi));
87 unsigned want = needSigned
88 ? (llvm::Log2_64_Ceil(std::max<uint64_t>(1, maxAbs)) + 1)
89 : std::max<unsigned>(1, llvm::Log2_64_Ceil(maxAbs + 1));
92 const unsigned bw = std::max<unsigned>(want, indexType.getBitSize().value());
95 moore::IntType::get(index.getContext(), bw, indexType.getDomain());
96 index =
context.materializeConversion(intType, index, needSigned, loc);
99 if (range.isLittleEndian())
102 return moore::NegOp::create(builder, loc, index);
106 moore::ConstantOp::create(builder, loc, intType, offset, needSigned);
107 if (range.isLittleEndian())
108 return moore::SubOp::create(builder, loc, index, offsetConst);
110 return moore::SubOp::create(builder, loc, offsetConst, index);
115 static_assert(int(slang::TimeUnit::Seconds) == 0);
116 static_assert(int(slang::TimeUnit::Milliseconds) == 1);
117 static_assert(int(slang::TimeUnit::Microseconds) == 2);
118 static_assert(int(slang::TimeUnit::Nanoseconds) == 3);
119 static_assert(int(slang::TimeUnit::Picoseconds) == 4);
120 static_assert(int(slang::TimeUnit::Femtoseconds) == 5);
122 static_assert(int(slang::TimeScaleMagnitude::One) == 1);
123 static_assert(int(slang::TimeScaleMagnitude::Ten) == 10);
124 static_assert(int(slang::TimeScaleMagnitude::Hundred) == 100);
126 auto exp =
static_cast<unsigned>(
context.timeScale.base.unit);
129 auto scale =
static_cast<uint64_t
>(
context.timeScale.base.magnitude);
138 Context &
context,
const slang::ast::HierarchicalValueExpression &expr) {
139 auto nameAttr =
context.builder.getStringAttr(expr.symbol.name);
140 for (
const auto &element : expr.ref.path) {
141 auto *inst = element.symbol->as_if<slang::ast::InstanceSymbol>();
144 auto *lowering =
context.interfaceInstances.lookup(inst);
147 if (
auto it = lowering->expandedMembers.find(&expr.symbol);
148 it != lowering->expandedMembers.end())
150 if (
auto it = lowering->expandedMembersByName.find(nameAttr);
151 it != lowering->expandedMembersByName.end())
158 const slang::ast::ClassPropertySymbol &expr) {
159 auto loc =
context.convertLocation(expr.location);
160 auto builder =
context.builder;
161 auto type =
context.convertType(expr.getType());
162 auto fieldTy = cast<moore::UnpackedType>(type);
163 auto fieldRefTy = moore::RefType::get(fieldTy);
165 if (expr.lifetime == slang::ast::VariableLifetime::Static) {
168 if (!
context.globalVariables.lookup(&expr)) {
169 if (failed(
context.convertGlobalVariable(expr))) {
174 if (
auto globalOp =
context.globalVariables.lookup(&expr))
175 return moore::GetGlobalVariableOp::create(builder, loc, globalOp);
177 mlir::emitError(loc) <<
"Failed to access static member variable "
178 << expr.name <<
" as a global variable";
183 mlir::Value instRef =
context.getImplicitThisRef();
185 mlir::emitError(loc) <<
"class property '" << expr.name
186 <<
"' referenced without an implicit 'this'";
190 auto fieldSym = mlir::FlatSymbolRefAttr::get(builder.getContext(), expr.name);
192 moore::ClassHandleType classTy =
193 cast<moore::ClassHandleType>(instRef.getType());
195 auto targetClassHandle =
196 context.getAncestorClassWithProperty(classTy, expr.name, loc);
197 if (!targetClassHandle)
200 auto upcastRef =
context.materializeConversion(targetClassHandle, instRef,
201 false, instRef.getLoc());
205 Value fieldRef = moore::ClassPropertyRefOp::create(builder, loc, fieldRefTy,
206 upcastRef, fieldSym);
218 ExprVisitor(
Context &context, Location loc,
bool isLvalue)
219 : context(context), loc(loc), builder(context.builder),
220 isLvalue(isLvalue) {}
226 Value convertLvalueOrRvalueExpression(
const slang::ast::Expression &expr) {
234 Value materializeSymbolRvalue(
const slang::ast::ValueSymbol &sym) {
236 if (isa<moore::RefType>(value.getType())) {
237 auto readOp = moore::ReadOp::create(builder, loc, value);
240 return readOp.getResult();
246 auto ref = moore::GetGlobalVariableOp::create(builder, loc, globalOp);
247 auto readOp = moore::ReadOp::create(builder, loc, ref);
250 return readOp.getResult();
253 if (
auto *
const property = sym.as_if<slang::ast::ClassPropertySymbol>()) {
255 auto readOp = moore::ReadOp::create(builder, loc, fieldRef);
258 return readOp.getResult();
264 Value visit(
const slang::ast::NewArrayExpression &expr) {
269 if (expr.initExpr()) {
271 <<
"unsupported expression: array `new` with initializer\n";
276 expr.sizeExpr(), context.
convertType(*expr.sizeExpr().type));
280 return moore::OpenUArrayCreateOp::create(builder, loc, type, initialSize);
284 Value visit(
const slang::ast::ElementSelectExpression &expr) {
286 auto value = convertLvalueOrRvalueExpression(expr.value());
291 auto derefType = value.getType();
293 derefType = cast<moore::RefType>(derefType).getNestedType();
295 if (!isa<moore::IntType, moore::ArrayType, moore::UnpackedArrayType,
296 moore::QueueType, moore::AssocArrayType, moore::StringType,
297 moore::OpenUnpackedArrayType>(derefType)) {
298 mlir::emitError(loc) <<
"unsupported expression: element select into "
299 << expr.value().type->toString() <<
"\n";
304 if (isa<moore::AssocArrayType>(derefType)) {
305 auto assocArray = cast<moore::AssocArrayType>(derefType);
306 auto expectedIndexType = assocArray.getIndexType();
312 if (givenIndex.getType() != expectedIndexType) {
314 <<
"Incorrect index type: expected index type of "
315 << expectedIndexType <<
" but was given " << givenIndex.getType();
319 return moore::AssocArrayExtractRefOp::create(
320 builder, loc, moore::RefType::get(cast<moore::UnpackedType>(type)),
323 return moore::AssocArrayExtractOp::create(builder, loc, type, value,
328 if (isa<moore::StringType>(derefType)) {
330 mlir::emitError(loc) <<
"string index assignment not supported";
335 auto i32Type = moore::IntType::getInt(builder.getContext(), 32);
341 return moore::StringGetOp::create(builder, loc, value, index);
345 isLvalue ? moore::RefType::get(cast<moore::UnpackedType>(type)) : type;
346 auto range = expr.value().type->getFixedRange();
347 if (
auto *constValue = expr.selector().getConstant();
348 constValue && constValue->isInteger()) {
349 assert(!constValue->hasUnknown());
350 assert(constValue->size() <= 32);
352 auto lowBit = constValue->integer().as<uint32_t>().value();
354 return llvm::TypeSwitch<Type, Value>(derefType)
355 .Case<moore::QueueType>([&](moore::QueueType) {
357 <<
"Unexpected LValue extract on Queue Type!";
361 return moore::ExtractRefOp::create(builder, loc, resultType,
363 range.translateIndex(lowBit));
366 return llvm::TypeSwitch<Type, Value>(derefType)
367 .Case<moore::QueueType>([&](moore::QueueType) {
369 <<
"Unexpected RValue extract on Queue Type!";
373 return moore::ExtractOp::create(builder, loc, resultType, value,
374 range.translateIndex(lowBit));
381 llvm::scope_exit restoreQueue([&] { context.
currentQueue = savedQueue; });
382 if (isa<moore::QueueType>(derefType)) {
385 if (isa<moore::RefType>(value.getType())) {
386 context.
currentQueue = moore::ReadOp::create(builder, loc, value);
397 return llvm::TypeSwitch<Type, Value>(derefType)
398 .Case<moore::QueueType>([&](moore::QueueType) {
399 return moore::DynQueueRefElementOp::create(builder, loc, resultType,
403 return moore::DynExtractRefOp::create(builder, loc, resultType,
408 return llvm::TypeSwitch<Type, Value>(derefType)
409 .Case<moore::QueueType>([&](moore::QueueType) {
410 return moore::DynQueueExtractOp::create(builder, loc, resultType,
411 value, lowBit, lowBit);
414 return moore::DynExtractOp::create(builder, loc, resultType, value,
421 Value visit(
const slang::ast::NullLiteral &expr) {
423 if (isa<moore::ClassHandleType, moore::ChandleType, moore::EventType,
424 moore::NullType>(type))
425 return moore::NullOp::create(builder, loc);
426 mlir::emitError(loc) <<
"No null value definition found for value of type "
432 Value visit(
const slang::ast::RangeSelectExpression &expr) {
434 auto value = convertLvalueOrRvalueExpression(expr.value());
438 auto derefType = value.getType();
440 derefType = cast<moore::RefType>(derefType).getNestedType();
442 if (isa<moore::QueueType>(derefType)) {
443 return handleQueueRangeSelectExpressions(expr, type, value);
445 return handleArrayRangeSelectExpressions(expr, type, value);
450 Value handleQueueRangeSelectExpressions(
451 const slang::ast::RangeSelectExpression &expr, Type type, Value value) {
453 llvm::scope_exit restoreQueue([&] { context.
currentQueue = savedQueue; });
459 isLvalue ? moore::RefType::get(cast<moore::UnpackedType>(type)) : type;
462 mlir::emitError(loc) <<
"queue lvalue range selections are not supported";
465 return moore::DynQueueExtractOp::create(builder, loc, resultType, value,
471 Value handleArrayRangeSelectExpressions(
472 const slang::ast::RangeSelectExpression &expr, Type type, Value value) {
473 std::optional<int32_t> constLeft;
474 std::optional<int32_t> constRight;
475 if (
auto *constant = expr.left().getConstant())
476 constLeft = constant->integer().as<int32_t>();
477 if (
auto *constant = expr.right().getConstant())
478 constRight = constant->integer().as<int32_t>();
484 <<
"unsupported expression: range select with non-constant bounds";
504 int32_t offsetConst = 0;
505 auto range = expr.value().type->getFixedRange();
507 using slang::ast::RangeSelectionKind;
508 if (expr.getSelectionKind() == RangeSelectionKind::Simple) {
513 assert(constRight &&
"constness checked in slang");
514 offsetConst = *constRight;
525 offsetConst = *constLeft;
536 int32_t offsetAdd = 0;
541 if (expr.getSelectionKind() == RangeSelectionKind::IndexedDown &&
542 range.isLittleEndian()) {
543 assert(constRight &&
"constness checked in slang");
544 offsetAdd = 1 - *constRight;
550 if (expr.getSelectionKind() == RangeSelectionKind::IndexedUp &&
551 !range.isLittleEndian()) {
552 assert(constRight &&
"constness checked in slang");
553 offsetAdd = *constRight - 1;
557 if (offsetAdd != 0) {
559 offsetDyn = moore::AddOp::create(
560 builder, loc, offsetDyn,
561 moore::ConstantOp::create(
562 builder, loc, cast<moore::IntType>(offsetDyn.getType()),
566 offsetConst += offsetAdd;
577 isLvalue ? moore::RefType::get(cast<moore::UnpackedType>(type)) : type;
582 return moore::DynExtractRefOp::create(builder, loc, resultType, value,
585 return moore::DynExtractOp::create(builder, loc, resultType, value,
589 offsetConst = range.translateIndex(offsetConst);
591 return moore::ExtractRefOp::create(builder, loc, resultType, value,
594 return moore::ExtractOp::create(builder, loc, resultType, value,
601 Value visit(
const slang::ast::ConcatenationExpression &expr) {
602 SmallVector<Value> operands;
603 if (expr.type->isString()) {
604 for (
auto *operand : expr.operands()) {
605 assert(!isLvalue &&
"checked by Slang");
606 auto value = convertLvalueOrRvalueExpression(*operand);
610 moore::StringType::get(context.
getContext()), value,
false,
614 operands.push_back(value);
616 return moore::StringConcatOp::create(builder, loc, operands);
618 if (expr.type->isQueue()) {
619 return handleQueueConcat(expr);
622 if (expr.type->isUnpackedArray()) {
623 assert(!isLvalue &&
"checked by Slang");
624 auto loweredType = context.
convertType(*expr.type, loc);
629 if (
auto arrayType = dyn_cast<moore::UnpackedArrayType>(loweredType))
631 else if (
auto openType =
632 dyn_cast<moore::OpenUnpackedArrayType>(loweredType))
637 SmallVector<Value> operands;
638 for (
auto *operand : expr.operands()) {
639 if (operand->type->isVoid())
644 operands.push_back(value);
647 auto arrayType = moore::UnpackedArrayType::get(
649 return moore::ArrayCreateOp::create(builder, loc, arrayType, operands);
652 for (
auto *operand : expr.operands()) {
656 if (operand->type->isVoid())
658 auto value = convertLvalueOrRvalueExpression(*operand);
665 operands.push_back(value);
668 return moore::ConcatRefOp::create(builder, loc, operands);
670 return moore::ConcatOp::create(builder, loc, operands);
677 Value handleQueueConcat(
const slang::ast::ConcatenationExpression &expr) {
678 SmallVector<Value> operands;
681 cast<moore::QueueType>(context.
convertType(*expr.type, loc));
693 Value contigElements;
695 for (
auto *operand : expr.operands()) {
696 bool isSingleElement =
701 if (!isSingleElement && contigElements) {
702 operands.push_back(moore::ReadOp::create(builder, loc, contigElements));
706 assert(!isLvalue &&
"checked by Slang");
707 auto value = convertLvalueOrRvalueExpression(*operand);
715 moore::RefType::get(context.
getContext(), queueType);
717 if (!contigElements) {
719 moore::VariableOp::create(builder, loc, queueRefType, {}, {});
721 moore::QueuePushBackOp::create(builder, loc, contigElements, value);
729 if (!(isa<moore::QueueType>(value.getType()) &&
730 cast<moore::QueueType>(value.getType()).getElementType() ==
736 operands.push_back(value);
739 if (contigElements) {
740 operands.push_back(moore::ReadOp::create(builder, loc, contigElements));
743 return moore::QueueConcatOp::create(builder, loc, queueType, operands);
747 Value visit(
const slang::ast::MemberAccessExpression &expr) {
752 auto *valueType = expr.value().type.get();
753 auto memberName = builder.getStringAttr(expr.member.name);
759 if (valueType->isVirtualInterface()) {
760 auto memberType = dyn_cast<moore::UnpackedType>(type);
763 <<
"unsupported virtual interface member type: " << type;
766 auto resultRefType = moore::RefType::get(memberType);
774 auto memberRef = moore::StructExtractOp::create(
775 builder, loc, resultRefType, memberName, base);
778 return moore::ReadOp::create(builder, loc, memberRef);
782 if (valueType->isStruct()) {
784 isLvalue ? moore::RefType::get(cast<moore::UnpackedType>(type))
786 auto value = convertLvalueOrRvalueExpression(expr.value());
791 return moore::StructExtractRefOp::create(builder, loc, resultType,
793 return moore::StructExtractOp::create(builder, loc, resultType,
798 if (valueType->isPackedUnion() || valueType->isUnpackedUnion()) {
800 isLvalue ? moore::RefType::get(cast<moore::UnpackedType>(type))
802 auto value = convertLvalueOrRvalueExpression(expr.value());
807 return moore::UnionExtractRefOp::create(builder, loc, resultType,
809 return moore::UnionExtractOp::create(builder, loc, type, memberName,
814 if (valueType->isClass()) {
818 auto targetTy = cast<moore::ClassHandleType>(valTy);
830 if (expr.member.kind != slang::ast::SymbolKind::Parameter) {
836 moore::ClassHandleType upcastTargetTy =
850 auto fieldSym = mlir::FlatSymbolRefAttr::get(builder.getContext(),
852 auto fieldRefTy = moore::RefType::get(cast<moore::UnpackedType>(type));
856 Value fieldRef = moore::ClassPropertyRefOp::create(
857 builder, loc, fieldRefTy, baseVal, fieldSym);
860 return isLvalue ? fieldRef
861 : moore::ReadOp::create(builder, loc, fieldRef);
864 slang::ConstantValue constVal;
865 if (
auto param = expr.member.as_if<slang::ast::ParameterSymbol>()) {
866 constVal = param->getValue();
871 mlir::emitError(loc) <<
"Parameter " << expr.member.name
872 <<
" has no constant value";
876 mlir::emitError(loc,
"expression of type ")
877 << valueType->toString() <<
" has no member fields";
889struct RvalueExprVisitor :
public ExprVisitor {
891 : ExprVisitor(
context, loc, false) {}
892 using ExprVisitor::visit;
895 Value visit(
const slang::ast::LValueReferenceExpression &expr) {
896 assert(!
context.lvalueStack.empty() &&
"parent assignments push lvalue");
897 auto lvalue =
context.lvalueStack.back();
898 return moore::ReadOp::create(builder, loc, lvalue);
902 Value visit(
const slang::ast::NamedValueExpression &expr) {
904 if (
auto value =
context.valueSymbols.lookup(&expr.symbol)) {
905 if (isa<moore::RefType>(value.getType())) {
906 auto readOp = moore::ReadOp::create(builder, loc, value);
907 if (
context.rvalueReadCallback)
908 context.rvalueReadCallback(readOp);
909 value = readOp.getResult();
915 if (
auto globalOp =
context.globalVariables.lookup(&expr.symbol)) {
916 auto value = moore::GetGlobalVariableOp::create(builder, loc, globalOp);
917 return moore::ReadOp::create(builder, loc, value);
921 if (
auto *
const property =
922 expr.symbol.as_if<slang::ast::ClassPropertySymbol>()) {
924 return moore::ReadOp::create(builder, loc, fieldRef).getResult();
931 if (
auto access =
context.virtualIfaceMembers.lookup(&expr.symbol);
933 auto type =
context.convertType(*expr.type);
936 auto memberType = dyn_cast<moore::UnpackedType>(type);
939 <<
"unsupported virtual interface member type: " << type;
943 Value base = materializeSymbolRvalue(*access.base);
945 auto d = mlir::emitError(loc,
"unknown name `")
946 << access.base->name <<
"`";
947 d.attachNote(
context.convertLocation(access.base->location))
948 <<
"no rvalue generated for virtual interface base";
952 auto fieldName = access.fieldName
954 : builder.getStringAttr(expr.symbol.name);
955 auto memberRefType = moore::RefType::get(memberType);
956 auto memberRef = moore::StructExtractOp::create(
957 builder, loc, memberRefType, fieldName, base);
958 auto readOp = moore::ReadOp::create(builder, loc, memberRef);
959 if (
context.rvalueReadCallback)
960 context.rvalueReadCallback(readOp);
961 return readOp.getResult();
965 auto constant =
context.evaluateConstant(expr);
966 if (
auto value =
context.materializeConstant(constant, *expr.type, loc))
971 auto d = mlir::emitError(loc,
"unknown name `") << expr.symbol.name <<
"`";
972 d.attachNote(
context.convertLocation(expr.symbol.location))
973 <<
"no rvalue generated for " << slang::ast::toString(expr.symbol.kind);
978 Value visit(
const slang::ast::HierarchicalValueExpression &expr) {
979 auto hierLoc =
context.convertLocation(expr.symbol.location);
985 if (!expr.ref.path.empty()) {
986 if (
auto *inst = expr.ref.path.front()
987 .symbol->as_if<slang::ast::InstanceSymbol>()) {
989 expr.symbol.getParentScope()->getContainingInstance();
990 if (&inst->body == symbolBody ||
991 (symbolBody && inst->body.getDeclaringDefinition() ==
992 symbolBody->getDeclaringDefinition())) {
993 if (
auto value =
context.valueSymbols.lookup(&expr.symbol)) {
994 if (isa<moore::RefType>(value.getType())) {
995 auto readOp = moore::ReadOp::create(builder, hierLoc, value);
996 if (
context.rvalueReadCallback)
997 context.rvalueReadCallback(readOp);
998 value = readOp.getResult();
1012 if (
auto key =
context.buildHierValueKey(expr)) {
1013 if (
auto it =
context.hierValueSymbols.find(*key);
1014 it !=
context.hierValueSymbols.end()) {
1015 auto value = it->second;
1016 if (isa<moore::RefType>(value.getType())) {
1017 auto readOp = moore::ReadOp::create(builder, hierLoc, value);
1018 if (
context.rvalueReadCallback)
1019 context.rvalueReadCallback(readOp);
1020 value = readOp.getResult();
1027 if (
auto value =
context.valueSymbols.lookup(&expr.symbol)) {
1028 if (isa<moore::RefType>(value.getType())) {
1029 auto readOp = moore::ReadOp::create(builder, hierLoc, value);
1030 if (
context.rvalueReadCallback)
1031 context.rvalueReadCallback(readOp);
1032 value = readOp.getResult();
1038 if (isa<moore::RefType>(value.getType())) {
1039 auto readOp = moore::ReadOp::create(builder, hierLoc, value);
1040 if (
context.rvalueReadCallback)
1041 context.rvalueReadCallback(readOp);
1042 return readOp.getResult();
1048 auto constant =
context.evaluateConstant(expr);
1049 if (
auto value =
context.materializeConstant(constant, *expr.type, loc))
1054 auto d = mlir::emitError(loc,
"unknown hierarchical name `")
1055 << expr.symbol.name <<
"`";
1056 d.attachNote(hierLoc) <<
"no rvalue generated for "
1057 << slang::ast::toString(expr.symbol.kind);
1063 Value visit(
const slang::ast::ArbitrarySymbolExpression &expr) {
1064 const auto &canonTy = expr.type->getCanonicalType();
1065 if (
const auto *vi = canonTy.as_if<slang::ast::VirtualInterfaceType>()) {
1066 auto value =
context.materializeVirtualInterfaceValue(*vi, loc);
1072 mlir::emitError(loc) <<
"unsupported arbitrary symbol expression of type "
1073 << expr.type->toString();
1078 Value visit(
const slang::ast::ConversionExpression &expr) {
1079 auto type =
context.convertType(*expr.type);
1082 return context.convertRvalueExpression(expr.operand(), type);
1086 Value visit(
const slang::ast::AssignmentExpression &expr) {
1087 auto lhs =
context.convertLvalueExpression(expr.left());
1092 context.lvalueStack.push_back(lhs);
1093 auto rhs =
context.convertRvalueExpression(
1094 expr.right(), cast<moore::RefType>(lhs.getType()).getNestedType());
1095 context.lvalueStack.pop_back();
1102 if (!expr.isNonBlocking()) {
1103 if (expr.timingControl)
1104 if (failed(
context.convertTimingControl(*expr.timingControl)))
1106 auto assignOp = moore::BlockingAssignOp::create(builder, loc, lhs, rhs);
1107 if (
context.variableAssignCallback)
1108 context.variableAssignCallback(assignOp);
1113 if (expr.timingControl) {
1115 if (
auto *ctrl = expr.timingControl->as_if<slang::ast::DelayControl>()) {
1116 auto delay =
context.convertRvalueExpression(
1117 ctrl->expr, moore::TimeType::get(builder.getContext()));
1120 auto assignOp = moore::DelayedNonBlockingAssignOp::create(
1121 builder, loc, lhs, rhs, delay);
1122 if (
context.variableAssignCallback)
1123 context.variableAssignCallback(assignOp);
1128 auto loc =
context.convertLocation(expr.timingControl->sourceRange);
1129 mlir::emitError(loc)
1130 <<
"unsupported non-blocking assignment timing control: "
1131 << slang::ast::toString(expr.timingControl->kind);
1134 auto assignOp = moore::NonBlockingAssignOp::create(builder, loc, lhs, rhs);
1135 if (
context.variableAssignCallback)
1136 context.variableAssignCallback(assignOp);
1142 template <
class ConcreteOp>
1143 Value createReduction(Value arg,
bool invert) {
1144 arg =
context.convertToSimpleBitVector(arg);
1147 Value result = ConcreteOp::create(builder, loc, arg);
1149 result = moore::NotOp::create(builder, loc, result);
1154 Value createIncrement(Value arg,
bool isInc,
bool isPost) {
1155 auto preValue = moore::ReadOp::create(builder, loc, arg);
1161 postValue = moore::NotOp::create(builder, loc, preValue).getResult();
1164 auto one = moore::ConstantOp::create(
1165 builder, loc, cast<moore::IntType>(preValue.getType()), 1);
1167 isInc ? moore::AddOp::create(builder, loc, preValue, one).getResult()
1168 : moore::SubOp::create(builder, loc, preValue, one).getResult();
1170 moore::BlockingAssignOp::create(builder, loc, arg, postValue);
1171 if (
context.variableAssignCallback)
1172 context.variableAssignCallback(assignOp);
1181 Value createRealIncrement(Value arg,
bool isInc,
bool isPost) {
1182 Value preValue = moore::ReadOp::create(builder, loc, arg);
1185 bool isTime = isa<moore::TimeType>(preValue.getType());
1187 preValue =
context.materializeConversion(
1188 moore::RealType::get(
context.getContext(), moore::RealWidth::f64),
1189 preValue,
false, loc);
1191 moore::RealType realTy =
1192 llvm::dyn_cast<moore::RealType>(preValue.getType());
1197 if (realTy.getWidth() == moore::RealWidth::f32) {
1198 oneAttr = builder.getFloatAttr(builder.getF32Type(), 1.0);
1199 }
else if (realTy.getWidth() == moore::RealWidth::f64) {
1201 oneAttr = builder.getFloatAttr(builder.getF64Type(), oneVal);
1203 mlir::emitError(loc) <<
"cannot construct increment for " << realTy;
1206 auto one = moore::ConstantRealOp::create(builder, loc, oneAttr);
1210 ? moore::AddRealOp::create(builder, loc, preValue, one).getResult()
1211 : moore::SubRealOp::create(builder, loc, preValue, one).getResult();
1214 postValue =
context.materializeConversion(
1215 moore::TimeType::get(
context.getContext()), postValue,
false, loc);
1218 moore::BlockingAssignOp::create(builder, loc, arg, postValue);
1220 if (
context.variableAssignCallback)
1221 context.variableAssignCallback(assignOp);
1228 Value visitRealUOp(
const slang::ast::UnaryExpression &expr) {
1229 Type opFTy =
context.convertType(*expr.operand().type);
1231 using slang::ast::UnaryOperator;
1233 if (expr.op == UnaryOperator::Preincrement ||
1234 expr.op == UnaryOperator::Predecrement ||
1235 expr.op == UnaryOperator::Postincrement ||
1236 expr.op == UnaryOperator::Postdecrement)
1237 arg =
context.convertLvalueExpression(expr.operand());
1239 arg =
context.convertRvalueExpression(expr.operand(), opFTy);
1244 if (isa<moore::TimeType>(arg.getType()))
1245 arg =
context.materializeConversion(
1246 moore::RealType::get(
context.getContext(), moore::RealWidth::f64),
1251 case UnaryOperator::Plus:
1253 case UnaryOperator::Minus:
1254 return moore::NegRealOp::create(builder, loc, arg);
1256 case UnaryOperator::Preincrement:
1257 return createRealIncrement(arg,
true,
false);
1258 case UnaryOperator::Predecrement:
1259 return createRealIncrement(arg,
false,
false);
1260 case UnaryOperator::Postincrement:
1261 return createRealIncrement(arg,
true,
true);
1262 case UnaryOperator::Postdecrement:
1263 return createRealIncrement(arg,
false,
true);
1265 case UnaryOperator::LogicalNot:
1266 arg =
context.convertToBool(arg);
1269 return moore::NotOp::create(builder, loc, arg);
1272 mlir::emitError(loc) <<
"Unary operator " << slang::ast::toString(expr.op)
1273 <<
" not supported with real values!\n";
1279 Value visit(
const slang::ast::UnaryExpression &expr) {
1281 const auto *floatType =
1282 expr.operand().type->as_if<slang::ast::FloatingType>();
1285 return visitRealUOp(expr);
1287 using slang::ast::UnaryOperator;
1289 if (expr.op == UnaryOperator::Preincrement ||
1290 expr.op == UnaryOperator::Predecrement ||
1291 expr.op == UnaryOperator::Postincrement ||
1292 expr.op == UnaryOperator::Postdecrement)
1293 arg =
context.convertLvalueExpression(expr.operand());
1295 arg =
context.convertRvalueExpression(expr.operand());
1302 case UnaryOperator::Plus:
1303 return context.convertToSimpleBitVector(arg);
1305 case UnaryOperator::Minus:
1306 arg =
context.convertToSimpleBitVector(arg);
1309 return moore::NegOp::create(builder, loc, arg);
1311 case UnaryOperator::BitwiseNot:
1312 arg =
context.convertToSimpleBitVector(arg);
1315 return moore::NotOp::create(builder, loc, arg);
1317 case UnaryOperator::BitwiseAnd:
1318 return createReduction<moore::ReduceAndOp>(arg,
false);
1319 case UnaryOperator::BitwiseOr:
1320 return createReduction<moore::ReduceOrOp>(arg,
false);
1321 case UnaryOperator::BitwiseXor:
1322 return createReduction<moore::ReduceXorOp>(arg,
false);
1323 case UnaryOperator::BitwiseNand:
1324 return createReduction<moore::ReduceAndOp>(arg,
true);
1325 case UnaryOperator::BitwiseNor:
1326 return createReduction<moore::ReduceOrOp>(arg,
true);
1327 case UnaryOperator::BitwiseXnor:
1328 return createReduction<moore::ReduceXorOp>(arg,
true);
1330 case UnaryOperator::LogicalNot:
1331 arg =
context.convertToBool(arg);
1334 return moore::NotOp::create(builder, loc, arg);
1336 case UnaryOperator::Preincrement:
1337 return createIncrement(arg,
true,
false);
1338 case UnaryOperator::Predecrement:
1339 return createIncrement(arg,
false,
false);
1340 case UnaryOperator::Postincrement:
1341 return createIncrement(arg,
true,
true);
1342 case UnaryOperator::Postdecrement:
1343 return createIncrement(arg,
false,
true);
1346 mlir::emitError(loc,
"unsupported unary operator");
1351 Value buildLogicalBOp(slang::ast::BinaryOperator op, Value lhs, Value rhs,
1352 std::optional<Domain> domain = std::nullopt) {
1353 using slang::ast::BinaryOperator;
1357 lhs =
context.convertToBool(lhs, domain.value());
1358 rhs =
context.convertToBool(rhs, domain.value());
1360 lhs =
context.convertToBool(lhs);
1361 rhs =
context.convertToBool(rhs);
1368 case BinaryOperator::LogicalAnd:
1369 return moore::AndOp::create(builder, loc, lhs, rhs);
1371 case BinaryOperator::LogicalOr:
1372 return moore::OrOp::create(builder, loc, lhs, rhs);
1374 case BinaryOperator::LogicalImplication: {
1376 auto notLHS = moore::NotOp::create(builder, loc, lhs);
1377 return moore::OrOp::create(builder, loc, notLHS, rhs);
1380 case BinaryOperator::LogicalEquivalence: {
1382 auto notLHS = moore::NotOp::create(builder, loc, lhs);
1383 auto notRHS = moore::NotOp::create(builder, loc, rhs);
1384 auto both = moore::AndOp::create(builder, loc, lhs, rhs);
1385 auto notBoth = moore::AndOp::create(builder, loc, notLHS, notRHS);
1386 return moore::OrOp::create(builder, loc, both, notBoth);
1390 llvm_unreachable(
"not a logical BinaryOperator");
1394 Value visitHandleBOp(
const slang::ast::BinaryExpression &expr) {
1396 auto lhs =
context.convertRvalueExpression(expr.left());
1399 auto rhs =
context.convertRvalueExpression(expr.right());
1403 using slang::ast::BinaryOperator;
1406 case BinaryOperator::Equality:
1407 return moore::HandleEqOp::create(builder, loc, lhs, rhs);
1408 case BinaryOperator::Inequality:
1409 return moore::HandleNeOp::create(builder, loc, lhs, rhs);
1410 case BinaryOperator::CaseEquality:
1411 return moore::HandleCaseEqOp::create(builder, loc, lhs, rhs);
1412 case BinaryOperator::CaseInequality:
1413 return moore::HandleCaseNeOp::create(builder, loc, lhs, rhs);
1416 mlir::emitError(loc)
1417 <<
"Binary operator " << slang::ast::toString(expr.op)
1418 <<
" not supported with class handle valued operands!\n";
1423 Value visitRealBOp(
const slang::ast::BinaryExpression &expr) {
1425 auto lhs =
context.convertRvalueExpression(expr.left());
1428 auto rhs =
context.convertRvalueExpression(expr.right());
1432 if (isa<moore::TimeType>(lhs.getType()) ||
1433 isa<moore::TimeType>(rhs.getType())) {
1434 lhs =
context.materializeConversion(
1435 moore::RealType::get(
context.getContext(), moore::RealWidth::f64),
1437 rhs =
context.materializeConversion(
1438 moore::RealType::get(
context.getContext(), moore::RealWidth::f64),
1442 using slang::ast::BinaryOperator;
1444 case BinaryOperator::Add:
1445 return moore::AddRealOp::create(builder, loc, lhs, rhs);
1446 case BinaryOperator::Subtract:
1447 return moore::SubRealOp::create(builder, loc, lhs, rhs);
1448 case BinaryOperator::Multiply:
1449 return moore::MulRealOp::create(builder, loc, lhs, rhs);
1450 case BinaryOperator::Divide:
1451 return moore::DivRealOp::create(builder, loc, lhs, rhs);
1452 case BinaryOperator::Power:
1453 return moore::PowRealOp::create(builder, loc, lhs, rhs);
1455 case BinaryOperator::Equality:
1456 return moore::EqRealOp::create(builder, loc, lhs, rhs);
1457 case BinaryOperator::Inequality:
1458 return moore::NeRealOp::create(builder, loc, lhs, rhs);
1460 case BinaryOperator::GreaterThan:
1461 return moore::FgtOp::create(builder, loc, lhs, rhs);
1462 case BinaryOperator::LessThan:
1463 return moore::FltOp::create(builder, loc, lhs, rhs);
1464 case BinaryOperator::GreaterThanEqual:
1465 return moore::FgeOp::create(builder, loc, lhs, rhs);
1466 case BinaryOperator::LessThanEqual:
1467 return moore::FleOp::create(builder, loc, lhs, rhs);
1469 case BinaryOperator::LogicalAnd:
1470 case BinaryOperator::LogicalOr:
1471 case BinaryOperator::LogicalImplication:
1472 case BinaryOperator::LogicalEquivalence:
1473 return buildLogicalBOp(expr.op, lhs, rhs);
1476 mlir::emitError(loc) <<
"Binary operator "
1477 << slang::ast::toString(expr.op)
1478 <<
" not supported with real valued operands!\n";
1485 template <
class ConcreteOp>
1486 Value createBinary(Value lhs, Value rhs) {
1487 lhs =
context.convertToSimpleBitVector(lhs);
1490 rhs =
context.convertToSimpleBitVector(rhs);
1493 return ConcreteOp::create(builder, loc, lhs, rhs);
1497 Value visit(
const slang::ast::BinaryExpression &expr) {
1498 if (expr.left().kind == slang::ast::ExpressionKind::TypeReference &&
1499 expr.right().kind == slang::ast::ExpressionKind::TypeReference) {
1501 expr.left().as<slang::ast::TypeReferenceExpression>().targetType;
1503 expr.right().as<slang::ast::TypeReferenceExpression>().targetType;
1504 bool value = lhsType.isMatching(rhsType);
1506 using slang::ast::BinaryOperator;
1508 case BinaryOperator::Equality:
1509 case BinaryOperator::CaseEquality:
1511 case BinaryOperator::Inequality:
1512 case BinaryOperator::CaseInequality:
1516 mlir::emitError(loc,
"unsupported type reference binary operator");
1520 auto type = moore::IntType::get(
context.getContext(), 1,
1521 moore::Domain::TwoValued);
1522 return moore::ConstantOp::create(builder, loc, type, value,
1527 const auto *rhsFloatType =
1528 expr.right().type->as_if<slang::ast::FloatingType>();
1529 const auto *lhsFloatType =
1530 expr.left().type->as_if<slang::ast::FloatingType>();
1533 if (rhsFloatType || lhsFloatType)
1534 return visitRealBOp(expr);
1537 const auto rhsIsClass = expr.right().type->isClass();
1538 const auto lhsIsClass = expr.left().type->isClass();
1539 const auto rhsIsChandle = expr.right().type->isCHandle();
1540 const auto lhsIsChandle = expr.left().type->isCHandle();
1542 if (rhsIsClass || lhsIsClass || rhsIsChandle || lhsIsChandle)
1543 return visitHandleBOp(expr);
1545 auto lhs =
context.convertRvalueExpression(expr.left());
1548 auto rhs =
context.convertRvalueExpression(expr.right());
1553 Domain domain = Domain::TwoValued;
1554 if (expr.type->isFourState() || expr.left().type->isFourState() ||
1555 expr.right().type->isFourState())
1556 domain = Domain::FourValued;
1558 using slang::ast::BinaryOperator;
1560 case BinaryOperator::Add:
1561 return createBinary<moore::AddOp>(lhs, rhs);
1562 case BinaryOperator::Subtract:
1563 return createBinary<moore::SubOp>(lhs, rhs);
1564 case BinaryOperator::Multiply:
1565 return createBinary<moore::MulOp>(lhs, rhs);
1566 case BinaryOperator::Divide:
1567 if (expr.type->isSigned())
1568 return createBinary<moore::DivSOp>(lhs, rhs);
1570 return createBinary<moore::DivUOp>(lhs, rhs);
1571 case BinaryOperator::Mod:
1572 if (expr.type->isSigned())
1573 return createBinary<moore::ModSOp>(lhs, rhs);
1575 return createBinary<moore::ModUOp>(lhs, rhs);
1576 case BinaryOperator::Power: {
1581 auto rhsCast =
context.materializeConversion(
1582 lhs.getType(), rhs, expr.right().type->isSigned(), rhs.getLoc());
1583 if (expr.type->isSigned())
1584 return createBinary<moore::PowSOp>(lhs, rhsCast);
1586 return createBinary<moore::PowUOp>(lhs, rhsCast);
1589 case BinaryOperator::BinaryAnd:
1590 return createBinary<moore::AndOp>(lhs, rhs);
1591 case BinaryOperator::BinaryOr:
1592 return createBinary<moore::OrOp>(lhs, rhs);
1593 case BinaryOperator::BinaryXor:
1594 return createBinary<moore::XorOp>(lhs, rhs);
1595 case BinaryOperator::BinaryXnor: {
1596 auto result = createBinary<moore::XorOp>(lhs, rhs);
1599 return moore::NotOp::create(builder, loc, result);
1602 case BinaryOperator::Equality:
1603 if (isa<moore::UnpackedArrayType>(lhs.getType()))
1604 return moore::UArrayCmpOp::create(
1605 builder, loc, moore::UArrayCmpPredicate::eq, lhs, rhs);
1606 else if (isa<moore::StringType>(lhs.getType()))
1607 return moore::StringCmpOp::create(
1608 builder, loc, moore::StringCmpPredicate::eq, lhs, rhs);
1609 else if (isa<moore::QueueType>(lhs.getType()))
1610 return moore::QueueCmpOp::create(
1611 builder, loc, moore::UArrayCmpPredicate::eq, lhs, rhs);
1613 return createBinary<moore::EqOp>(lhs, rhs);
1614 case BinaryOperator::Inequality:
1615 if (isa<moore::UnpackedArrayType>(lhs.getType()))
1616 return moore::UArrayCmpOp::create(
1617 builder, loc, moore::UArrayCmpPredicate::ne, lhs, rhs);
1618 else if (isa<moore::StringType>(lhs.getType()))
1619 return moore::StringCmpOp::create(
1620 builder, loc, moore::StringCmpPredicate::ne, lhs, rhs);
1621 else if (isa<moore::QueueType>(lhs.getType()))
1622 return moore::QueueCmpOp::create(
1623 builder, loc, moore::UArrayCmpPredicate::ne, lhs, rhs);
1625 return createBinary<moore::NeOp>(lhs, rhs);
1626 case BinaryOperator::CaseEquality:
1627 return createBinary<moore::CaseEqOp>(lhs, rhs);
1628 case BinaryOperator::CaseInequality:
1629 return createBinary<moore::CaseNeOp>(lhs, rhs);
1630 case BinaryOperator::WildcardEquality:
1631 return createBinary<moore::WildcardEqOp>(lhs, rhs);
1632 case BinaryOperator::WildcardInequality:
1633 return createBinary<moore::WildcardNeOp>(lhs, rhs);
1635 case BinaryOperator::GreaterThanEqual:
1636 if (expr.left().type->isSigned())
1637 return createBinary<moore::SgeOp>(lhs, rhs);
1638 else if (isa<moore::StringType>(lhs.getType()))
1639 return moore::StringCmpOp::create(
1640 builder, loc, moore::StringCmpPredicate::ge, lhs, rhs);
1642 return createBinary<moore::UgeOp>(lhs, rhs);
1643 case BinaryOperator::GreaterThan:
1644 if (expr.left().type->isSigned())
1645 return createBinary<moore::SgtOp>(lhs, rhs);
1646 else if (isa<moore::StringType>(lhs.getType()))
1647 return moore::StringCmpOp::create(
1648 builder, loc, moore::StringCmpPredicate::gt, lhs, rhs);
1650 return createBinary<moore::UgtOp>(lhs, rhs);
1651 case BinaryOperator::LessThanEqual:
1652 if (expr.left().type->isSigned())
1653 return createBinary<moore::SleOp>(lhs, rhs);
1654 else if (isa<moore::StringType>(lhs.getType()))
1655 return moore::StringCmpOp::create(
1656 builder, loc, moore::StringCmpPredicate::le, lhs, rhs);
1658 return createBinary<moore::UleOp>(lhs, rhs);
1659 case BinaryOperator::LessThan:
1660 if (expr.left().type->isSigned())
1661 return createBinary<moore::SltOp>(lhs, rhs);
1662 else if (isa<moore::StringType>(lhs.getType()))
1663 return moore::StringCmpOp::create(
1664 builder, loc, moore::StringCmpPredicate::lt, lhs, rhs);
1666 return createBinary<moore::UltOp>(lhs, rhs);
1668 case BinaryOperator::LogicalAnd:
1669 case BinaryOperator::LogicalOr:
1670 case BinaryOperator::LogicalImplication:
1671 case BinaryOperator::LogicalEquivalence:
1672 return buildLogicalBOp(expr.op, lhs, rhs, domain);
1674 case BinaryOperator::LogicalShiftLeft:
1675 return createBinary<moore::ShlOp>(lhs, rhs);
1676 case BinaryOperator::LogicalShiftRight:
1677 return createBinary<moore::ShrOp>(lhs, rhs);
1678 case BinaryOperator::ArithmeticShiftLeft:
1679 return createBinary<moore::ShlOp>(lhs, rhs);
1680 case BinaryOperator::ArithmeticShiftRight: {
1683 lhs =
context.convertToSimpleBitVector(lhs);
1684 rhs =
context.convertToSimpleBitVector(rhs);
1687 if (expr.type->isSigned())
1688 return moore::AShrOp::create(builder, loc, lhs, rhs);
1689 return moore::ShrOp::create(builder, loc, lhs, rhs);
1693 mlir::emitError(loc,
"unsupported binary operator");
1698 Value visit(
const slang::ast::UnbasedUnsizedIntegerLiteral &expr) {
1699 return context.materializeSVInt(expr.getValue(), *expr.type, loc);
1703 Value visit(
const slang::ast::IntegerLiteral &expr) {
1704 return context.materializeSVInt(expr.getValue(), *expr.type, loc);
1708 Value visit(
const slang::ast::TimeLiteral &expr) {
1713 double value = std::round(expr.getValue() * scale);
1723 static constexpr uint64_t limit =
1724 (std::numeric_limits<uint64_t>::max() >> 11) << 11;
1725 if (value > limit) {
1726 mlir::emitError(loc) <<
"time value is larger than " << limit <<
" fs";
1730 return moore::ConstantTimeOp::create(builder, loc,
1731 static_cast<uint64_t
>(value));
1735 Value visit(
const slang::ast::ReplicationExpression &expr) {
1736 auto type =
context.convertType(*expr.type);
1737 auto value =
context.convertRvalueExpression(expr.concat());
1740 return moore::ReplicateOp::create(builder, loc, type, value);
1744 Value visit(
const slang::ast::InsideExpression &expr) {
1745 auto lhs =
context.convertToSimpleBitVector(
1746 context.convertRvalueExpression(expr.left()));
1751 SmallVector<Value> conditions;
1754 for (
const auto *listExpr : expr.rangeList()) {
1755 auto cond =
context.convertInsideCheck(lhs, loc, *listExpr);
1759 conditions.push_back(cond);
1763 auto result = conditions.back();
1764 conditions.pop_back();
1765 while (!conditions.empty()) {
1766 result = moore::OrOp::create(builder, loc, conditions.back(), result);
1767 conditions.pop_back();
1773 Value visit(
const slang::ast::ConditionalExpression &expr) {
1774 auto type =
context.convertType(*expr.type);
1777 if (expr.conditions.size() > 1) {
1778 mlir::emitError(loc)
1779 <<
"unsupported conditional expression with more than one condition";
1782 const auto &cond = expr.conditions[0];
1784 mlir::emitError(loc) <<
"unsupported conditional expression with pattern";
1788 context.convertToBool(
context.convertRvalueExpression(*cond.expr));
1791 auto conditionalOp =
1792 moore::ConditionalOp::create(builder, loc, type, value);
1795 auto &trueBlock = conditionalOp.getTrueRegion().emplaceBlock();
1796 auto &falseBlock = conditionalOp.getFalseRegion().emplaceBlock();
1798 OpBuilder::InsertionGuard g(builder);
1801 builder.setInsertionPointToStart(&trueBlock);
1802 auto trueValue =
context.convertRvalueExpression(expr.left(), type);
1805 moore::YieldOp::create(builder, loc, trueValue);
1808 builder.setInsertionPointToStart(&falseBlock);
1809 auto falseValue =
context.convertRvalueExpression(expr.right(), type);
1812 moore::YieldOp::create(builder, loc, falseValue);
1814 return conditionalOp.getResult();
1818 Value visit(
const slang::ast::CallExpression &expr) {
1820 auto constant =
context.evaluateConstant(expr);
1821 if (
auto value =
context.materializeConstant(constant, *expr.type, loc))
1825 [&](
auto &subroutine) {
return visitCall(expr, subroutine); },
1831 std::pair<Value, moore::ClassHandleType>
1832 getMethodReceiverTypeHandle(
const slang::ast::CallExpression &expr) {
1834 moore::ClassHandleType handleTy;
1838 if (
const slang::ast::Expression *recvExpr = expr.thisClass()) {
1839 thisRef =
context.convertRvalueExpression(*recvExpr);
1844 thisRef =
context.getImplicitThisRef();
1846 mlir::emitError(loc) <<
"method '" << expr.getSubroutineName()
1847 <<
"' called without an object";
1851 handleTy = cast<moore::ClassHandleType>(thisRef.getType());
1852 return {thisRef, handleTy};
1856 mlir::CallOpInterface
1857 buildMethodCall(
const slang::ast::SubroutineSymbol *subroutine,
1859 moore::ClassHandleType actualHandleTy, Value actualThisRef,
1860 SmallVector<Value> &arguments,
1861 SmallVector<Type> &resultTypes) {
1864 auto funcTy = cast<FunctionType>(lowering->
op.getFunctionType());
1865 auto expected0 = funcTy.getInput(0);
1866 auto expectedHdlTy = cast<moore::ClassHandleType>(expected0);
1869 auto implicitThisRef =
context.materializeConversion(
1870 expectedHdlTy, actualThisRef,
false, actualThisRef.getLoc());
1873 SmallVector<Value> explicitArguments;
1874 explicitArguments.reserve(arguments.size() + 1);
1875 explicitArguments.push_back(implicitThisRef);
1876 explicitArguments.append(arguments.begin(), arguments.end());
1879 const bool isVirtual =
1880 (subroutine->flags & slang::ast::MethodFlags::Virtual) != 0;
1883 auto calleeSym = lowering->
op.getNameAttr().getValue();
1884 if (isa<moore::CoroutineOp>(lowering->
op.getOperation()))
1885 return moore::CallCoroutineOp::create(builder, loc, resultTypes,
1886 calleeSym, explicitArguments);
1887 return mlir::func::CallOp::create(builder, loc, resultTypes, calleeSym,
1891 auto funcName = subroutine->name;
1892 auto method = moore::VTableLoadMethodOp::create(
1893 builder, loc, funcTy, actualThisRef,
1894 SymbolRefAttr::get(
context.getContext(), funcName));
1895 return mlir::func::CallIndirectOp::create(builder, loc, method,
1900 Value visitCall(
const slang::ast::CallExpression &expr,
1901 const slang::ast::SubroutineSymbol *subroutine) {
1903 const bool isMethod = (subroutine->thisVar !=
nullptr);
1905 auto *lowering =
context.declareFunction(*subroutine);
1909 if (isa<moore::DPIFuncOp>(lowering->
op.getOperation())) {
1910 SmallVector<Value> operands;
1911 SmallVector<Value> resultTargets;
1913 for (
auto [callArg, declArg] :
1914 llvm::zip(expr.arguments(), subroutine->getArguments())) {
1915 auto *actual = callArg;
1916 if (
const auto *assign =
1917 actual->as_if<slang::ast::AssignmentExpression>())
1918 actual = &assign->left();
1920 auto argType =
context.convertType(declArg->getType());
1924 switch (declArg->direction) {
1925 case slang::ast::ArgumentDirection::In: {
1926 auto value =
context.convertRvalueExpression(*actual, argType);
1929 operands.push_back(value);
1932 case slang::ast::ArgumentDirection::Out: {
1933 auto lvalue =
context.convertLvalueExpression(*actual);
1936 resultTargets.push_back(lvalue);
1939 case slang::ast::ArgumentDirection::InOut:
1940 case slang::ast::ArgumentDirection::Ref: {
1941 auto lvalue =
context.convertLvalueExpression(*actual);
1944 auto value =
context.convertRvalueExpression(*actual, argType);
1947 operands.push_back(value);
1948 resultTargets.push_back(lvalue);
1954 SmallVector<Type> resultTypes(
1955 cast<FunctionType>(lowering->
op.getFunctionType()).getResults());
1956 auto callOp = moore::FuncDPICallOp::create(
1957 builder, loc, resultTypes,
1958 SymbolRefAttr::get(lowering->
op.getNameAttr()), operands);
1960 unsigned resultIndex = 0;
1961 unsigned targetIndex = 0;
1962 for (
const auto *declArg : subroutine->getArguments()) {
1963 auto argType =
context.convertType(declArg->getType());
1967 switch (declArg->direction) {
1968 case slang::ast::ArgumentDirection::Out:
1969 case slang::ast::ArgumentDirection::InOut:
1970 case slang::ast::ArgumentDirection::Ref: {
1971 auto lvalue = resultTargets[targetIndex++];
1972 auto refTy = dyn_cast<moore::RefType>(lvalue.getType());
1974 lowering->
op->emitError(
1975 "expected DPI output target to be moore::RefType");
1978 auto converted =
context.materializeConversion(
1979 refTy.getNestedType(), callOp->getResult(resultIndex++),
1980 declArg->getType().isSigned(), loc);
1983 moore::BlockingAssignOp::create(builder, loc, lvalue, converted);
1991 if (!subroutine->getReturnType().isVoid())
1992 return callOp->getResult(resultIndex);
1994 return mlir::UnrealizedConversionCastOp::create(
1995 builder, loc, moore::VoidType::get(
context.getContext()),
2003 SmallVector<Value> arguments;
2004 for (
auto [callArg, declArg] :
2005 llvm::zip(expr.arguments(), subroutine->getArguments())) {
2009 auto *expr = callArg;
2010 if (
const auto *assign = expr->as_if<slang::ast::AssignmentExpression>())
2011 expr = &assign->left();
2014 auto type =
context.convertType(declArg->getType());
2015 if (declArg->direction == slang::ast::ArgumentDirection::In) {
2016 value =
context.convertRvalueExpression(*expr, type);
2018 Value lvalue =
context.convertLvalueExpression(*expr);
2019 auto unpackedType = dyn_cast<moore::UnpackedType>(type);
2023 context.materializeConversion(moore::RefType::get(unpackedType),
2024 lvalue, expr->type->isSigned(), loc);
2028 arguments.push_back(value);
2035 for (
auto *sym : lowering->capturedSymbols) {
2036 Value val =
context.valueSymbols.lookup(sym);
2038 mlir::emitError(loc) <<
"failed to resolve captured variable `"
2039 << sym->name <<
"` at call site";
2042 arguments.push_back(val);
2046 SmallVector<Type> resultTypes(
2047 cast<FunctionType>(lowering->
op.getFunctionType()).getResults().begin(),
2048 cast<FunctionType>(lowering->
op.getFunctionType()).getResults().end());
2050 mlir::CallOpInterface callOp;
2054 auto [thisRef, tyHandle] = getMethodReceiverTypeHandle(expr);
2055 callOp = buildMethodCall(subroutine, lowering, tyHandle, thisRef,
2056 arguments, resultTypes);
2057 }
else if (isa<moore::CoroutineOp>(lowering->
op.getOperation())) {
2059 auto coroutine = cast<moore::CoroutineOp>(lowering->
op.getOperation());
2061 moore::CallCoroutineOp::create(builder, loc, coroutine, arguments);
2064 auto funcOp = cast<mlir::func::FuncOp>(lowering->
op.getOperation());
2065 callOp = mlir::func::CallOp::create(builder, loc, funcOp, arguments);
2068 auto result = resultTypes.size() > 0 ? callOp->getOpResult(0) : Value{};
2072 if (resultTypes.size() == 0)
2073 return mlir::UnrealizedConversionCastOp::create(
2074 builder, loc, moore::VoidType::get(
context.getContext()),
2082 Value visitCall(
const slang::ast::CallExpression &expr,
2083 const slang::ast::CallExpression::SystemCallInfo &info) {
2084 using ksn = slang::parsing::KnownSystemName;
2085 const auto &subroutine = *
info.subroutine;
2086 auto nameId = subroutine.knownNameId;
2098 return context.convertAssertionCallExpression(expr, info, loc);
2103 auto args = expr.arguments();
2111 if (nameId == ksn::SFormatF) {
2113 auto fmtValue =
context.convertFormatString(
2114 expr.arguments(), loc, moore::IntFormat::Decimal,
false);
2115 if (failed(fmtValue))
2117 return fmtValue.value();
2121 auto result =
context.convertSystemCall(subroutine, loc, args);
2125 auto ty =
context.convertType(*expr.type);
2129 bool isSigned = expr.type->isSigned();
2130 if (nameId == ksn::CountOnes || nameId == ksn::IsUnknown ||
2131 nameId == ksn::OneHot || nameId == ksn::OneHot0)
2133 return context.materializeConversion(ty, result, isSigned, loc);
2137 Value visit(
const slang::ast::StringLiteral &expr) {
2138 auto type =
context.convertType(*expr.type);
2139 return moore::ConstantStringOp::create(builder, loc, type, expr.getValue());
2143 Value visit(
const slang::ast::RealLiteral &expr) {
2144 auto fTy = mlir::Float64Type::get(
context.getContext());
2145 auto attr = mlir::FloatAttr::get(fTy, expr.getValue());
2146 return moore::ConstantRealOp::create(builder, loc, attr).getResult();
2151 FailureOr<SmallVector<Value>>
2152 convertElements(
const slang::ast::AssignmentPatternExpressionBase &expr,
2153 std::variant<Type, ArrayRef<Type>> expectedTypes,
2154 unsigned replCount) {
2155 const auto &elts = expr.elements();
2156 const size_t elementCount = elts.size();
2159 const bool hasBroadcast =
2160 std::holds_alternative<Type>(expectedTypes) &&
2161 static_cast<bool>(std::get<Type>(expectedTypes));
2163 const bool hasPerElem =
2164 std::holds_alternative<ArrayRef<Type>>(expectedTypes) &&
2165 !std::get<ArrayRef<Type>>(expectedTypes).empty();
2169 auto types = std::get<ArrayRef<Type>>(expectedTypes);
2170 if (types.size() != elementCount) {
2171 mlir::emitError(loc)
2172 <<
"assignment pattern arity mismatch: expected " << types.size()
2173 <<
" elements, got " << elementCount;
2178 SmallVector<Value> converted;
2179 converted.reserve(elementCount * std::max(1u, replCount));
2182 if (!hasBroadcast && !hasPerElem) {
2184 for (
const auto *elementExpr : elts) {
2185 Value v =
context.convertRvalueExpression(*elementExpr);
2188 converted.push_back(v);
2190 }
else if (hasBroadcast) {
2192 Type want = std::get<Type>(expectedTypes);
2193 for (
const auto *elementExpr : elts) {
2194 Value v = want ?
context.convertRvalueExpression(*elementExpr, want)
2195 :
context.convertRvalueExpression(*elementExpr);
2198 converted.push_back(v);
2201 auto types = std::get<ArrayRef<Type>>(expectedTypes);
2202 for (
size_t i = 0; i < elementCount; ++i) {
2203 Type want = types[i];
2204 const auto *elementExpr = elts[i];
2205 Value v = want ?
context.convertRvalueExpression(*elementExpr, want)
2206 :
context.convertRvalueExpression(*elementExpr);
2209 converted.push_back(v);
2213 for (
unsigned i = 1; i < replCount; ++i)
2214 converted.append(converted.begin(), converted.begin() + elementCount);
2220 Value visitAssignmentPattern(
2221 const slang::ast::AssignmentPatternExpressionBase &expr,
2222 unsigned replCount = 1) {
2223 auto type =
context.convertType(*expr.type);
2224 const auto &elts = expr.elements();
2227 if (
auto intType = dyn_cast<moore::IntType>(type)) {
2228 auto elements = convertElements(expr, {}, replCount);
2230 if (failed(elements))
2233 assert(intType.getWidth() == elements->size());
2234 std::reverse(elements->begin(), elements->end());
2235 return moore::ConcatOp::create(builder, loc, intType, *elements);
2239 if (
auto structType = dyn_cast<moore::StructType>(type)) {
2240 SmallVector<Type> expectedTy;
2241 expectedTy.reserve(structType.getMembers().size());
2242 for (
auto member : structType.getMembers())
2243 expectedTy.push_back(member.type);
2245 FailureOr<SmallVector<Value>> elements;
2246 if (expectedTy.size() == elts.size())
2247 elements = convertElements(expr, expectedTy, replCount);
2249 elements = convertElements(expr, {}, replCount);
2251 if (failed(elements))
2254 assert(structType.getMembers().size() == elements->size());
2255 return moore::StructCreateOp::create(builder, loc, structType, *elements);
2259 if (
auto structType = dyn_cast<moore::UnpackedStructType>(type)) {
2260 SmallVector<Type> expectedTy;
2261 expectedTy.reserve(structType.getMembers().size());
2262 for (
auto member : structType.getMembers())
2263 expectedTy.push_back(member.type);
2265 FailureOr<SmallVector<Value>> elements;
2266 if (expectedTy.size() == elts.size())
2267 elements = convertElements(expr, expectedTy, replCount);
2269 elements = convertElements(expr, {}, replCount);
2271 if (failed(elements))
2274 assert(structType.getMembers().size() == elements->size());
2276 return moore::StructCreateOp::create(builder, loc, structType, *elements);
2280 if (
auto arrayType = dyn_cast<moore::ArrayType>(type)) {
2282 convertElements(expr, arrayType.getElementType(), replCount);
2284 if (failed(elements))
2287 assert(arrayType.getSize() == elements->size());
2288 return moore::ArrayCreateOp::create(builder, loc, arrayType, *elements);
2292 if (
auto arrayType = dyn_cast<moore::UnpackedArrayType>(type)) {
2294 convertElements(expr, arrayType.getElementType(), replCount);
2296 if (failed(elements))
2299 assert(arrayType.getSize() == elements->size());
2300 return moore::ArrayCreateOp::create(builder, loc, arrayType, *elements);
2304 if (
auto openType = dyn_cast<moore::OpenUnpackedArrayType>(type)) {
2306 convertElements(expr, openType.getElementType(), replCount);
2308 if (failed(elements))
2311 auto arrayType = moore::UnpackedArrayType::get(
2312 context.getContext(), elements->size(), openType.getElementType());
2313 return moore::ArrayCreateOp::create(builder, loc, arrayType, *elements);
2316 mlir::emitError(loc) <<
"unsupported assignment pattern with type " << type;
2320 Value visit(
const slang::ast::SimpleAssignmentPatternExpression &expr) {
2321 return visitAssignmentPattern(expr);
2324 Value visit(
const slang::ast::StructuredAssignmentPatternExpression &expr) {
2325 return visitAssignmentPattern(expr);
2328 Value visit(
const slang::ast::ReplicatedAssignmentPatternExpression &expr) {
2330 context.evaluateConstant(expr.count()).integer().as<
unsigned>();
2331 assert(count &&
"Slang guarantees constant non-zero replication count");
2332 return visitAssignmentPattern(expr, *count);
2335 Value visit(
const slang::ast::StreamingConcatenationExpression &expr) {
2336 SmallVector<Value> operands;
2337 for (
auto stream : expr.streams()) {
2338 auto operandLoc =
context.convertLocation(stream.operand->sourceRange);
2339 if (!stream.constantWithWidth.has_value() && stream.withExpr) {
2340 mlir::emitError(operandLoc)
2341 <<
"Moore only support streaming "
2342 "concatenation with fixed size 'with expression'";
2346 if (stream.constantWithWidth.has_value()) {
2347 value =
context.convertRvalueExpression(*stream.withExpr);
2348 auto type = cast<moore::UnpackedType>(value.getType());
2349 auto intType = moore::IntType::get(
2350 context.getContext(), type.getBitSize().value(), type.getDomain());
2352 value =
context.materializeConversion(intType, value,
false, loc);
2354 value =
context.convertRvalueExpression(*stream.operand);
2357 value =
context.convertToSimpleBitVector(value);
2360 operands.push_back(value);
2364 if (operands.size() == 1) {
2367 value = operands.front();
2369 value = moore::ConcatOp::create(builder, loc, operands).getResult();
2372 if (expr.getSliceSize() == 0) {
2376 auto type = cast<moore::IntType>(value.getType());
2377 SmallVector<Value> slicedOperands;
2378 auto iterMax = type.getWidth() / expr.getSliceSize();
2379 auto remainSize = type.getWidth() % expr.getSliceSize();
2381 for (
size_t i = 0; i < iterMax; i++) {
2382 auto extractResultType = moore::IntType::get(
2383 context.getContext(), expr.getSliceSize(), type.getDomain());
2385 auto extracted = moore::ExtractOp::create(builder, loc, extractResultType,
2386 value, i * expr.getSliceSize());
2387 slicedOperands.push_back(extracted);
2391 auto extractResultType = moore::IntType::get(
2392 context.getContext(), remainSize, type.getDomain());
2395 moore::ExtractOp::create(builder, loc, extractResultType, value,
2396 iterMax * expr.getSliceSize());
2397 slicedOperands.push_back(extracted);
2400 return moore::ConcatOp::create(builder, loc, slicedOperands);
2403 Value visit(
const slang::ast::AssertionInstanceExpression &expr) {
2404 return context.convertAssertionExpression(expr.body, loc);
2407 Value visit(
const slang::ast::UnboundedLiteral &expr) {
2409 "slang checks $ only used within queue index expression");
2413 moore::QueueSizeBIOp::create(builder, loc,
context.getIndexedQueue());
2414 auto one = moore::ConstantOp::create(builder, loc, queueSize.getType(), 1);
2415 auto lastElement = moore::SubOp::create(builder, loc, queueSize, one);
2432 Value visit(
const slang::ast::NewClassExpression &expr) {
2433 auto type =
context.convertType(*expr.type);
2434 auto classTy = dyn_cast<moore::ClassHandleType>(type);
2440 if (!classTy && expr.isSuperClass) {
2441 newObj =
context.getImplicitThisRef();
2442 if (!newObj || !newObj.getType() ||
2443 !isa<moore::ClassHandleType>(newObj.getType())) {
2444 mlir::emitError(loc) <<
"implicit this ref was not set while "
2445 "converting new class function";
2448 auto thisType = cast<moore::ClassHandleType>(newObj.getType());
2450 cast<moore::ClassDeclOp>(*
context.symbolTable.lookupNearestSymbolFrom(
2451 context.intoModuleOp, thisType.getClassSym()));
2452 auto baseClassSym = classDecl.getBase();
2453 classTy = circt::moore::ClassHandleType::get(
context.getContext(),
2454 baseClassSym.value());
2457 newObj = moore::ClassNewOp::create(builder, loc, classTy, {});
2460 const auto *constructor = expr.constructorCall();
2465 if (
const auto *callConstructor =
2466 constructor->as_if<slang::ast::CallExpression>())
2467 if (
const auto *subroutine =
2468 std::get_if<const slang::ast::SubroutineSymbol *>(
2469 &callConstructor->subroutine)) {
2470 if (!(*subroutine)->thisVar) {
2471 mlir::emitError(loc)
2472 <<
"unsupported constructor call without `this` argument";
2476 llvm::SaveAndRestore saveThis(
context.currentThisRef, newObj);
2477 if (!visitCall(*callConstructor, *subroutine))
2485 template <
typename T>
2486 Value visit(T &&node) {
2487 mlir::emitError(loc,
"unsupported expression: ")
2488 << slang::ast::toString(node.kind);
2492 Value visitInvalid(
const slang::ast::Expression &expr) {
2493 mlir::emitError(loc,
"invalid expression");
2504struct LvalueExprVisitor :
public ExprVisitor {
2506 : ExprVisitor(
context, loc, true) {}
2507 using ExprVisitor::visit;
2510 Value visit(
const slang::ast::NamedValueExpression &expr) {
2512 if (
auto value =
context.valueSymbols.lookup(&expr.symbol))
2516 if (
auto globalOp =
context.globalVariables.lookup(&expr.symbol))
2517 return moore::GetGlobalVariableOp::create(builder, loc, globalOp);
2519 if (
auto *
const property =
2520 expr.symbol.as_if<slang::ast::ClassPropertySymbol>()) {
2524 if (
auto access =
context.virtualIfaceMembers.lookup(&expr.symbol);
2526 auto type =
context.convertType(*expr.type);
2529 auto memberType = dyn_cast<moore::UnpackedType>(type);
2531 mlir::emitError(loc)
2532 <<
"unsupported virtual interface member type: " << type;
2536 Value base = materializeSymbolRvalue(*access.base);
2538 auto d = mlir::emitError(loc,
"unknown name `")
2539 << access.base->name <<
"`";
2540 d.attachNote(
context.convertLocation(access.base->location))
2541 <<
"no rvalue generated for virtual interface base";
2545 auto fieldName = access.fieldName
2547 : builder.getStringAttr(expr.symbol.name);
2548 auto memberRefType = moore::RefType::get(memberType);
2549 return moore::StructExtractOp::create(builder, loc, memberRefType,
2553 auto d = mlir::emitError(loc,
"unknown name `") << expr.symbol.name <<
"`";
2554 d.attachNote(
context.convertLocation(expr.symbol.location))
2555 <<
"no lvalue generated for " << slang::ast::toString(expr.symbol.kind);
2560 Value visit(
const slang::ast::HierarchicalValueExpression &expr) {
2563 if (!expr.ref.path.empty()) {
2564 if (
auto *inst = expr.ref.path.front()
2565 .symbol->as_if<slang::ast::InstanceSymbol>()) {
2567 expr.symbol.getParentScope()->getContainingInstance();
2568 if (&inst->body == symbolBody ||
2569 (symbolBody && inst->body.getDeclaringDefinition() ==
2570 symbolBody->getDeclaringDefinition())) {
2571 if (
auto value =
context.valueSymbols.lookup(&expr.symbol))
2580 if (
auto key =
context.buildHierValueKey(expr)) {
2581 if (
auto it =
context.hierValueSymbols.find(*key);
2582 it !=
context.hierValueSymbols.end())
2587 if (
auto value =
context.valueSymbols.lookup(&expr.symbol))
2594 if (
auto globalOp =
context.globalVariables.lookup(&expr.symbol))
2595 return moore::GetGlobalVariableOp::create(builder, loc, globalOp);
2599 auto d = mlir::emitError(loc,
"unknown hierarchical name `")
2600 << expr.symbol.name <<
"`";
2601 d.attachNote(
context.convertLocation(expr.symbol.location))
2602 <<
"no lvalue generated for " << slang::ast::toString(expr.symbol.kind);
2606 Value visit(
const slang::ast::StreamingConcatenationExpression &expr) {
2607 SmallVector<Value> operands;
2608 for (
auto stream : expr.streams()) {
2609 auto operandLoc =
context.convertLocation(stream.operand->sourceRange);
2610 if (!stream.constantWithWidth.has_value() && stream.withExpr) {
2611 mlir::emitError(operandLoc)
2612 <<
"Moore only support streaming "
2613 "concatenation with fixed size 'with expression'";
2617 if (stream.constantWithWidth.has_value()) {
2618 value =
context.convertLvalueExpression(*stream.withExpr);
2619 auto type = cast<moore::UnpackedType>(
2620 cast<moore::RefType>(value.getType()).getNestedType());
2621 auto intType = moore::RefType::get(moore::IntType::get(
2622 context.getContext(), type.getBitSize().value(), type.getDomain()));
2624 value =
context.materializeConversion(intType, value,
false, loc);
2626 value =
context.convertLvalueExpression(*stream.operand);
2631 operands.push_back(value);
2634 if (operands.size() == 1) {
2637 value = operands.front();
2639 value = moore::ConcatRefOp::create(builder, loc, operands).getResult();
2642 if (expr.getSliceSize() == 0) {
2646 auto type = cast<moore::IntType>(
2647 cast<moore::RefType>(value.getType()).getNestedType());
2648 SmallVector<Value> slicedOperands;
2649 auto widthSum = type.getWidth();
2650 auto domain = type.getDomain();
2651 auto iterMax = widthSum / expr.getSliceSize();
2652 auto remainSize = widthSum % expr.getSliceSize();
2654 for (
size_t i = 0; i < iterMax; i++) {
2655 auto extractResultType = moore::RefType::get(moore::IntType::get(
2656 context.getContext(), expr.getSliceSize(), domain));
2658 auto extracted = moore::ExtractRefOp::create(
2659 builder, loc, extractResultType, value, i * expr.getSliceSize());
2660 slicedOperands.push_back(extracted);
2664 auto extractResultType = moore::RefType::get(
2665 moore::IntType::get(
context.getContext(), remainSize, domain));
2668 moore::ExtractRefOp::create(builder, loc, extractResultType, value,
2669 iterMax * expr.getSliceSize());
2670 slicedOperands.push_back(extracted);
2673 return moore::ConcatRefOp::create(builder, loc, slicedOperands);
2677 template <
typename T>
2678 Value visit(T &&node) {
2679 return context.convertRvalueExpression(node);
2682 Value visitInvalid(
const slang::ast::Expression &expr) {
2683 mlir::emitError(loc,
"invalid expression");
2693std::optional<std::pair<const slang::ast::InstanceSymbol *, mlir::StringAttr>>
2694Context::buildHierValueKey(
2695 const slang::ast::HierarchicalValueExpression &expr) {
2696 if (expr.ref.path.empty())
2697 return std::nullopt;
2699 const slang::ast::InstanceSymbol *firstInst =
nullptr;
2700 SmallVector<StringRef, 4> names;
2701 for (
auto &elem : expr.ref.path) {
2702 if (
auto *inst = elem.symbol->as_if<slang::ast::InstanceSymbol>()) {
2706 names.push_back(inst->name);
2710 names.push_back(expr.symbol.name);
2711 std::string hierName = llvm::join(names,
".");
2714 return std::nullopt;
2715 return std::make_pair(firstInst,
builder.getStringAttr(hierName));
2723 Type requiredType) {
2725 auto value = expr.visit(RvalueExprVisitor(*
this, loc));
2726 if (value && requiredType)
2734 return expr.visit(LvalueExprVisitor(*
this, loc));
2742 if (
auto type = dyn_cast_or_null<moore::IntType>(value.getType()))
2743 if (type.getBitSize() == 1)
2745 if (
auto type = dyn_cast_or_null<moore::UnpackedType>(value.getType()))
2746 return moore::BoolCastOp::create(
builder, value.getLoc(), value);
2747 mlir::emitError(value.getLoc(),
"expression of type ")
2748 << value.getType() <<
" cannot be cast to a boolean";
2754 const slang::ast::Type &astType,
2756 const auto *floatType = astType.as_if<slang::ast::FloatingType>();
2760 if (svreal.isShortReal() &&
2761 floatType->floatKind == slang::ast::FloatingType::ShortReal) {
2762 attr = FloatAttr::get(
builder.getF32Type(), svreal.shortReal().v);
2763 }
else if (svreal.isReal() &&
2764 floatType->floatKind == slang::ast::FloatingType::Real) {
2765 attr = FloatAttr::get(
builder.getF64Type(), svreal.real().v);
2767 mlir::emitError(loc) <<
"invalid real constant";
2771 return moore::ConstantRealOp::create(
builder, loc, attr);
2776 const slang::ast::Type &astType,
2778 slang::ConstantValue intVal = stringLiteral.convertToInt();
2779 auto effectiveWidth = intVal.getEffectiveWidth();
2780 if (!effectiveWidth)
2783 auto intTy = moore::IntType::getInt(
getContext(), effectiveWidth.value());
2785 if (astType.isString()) {
2786 auto immInt = moore::ConstantStringOp::create(
builder, loc, intTy,
2787 stringLiteral.toString())
2789 return moore::IntToStringOp::create(
builder, loc, immInt).getResult();
2796 const slang::ast::Type &astType, Location loc) {
2801 bool typeIsFourValued =
false;
2802 if (
auto unpackedType = dyn_cast<moore::UnpackedType>(type))
2806 auto intType = moore::IntType::get(
getContext(), fvint.getBitWidth(),
2807 fvint.hasUnknown() || typeIsFourValued
2810 auto result = moore::ConstantOp::create(
builder, loc, intType, fvint);
2815 const slang::ConstantValue &constant,
2816 const slang::ast::FixedSizeUnpackedArrayType &astType, Location loc) {
2823 if (astType.elementType.isString()) {
2824 auto arrayType = dyn_cast<moore::UnpackedArrayType>(type);
2828 SmallVector<Value> elemVals;
2829 for (
const auto &elem : constant.elements()) {
2830 if (!elem.isString())
2835 elemVals.push_back(value);
2837 if (elemVals.size() != arrayType.getSize())
2839 return moore::ArrayCreateOp::create(
builder, loc, arrayType, elemVals);
2844 if (astType.elementType.isIntegral())
2845 bitWidth = astType.elementType.getBitWidth();
2849 bool typeIsFourValued =
false;
2852 if (
auto unpackedType = dyn_cast<moore::UnpackedType>(type))
2863 auto intType = moore::IntType::get(
getContext(), bitWidth, domain);
2865 auto arrType = moore::UnpackedArrayType::get(
2866 getContext(), constant.elements().size(), intType);
2868 llvm::SmallVector<mlir::Value> elemVals;
2869 moore::ConstantOp constOp;
2871 mlir::OpBuilder::InsertionGuard guard(
builder);
2874 for (
auto elem : constant.elements()) {
2876 constOp = moore::ConstantOp::create(
builder, loc, intType, fvInt);
2877 elemVals.push_back(constOp.getResult());
2882 auto arrayOp = moore::ArrayCreateOp::create(
builder, loc, arrType, elemVals);
2884 return arrayOp.getResult();
2888 const slang::ast::Type &type, Location loc) {
2890 if (
auto *arr = type.as_if<slang::ast::FixedSizeUnpackedArrayType>())
2892 if (constant.isInteger())
2894 if (constant.isReal() || constant.isShortReal())
2896 if (constant.isString())
2904 using slang::ast::EvalFlags;
2905 slang::ast::EvalContext evalContext(
2907 slang::ast::LookupLocation::max),
2908 EvalFlags::CacheResults | EvalFlags::SpecparamsAllowed);
2909 return expr.eval(evalContext);
2918 auto type = moore::IntType::get(
getContext(), 1, domain);
2925 if (isa<moore::IntType>(value.getType()))
2932 if (
auto packed = dyn_cast<moore::PackedType>(value.getType()))
2933 if (
auto sbvType = packed.getSimpleBitVector())
2936 mlir::emitError(value.getLoc()) <<
"expression of type " << value.getType()
2937 <<
" cannot be cast to a simple bit vector";
2945 Location loc,
bool fallible) {
2946 if (isa<moore::IntType>(value.getType()))
2949 auto &builder =
context.builder;
2950 auto packedType = cast<moore::PackedType>(value.getType());
2951 auto intType = packedType.getSimpleBitVector();
2956 if (isa<moore::TimeType>(packedType) &&
2958 value = builder.createOrFold<moore::TimeToLogicOp>(loc, value);
2959 auto scale = moore::ConstantOp::create(builder, loc, intType,
2961 return builder.createOrFold<moore::DivUOp>(loc, value, scale);
2967 if (packedType.containsTimeType()) {
2969 mlir::emitError(loc) <<
"unsupported conversion: " << packedType
2970 <<
" cannot be converted to " << intType
2971 <<
"; contains a time type";
2976 return builder.createOrFold<moore::PackedToSBVOp>(loc, value);
2984 Value value, Location loc,
2986 if (value.getType() == packedType)
2989 auto &builder =
context.builder;
2990 auto intType = cast<moore::IntType>(value.getType());
2995 if (isa<moore::TimeType>(packedType) &&
2997 auto scale = moore::ConstantOp::create(builder, loc, intType,
2999 value = builder.createOrFold<moore::MulOp>(loc, value, scale);
3000 return builder.createOrFold<moore::LogicToTimeOp>(loc, value);
3008 mlir::emitError(loc) <<
"unsupported conversion: " << intType
3009 <<
" cannot be converted to " << packedType
3010 <<
"; contains a time type";
3015 return builder.createOrFold<moore::SBVToPackedOp>(loc, packedType, value);
3021 moore::ClassHandleType expectedHandleTy) {
3022 auto loc = actualHandle.getLoc();
3024 auto actualTy = actualHandle.getType();
3025 auto actualHandleTy = dyn_cast<moore::ClassHandleType>(actualTy);
3026 if (!actualHandleTy) {
3027 mlir::emitError(loc) <<
"expected a !moore.class<...> value, got "
3033 if (actualHandleTy == expectedHandleTy)
3034 return actualHandle;
3036 if (!
context.isClassDerivedFrom(actualHandleTy, expectedHandleTy)) {
3037 mlir::emitError(loc)
3038 <<
"receiver class " << actualHandleTy.getClassSym()
3039 <<
" is not the same as, or derived from, expected base class "
3040 << expectedHandleTy.getClassSym().getRootReference();
3045 auto casted = moore::ClassUpcastOp::create(
context.builder, loc,
3046 expectedHandleTy, actualHandle)
3052 Location loc,
bool fallible) {
3054 if (type == value.getType())
3059 auto dstPacked = dyn_cast<moore::PackedType>(type);
3060 auto srcPacked = dyn_cast<moore::PackedType>(value.getType());
3061 auto dstInt = dstPacked ? dstPacked.getSimpleBitVector() : moore::IntType();
3062 auto srcInt = srcPacked ? srcPacked.getSimpleBitVector() : moore::IntType();
3064 if (dstInt && srcInt) {
3072 auto resizedType = moore::IntType::get(
3073 value.getContext(), dstInt.getWidth(), srcPacked.getDomain());
3074 if (dstInt.getWidth() < srcInt.getWidth()) {
3075 value =
builder.createOrFold<moore::TruncOp>(loc, resizedType, value);
3076 }
else if (dstInt.getWidth() > srcInt.getWidth()) {
3078 value =
builder.createOrFold<moore::SExtOp>(loc, resizedType, value);
3080 value =
builder.createOrFold<moore::ZExtOp>(loc, resizedType, value);
3084 if (dstInt.getDomain() != srcInt.getDomain()) {
3086 value =
builder.createOrFold<moore::LogicToIntOp>(loc, value);
3088 value =
builder.createOrFold<moore::IntToLogicOp>(loc, value);
3097 assert(value.getType() == type);
3102 if (isa<moore::StringType>(type) &&
3103 isa<moore::FormatStringType>(value.getType())) {
3104 return builder.createOrFold<moore::FormatStringToStringOp>(loc, value);
3108 if (isa<moore::FormatStringType>(type) &&
3109 isa<moore::StringType>(value.getType())) {
3110 return builder.createOrFold<moore::FormatStringOp>(loc, value);
3115 if (isa<moore::QueueType>(type) && isa<moore::QueueType>(value.getType()) &&
3116 cast<moore::QueueType>(type).getElementType() ==
3117 cast<moore::QueueType>(value.getType()).getElementType())
3118 return builder.createOrFold<moore::QueueResizeOp>(loc, type, value);
3121 if (isa<moore::QueueType>(type) &&
3122 isa<moore::UnpackedArrayType>(value.getType())) {
3123 auto queueElType = dyn_cast<moore::QueueType>(type).getElementType();
3124 auto unpackedArrayElType =
3125 dyn_cast<moore::UnpackedArrayType>(value.getType()).getElementType();
3127 if (queueElType == unpackedArrayElType) {
3128 return builder.createOrFold<moore::QueueFromUnpackedArrayOp>(loc, type,
3134 if (dstInt && isa<moore::RealType>(value.getType())) {
3135 auto twoValInt =
builder.createOrFold<moore::RealToIntOp>(
3136 loc, dstInt.getTwoValued(), value);
3141 if (isa<moore::RealType>(type) && isa<moore::IntType>(value.getType())) {
3144 if (dyn_cast<moore::IntType>(value.getType()).getDomain() ==
3149 dyn_cast<moore::IntType>(value.getType()).getTwoValued(), value,
true,
3153 return builder.createOrFold<moore::SIntToRealOp>(loc, type, twoValInt);
3154 return builder.createOrFold<moore::UIntToRealOp>(loc, type, twoValInt);
3157 auto getBuiltinFloatType = [&](moore::RealType type) -> Type {
3159 return mlir::Float32Type::get(
builder.getContext());
3161 return mlir::Float64Type::get(
builder.getContext());
3165 if (isa<moore::TimeType>(type) && isa<moore::RealType>(value.getType())) {
3167 moore::IntType::get(
builder.getContext(), 64, Domain::TwoValued);
3169 getBuiltinFloatType(cast<moore::RealType>(value.getType()));
3170 auto scale = moore::ConstantRealOp::create(
3171 builder, loc, value.getType(),
3173 auto scaled =
builder.createOrFold<moore::MulRealOp>(loc, value, scale);
3174 auto asInt = moore::RealToIntOp::create(
builder, loc, intType, scaled);
3175 auto asLogic = moore::IntToLogicOp::create(
builder, loc, asInt);
3176 return moore::LogicToTimeOp::create(
builder, loc, asLogic);
3180 if (isa<moore::RealType>(type) && isa<moore::TimeType>(value.getType())) {
3181 auto asLogic = moore::TimeToLogicOp::create(
builder, loc, value);
3182 auto asInt = moore::LogicToIntOp::create(
builder, loc, asLogic);
3183 auto asReal = moore::UIntToRealOp::create(
builder, loc, type, asInt);
3184 Type floatType = getBuiltinFloatType(cast<moore::RealType>(type));
3185 auto scale = moore::ConstantRealOp::create(
3188 return moore::DivRealOp::create(
builder, loc, asReal, scale);
3192 if (isa<moore::StringType>(type)) {
3193 if (
auto intType = dyn_cast<moore::IntType>(value.getType())) {
3195 value = moore::LogicToIntOp::create(
builder, loc, value);
3196 return moore::IntToStringOp::create(
builder, loc, value);
3201 if (
auto intType = dyn_cast<moore::IntType>(type)) {
3202 if (isa<moore::StringType>(value.getType())) {
3203 value = moore::StringToIntOp::create(
builder, loc, intType.getTwoValued(),
3207 return moore::IntToLogicOp::create(
builder, loc, value);
3214 if (isa<moore::FormatStringType>(type)) {
3216 value, isSigned, loc);
3219 return moore::FormatStringOp::create(
builder, loc, asStr, {}, {}, {});
3222 if (isa<moore::RealType>(type) && isa<moore::RealType>(value.getType()))
3223 return builder.createOrFold<moore::ConvertRealOp>(loc, type, value);
3225 if (isa<moore::ClassHandleType>(type) &&
3226 isa<moore::ClassHandleType>(value.getType()))
3230 if (fallible && value.getType() != type)
3232 if (value.getType() != type)
3233 value = moore::ConversionOp::create(
builder, loc, type, value);
3239template <
typename OpTy>
3242 std::span<const slang::ast::Expression *const> args) {
3244 assert(args.size() == 1 &&
"real math builtin expects 1 argument");
3245 auto value =
context.convertRvalueExpression(*args[0]);
3248 return OpTy::create(
context.builder, loc, value);
3252 const slang::ast::SystemSubroutine &subroutine, Location loc,
3253 std::span<const slang::ast::Expression *const> args) {
3254 using ksn = slang::parsing::KnownSystemName;
3255 StringRef name = subroutine.name;
3256 auto nameId = subroutine.knownNameId;
3257 size_t numArgs = args.size();
3265 if (nameId == ksn::URandom || nameId == ksn::Random) {
3266 auto i32Ty = moore::IntType::getInt(
builder.getContext(), 32);
3267 auto minval = moore::ConstantOp::create(
builder, loc, i32Ty, 0);
3269 moore::ConstantOp::create(
builder, loc, i32Ty, APInt::getAllOnes(32));
3276 return moore::UrandomRangeBIOp::create(
builder, loc, minval, maxval, seed);
3279 if (nameId == ksn::URandomRange) {
3280 auto i32Ty = moore::IntType::getInt(
builder.getContext(), 32);
3290 minval = moore::ConstantOp::create(
builder, loc, i32Ty, 0);
3292 return moore::UrandomRangeBIOp::create(
builder, loc, minval, maxval,
3300 if (nameId == ksn::Time || nameId == ksn::STime || nameId == ksn::RealTime) {
3302 assert(numArgs == 0 &&
"time functions take no arguments");
3303 return moore::TimeBIOp::create(
builder, loc);
3310 if (nameId == ksn::Clog2) {
3312 assert(numArgs == 1 &&
"`$clog2` takes 1 argument");
3319 return moore::Clog2BIOp::create(
builder, loc, value);
3326 if (nameId == ksn::IsUnknown) {
3327 assert(numArgs == 1 &&
"`$isunknown` takes 1 argument");
3332 if (!isa<moore::IntType>(value.getType())) {
3333 if (!isa<moore::PackedType>(value.getType())) {
3334 mlir::emitError(loc) <<
"expected integer argument for `$isunknown`";
3342 auto valTy = dyn_cast<moore::IntType>(value.getType());
3346 if (nameId == ksn::OneHot0 || nameId == ksn::OneHot) {
3347 assert(numArgs == 1 &&
"`$onehot`/`$onehot0` takes 1 argument");
3351 if (!isa<moore::IntType>(value.getType())) {
3352 if (!isa<moore::PackedType>(value.getType())) {
3353 mlir::emitError(loc)
3354 <<
"expected integer argument for `$onehot`/`$onehot0`";
3362 auto valTy = dyn_cast<moore::IntType>(value.getType());
3364 mlir::emitError(loc) <<
"expected integer argument for `"
3365 << subroutine.name <<
"`";
3372 if (valTy.getDomain() == Domain::FourValued) {
3373 Value isUnknownMoore =
3376 builder.createOrFold<moore::ToBuiltinIntOp>(loc, isUnknownMoore);
3384 auto minusOne = comb::SubOp::create(
builder, loc, intVal, one);
3385 auto anded = comb::AndOp::create(
builder, loc, intVal, minusOne);
3387 Value result = comb::ICmpOp::create(
builder, loc, comb::ICmpPredicate::eq,
3388 anded, zero,
false);
3391 if (nameId == ksn::OneHot) {
3392 auto isNotZero = comb::ICmpOp::create(
3393 builder, loc, comb::ICmpPredicate::ne, intVal, zero,
false);
3394 result = comb::AndOp::create(
builder, loc, result, isNotZero);
3401 result = comb::MuxOp::create(
builder, loc, isUnknown, zeroI1, result);
3402 Value resultMoore = moore::FromBuiltinIntOp::create(
builder, loc, result);
3403 return moore::IntToLogicOp::create(
builder, loc, resultMoore).getResult();
3405 return moore::FromBuiltinIntOp::create(
builder, loc, result);
3408 if (nameId == ksn::CountOnes) {
3409 assert(numArgs == 1 &&
"`$countones` takes 1 argument");
3413 if (!isa<moore::IntType>(value.getType())) {
3414 if (!isa<moore::PackedType>(value.getType())) {
3415 mlir::emitError(loc) <<
"expected integer argument for `$countones`";
3423 auto valTy = dyn_cast<moore::IntType>(value.getType());
3425 mlir::emitError(loc) <<
"expected integer argument for `$countones`";
3433 auto builtinIntTy = cast<IntegerType>(intVal.getType());
3434 unsigned width = builtinIntTy.getWidth();
3435 unsigned resultWidth = llvm::Log2_32_Ceil(width + 1);
3436 auto i1Ty =
builder.getI1Type();
3437 unsigned padWidth = resultWidth - 1;
3439 builder.getIntegerType(padWidth), 0);
3443 Value sum = comb::ConcatOp::create(
builder, loc, ValueRange{zeros, bit0});
3445 for (
unsigned i = 1; i < width; ++i) {
3448 comb::ConcatOp::create(
builder, loc, ValueRange{zeros, bit});
3449 sum = comb::AddOp::create(
builder, loc, sum, extended);
3453 return moore::FromBuiltinIntOp::create(
builder, loc, sum);
3457 if (nameId == ksn::Ln)
3458 return convertRealMathBI<moore::LnBIOp>(*
this, loc, name, args);
3459 if (nameId == ksn::Log10)
3460 return convertRealMathBI<moore::Log10BIOp>(*
this, loc, name, args);
3461 if (nameId == ksn::Exp)
3462 return convertRealMathBI<moore::ExpBIOp>(*
this, loc, name, args);
3463 if (nameId == ksn::Sqrt)
3464 return convertRealMathBI<moore::SqrtBIOp>(*
this, loc, name, args);
3465 if (nameId == ksn::Floor)
3466 return convertRealMathBI<moore::FloorBIOp>(*
this, loc, name, args);
3467 if (nameId == ksn::Ceil)
3468 return convertRealMathBI<moore::CeilBIOp>(*
this, loc, name, args);
3469 if (nameId == ksn::Sin)
3470 return convertRealMathBI<moore::SinBIOp>(*
this, loc, name, args);
3471 if (nameId == ksn::Cos)
3472 return convertRealMathBI<moore::CosBIOp>(*
this, loc, name, args);
3473 if (nameId == ksn::Tan)
3474 return convertRealMathBI<moore::TanBIOp>(*
this, loc, name, args);
3475 if (nameId == ksn::Asin)
3476 return convertRealMathBI<moore::AsinBIOp>(*
this, loc, name, args);
3477 if (nameId == ksn::Acos)
3478 return convertRealMathBI<moore::AcosBIOp>(*
this, loc, name, args);
3479 if (nameId == ksn::Atan)
3480 return convertRealMathBI<moore::AtanBIOp>(*
this, loc, name, args);
3481 if (nameId == ksn::Sinh)
3482 return convertRealMathBI<moore::SinhBIOp>(*
this, loc, name, args);
3483 if (nameId == ksn::Cosh)
3484 return convertRealMathBI<moore::CoshBIOp>(*
this, loc, name, args);
3485 if (nameId == ksn::Tanh)
3486 return convertRealMathBI<moore::TanhBIOp>(*
this, loc, name, args);
3487 if (nameId == ksn::Asinh)
3488 return convertRealMathBI<moore::AsinhBIOp>(*
this, loc, name, args);
3489 if (nameId == ksn::Acosh)
3490 return convertRealMathBI<moore::AcoshBIOp>(*
this, loc, name, args);
3491 if (nameId == ksn::Atanh)
3492 return convertRealMathBI<moore::AtanhBIOp>(*
this, loc, name, args);
3498 if (nameId == ksn::Signed || nameId == ksn::Unsigned) {
3500 assert(numArgs == 1 &&
"`$signed`/`$unsigned` take 1 argument");
3506 if (nameId == ksn::RealToBits)
3507 return convertRealMathBI<moore::RealtobitsBIOp>(*
this, loc, name, args);
3508 if (nameId == ksn::BitsToReal)
3509 return convertRealMathBI<moore::BitstorealBIOp>(*
this, loc, name, args);
3510 if (nameId == ksn::ShortrealToBits)
3511 return convertRealMathBI<moore::ShortrealtobitsBIOp>(*
this, loc, name,
3513 if (nameId == ksn::BitsToShortreal)
3514 return convertRealMathBI<moore::BitstoshortrealBIOp>(*
this, loc, name,
3517 if (nameId == ksn::Cast) {
3518 assert(numArgs == 2 &&
"`cast` takes 2 arguments");
3519 auto *dstExpr = args[0];
3524 if (
auto *assign = dstExpr->as_if<slang::ast::AssignmentExpression>())
3525 dstExpr = &assign->left();
3534 if (isa<moore::ClassHandleType>(dstType) ||
3535 isa<moore::ClassHandleType>(src.getType())) {
3536 auto i1Ty = moore::IntType::getInt(
builder.getContext(), 1);
3537 return moore::ConstantOp::create(
builder, loc, i1Ty, 0,
3541 dstType, src, args[1]->type->isSigned(), loc,
true);
3542 auto i1Ty = moore::IntType::getInt(
builder.getContext(), 1);
3544 return moore::ConstantOp::create(
builder, loc, i1Ty, 0,
3546 moore::BlockingAssignOp::create(
builder, loc, dst, converted);
3547 return moore::ConstantOp::create(
builder, loc, i1Ty, 1,
3555 if (nameId == ksn::Len) {
3557 assert(numArgs == 1 &&
"`len` takes 1 argument");
3558 auto stringType = moore::StringType::get(
getContext());
3562 return moore::StringLenOp::create(
builder, loc, value);
3565 if (nameId == ksn::Getc) {
3567 assert(numArgs == 2 &&
"`getc` takes 2 arguments");
3568 auto stringType = moore::StringType::get(
getContext());
3573 return moore::StringGetOp::create(
builder, loc, str, index);
3576 if (nameId == ksn::ToUpper) {
3578 assert(numArgs == 1 &&
"`toupper` takes 1 argument");
3579 auto stringType = moore::StringType::get(
getContext());
3583 return moore::StringToUpperOp::create(
builder, loc, value);
3586 if (nameId == ksn::ToLower) {
3588 assert(numArgs == 1 &&
"`tolower` takes 1 argument");
3589 auto stringType = moore::StringType::get(
getContext());
3593 return moore::StringToLowerOp::create(
builder, loc, value);
3596 if (nameId == ksn::Compare || nameId == ksn::ICompare) {
3599 auto stringType = moore::StringType::get(
getContext());
3604 if (nameId == ksn::Compare)
3605 return moore::StringCompareOp::create(
builder, loc, lhs, rhs);
3606 return moore::StringICompareOp::create(
builder, loc, lhs, rhs);
3609 if (nameId == ksn::Substr) {
3611 assert(numArgs == 3 &&
"`substr` takes 3 arguments");
3612 auto stringType = moore::StringType::get(
getContext());
3616 if (!str || !start || !end)
3618 return moore::StringSubstrOp::create(
builder, loc, str, start, end);
3621 if (nameId == ksn::AToI || nameId == ksn::AToHex || nameId == ksn::AToOct ||
3622 nameId == ksn::AToBin) {
3624 assert(numArgs == 1 &&
"`atoi/hex/oct/bin` takes 1 argument");
3625 auto stringType = moore::StringType::get(
getContext());
3629 auto integerType = moore::IntType::getLogic(
builder.getContext(), 32);
3632 return moore::StringAtoiOp::create(
builder, loc, integerType, str);
3634 return moore::StringAtohexOp::create(
builder, loc, integerType, str);
3636 return moore::StringAtooctOp::create(
builder, loc, integerType, str);
3638 return moore::StringAtobinOp::create(
builder, loc, integerType, str);
3640 llvm_unreachable(
"unexpected string to integer conversion");
3644 if (nameId == ksn::AToReal) {
3646 assert(numArgs == 1 &&
"`atoreal` takes 1 argument");
3647 auto stringType = moore::StringType::get(
getContext());
3652 return moore::StringAtorealOp::create(
builder, loc, realType, str);
3659 if (nameId == ksn::ArraySize) {
3661 assert(numArgs == 1 &&
"`size` takes 1 argument");
3662 if (args[0]->type->isQueue()) {
3666 return moore::QueueSizeBIOp::create(
builder, loc, value);
3668 if (args[0]->type->getCanonicalType().kind ==
3669 slang::ast::SymbolKind::DynamicArrayType) {
3673 return moore::OpenUArraySizeOp::create(
builder, loc, value);
3675 if (args[0]->type->isAssociativeArray()) {
3679 return moore::AssocArraySizeOp::create(
builder, loc, value);
3681 emitError(loc) <<
"unsupported member function `size` on type `"
3682 << args[0]->type->toString() <<
"`";
3686 if (nameId == ksn::Delete) {
3688 assert(numArgs == 1 &&
"`delete` takes 1 argument");
3689 if (args[0]->type->getCanonicalType().kind ==
3690 slang::ast::SymbolKind::DynamicArrayType) {
3694 return moore::OpenUArrayDeleteOp::create(
builder, loc, value);
3696 emitError(loc) <<
"unsupported member function `delete` on type `"
3697 << args[0]->type->toString() <<
"`";
3701 if (nameId == ksn::PopBack) {
3703 assert(numArgs == 1 &&
"`pop_back` takes 1 argument");
3704 assert(args[0]->type->isQueue() &&
"`pop_back` is only valid on queues");
3708 return moore::QueuePopBackOp::create(
builder, loc, value);
3711 if (nameId == ksn::PopFront) {
3713 assert(numArgs == 1 &&
"`pop_front` takes 1 argument");
3714 assert(args[0]->type->isQueue() &&
"`pop_front` is only valid on queues");
3718 return moore::QueuePopFrontOp::create(
builder, loc, value);
3725 if (nameId == ksn::Num) {
3726 if (args[0]->type->isAssociativeArray()) {
3727 assert(numArgs == 1 &&
"`num` takes 1 argument");
3731 return moore::AssocArraySizeOp::create(
builder, loc, value);
3733 emitError(loc) <<
"unsupported system call `" << name <<
"`";
3737 if (nameId == ksn::Exists) {
3739 assert(numArgs == 2 &&
"`exists` takes 2 arguments");
3740 assert(args[0]->type->isAssociativeArray() &&
3741 "`exists` is only valid on associative arrays");
3746 return moore::AssocArrayExistsOp::create(
builder, loc, array, key);
3753 if (nameId == ksn::First || nameId == ksn::Last || nameId == ksn::Next ||
3754 nameId == ksn::Prev) {
3755 if (args[0]->type->isAssociativeArray()) {
3756 assert(numArgs == 2 &&
"traversal methods take 2 arguments");
3761 if (nameId == ksn::First)
3762 return moore::AssocArrayFirstOp::create(
builder, loc, array, key);
3763 if (nameId == ksn::Last)
3764 return moore::AssocArrayLastOp::create(
builder, loc, array, key);
3765 if (nameId == ksn::Next)
3766 return moore::AssocArrayNextOp::create(
builder, loc, array, key);
3767 if (nameId == ksn::Prev)
3768 return moore::AssocArrayPrevOp::create(
builder, loc, array, key);
3769 llvm_unreachable(
"all traversal cases handled above");
3771 emitError(loc) <<
"unsupported system call `" << name <<
"`";
3779 if (nameId == ksn::FOpen) {
3780 assert(numArgs >= 1 && numArgs <= 2 &&
"`$fopen` takes 1 or 2 arguments");
3785 moore::FOpenModeAttr modeAttr;
3787 auto *strLit = args[1]
3788 ->unwrapImplicitConversions()
3789 .as_if<slang::ast::StringLiteral>();
3791 return emitError(loc) <<
"$fopen mode must be a string literal",
3795 llvm::StringSwitch<std::optional<moore::FOpenMode>>(
3797 .Cases({
"r",
"rb"}, moore::FOpenMode::Read)
3798 .Cases({
"w",
"wb"}, moore::FOpenMode::Write)
3799 .Cases({
"a",
"ab"}, moore::FOpenMode::Append)
3800 .Cases({
"r+",
"r+b",
"rb+"}, moore::FOpenMode::ReadUpdate)
3801 .Cases({
"w+",
"w+b",
"wb+"}, moore::FOpenMode::WriteUpdate)
3802 .Cases({
"a+",
"a+b",
"ab+"}, moore::FOpenMode::AppendUpdate)
3803 .Default(std::nullopt);
3806 return emitError(loc)
3807 <<
"invalid $fopen mode '" << strLit->getValue() <<
"'",
3809 modeAttr = moore::FOpenModeAttr::get(
getContext(), *mode);
3811 return moore::FOpenBIOp::create(
builder, loc, filename, modeAttr);
3818 if (nameId == ksn::TestPlusArgs) {
3820 assert(numArgs == 1 &&
"`$test$plusargs` takes 1 argument");
3822 args[0]->unwrapImplicitConversions().as_if<slang::ast::StringLiteral>();
3824 return emitError(loc) <<
"`$test$plusargs` argument must be a string "
3827 auto foundTy = moore::IntType::getInt(
getContext(), 1);
3828 return moore::PlusArgsTestBIOp::create(
3829 builder, loc, foundTy,
builder.getStringAttr(strLit->getValue()));
3832 if (nameId == ksn::ValuePlusArgs) {
3836 assert(numArgs == 2 &&
"`$value$plusargs` takes 2 arguments");
3838 args[0]->unwrapImplicitConversions().as_if<slang::ast::StringLiteral>();
3840 return emitError(loc) <<
"`$value$plusargs` format must be a string "
3845 const auto *valueArg = args[1];
3846 if (
const auto *assign =
3847 valueArg->as_if<slang::ast::AssignmentExpression>())
3848 valueArg = &assign->left();
3852 auto resultType = cast<moore::RefType>(lvalue.getType()).getNestedType();
3853 auto foundTy = moore::IntType::getInt(
getContext(), 1);
3854 auto op = moore::PlusArgsValueBIOp::create(
3855 builder, loc, foundTy, resultType,
3856 builder.getStringAttr(strLit->getValue()));
3857 moore::BlockingAssignOp::create(
builder, loc, lvalue, op.getResult());
3858 return op.getFound();
3862 emitError(loc) <<
"unsupported system call `" << name <<
"`";
3868 return context.symbolTable.lookupNearestSymbolFrom(
context.intoModuleOp, sym);
3872 const moore::ClassHandleType &baseTy) {
3873 if (!actualTy || !baseTy)
3876 mlir::SymbolRefAttr actualSym = actualTy.getClassSym();
3877 mlir::SymbolRefAttr baseSym = baseTy.getClassSym();
3879 if (actualSym == baseSym)
3882 auto *op =
resolve(*
this, actualSym);
3883 auto decl = llvm::dyn_cast_or_null<moore::ClassDeclOp>(op);
3886 mlir::SymbolRefAttr curBase = decl.getBaseAttr();
3889 if (curBase == baseSym)
3891 decl = llvm::dyn_cast_or_null<moore::ClassDeclOp>(
resolve(*
this, curBase));
3896moore::ClassHandleType
3898 llvm::StringRef fieldName, Location loc) {
3900 mlir::SymbolRefAttr classSym = actualTy.getClassSym();
3904 auto *op =
resolve(*
this, classSym);
3905 auto decl = llvm::dyn_cast_or_null<moore::ClassDeclOp>(op);
3910 for (
auto &block : decl.getBody()) {
3911 for (
auto &opInBlock : block) {
3913 llvm::dyn_cast<moore::ClassPropertyDeclOp>(&opInBlock)) {
3914 if (prop.getSymName() == fieldName) {
3916 return moore::ClassHandleType::get(actualTy.getContext(), classSym);
3923 classSym = decl.getBaseAttr();
3927 mlir::emitError(loc) <<
"unknown property `" << fieldName <<
"`";
3936 const slang::ast::Expression &expr) {
3939 if (
const auto *valueRange = expr.as_if<slang::ast::ValueRangeExpression>()) {
3944 if (!insideLhs || !lowBound || !highBound)
3947 Value rangeLhs, rangeRhs;
3950 if (valueRange->left().type->isSigned() ||
3951 insideLhs.getType().isSignedInteger()) {
3952 rangeLhs = moore::SgeOp::create(
builder, loc, insideLhs, lowBound);
3954 rangeLhs = moore::UgeOp::create(
builder, loc, insideLhs, lowBound);
3957 if (valueRange->right().type->isSigned() ||
3958 insideLhs.getType().isSignedInteger()) {
3959 rangeRhs = moore::SleOp::create(
builder, loc, insideLhs, highBound);
3961 rangeRhs = moore::UleOp::create(
builder, loc, insideLhs, highBound);
3964 return moore::AndOp::create(
builder, loc, rangeLhs, rangeRhs);
3968 if (!expr.type->isIntegral()) {
3969 if (expr.type->isUnpackedArray()) {
3970 mlir::emitError(loc,
3971 "unpacked arrays in 'inside' expressions not supported");
3975 loc,
"only simple bit vectors supported in 'inside' expressions");
3982 return moore::WildcardEqOp::create(
builder, loc, insideLhs, value);
assert(baseType &&"element must be base type")
static std::unique_ptr< Context > context
static Value convertRealMathBI(Context &context, Location loc, StringRef name, std::span< const slang::ast::Expression *const > args)
Helper function to convert real math builtin functions that take exactly one argument.
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 lookupExpandedInterfaceMember(Context &context, const slang::ast::HierarchicalValueExpression &expr)
Resolve a hierarchical value that refers to a member of an expanded interface instance.
static Value visitClassProperty(Context &context, const slang::ast::ClassPropertySymbol &expr)
static Value materializeSBVToPackedConversion(Context &context, moore::PackedType packedType, Value value, Location loc, bool fallible)
Create the necessary operations to convert from a simple bit vector IntType to an equivalent PackedTy...
static Value materializePackedToSBVConversion(Context &context, Value value, Location loc, bool fallible)
Create the necessary operations to convert from a PackedType to the corresponding simple bit vector I...
static Value getIsUnknown(OpBuilder &builder, Location loc, Value value, moore::IntType valTy, MLIRContext *ctx)
Check if a Moore integer value contains any unknown (x/z) bits.
static uint64_t getTimeScaleInFemtoseconds(Context &context)
Get the currently active timescale as an integer number of femtoseconds.
static Value coerceToBuiltinInt(OpBuilder &builder, Location loc, Value value, moore::IntType valTy)
Coerce a Moore integer value to a builtin integer, handling four-valued inputs by first mapping x/z t...
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.
static FVInt getAllX(unsigned numBits)
Construct an FVInt with all bits set to X.
A packed SystemVerilog type.
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.
An unpacked SystemVerilog type.
Domain
The number of values each bit of a type can assume.
@ 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.
@ f32
A standard 32-Bit floating point number ("float")
@ f64
A 64-bit double-precision floation point number ("double")
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 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.
Value convertInsideCheck(Value insideLhs, Location loc, const slang::ast::Expression &expr)
Convert the inside/set-membership expression.
DenseMap< const slang::ast::ValueSymbol *, moore::GlobalVariableOp > globalVariables
A table of defined global variables that may be referred to by name in expressions.
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.
std::function< void(moore::ReadOp)> rvalueReadCallback
A listener called for every variable or net being read.
bool isClassDerivedFrom(const moore::ClassHandleType &actualTy, const moore::ClassHandleType &baseTy)
Checks whether one class (actualTy) is derived from another class (baseTy).
Value convertSystemCall(const slang::ast::SystemSubroutine &subroutine, Location loc, std::span< const slang::ast::Expression *const > args)
Convert system function calls.
Type convertType(const slang::ast::Type &type, LocationAttr loc={})
Convert a slang type into an MLIR type.
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.
ValueSymbols valueSymbols
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={})
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.
Value materializeConversion(Type type, Value value, bool isSigned, Location loc, bool fallible=false)
Helper function to insert the necessary operations to cast a value from one type to another.
Value currentQueue
Variable that tracks the queue which we are currently converting the index expression for.
MLIRContext * getContext()
Return the MLIR context.
Location convertLocation(slang::SourceLocation loc)
Convert a slang SourceLocation into an MLIR Location.
Function lowering information.
mlir::FunctionOpInterface op