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);
66 const slang::ConstantRange &range) {
67 auto &builder =
context.builder;
68 auto indexType = cast<moore::UnpackedType>(index.getType());
71 auto lo = range.lower();
72 auto hi = range.upper();
73 auto offset = range.isDescending() ? lo : hi;
76 const bool needSigned = (lo < 0) || (hi < 0);
79 const uint64_t maxAbs = std::max<uint64_t>(std::abs(lo), std::abs(hi));
84 unsigned want = needSigned
85 ? (llvm::Log2_64_Ceil(std::max<uint64_t>(1, maxAbs)) + 1)
86 : std::max<unsigned>(1, llvm::Log2_64_Ceil(maxAbs + 1));
89 const unsigned bw = std::max<unsigned>(want, indexType.getBitSize().value());
92 moore::IntType::get(index.getContext(), bw, indexType.getDomain());
93 index =
context.materializeConversion(intType, index, needSigned, loc);
96 if (range.isDescending())
99 return moore::NegOp::create(builder, loc, index);
103 moore::ConstantOp::create(builder, loc, intType, offset, needSigned);
104 if (range.isDescending())
105 return moore::SubOp::create(builder, loc, index, offsetConst);
107 return moore::SubOp::create(builder, loc, offsetConst, index);
112 static_assert(int(slang::TimeUnit::Seconds) == 0);
113 static_assert(int(slang::TimeUnit::Milliseconds) == 1);
114 static_assert(int(slang::TimeUnit::Microseconds) == 2);
115 static_assert(int(slang::TimeUnit::Nanoseconds) == 3);
116 static_assert(int(slang::TimeUnit::Picoseconds) == 4);
117 static_assert(int(slang::TimeUnit::Femtoseconds) == 5);
119 static_assert(int(slang::TimeScaleMagnitude::One) == 1);
120 static_assert(int(slang::TimeScaleMagnitude::Ten) == 10);
121 static_assert(int(slang::TimeScaleMagnitude::Hundred) == 100);
123 auto exp =
static_cast<unsigned>(
context.timeScale.base.unit);
126 auto scale =
static_cast<uint64_t
>(
context.timeScale.base.magnitude);
135 Context &
context,
const slang::ast::HierarchicalValueExpression &expr) {
136 auto nameAttr =
context.builder.getStringAttr(expr.symbol.name);
137 for (
const auto &element : expr.ref.path) {
138 auto *inst = element.symbol->as_if<slang::ast::InstanceSymbol>();
141 auto *lowering =
context.interfaceInstances.lookup(inst);
144 if (
auto it = lowering->expandedMembers.find(&expr.symbol);
145 it != lowering->expandedMembers.end())
147 if (
auto it = lowering->expandedMembersByName.find(nameAttr);
148 it != lowering->expandedMembersByName.end())
155 const slang::ast::ClassPropertySymbol &expr) {
156 auto loc =
context.convertLocation(expr.location);
157 auto builder =
context.builder;
158 auto type =
context.convertType(expr.getType());
159 auto fieldTy = cast<moore::UnpackedType>(type);
160 auto fieldRefTy = moore::RefType::get(fieldTy);
162 if (expr.lifetime == slang::ast::VariableLifetime::Static) {
165 if (!
context.globalVariables.lookup(&expr)) {
166 if (failed(
context.convertGlobalVariable(expr))) {
171 if (
auto globalOp =
context.globalVariables.lookup(&expr))
172 return moore::GetGlobalVariableOp::create(builder, loc, globalOp);
174 mlir::emitError(loc) <<
"Failed to access static member variable "
175 << expr.name <<
" as a global variable";
180 mlir::Value instRef =
context.getImplicitThisRef();
182 mlir::emitError(loc) <<
"class property '" << expr.name
183 <<
"' referenced without an implicit 'this'";
187 auto fieldSym = mlir::FlatSymbolRefAttr::get(builder.getContext(), expr.name);
189 moore::ClassHandleType classTy =
190 cast<moore::ClassHandleType>(instRef.getType());
192 auto targetClassHandle =
193 context.getAncestorClassWithProperty(classTy, expr.name, loc);
194 if (!targetClassHandle)
197 auto upcastRef =
context.materializeConversion(targetClassHandle, instRef,
198 false, instRef.getLoc());
202 Value fieldRef = moore::ClassPropertyRefOp::create(builder, loc, fieldRefTy,
203 upcastRef, fieldSym);
215 ExprVisitor(
Context &context, Location loc,
bool isLvalue)
216 : context(context), loc(loc), builder(context.builder),
217 isLvalue(isLvalue) {}
223 Value convertLvalueOrRvalueExpression(
const slang::ast::Expression &expr) {
231 Value materializeSymbolRvalue(
const slang::ast::ValueSymbol &sym) {
233 if (isa<moore::RefType>(value.getType())) {
234 auto readOp = moore::ReadOp::create(builder, loc, value);
237 return readOp.getResult();
243 auto ref = moore::GetGlobalVariableOp::create(builder, loc, globalOp);
244 auto readOp = moore::ReadOp::create(builder, loc, ref);
247 return readOp.getResult();
250 if (
auto *
const property = sym.as_if<slang::ast::ClassPropertySymbol>()) {
252 auto readOp = moore::ReadOp::create(builder, loc, fieldRef);
255 return readOp.getResult();
261 Value visit(
const slang::ast::NewArrayExpression &expr) {
266 if (expr.initExpr()) {
268 <<
"unsupported expression: array `new` with initializer\n";
273 expr.sizeExpr(), context.
convertType(*expr.sizeExpr().type));
277 return moore::OpenUArrayCreateOp::create(builder, loc, type, initialSize);
281 Value visit(
const slang::ast::ElementSelectExpression &expr) {
283 auto value = convertLvalueOrRvalueExpression(expr.value());
288 auto derefType = value.getType();
290 derefType = cast<moore::RefType>(derefType).getNestedType();
292 if (!isa<moore::IntType, moore::ArrayType, moore::UnpackedArrayType,
293 moore::QueueType, moore::AssocArrayType, moore::StringType,
294 moore::OpenUnpackedArrayType, moore::StructType, moore::UnionType>(
296 mlir::emitError(loc) <<
"unsupported expression: element select into "
297 << expr.value().type->toString() <<
"\n";
301 if (!isLvalue && isa<moore::StructType, moore::UnionType>(derefType)) {
305 derefType = value.getType();
309 if (isa<moore::AssocArrayType>(derefType)) {
310 auto assocArray = cast<moore::AssocArrayType>(derefType);
311 auto expectedIndexType = assocArray.getIndexType();
317 if (givenIndex.getType() != expectedIndexType) {
319 <<
"Incorrect index type: expected index type of "
320 << expectedIndexType <<
" but was given " << givenIndex.getType();
324 return moore::AssocArrayExtractRefOp::create(
325 builder, loc, moore::RefType::get(cast<moore::UnpackedType>(type)),
328 return moore::AssocArrayExtractOp::create(builder, loc, type, value,
333 if (isa<moore::StringType>(derefType)) {
335 mlir::emitError(loc) <<
"string index assignment not supported";
340 auto i32Type = moore::IntType::getInt(builder.getContext(), 32);
346 return moore::StringGetOp::create(builder, loc, value, index);
350 isLvalue ? moore::RefType::get(cast<moore::UnpackedType>(type)) : type;
351 auto range = expr.value().type->getFixedRange();
352 if (
auto *constValue = expr.selector().getConstant();
353 constValue && constValue->isInteger()) {
354 assert(!constValue->hasUnknown());
355 assert(constValue->size() <= 32);
357 auto lowBit = constValue->integer().as<uint32_t>().value();
359 return llvm::TypeSwitch<Type, Value>(derefType)
360 .Case<moore::QueueType>([&](moore::QueueType) {
362 <<
"Unexpected LValue extract on Queue Type!";
366 return moore::ExtractRefOp::create(builder, loc, resultType,
368 range.translateIndex(lowBit));
371 return llvm::TypeSwitch<Type, Value>(derefType)
372 .Case<moore::QueueType>([&](moore::QueueType) {
374 <<
"Unexpected RValue extract on Queue Type!";
378 return moore::ExtractOp::create(builder, loc, resultType, value,
379 range.translateIndex(lowBit));
386 llvm::scope_exit restoreQueue([&] { context.
currentQueue = savedQueue; });
387 if (isa<moore::QueueType>(derefType)) {
390 if (isa<moore::RefType>(value.getType())) {
391 context.
currentQueue = moore::ReadOp::create(builder, loc, value);
402 return llvm::TypeSwitch<Type, Value>(derefType)
403 .Case<moore::QueueType>([&](moore::QueueType) {
404 return moore::DynQueueRefElementOp::create(builder, loc, resultType,
408 return moore::DynExtractRefOp::create(builder, loc, resultType,
413 return llvm::TypeSwitch<Type, Value>(derefType)
414 .Case<moore::QueueType>([&](moore::QueueType) {
415 return moore::DynQueueExtractOp::create(builder, loc, resultType,
416 value, lowBit, lowBit);
419 return moore::DynExtractOp::create(builder, loc, resultType, value,
426 Value visit(
const slang::ast::NullLiteral &expr) {
428 if (isa<moore::ClassHandleType, moore::ChandleType, moore::EventType,
429 moore::NullType>(type))
430 return moore::NullOp::create(builder, loc);
431 mlir::emitError(loc) <<
"No null value definition found for value of type "
437 Value visit(
const slang::ast::RangeSelectExpression &expr) {
439 auto value = convertLvalueOrRvalueExpression(expr.value());
443 auto derefType = value.getType();
445 derefType = cast<moore::RefType>(derefType).getNestedType();
447 if (isa<moore::QueueType>(derefType)) {
448 return handleQueueRangeSelectExpressions(expr, type, value);
450 if (!isLvalue && isa<moore::StructType, moore::UnionType>(derefType)) {
456 return handleArrayRangeSelectExpressions(expr, type, value);
461 Value handleQueueRangeSelectExpressions(
462 const slang::ast::RangeSelectExpression &expr, Type type, Value value) {
464 llvm::scope_exit restoreQueue([&] { context.
currentQueue = savedQueue; });
470 isLvalue ? moore::RefType::get(cast<moore::UnpackedType>(type)) : type;
473 mlir::emitError(loc) <<
"queue lvalue range selections are not supported";
476 return moore::DynQueueExtractOp::create(builder, loc, resultType, value,
482 Value handleArrayRangeSelectExpressions(
483 const slang::ast::RangeSelectExpression &expr, Type type, Value value) {
484 std::optional<int32_t> constLeft;
485 std::optional<int32_t> constRight;
486 if (
auto *constant = expr.left().getConstant())
487 constLeft = constant->integer().as<int32_t>();
488 if (
auto *constant = expr.right().getConstant())
489 constRight = constant->integer().as<int32_t>();
495 <<
"unsupported expression: range select with non-constant bounds";
515 int32_t offsetConst = 0;
516 auto range = expr.value().type->getFixedRange();
518 using slang::ast::RangeSelectionKind;
519 if (expr.getSelectionKind() == RangeSelectionKind::Simple) {
524 assert(constRight &&
"constness checked in slang");
525 offsetConst = *constRight;
536 offsetConst = *constLeft;
547 int32_t offsetAdd = 0;
552 if (expr.getSelectionKind() == RangeSelectionKind::IndexedDown &&
553 range.isDescending()) {
554 assert(constRight &&
"constness checked in slang");
555 offsetAdd = 1 - *constRight;
561 if (expr.getSelectionKind() == RangeSelectionKind::IndexedUp &&
562 !range.isDescending()) {
563 assert(constRight &&
"constness checked in slang");
564 offsetAdd = *constRight - 1;
568 if (offsetAdd != 0) {
570 offsetDyn = moore::AddOp::create(
571 builder, loc, offsetDyn,
572 moore::ConstantOp::create(
573 builder, loc, cast<moore::IntType>(offsetDyn.getType()),
577 offsetConst += offsetAdd;
588 isLvalue ? moore::RefType::get(cast<moore::UnpackedType>(type)) : type;
593 return moore::DynExtractRefOp::create(builder, loc, resultType, value,
596 return moore::DynExtractOp::create(builder, loc, resultType, value,
600 offsetConst = range.translateIndex(offsetConst);
602 return moore::ExtractRefOp::create(builder, loc, resultType, value,
605 return moore::ExtractOp::create(builder, loc, resultType, value,
612 Value visit(
const slang::ast::ConcatenationExpression &expr) {
613 SmallVector<Value> operands;
614 if (expr.type->isString()) {
615 for (
auto *operand : expr.operands()) {
616 assert(!isLvalue &&
"checked by Slang");
617 auto value = convertLvalueOrRvalueExpression(*operand);
621 moore::StringType::get(context.
getContext()), value,
false,
625 operands.push_back(value);
627 return moore::StringConcatOp::create(builder, loc, operands);
629 if (expr.type->isQueue()) {
630 return handleQueueConcat(expr);
633 if (expr.type->isUnpackedArray()) {
634 assert(!isLvalue &&
"checked by Slang");
635 auto loweredType = context.
convertType(*expr.type, loc);
640 if (
auto arrayType = dyn_cast<moore::UnpackedArrayType>(loweredType))
642 else if (
auto openType =
643 dyn_cast<moore::OpenUnpackedArrayType>(loweredType))
648 SmallVector<Value> operands;
649 for (
auto *operand : expr.operands()) {
650 if (operand->type->isVoid())
655 operands.push_back(value);
658 auto arrayType = moore::UnpackedArrayType::get(
660 return moore::ArrayCreateOp::create(builder, loc, arrayType, operands);
663 for (
auto *operand : expr.operands()) {
667 if (operand->type->isVoid())
669 auto value = convertLvalueOrRvalueExpression(*operand);
676 operands.push_back(value);
679 return moore::ConcatRefOp::create(builder, loc, operands);
681 return moore::ConcatOp::create(builder, loc, operands);
688 Value handleQueueConcat(
const slang::ast::ConcatenationExpression &expr) {
689 SmallVector<Value> operands;
692 cast<moore::QueueType>(context.
convertType(*expr.type, loc));
704 Value contigElements;
706 for (
auto *operand : expr.operands()) {
707 bool isSingleElement =
712 if (!isSingleElement && contigElements) {
713 operands.push_back(moore::ReadOp::create(builder, loc, contigElements));
717 assert(!isLvalue &&
"checked by Slang");
718 auto value = convertLvalueOrRvalueExpression(*operand);
726 moore::RefType::get(context.
getContext(), queueType);
728 if (!contigElements) {
730 moore::VariableOp::create(builder, loc, queueRefType, {}, {});
732 moore::QueuePushBackOp::create(builder, loc, contigElements, value);
740 if (!(isa<moore::QueueType>(value.getType()) &&
741 cast<moore::QueueType>(value.getType()).getElementType() ==
747 operands.push_back(value);
750 if (contigElements) {
751 operands.push_back(moore::ReadOp::create(builder, loc, contigElements));
754 return moore::QueueConcatOp::create(builder, loc, queueType, operands);
758 Value visit(
const slang::ast::MemberAccessExpression &expr) {
763 auto *valueType = expr.value().type.get();
764 auto memberName = builder.getStringAttr(expr.member.name);
770 if (valueType->isVirtualInterface()) {
771 auto memberType = dyn_cast<moore::UnpackedType>(type);
774 <<
"unsupported virtual interface member type: " << type;
777 auto resultRefType = moore::RefType::get(memberType);
785 auto memberRef = moore::StructExtractOp::create(
786 builder, loc, resultRefType, memberName, base);
789 return moore::ReadOp::create(builder, loc, memberRef);
793 if (valueType->isStruct()) {
795 isLvalue ? moore::RefType::get(cast<moore::UnpackedType>(type))
797 auto value = convertLvalueOrRvalueExpression(expr.value());
802 return moore::StructExtractRefOp::create(builder, loc, resultType,
804 return moore::StructExtractOp::create(builder, loc, resultType,
809 if (valueType->isPackedUnion() || valueType->isUnpackedUnion()) {
811 isLvalue ? moore::RefType::get(cast<moore::UnpackedType>(type))
813 auto value = convertLvalueOrRvalueExpression(expr.value());
818 return moore::UnionExtractRefOp::create(builder, loc, resultType,
820 return moore::UnionExtractOp::create(builder, loc, type, memberName,
825 if (valueType->isClass()) {
829 auto targetTy = cast<moore::ClassHandleType>(valTy);
841 if (expr.member.kind != slang::ast::SymbolKind::Parameter) {
847 moore::ClassHandleType upcastTargetTy =
861 auto fieldSym = mlir::FlatSymbolRefAttr::get(builder.getContext(),
863 auto fieldRefTy = moore::RefType::get(cast<moore::UnpackedType>(type));
867 Value fieldRef = moore::ClassPropertyRefOp::create(
868 builder, loc, fieldRefTy, baseVal, fieldSym);
871 return isLvalue ? fieldRef
872 : moore::ReadOp::create(builder, loc, fieldRef);
875 slang::ConstantValue constVal;
876 if (
auto param = expr.member.as_if<slang::ast::ParameterSymbol>()) {
877 constVal = param->getValue();
882 mlir::emitError(loc) <<
"Parameter " << expr.member.name
883 <<
" has no constant value";
887 mlir::emitError(loc,
"expression of type ")
888 << valueType->toString() <<
" has no member fields";
900struct RvalueExprVisitor :
public ExprVisitor {
902 : ExprVisitor(
context, loc, false) {}
903 using ExprVisitor::visit;
906 Value visit(
const slang::ast::LValueReferenceExpression &expr) {
907 assert(!
context.lvalueStack.empty() &&
"parent assignments push lvalue");
908 auto lvalue =
context.lvalueStack.back();
909 return moore::ReadOp::create(builder, loc, lvalue);
913 Value visit(
const slang::ast::NamedValueExpression &expr) {
915 if (
auto value =
context.valueSymbols.lookup(&expr.symbol)) {
916 if (isa<moore::RefType>(value.getType())) {
917 auto readOp = moore::ReadOp::create(builder, loc, value);
918 if (
context.rvalueReadCallback)
919 context.rvalueReadCallback(readOp);
920 value = readOp.getResult();
926 if (
auto globalOp =
context.globalVariables.lookup(&expr.symbol)) {
927 auto value = moore::GetGlobalVariableOp::create(builder, loc, globalOp);
928 return moore::ReadOp::create(builder, loc, value);
932 if (
auto *
const property =
933 expr.symbol.as_if<slang::ast::ClassPropertySymbol>()) {
935 return moore::ReadOp::create(builder, loc, fieldRef).getResult();
942 if (
auto access =
context.virtualIfaceMembers.lookup(&expr.symbol);
944 auto type =
context.convertType(*expr.type);
947 auto memberType = dyn_cast<moore::UnpackedType>(type);
950 <<
"unsupported virtual interface member type: " << type;
954 Value base = materializeSymbolRvalue(*access.base);
956 auto d = mlir::emitError(loc,
"unknown name `")
957 << access.base->name <<
"`";
958 d.attachNote(
context.convertLocation(access.base->location))
959 <<
"no rvalue generated for virtual interface base";
963 auto fieldName = access.fieldName
965 : builder.getStringAttr(expr.symbol.name);
966 auto memberRefType = moore::RefType::get(memberType);
967 auto memberRef = moore::StructExtractOp::create(
968 builder, loc, memberRefType, fieldName, base);
969 auto readOp = moore::ReadOp::create(builder, loc, memberRef);
970 if (
context.rvalueReadCallback)
971 context.rvalueReadCallback(readOp);
972 return readOp.getResult();
976 auto constant =
context.evaluateConstant(expr);
977 if (
auto value =
context.materializeConstant(constant, *expr.type, loc))
982 auto d = mlir::emitError(loc,
"unknown name `") << expr.symbol.name <<
"`";
983 d.attachNote(
context.convertLocation(expr.symbol.location))
984 <<
"no rvalue generated for " << slang::ast::toString(expr.symbol.kind);
989 Value visit(
const slang::ast::HierarchicalValueExpression &expr) {
990 auto hierLoc =
context.convertLocation(expr.symbol.location);
996 if (!expr.ref.path.empty()) {
997 if (
auto *inst = expr.ref.path.front()
998 .symbol->as_if<slang::ast::InstanceSymbol>()) {
1000 expr.symbol.getParentScope()->getContainingInstance();
1001 if (&inst->body == symbolBody ||
1002 (symbolBody && inst->body.getDeclaringDefinition() ==
1003 symbolBody->getDeclaringDefinition())) {
1004 if (
auto value =
context.valueSymbols.lookup(&expr.symbol)) {
1005 if (isa<moore::RefType>(value.getType())) {
1006 auto readOp = moore::ReadOp::create(builder, hierLoc, value);
1007 if (
context.rvalueReadCallback)
1008 context.rvalueReadCallback(readOp);
1009 value = readOp.getResult();
1019 if (
auto value =
context.resolveCapturedValue(expr.symbol)) {
1020 if (isa<moore::RefType>(value.getType())) {
1021 auto readOp = moore::ReadOp::create(builder, hierLoc, value);
1022 if (
context.rvalueReadCallback)
1023 context.rvalueReadCallback(readOp);
1024 value = readOp.getResult();
1033 if (
auto key =
context.buildHierValueKey(expr)) {
1034 if (
auto it =
context.hierValueSymbols.find(*key);
1035 it !=
context.hierValueSymbols.end()) {
1036 auto value = it->second;
1037 if (isa<moore::RefType>(value.getType())) {
1038 auto readOp = moore::ReadOp::create(builder, hierLoc, value);
1039 if (
context.rvalueReadCallback)
1040 context.rvalueReadCallback(readOp);
1041 value = readOp.getResult();
1048 if (
auto value =
context.valueSymbols.lookup(&expr.symbol)) {
1049 if (isa<moore::RefType>(value.getType())) {
1050 auto readOp = moore::ReadOp::create(builder, hierLoc, value);
1051 if (
context.rvalueReadCallback)
1052 context.rvalueReadCallback(readOp);
1053 value = readOp.getResult();
1059 if (isa<moore::RefType>(value.getType())) {
1060 auto readOp = moore::ReadOp::create(builder, hierLoc, value);
1061 if (
context.rvalueReadCallback)
1062 context.rvalueReadCallback(readOp);
1063 return readOp.getResult();
1071 slang::ConstantValue constant;
1072 switch (expr.symbol.kind) {
1073 case slang::ast::SymbolKind::Parameter:
1074 constant = expr.symbol.as<slang::ast::ParameterSymbol>().getValue(
1077 case slang::ast::SymbolKind::Specparam:
1078 constant = expr.symbol.as<slang::ast::SpecparamSymbol>().getValue(
1081 case slang::ast::SymbolKind::EnumValue:
1082 constant = expr.symbol.as<slang::ast::EnumValueSymbol>().getValue(
1086 constant =
context.evaluateConstant(expr);
1089 if (
auto value =
context.materializeConstant(constant, *expr.type, loc))
1094 auto d = mlir::emitError(loc,
"unknown hierarchical name `")
1095 << expr.symbol.name <<
"`";
1096 d.attachNote(hierLoc) <<
"no rvalue generated for "
1097 << slang::ast::toString(expr.symbol.kind);
1103 Value visit(
const slang::ast::ArbitrarySymbolExpression &expr) {
1104 const auto &canonTy = expr.type->getCanonicalType();
1105 if (
const auto *vi = canonTy.as_if<slang::ast::VirtualInterfaceType>()) {
1106 auto value =
context.materializeVirtualInterfaceValue(*vi, loc);
1112 mlir::emitError(loc) <<
"unsupported arbitrary symbol expression of type "
1113 << expr.type->toString();
1118 Value visit(
const slang::ast::ConversionExpression &expr) {
1119 auto type =
context.convertType(*expr.type);
1122 return context.convertRvalueExpression(expr.operand(), type);
1126 Value visit(
const slang::ast::AssignmentExpression &expr) {
1127 auto lhs =
context.convertLvalueExpression(expr.left());
1132 context.lvalueStack.push_back(lhs);
1133 auto rhs =
context.convertRvalueExpression(
1134 expr.right(), cast<moore::RefType>(lhs.getType()).getNestedType());
1135 context.lvalueStack.pop_back();
1142 if (!expr.isNonBlocking()) {
1143 if (expr.timingControl)
1144 if (failed(
context.convertTimingControl(*expr.timingControl)))
1146 auto assignOp = moore::BlockingAssignOp::create(builder, loc, lhs, rhs);
1147 if (
context.variableAssignCallback)
1148 context.variableAssignCallback(assignOp);
1153 if (expr.timingControl) {
1155 if (
auto *ctrl = expr.timingControl->as_if<slang::ast::DelayControl>()) {
1156 auto delay =
context.convertRvalueExpression(
1157 ctrl->expr, moore::TimeType::get(builder.getContext()));
1160 auto assignOp = moore::DelayedNonBlockingAssignOp::create(
1161 builder, loc, lhs, rhs, delay);
1162 if (
context.variableAssignCallback)
1163 context.variableAssignCallback(assignOp);
1168 auto loc =
context.convertLocation(expr.timingControl->sourceRange);
1169 mlir::emitError(loc)
1170 <<
"unsupported non-blocking assignment timing control: "
1171 << slang::ast::toString(expr.timingControl->kind);
1174 auto assignOp = moore::NonBlockingAssignOp::create(builder, loc, lhs, rhs);
1175 if (
context.variableAssignCallback)
1176 context.variableAssignCallback(assignOp);
1182 template <
class ConcreteOp>
1183 Value createReduction(Value arg,
bool invert) {
1184 arg =
context.convertToSimpleBitVector(arg);
1187 Value result = ConcreteOp::create(builder, loc, arg);
1189 result = moore::NotOp::create(builder, loc, result);
1194 Value createIncrement(Value arg,
bool isInc,
bool isPost) {
1195 auto preValue = moore::ReadOp::create(builder, loc, arg);
1201 postValue = moore::NotOp::create(builder, loc, preValue).getResult();
1204 auto one = moore::ConstantOp::create(
1205 builder, loc, cast<moore::IntType>(preValue.getType()), 1);
1207 isInc ? moore::AddOp::create(builder, loc, preValue, one).getResult()
1208 : moore::SubOp::create(builder, loc, preValue, one).getResult();
1210 moore::BlockingAssignOp::create(builder, loc, arg, postValue);
1211 if (
context.variableAssignCallback)
1212 context.variableAssignCallback(assignOp);
1221 Value createRealIncrement(Value arg,
bool isInc,
bool isPost) {
1222 Value preValue = moore::ReadOp::create(builder, loc, arg);
1225 bool isTime = isa<moore::TimeType>(preValue.getType());
1227 preValue =
context.materializeConversion(
1228 moore::RealType::get(
context.getContext(), moore::RealWidth::f64),
1229 preValue,
false, loc);
1231 moore::RealType realTy =
1232 llvm::dyn_cast<moore::RealType>(preValue.getType());
1237 if (realTy.getWidth() == moore::RealWidth::f32) {
1238 oneAttr = builder.getFloatAttr(builder.getF32Type(), 1.0);
1239 }
else if (realTy.getWidth() == moore::RealWidth::f64) {
1241 oneAttr = builder.getFloatAttr(builder.getF64Type(), oneVal);
1243 mlir::emitError(loc) <<
"cannot construct increment for " << realTy;
1246 auto one = moore::ConstantRealOp::create(builder, loc, oneAttr);
1250 ? moore::AddRealOp::create(builder, loc, preValue, one).getResult()
1251 : moore::SubRealOp::create(builder, loc, preValue, one).getResult();
1254 postValue =
context.materializeConversion(
1255 moore::TimeType::get(
context.getContext()), postValue,
false, loc);
1258 moore::BlockingAssignOp::create(builder, loc, arg, postValue);
1260 if (
context.variableAssignCallback)
1261 context.variableAssignCallback(assignOp);
1268 Value visitRealUOp(
const slang::ast::UnaryExpression &expr) {
1269 Type opFTy =
context.convertType(*expr.operand().type);
1271 using slang::ast::UnaryOperator;
1273 if (expr.op == UnaryOperator::Preincrement ||
1274 expr.op == UnaryOperator::Predecrement ||
1275 expr.op == UnaryOperator::Postincrement ||
1276 expr.op == UnaryOperator::Postdecrement)
1277 arg =
context.convertLvalueExpression(expr.operand());
1279 arg =
context.convertRvalueExpression(expr.operand(), opFTy);
1284 if (isa<moore::TimeType>(arg.getType()))
1285 arg =
context.materializeConversion(
1286 moore::RealType::get(
context.getContext(), moore::RealWidth::f64),
1291 case UnaryOperator::Plus:
1293 case UnaryOperator::Minus:
1294 return moore::NegRealOp::create(builder, loc, arg);
1296 case UnaryOperator::Preincrement:
1297 return createRealIncrement(arg,
true,
false);
1298 case UnaryOperator::Predecrement:
1299 return createRealIncrement(arg,
false,
false);
1300 case UnaryOperator::Postincrement:
1301 return createRealIncrement(arg,
true,
true);
1302 case UnaryOperator::Postdecrement:
1303 return createRealIncrement(arg,
false,
true);
1305 case UnaryOperator::LogicalNot:
1306 arg =
context.convertToBool(arg);
1309 return moore::NotOp::create(builder, loc, arg);
1312 mlir::emitError(loc) <<
"Unary operator " << slang::ast::toString(expr.op)
1313 <<
" not supported with real values!\n";
1319 Value visit(
const slang::ast::UnaryExpression &expr) {
1321 const auto *floatType =
1322 expr.operand().type->as_if<slang::ast::FloatingType>();
1325 return visitRealUOp(expr);
1327 using slang::ast::UnaryOperator;
1329 if (expr.op == UnaryOperator::Preincrement ||
1330 expr.op == UnaryOperator::Predecrement ||
1331 expr.op == UnaryOperator::Postincrement ||
1332 expr.op == UnaryOperator::Postdecrement)
1333 arg =
context.convertLvalueExpression(expr.operand());
1335 arg =
context.convertRvalueExpression(expr.operand());
1342 case UnaryOperator::Plus:
1343 return context.convertToSimpleBitVector(arg);
1345 case UnaryOperator::Minus:
1346 arg =
context.convertToSimpleBitVector(arg);
1349 return moore::NegOp::create(builder, loc, arg);
1351 case UnaryOperator::BitwiseNot:
1352 arg =
context.convertToSimpleBitVector(arg);
1355 return moore::NotOp::create(builder, loc, arg);
1357 case UnaryOperator::BitwiseAnd:
1358 return createReduction<moore::ReduceAndOp>(arg,
false);
1359 case UnaryOperator::BitwiseOr:
1360 return createReduction<moore::ReduceOrOp>(arg,
false);
1361 case UnaryOperator::BitwiseXor:
1362 return createReduction<moore::ReduceXorOp>(arg,
false);
1363 case UnaryOperator::BitwiseNand:
1364 return createReduction<moore::ReduceAndOp>(arg,
true);
1365 case UnaryOperator::BitwiseNor:
1366 return createReduction<moore::ReduceOrOp>(arg,
true);
1367 case UnaryOperator::BitwiseXnor:
1368 return createReduction<moore::ReduceXorOp>(arg,
true);
1370 case UnaryOperator::LogicalNot:
1371 arg =
context.convertToBool(arg);
1374 return moore::NotOp::create(builder, loc, arg);
1376 case UnaryOperator::Preincrement:
1377 return createIncrement(arg,
true,
false);
1378 case UnaryOperator::Predecrement:
1379 return createIncrement(arg,
false,
false);
1380 case UnaryOperator::Postincrement:
1381 return createIncrement(arg,
true,
true);
1382 case UnaryOperator::Postdecrement:
1383 return createIncrement(arg,
false,
true);
1386 mlir::emitError(loc,
"unsupported unary operator");
1391 Value buildLogicalBOp(slang::ast::BinaryOperator op, Value lhs, Value rhs,
1392 std::optional<Domain> domain = std::nullopt) {
1393 using slang::ast::BinaryOperator;
1397 lhs =
context.convertToBool(lhs, domain.value());
1398 rhs =
context.convertToBool(rhs, domain.value());
1400 lhs =
context.convertToBool(lhs);
1401 rhs =
context.convertToBool(rhs);
1408 case BinaryOperator::LogicalAnd:
1409 return moore::AndOp::create(builder, loc, lhs, rhs);
1411 case BinaryOperator::LogicalOr:
1412 return moore::OrOp::create(builder, loc, lhs, rhs);
1414 case BinaryOperator::LogicalImplication: {
1416 auto notLHS = moore::NotOp::create(builder, loc, lhs);
1417 return moore::OrOp::create(builder, loc, notLHS, rhs);
1420 case BinaryOperator::LogicalEquivalence: {
1422 auto notLHS = moore::NotOp::create(builder, loc, lhs);
1423 auto notRHS = moore::NotOp::create(builder, loc, rhs);
1424 auto both = moore::AndOp::create(builder, loc, lhs, rhs);
1425 auto notBoth = moore::AndOp::create(builder, loc, notLHS, notRHS);
1426 return moore::OrOp::create(builder, loc, both, notBoth);
1430 llvm_unreachable(
"not a logical BinaryOperator");
1434 Value visitHandleBOp(
const slang::ast::BinaryExpression &expr) {
1436 auto lhs =
context.convertRvalueExpression(expr.left());
1439 auto rhs =
context.convertRvalueExpression(expr.right());
1443 using slang::ast::BinaryOperator;
1446 case BinaryOperator::Equality:
1447 return moore::HandleEqOp::create(builder, loc, lhs, rhs);
1448 case BinaryOperator::Inequality:
1449 return moore::HandleNeOp::create(builder, loc, lhs, rhs);
1450 case BinaryOperator::CaseEquality:
1451 return moore::HandleCaseEqOp::create(builder, loc, lhs, rhs);
1452 case BinaryOperator::CaseInequality:
1453 return moore::HandleCaseNeOp::create(builder, loc, lhs, rhs);
1456 mlir::emitError(loc)
1457 <<
"Binary operator " << slang::ast::toString(expr.op)
1458 <<
" not supported with class handle valued operands!\n";
1463 Value visitRealBOp(
const slang::ast::BinaryExpression &expr) {
1465 auto lhs =
context.convertRvalueExpression(expr.left());
1468 auto rhs =
context.convertRvalueExpression(expr.right());
1472 if (isa<moore::TimeType>(lhs.getType()) ||
1473 isa<moore::TimeType>(rhs.getType())) {
1474 lhs =
context.materializeConversion(
1475 moore::RealType::get(
context.getContext(), moore::RealWidth::f64),
1477 rhs =
context.materializeConversion(
1478 moore::RealType::get(
context.getContext(), moore::RealWidth::f64),
1482 using slang::ast::BinaryOperator;
1484 case BinaryOperator::Add:
1485 return moore::AddRealOp::create(builder, loc, lhs, rhs);
1486 case BinaryOperator::Subtract:
1487 return moore::SubRealOp::create(builder, loc, lhs, rhs);
1488 case BinaryOperator::Multiply:
1489 return moore::MulRealOp::create(builder, loc, lhs, rhs);
1490 case BinaryOperator::Divide:
1491 return moore::DivRealOp::create(builder, loc, lhs, rhs);
1492 case BinaryOperator::Power:
1493 return moore::PowRealOp::create(builder, loc, lhs, rhs);
1495 case BinaryOperator::Equality:
1496 return moore::EqRealOp::create(builder, loc, lhs, rhs);
1497 case BinaryOperator::Inequality:
1498 return moore::NeRealOp::create(builder, loc, lhs, rhs);
1500 case BinaryOperator::GreaterThan:
1501 return moore::FgtOp::create(builder, loc, lhs, rhs);
1502 case BinaryOperator::LessThan:
1503 return moore::FltOp::create(builder, loc, lhs, rhs);
1504 case BinaryOperator::GreaterThanEqual:
1505 return moore::FgeOp::create(builder, loc, lhs, rhs);
1506 case BinaryOperator::LessThanEqual:
1507 return moore::FleOp::create(builder, loc, lhs, rhs);
1509 case BinaryOperator::LogicalAnd:
1510 case BinaryOperator::LogicalOr:
1511 case BinaryOperator::LogicalImplication:
1512 case BinaryOperator::LogicalEquivalence: {
1513 Domain domain = Domain::TwoValued;
1514 if (expr.left().type->isFourState() || expr.right().type->isFourState())
1515 domain = Domain::FourValued;
1516 return buildLogicalBOp(expr.op, lhs, rhs, domain);
1520 mlir::emitError(loc) <<
"Binary operator "
1521 << slang::ast::toString(expr.op)
1522 <<
" not supported with real valued operands!\n";
1529 template <
class ConcreteOp>
1530 Value createBinary(Value lhs, Value rhs) {
1531 lhs =
context.convertToSimpleBitVector(lhs);
1534 rhs =
context.convertToSimpleBitVector(rhs);
1537 return ConcreteOp::create(builder, loc, lhs, rhs);
1541 Value visit(
const slang::ast::BinaryExpression &expr) {
1542 if (expr.left().kind == slang::ast::ExpressionKind::TypeReference &&
1543 expr.right().kind == slang::ast::ExpressionKind::TypeReference) {
1545 expr.left().as<slang::ast::TypeReferenceExpression>().targetType;
1547 expr.right().as<slang::ast::TypeReferenceExpression>().targetType;
1548 bool value = lhsType.isMatching(rhsType);
1550 using slang::ast::BinaryOperator;
1552 case BinaryOperator::Equality:
1553 case BinaryOperator::CaseEquality:
1555 case BinaryOperator::Inequality:
1556 case BinaryOperator::CaseInequality:
1560 mlir::emitError(loc,
"unsupported type reference binary operator");
1564 auto type = moore::IntType::get(
context.getContext(), 1,
1565 moore::Domain::TwoValued);
1566 return moore::ConstantOp::create(builder, loc, type, value,
1571 const auto *rhsFloatType =
1572 expr.right().type->as_if<slang::ast::FloatingType>();
1573 const auto *lhsFloatType =
1574 expr.left().type->as_if<slang::ast::FloatingType>();
1577 if (rhsFloatType || lhsFloatType)
1578 return visitRealBOp(expr);
1581 const auto rhsIsClass = expr.right().type->isClass();
1582 const auto lhsIsClass = expr.left().type->isClass();
1583 const auto rhsIsChandle = expr.right().type->isCHandle();
1584 const auto lhsIsChandle = expr.left().type->isCHandle();
1586 if (rhsIsClass || lhsIsClass || rhsIsChandle || lhsIsChandle)
1587 return visitHandleBOp(expr);
1589 auto lhs =
context.convertRvalueExpression(expr.left());
1592 auto rhs =
context.convertRvalueExpression(expr.right());
1597 Domain domain = Domain::TwoValued;
1598 if (expr.type->isFourState() || expr.left().type->isFourState() ||
1599 expr.right().type->isFourState())
1600 domain = Domain::FourValued;
1602 using slang::ast::BinaryOperator;
1604 case BinaryOperator::Add:
1605 return createBinary<moore::AddOp>(lhs, rhs);
1606 case BinaryOperator::Subtract:
1607 return createBinary<moore::SubOp>(lhs, rhs);
1608 case BinaryOperator::Multiply:
1609 return createBinary<moore::MulOp>(lhs, rhs);
1610 case BinaryOperator::Divide:
1611 if (expr.type->isSigned())
1612 return createBinary<moore::DivSOp>(lhs, rhs);
1614 return createBinary<moore::DivUOp>(lhs, rhs);
1615 case BinaryOperator::Mod:
1616 if (expr.type->isSigned())
1617 return createBinary<moore::ModSOp>(lhs, rhs);
1619 return createBinary<moore::ModUOp>(lhs, rhs);
1620 case BinaryOperator::Power: {
1625 auto rhsCast =
context.materializeConversion(
1626 lhs.getType(), rhs, expr.right().type->isSigned(), rhs.getLoc());
1627 if (expr.type->isSigned())
1628 return createBinary<moore::PowSOp>(lhs, rhsCast);
1630 return createBinary<moore::PowUOp>(lhs, rhsCast);
1633 case BinaryOperator::BinaryAnd:
1634 return createBinary<moore::AndOp>(lhs, rhs);
1635 case BinaryOperator::BinaryOr:
1636 return createBinary<moore::OrOp>(lhs, rhs);
1637 case BinaryOperator::BinaryXor:
1638 return createBinary<moore::XorOp>(lhs, rhs);
1639 case BinaryOperator::BinaryXnor: {
1640 auto result = createBinary<moore::XorOp>(lhs, rhs);
1643 return moore::NotOp::create(builder, loc, result);
1646 case BinaryOperator::Equality:
1647 if (isa<moore::UnpackedArrayType>(lhs.getType()))
1648 return moore::UArrayCmpOp::create(
1649 builder, loc, moore::UArrayCmpPredicate::eq, lhs, rhs);
1650 else if (isa<moore::StringType>(lhs.getType()))
1651 return moore::StringCmpOp::create(
1652 builder, loc, moore::StringCmpPredicate::eq, lhs, rhs);
1653 else if (isa<moore::QueueType>(lhs.getType()))
1654 return moore::QueueCmpOp::create(
1655 builder, loc, moore::UArrayCmpPredicate::eq, lhs, rhs);
1657 return createBinary<moore::EqOp>(lhs, rhs);
1658 case BinaryOperator::Inequality:
1659 if (isa<moore::UnpackedArrayType>(lhs.getType()))
1660 return moore::UArrayCmpOp::create(
1661 builder, loc, moore::UArrayCmpPredicate::ne, lhs, rhs);
1662 else if (isa<moore::StringType>(lhs.getType()))
1663 return moore::StringCmpOp::create(
1664 builder, loc, moore::StringCmpPredicate::ne, lhs, rhs);
1665 else if (isa<moore::QueueType>(lhs.getType()))
1666 return moore::QueueCmpOp::create(
1667 builder, loc, moore::UArrayCmpPredicate::ne, lhs, rhs);
1669 return createBinary<moore::NeOp>(lhs, rhs);
1670 case BinaryOperator::CaseEquality:
1671 return createBinary<moore::CaseEqOp>(lhs, rhs);
1672 case BinaryOperator::CaseInequality:
1673 return createBinary<moore::CaseNeOp>(lhs, rhs);
1674 case BinaryOperator::WildcardEquality:
1675 return createBinary<moore::WildcardEqOp>(lhs, rhs);
1676 case BinaryOperator::WildcardInequality:
1677 return createBinary<moore::WildcardNeOp>(lhs, rhs);
1679 case BinaryOperator::GreaterThanEqual:
1680 if (expr.left().type->isSigned())
1681 return createBinary<moore::SgeOp>(lhs, rhs);
1682 else if (isa<moore::StringType>(lhs.getType()))
1683 return moore::StringCmpOp::create(
1684 builder, loc, moore::StringCmpPredicate::ge, lhs, rhs);
1686 return createBinary<moore::UgeOp>(lhs, rhs);
1687 case BinaryOperator::GreaterThan:
1688 if (expr.left().type->isSigned())
1689 return createBinary<moore::SgtOp>(lhs, rhs);
1690 else if (isa<moore::StringType>(lhs.getType()))
1691 return moore::StringCmpOp::create(
1692 builder, loc, moore::StringCmpPredicate::gt, lhs, rhs);
1694 return createBinary<moore::UgtOp>(lhs, rhs);
1695 case BinaryOperator::LessThanEqual:
1696 if (expr.left().type->isSigned())
1697 return createBinary<moore::SleOp>(lhs, rhs);
1698 else if (isa<moore::StringType>(lhs.getType()))
1699 return moore::StringCmpOp::create(
1700 builder, loc, moore::StringCmpPredicate::le, lhs, rhs);
1702 return createBinary<moore::UleOp>(lhs, rhs);
1703 case BinaryOperator::LessThan:
1704 if (expr.left().type->isSigned())
1705 return createBinary<moore::SltOp>(lhs, rhs);
1706 else if (isa<moore::StringType>(lhs.getType()))
1707 return moore::StringCmpOp::create(
1708 builder, loc, moore::StringCmpPredicate::lt, lhs, rhs);
1710 return createBinary<moore::UltOp>(lhs, rhs);
1712 case BinaryOperator::LogicalAnd:
1713 case BinaryOperator::LogicalOr:
1714 case BinaryOperator::LogicalImplication:
1715 case BinaryOperator::LogicalEquivalence:
1716 return buildLogicalBOp(expr.op, lhs, rhs, domain);
1718 case BinaryOperator::LogicalShiftLeft:
1719 return createBinary<moore::ShlOp>(lhs, rhs);
1720 case BinaryOperator::LogicalShiftRight:
1721 return createBinary<moore::ShrOp>(lhs, rhs);
1722 case BinaryOperator::ArithmeticShiftLeft:
1723 return createBinary<moore::ShlOp>(lhs, rhs);
1724 case BinaryOperator::ArithmeticShiftRight: {
1727 lhs =
context.convertToSimpleBitVector(lhs);
1728 rhs =
context.convertToSimpleBitVector(rhs);
1731 if (expr.type->isSigned())
1732 return moore::AShrOp::create(builder, loc, lhs, rhs);
1733 return moore::ShrOp::create(builder, loc, lhs, rhs);
1737 mlir::emitError(loc,
"unsupported binary operator");
1742 Value visit(
const slang::ast::UnbasedUnsizedIntegerLiteral &expr) {
1743 return context.materializeSVInt(expr.getValue(), *expr.type, loc);
1747 Value visit(
const slang::ast::IntegerLiteral &expr) {
1748 return context.materializeSVInt(expr.getValue(), *expr.type, loc);
1752 Value visit(
const slang::ast::TimeLiteral &expr) {
1757 double value = std::round(expr.getValue() * scale);
1767 static constexpr uint64_t limit =
1768 (std::numeric_limits<uint64_t>::max() >> 11) << 11;
1769 if (value > limit) {
1770 mlir::emitError(loc) <<
"time value is larger than " << limit <<
" fs";
1774 return moore::ConstantTimeOp::create(builder, loc,
1775 static_cast<uint64_t
>(value));
1779 Value visit(
const slang::ast::ReplicationExpression &expr) {
1780 auto type =
context.convertType(*expr.type);
1781 auto value =
context.convertRvalueExpression(expr.concat());
1784 return moore::ReplicateOp::create(builder, loc, type, value);
1788 Value visit(
const slang::ast::InsideExpression &expr) {
1789 auto lhs =
context.convertToSimpleBitVector(
1790 context.convertRvalueExpression(expr.left()));
1795 SmallVector<Value> conditions;
1798 for (
const auto *listExpr : expr.rangeList()) {
1799 auto cond =
context.convertInsideCheck(lhs, loc, *listExpr);
1803 conditions.push_back(cond);
1807 auto result = conditions.back();
1808 conditions.pop_back();
1809 while (!conditions.empty()) {
1810 result = moore::OrOp::create(builder, loc, conditions.back(), result);
1811 conditions.pop_back();
1817 Value visit(
const slang::ast::ConditionalExpression &expr) {
1818 auto type =
context.convertType(*expr.type);
1821 if (expr.conditions.size() > 1) {
1822 mlir::emitError(loc)
1823 <<
"unsupported conditional expression with more than one condition";
1826 const auto &cond = expr.conditions[0];
1828 mlir::emitError(loc) <<
"unsupported conditional expression with pattern";
1832 context.convertToBool(
context.convertRvalueExpression(*cond.expr));
1835 auto conditionalOp =
1836 moore::ConditionalOp::create(builder, loc, type, value);
1839 auto &trueBlock = conditionalOp.getTrueRegion().emplaceBlock();
1840 auto &falseBlock = conditionalOp.getFalseRegion().emplaceBlock();
1842 OpBuilder::InsertionGuard g(builder);
1845 builder.setInsertionPointToStart(&trueBlock);
1846 auto trueValue =
context.convertRvalueExpression(expr.left(), type);
1849 moore::YieldOp::create(builder, loc, trueValue);
1852 builder.setInsertionPointToStart(&falseBlock);
1853 auto falseValue =
context.convertRvalueExpression(expr.right(), type);
1856 moore::YieldOp::create(builder, loc, falseValue);
1858 return conditionalOp.getResult();
1862 Value visit(
const slang::ast::CallExpression &expr) {
1864 auto constant =
context.evaluateConstant(expr);
1865 if (
auto value =
context.materializeConstant(constant, *expr.type, loc))
1869 [&](
auto &subroutine) {
return visitCall(expr, subroutine); },
1875 std::pair<Value, moore::ClassHandleType>
1876 getMethodReceiverTypeHandle(
const slang::ast::CallExpression &expr) {
1878 moore::ClassHandleType handleTy;
1882 if (
const slang::ast::Expression *recvExpr = expr.thisClass()) {
1883 thisRef =
context.convertRvalueExpression(*recvExpr);
1888 thisRef =
context.getImplicitThisRef();
1890 mlir::emitError(loc) <<
"method '" << expr.getSubroutineName()
1891 <<
"' called without an object";
1895 handleTy = cast<moore::ClassHandleType>(thisRef.getType());
1896 return {thisRef, handleTy};
1900 mlir::CallOpInterface
1901 buildMethodCall(
const slang::ast::SubroutineSymbol *subroutine,
1903 moore::ClassHandleType actualHandleTy, Value actualThisRef,
1904 SmallVector<Value> &arguments,
1905 SmallVector<Type> &resultTypes) {
1908 auto funcTy = cast<FunctionType>(lowering->
op.getFunctionType());
1909 auto expected0 = funcTy.getInput(0);
1910 auto expectedHdlTy = cast<moore::ClassHandleType>(expected0);
1913 auto implicitThisRef =
context.materializeConversion(
1914 expectedHdlTy, actualThisRef,
false, actualThisRef.getLoc());
1917 SmallVector<Value> explicitArguments;
1918 explicitArguments.reserve(arguments.size() + 1);
1919 explicitArguments.push_back(implicitThisRef);
1920 explicitArguments.append(arguments.begin(), arguments.end());
1923 const bool isVirtual =
1924 (subroutine->flags & slang::ast::MethodFlags::Virtual) != 0;
1927 auto calleeSym = lowering->
op.getNameAttr().getValue();
1928 if (isa<moore::CoroutineOp>(lowering->
op.getOperation()))
1929 return moore::CallCoroutineOp::create(builder, loc, resultTypes,
1930 calleeSym, explicitArguments);
1931 return mlir::func::CallOp::create(builder, loc, resultTypes, calleeSym,
1935 auto funcName = subroutine->name;
1936 auto method = moore::VTableLoadMethodOp::create(
1937 builder, loc, funcTy, actualThisRef,
1938 SymbolRefAttr::get(
context.getContext(), funcName));
1939 return mlir::func::CallIndirectOp::create(builder, loc, method,
1944 Value visitCall(
const slang::ast::CallExpression &expr,
1945 const slang::ast::SubroutineSymbol *subroutine) {
1947 const bool isMethod = (subroutine->thisVar !=
nullptr);
1949 auto *lowering =
context.declareFunction(*subroutine);
1953 if (isa<moore::DPIFuncOp>(lowering->
op.getOperation())) {
1954 SmallVector<Value> operands;
1955 SmallVector<Value> resultTargets;
1957 for (
auto [callArg, declArg] :
1958 llvm::zip(expr.arguments(), subroutine->getArguments())) {
1959 auto *actual = callArg;
1960 if (
const auto *assign =
1961 actual->as_if<slang::ast::AssignmentExpression>())
1962 actual = &assign->left();
1964 auto argType =
context.convertType(declArg->getType());
1968 switch (declArg->direction) {
1969 case slang::ast::ArgumentDirection::In: {
1970 auto value =
context.convertRvalueExpression(*actual, argType);
1973 operands.push_back(value);
1976 case slang::ast::ArgumentDirection::Out: {
1977 auto lvalue =
context.convertLvalueExpression(*actual);
1980 resultTargets.push_back(lvalue);
1983 case slang::ast::ArgumentDirection::InOut:
1984 case slang::ast::ArgumentDirection::Ref: {
1985 auto lvalue =
context.convertLvalueExpression(*actual);
1988 auto value =
context.convertRvalueExpression(*actual, argType);
1991 operands.push_back(value);
1992 resultTargets.push_back(lvalue);
1998 SmallVector<Type> resultTypes(
1999 cast<FunctionType>(lowering->
op.getFunctionType()).getResults());
2000 auto callOp = moore::FuncDPICallOp::create(
2001 builder, loc, resultTypes,
2002 SymbolRefAttr::get(lowering->
op.getNameAttr()), operands);
2004 unsigned resultIndex = 0;
2005 unsigned targetIndex = 0;
2006 for (
const auto *declArg : subroutine->getArguments()) {
2007 auto argType =
context.convertType(declArg->getType());
2011 switch (declArg->direction) {
2012 case slang::ast::ArgumentDirection::Out:
2013 case slang::ast::ArgumentDirection::InOut:
2014 case slang::ast::ArgumentDirection::Ref: {
2015 auto lvalue = resultTargets[targetIndex++];
2016 auto refTy = dyn_cast<moore::RefType>(lvalue.getType());
2018 lowering->
op->emitError(
2019 "expected DPI output target to be moore::RefType");
2022 auto converted =
context.materializeConversion(
2023 refTy.getNestedType(), callOp->getResult(resultIndex++),
2024 declArg->getType().isSigned(), loc);
2027 moore::BlockingAssignOp::create(builder, loc, lvalue, converted);
2035 if (!subroutine->getReturnType().isVoid())
2036 return callOp->getResult(resultIndex);
2038 return mlir::UnrealizedConversionCastOp::create(
2039 builder, loc, moore::VoidType::get(
context.getContext()),
2047 SmallVector<Value> arguments;
2048 for (
auto [callArg, declArg] :
2049 llvm::zip(expr.arguments(), subroutine->getArguments())) {
2053 auto *expr = callArg;
2054 if (
const auto *assign = expr->as_if<slang::ast::AssignmentExpression>())
2055 expr = &assign->left();
2058 auto type =
context.convertType(declArg->getType());
2059 if (declArg->direction == slang::ast::ArgumentDirection::In) {
2060 value =
context.convertRvalueExpression(*expr, type);
2062 Value lvalue =
context.convertLvalueExpression(*expr);
2063 auto unpackedType = dyn_cast<moore::UnpackedType>(type);
2067 context.materializeConversion(moore::RefType::get(unpackedType),
2068 lvalue, expr->type->isSigned(), loc);
2072 arguments.push_back(value);
2079 for (
auto *sym : lowering->capturedSymbols) {
2080 Value val =
context.valueSymbols.lookup(sym);
2082 mlir::emitError(loc) <<
"failed to resolve captured variable `"
2083 << sym->name <<
"` at call site";
2086 arguments.push_back(val);
2090 SmallVector<Type> resultTypes(
2091 cast<FunctionType>(lowering->
op.getFunctionType()).getResults().begin(),
2092 cast<FunctionType>(lowering->
op.getFunctionType()).getResults().end());
2094 mlir::CallOpInterface callOp;
2098 auto [thisRef, tyHandle] = getMethodReceiverTypeHandle(expr);
2099 callOp = buildMethodCall(subroutine, lowering, tyHandle, thisRef,
2100 arguments, resultTypes);
2101 }
else if (isa<moore::CoroutineOp>(lowering->
op.getOperation())) {
2103 auto coroutine = cast<moore::CoroutineOp>(lowering->
op.getOperation());
2105 moore::CallCoroutineOp::create(builder, loc, coroutine, arguments);
2108 auto funcOp = cast<mlir::func::FuncOp>(lowering->
op.getOperation());
2109 callOp = mlir::func::CallOp::create(builder, loc, funcOp, arguments);
2112 auto result = resultTypes.size() > 0 ? callOp->getOpResult(0) : Value{};
2116 if (resultTypes.size() == 0)
2117 return mlir::UnrealizedConversionCastOp::create(
2118 builder, loc, moore::VoidType::get(
context.getContext()),
2126 Value visitCall(
const slang::ast::CallExpression &expr,
2127 const slang::ast::CallExpression::SystemCallInfo &info) {
2128 using ksn = slang::parsing::KnownSystemName;
2129 const auto &subroutine = *
info.subroutine;
2130 auto nameId = subroutine.knownNameId;
2141 return context.convertSampledValueCallExpression(expr, info, loc);
2146 auto args = expr.arguments();
2154 if (nameId == ksn::SFormatF) {
2156 auto fmtValue =
context.convertFormatString(
2157 expr.arguments(), loc, moore::IntFormat::Decimal,
false);
2158 if (failed(fmtValue))
2160 return fmtValue.value();
2164 auto result =
context.convertSystemCall(subroutine, loc, args);
2168 auto ty =
context.convertType(*expr.type);
2172 bool isSigned = expr.type->isSigned();
2173 if (nameId == ksn::CountOnes || nameId == ksn::IsUnknown ||
2174 nameId == ksn::OneHot || nameId == ksn::OneHot0)
2176 return context.materializeConversion(ty, result, isSigned, loc);
2180 Value visit(
const slang::ast::StringLiteral &expr) {
2181 auto type =
context.convertType(*expr.type);
2182 return moore::ConstantStringOp::create(builder, loc, type, expr.getValue());
2186 Value visit(
const slang::ast::RealLiteral &expr) {
2187 auto fTy = mlir::Float64Type::get(
context.getContext());
2188 auto attr = mlir::FloatAttr::get(fTy, expr.getValue());
2189 return moore::ConstantRealOp::create(builder, loc, attr).getResult();
2194 FailureOr<SmallVector<Value>>
2195 convertElements(
const slang::ast::AssignmentPatternExpressionBase &expr,
2196 std::variant<Type, ArrayRef<Type>> expectedTypes,
2197 unsigned replCount) {
2198 const auto &elts = expr.elements();
2199 const size_t elementCount = elts.size();
2202 const bool hasBroadcast =
2203 std::holds_alternative<Type>(expectedTypes) &&
2204 static_cast<bool>(std::get<Type>(expectedTypes));
2206 const bool hasPerElem =
2207 std::holds_alternative<ArrayRef<Type>>(expectedTypes) &&
2208 !std::get<ArrayRef<Type>>(expectedTypes).empty();
2212 auto types = std::get<ArrayRef<Type>>(expectedTypes);
2213 if (types.size() != elementCount) {
2214 mlir::emitError(loc)
2215 <<
"assignment pattern arity mismatch: expected " << types.size()
2216 <<
" elements, got " << elementCount;
2221 SmallVector<Value> converted;
2222 converted.reserve(elementCount * std::max(1u, replCount));
2225 if (!hasBroadcast && !hasPerElem) {
2227 for (
const auto *elementExpr : elts) {
2228 Value v =
context.convertRvalueExpression(*elementExpr);
2231 converted.push_back(v);
2233 }
else if (hasBroadcast) {
2235 Type want = std::get<Type>(expectedTypes);
2236 for (
const auto *elementExpr : elts) {
2237 Value v = want ?
context.convertRvalueExpression(*elementExpr, want)
2238 :
context.convertRvalueExpression(*elementExpr);
2241 converted.push_back(v);
2244 auto types = std::get<ArrayRef<Type>>(expectedTypes);
2245 for (
size_t i = 0; i < elementCount; ++i) {
2246 Type want = types[i];
2247 const auto *elementExpr = elts[i];
2248 Value v = want ?
context.convertRvalueExpression(*elementExpr, want)
2249 :
context.convertRvalueExpression(*elementExpr);
2252 converted.push_back(v);
2256 for (
unsigned i = 1; i < replCount; ++i)
2257 converted.append(converted.begin(), converted.begin() + elementCount);
2263 Value visitAssignmentPattern(
2264 const slang::ast::AssignmentPatternExpressionBase &expr,
2265 unsigned replCount = 1) {
2266 auto type =
context.convertType(*expr.type);
2267 const auto &elts = expr.elements();
2270 if (
auto intType = dyn_cast<moore::IntType>(type)) {
2271 auto elements = convertElements(expr, {}, replCount);
2273 if (failed(elements))
2276 assert(intType.getWidth() == elements->size());
2277 std::reverse(elements->begin(), elements->end());
2278 return moore::ConcatOp::create(builder, loc, intType, *elements);
2282 if (
auto structType = dyn_cast<moore::StructType>(type)) {
2283 SmallVector<Type> expectedTy;
2284 expectedTy.reserve(structType.getMembers().size());
2285 for (
auto member : structType.getMembers())
2286 expectedTy.push_back(member.type);
2288 FailureOr<SmallVector<Value>> elements;
2289 if (expectedTy.size() == elts.size())
2290 elements = convertElements(expr, expectedTy, replCount);
2292 elements = convertElements(expr, {}, replCount);
2294 if (failed(elements))
2297 assert(structType.getMembers().size() == elements->size());
2298 return moore::StructCreateOp::create(builder, loc, structType, *elements);
2302 if (
auto structType = dyn_cast<moore::UnpackedStructType>(type)) {
2303 SmallVector<Type> expectedTy;
2304 expectedTy.reserve(structType.getMembers().size());
2305 for (
auto member : structType.getMembers())
2306 expectedTy.push_back(member.type);
2308 FailureOr<SmallVector<Value>> elements;
2309 if (expectedTy.size() == elts.size())
2310 elements = convertElements(expr, expectedTy, replCount);
2312 elements = convertElements(expr, {}, replCount);
2314 if (failed(elements))
2317 assert(structType.getMembers().size() == elements->size());
2319 return moore::StructCreateOp::create(builder, loc, structType, *elements);
2323 if (
auto arrayType = dyn_cast<moore::ArrayType>(type)) {
2325 convertElements(expr, arrayType.getElementType(), replCount);
2327 if (failed(elements))
2330 assert(arrayType.getSize() == elements->size());
2331 return moore::ArrayCreateOp::create(builder, loc, arrayType, *elements);
2335 if (
auto arrayType = dyn_cast<moore::UnpackedArrayType>(type)) {
2337 convertElements(expr, arrayType.getElementType(), replCount);
2339 if (failed(elements))
2342 assert(arrayType.getSize() == elements->size());
2343 return moore::ArrayCreateOp::create(builder, loc, arrayType, *elements);
2347 if (
auto openType = dyn_cast<moore::OpenUnpackedArrayType>(type)) {
2349 convertElements(expr, openType.getElementType(), replCount);
2351 if (failed(elements))
2354 auto arrayType = moore::UnpackedArrayType::get(
2355 context.getContext(), elements->size(), openType.getElementType());
2356 return moore::ArrayCreateOp::create(builder, loc, arrayType, *elements);
2359 mlir::emitError(loc) <<
"unsupported assignment pattern with type " << type;
2363 Value visit(
const slang::ast::SimpleAssignmentPatternExpression &expr) {
2364 return visitAssignmentPattern(expr);
2367 Value visit(
const slang::ast::StructuredAssignmentPatternExpression &expr) {
2368 return visitAssignmentPattern(expr);
2371 Value visit(
const slang::ast::ReplicatedAssignmentPatternExpression &expr) {
2373 context.evaluateConstant(expr.count()).integer().as<
unsigned>();
2374 assert(count &&
"Slang guarantees constant non-zero replication count");
2375 return visitAssignmentPattern(expr, *count);
2378 Value visit(
const slang::ast::StreamingConcatenationExpression &expr) {
2379 SmallVector<Value> operands;
2380 for (
auto stream : expr.streams()) {
2381 auto operandLoc =
context.convertLocation(stream.operand->sourceRange);
2382 if (!stream.constantWithWidth.has_value() && stream.withExpr) {
2383 mlir::emitError(operandLoc)
2384 <<
"Moore only support streaming "
2385 "concatenation with fixed size 'with expression'";
2389 if (stream.constantWithWidth.has_value()) {
2390 value =
context.convertRvalueExpression(*stream.withExpr);
2391 auto type = cast<moore::UnpackedType>(value.getType());
2392 auto intType = moore::IntType::get(
2393 context.getContext(), type.getBitSize().value(), type.getDomain());
2395 value =
context.materializeConversion(intType, value,
false, loc);
2397 value =
context.convertRvalueExpression(*stream.operand);
2400 value =
context.convertToSimpleBitVector(value);
2403 operands.push_back(value);
2407 if (operands.size() == 1) {
2410 value = operands.front();
2412 value = moore::ConcatOp::create(builder, loc, operands).getResult();
2415 if (expr.getSliceSize() == 0) {
2419 auto type = cast<moore::IntType>(value.getType());
2420 SmallVector<Value> slicedOperands;
2421 auto iterMax = type.getWidth() / expr.getSliceSize();
2422 auto remainSize = type.getWidth() % expr.getSliceSize();
2424 for (
size_t i = 0; i < iterMax; i++) {
2425 auto extractResultType = moore::IntType::get(
2426 context.getContext(), expr.getSliceSize(), type.getDomain());
2428 auto extracted = moore::ExtractOp::create(builder, loc, extractResultType,
2429 value, i * expr.getSliceSize());
2430 slicedOperands.push_back(extracted);
2434 auto extractResultType = moore::IntType::get(
2435 context.getContext(), remainSize, type.getDomain());
2438 moore::ExtractOp::create(builder, loc, extractResultType, value,
2439 iterMax * expr.getSliceSize());
2440 slicedOperands.push_back(extracted);
2443 return moore::ConcatOp::create(builder, loc, slicedOperands);
2446 Value visit(
const slang::ast::AssertionInstanceExpression &expr) {
2447 return context.convertAssertionExpression(expr.body, loc);
2450 Value visit(
const slang::ast::UnboundedLiteral &expr) {
2452 "slang checks $ only used within queue index expression");
2456 moore::QueueSizeBIOp::create(builder, loc,
context.getIndexedQueue());
2457 auto one = moore::ConstantOp::create(builder, loc, queueSize.getType(), 1);
2458 auto lastElement = moore::SubOp::create(builder, loc, queueSize, one);
2475 Value visit(
const slang::ast::NewClassExpression &expr) {
2476 auto type =
context.convertType(*expr.type);
2477 auto classTy = dyn_cast<moore::ClassHandleType>(type);
2483 if (!classTy && expr.isSuperClass) {
2484 newObj =
context.getImplicitThisRef();
2485 if (!newObj || !newObj.getType() ||
2486 !isa<moore::ClassHandleType>(newObj.getType())) {
2487 mlir::emitError(loc) <<
"implicit this ref was not set while "
2488 "converting new class function";
2491 auto thisType = cast<moore::ClassHandleType>(newObj.getType());
2493 cast<moore::ClassDeclOp>(*
context.symbolTable.lookupNearestSymbolFrom(
2494 context.intoModuleOp, thisType.getClassSym()));
2495 auto baseClassSym = classDecl.getBase();
2496 classTy = circt::moore::ClassHandleType::get(
context.getContext(),
2497 baseClassSym.value());
2500 newObj = moore::ClassNewOp::create(builder, loc, classTy, {});
2503 const auto *constructor = expr.constructorCall();
2508 if (
const auto *callConstructor =
2509 constructor->as_if<slang::ast::CallExpression>())
2510 if (
const auto *subroutine =
2511 std::get_if<const slang::ast::SubroutineSymbol *>(
2512 &callConstructor->subroutine)) {
2513 if (!(*subroutine)->thisVar) {
2514 mlir::emitError(loc)
2515 <<
"unsupported constructor call without `this` argument";
2519 llvm::SaveAndRestore saveThis(
context.currentThisRef, newObj);
2520 if (!visitCall(*callConstructor, *subroutine))
2528 template <
typename T>
2529 Value visit(T &&node) {
2530 mlir::emitError(loc,
"unsupported expression: ")
2531 << slang::ast::toString(node.kind);
2535 Value visitInvalid(
const slang::ast::Expression &expr) {
2536 mlir::emitError(loc,
"invalid expression");
2547struct LvalueExprVisitor :
public ExprVisitor {
2549 : ExprVisitor(
context, loc, true) {}
2550 using ExprVisitor::visit;
2553 Value visit(
const slang::ast::NamedValueExpression &expr) {
2555 if (
auto value =
context.valueSymbols.lookup(&expr.symbol))
2559 if (
auto globalOp =
context.globalVariables.lookup(&expr.symbol))
2560 return moore::GetGlobalVariableOp::create(builder, loc, globalOp);
2562 if (
auto *
const property =
2563 expr.symbol.as_if<slang::ast::ClassPropertySymbol>()) {
2567 if (
auto access =
context.virtualIfaceMembers.lookup(&expr.symbol);
2569 auto type =
context.convertType(*expr.type);
2572 auto memberType = dyn_cast<moore::UnpackedType>(type);
2574 mlir::emitError(loc)
2575 <<
"unsupported virtual interface member type: " << type;
2579 Value base = materializeSymbolRvalue(*access.base);
2581 auto d = mlir::emitError(loc,
"unknown name `")
2582 << access.base->name <<
"`";
2583 d.attachNote(
context.convertLocation(access.base->location))
2584 <<
"no rvalue generated for virtual interface base";
2588 auto fieldName = access.fieldName
2590 : builder.getStringAttr(expr.symbol.name);
2591 auto memberRefType = moore::RefType::get(memberType);
2592 return moore::StructExtractOp::create(builder, loc, memberRefType,
2596 auto d = mlir::emitError(loc,
"unknown name `") << expr.symbol.name <<
"`";
2597 d.attachNote(
context.convertLocation(expr.symbol.location))
2598 <<
"no lvalue generated for " << slang::ast::toString(expr.symbol.kind);
2603 Value visit(
const slang::ast::HierarchicalValueExpression &expr) {
2606 if (!expr.ref.path.empty()) {
2607 if (
auto *inst = expr.ref.path.front()
2608 .symbol->as_if<slang::ast::InstanceSymbol>()) {
2610 expr.symbol.getParentScope()->getContainingInstance();
2611 if (&inst->body == symbolBody ||
2612 (symbolBody && inst->body.getDeclaringDefinition() ==
2613 symbolBody->getDeclaringDefinition())) {
2614 if (
auto value =
context.valueSymbols.lookup(&expr.symbol))
2621 if (
auto value =
context.resolveCapturedValue(expr.symbol))
2627 if (
auto key =
context.buildHierValueKey(expr)) {
2628 if (
auto it =
context.hierValueSymbols.find(*key);
2629 it !=
context.hierValueSymbols.end())
2634 if (
auto value =
context.valueSymbols.lookup(&expr.symbol))
2641 if (
auto globalOp =
context.globalVariables.lookup(&expr.symbol))
2642 return moore::GetGlobalVariableOp::create(builder, loc, globalOp);
2646 auto d = mlir::emitError(loc,
"unknown hierarchical name `")
2647 << expr.symbol.name <<
"`";
2648 d.attachNote(
context.convertLocation(expr.symbol.location))
2649 <<
"no lvalue generated for " << slang::ast::toString(expr.symbol.kind);
2653 Value visit(
const slang::ast::StreamingConcatenationExpression &expr) {
2654 SmallVector<Value> operands;
2655 for (
auto stream : expr.streams()) {
2656 auto operandLoc =
context.convertLocation(stream.operand->sourceRange);
2657 if (!stream.constantWithWidth.has_value() && stream.withExpr) {
2658 mlir::emitError(operandLoc)
2659 <<
"Moore only support streaming "
2660 "concatenation with fixed size 'with expression'";
2664 if (stream.constantWithWidth.has_value()) {
2665 value =
context.convertLvalueExpression(*stream.withExpr);
2666 auto type = cast<moore::UnpackedType>(
2667 cast<moore::RefType>(value.getType()).getNestedType());
2668 auto intType = moore::RefType::get(moore::IntType::get(
2669 context.getContext(), type.getBitSize().value(), type.getDomain()));
2671 value =
context.materializeConversion(intType, value,
false, loc);
2673 value =
context.convertLvalueExpression(*stream.operand);
2678 operands.push_back(value);
2681 if (operands.size() == 1) {
2684 value = operands.front();
2686 value = moore::ConcatRefOp::create(builder, loc, operands).getResult();
2689 if (expr.getSliceSize() == 0) {
2693 auto type = cast<moore::IntType>(
2694 cast<moore::RefType>(value.getType()).getNestedType());
2695 SmallVector<Value> slicedOperands;
2696 auto widthSum = type.getWidth();
2697 auto domain = type.getDomain();
2698 auto iterMax = widthSum / expr.getSliceSize();
2699 auto remainSize = widthSum % expr.getSliceSize();
2701 for (
size_t i = 0; i < iterMax; i++) {
2702 auto extractResultType = moore::RefType::get(moore::IntType::get(
2703 context.getContext(), expr.getSliceSize(), domain));
2705 auto extracted = moore::ExtractRefOp::create(
2706 builder, loc, extractResultType, value, i * expr.getSliceSize());
2707 slicedOperands.push_back(extracted);
2711 auto extractResultType = moore::RefType::get(
2712 moore::IntType::get(
context.getContext(), remainSize, domain));
2715 moore::ExtractRefOp::create(builder, loc, extractResultType, value,
2716 iterMax * expr.getSliceSize());
2717 slicedOperands.push_back(extracted);
2720 return moore::ConcatRefOp::create(builder, loc, slicedOperands);
2724 template <
typename T>
2725 Value visit(T &&node) {
2726 return context.convertRvalueExpression(node);
2729 Value visitInvalid(
const slang::ast::Expression &expr) {
2730 mlir::emitError(loc,
"invalid expression");
2740Value Context::resolveCapturedValue(
const slang::ast::ValueSymbol &sym) {
2748std::optional<std::pair<const slang::ast::InstanceSymbol *, mlir::StringAttr>>
2750 const slang::ast::HierarchicalValueExpression &expr) {
2751 if (expr.ref.path.empty())
2752 return std::nullopt;
2754 const slang::ast::InstanceSymbol *firstInst =
nullptr;
2755 SmallVector<StringRef, 4> names;
2756 for (
auto &elem : expr.ref.path) {
2757 if (
auto *inst = elem.symbol->as_if<slang::ast::InstanceSymbol>()) {
2761 names.push_back(inst->name);
2765 names.push_back(expr.symbol.name);
2766 std::string hierName = llvm::join(names,
".");
2769 return std::nullopt;
2770 return std::make_pair(firstInst,
builder.getStringAttr(hierName));
2778 Type requiredType) {
2780 auto value = expr.visit(RvalueExprVisitor(*
this, loc));
2781 if (value && requiredType)
2789 return expr.visit(LvalueExprVisitor(*
this, loc));
2797 if (
auto type = dyn_cast_or_null<moore::IntType>(value.getType()))
2798 if (type.getBitSize() == 1)
2800 if (
auto type = dyn_cast_or_null<moore::UnpackedType>(value.getType()))
2801 return moore::BoolCastOp::create(
builder, value.getLoc(), value);
2802 mlir::emitError(value.getLoc(),
"expression of type ")
2803 << value.getType() <<
" cannot be cast to a boolean";
2809 const slang::ast::Type &astType,
2811 const auto *floatType = astType.as_if<slang::ast::FloatingType>();
2815 if (svreal.isShortReal() &&
2816 floatType->floatKind == slang::ast::FloatingType::ShortReal) {
2817 attr = FloatAttr::get(
builder.getF32Type(), svreal.shortReal().v);
2818 }
else if (svreal.isReal() &&
2819 floatType->floatKind == slang::ast::FloatingType::Real) {
2820 attr = FloatAttr::get(
builder.getF64Type(), svreal.real().v);
2822 mlir::emitError(loc) <<
"invalid real constant";
2826 return moore::ConstantRealOp::create(
builder, loc, attr);
2831 const slang::ast::Type &astType,
2833 if (!astType.isString())
2835 const std::string &str = stringLiteral.str();
2836 auto intTy = moore::IntType::getInt(
getContext(),
2837 static_cast<unsigned>(str.size() * 8));
2839 moore::ConstantStringOp::create(
builder, loc, intTy, str).getResult();
2840 return moore::IntToStringOp::create(
builder, loc, immInt).getResult();
2845 const slang::ast::Type &astType, Location loc) {
2850 bool typeIsFourValued =
false;
2851 if (
auto unpackedType = dyn_cast<moore::UnpackedType>(type))
2855 auto intType = moore::IntType::get(
getContext(), fvint.getBitWidth(),
2856 fvint.hasUnknown() || typeIsFourValued
2859 auto result = moore::ConstantOp::create(
builder, loc, intType, fvint);
2864 const slang::ConstantValue &constant,
2865 const slang::ast::FixedSizeUnpackedArrayType &astType, Location loc) {
2872 if (astType.elementType.isString()) {
2873 auto arrayType = dyn_cast<moore::UnpackedArrayType>(type);
2877 SmallVector<Value> elemVals;
2878 for (
const auto &elem : constant.elements()) {
2879 if (!elem.isString())
2884 elemVals.push_back(value);
2886 if (elemVals.size() != arrayType.getSize())
2888 return moore::ArrayCreateOp::create(
builder, loc, arrayType, elemVals);
2893 if (astType.elementType.isIntegral())
2894 bitWidth = astType.elementType.getBitWidth();
2898 bool typeIsFourValued =
false;
2901 if (
auto unpackedType = dyn_cast<moore::UnpackedType>(type))
2912 auto intType = moore::IntType::get(
getContext(), bitWidth, domain);
2914 auto arrType = moore::UnpackedArrayType::get(
2915 getContext(), constant.elements().size(), intType);
2917 llvm::SmallVector<mlir::Value> elemVals;
2918 moore::ConstantOp constOp;
2920 mlir::OpBuilder::InsertionGuard guard(
builder);
2923 for (
auto elem : constant.elements()) {
2925 constOp = moore::ConstantOp::create(
builder, loc, intType, fvInt);
2926 elemVals.push_back(constOp.getResult());
2931 auto arrayOp = moore::ArrayCreateOp::create(
builder, loc, arrType, elemVals);
2933 return arrayOp.getResult();
2937 const slang::ast::Type &type, Location loc) {
2939 if (
auto *arr = type.as_if<slang::ast::FixedSizeUnpackedArrayType>())
2941 if (constant.isInteger())
2943 if (constant.isReal() || constant.isShortReal())
2945 if (constant.isString())
2953 using slang::ast::EvalFlags;
2954 slang::ast::EvalContext evalContext(
2956 slang::ast::LookupLocation::max),
2957 EvalFlags::CacheResults | EvalFlags::SpecparamsAllowed);
2958 return expr.eval(evalContext);
2967 auto type = moore::IntType::get(
getContext(), 1, domain);
2974 if (isa<moore::IntType>(value.getType()))
2981 if (
auto packed = dyn_cast<moore::PackedType>(value.getType()))
2982 if (
auto sbvType = packed.getSimpleBitVector())
2985 mlir::emitError(value.getLoc()) <<
"expression of type " << value.getType()
2986 <<
" cannot be cast to a simple bit vector";
2992 if (isa<moore::IntType>(value.getType()))
2995 auto packedType = cast<moore::PackedType>(value.getType());
2996 auto intType = packedType.getSimpleBitVector();
3001 if (isa<moore::TimeType>(packedType) &&
3003 value =
builder.createOrFold<moore::TimeToLogicOp>(loc, value);
3004 auto scale = moore::ConstantOp::create(
builder, loc, intType,
3006 return builder.createOrFold<moore::DivUOp>(loc, value, scale);
3012 if (packedType.containsTimeType()) {
3014 mlir::emitError(loc) <<
"unsupported conversion: " << packedType
3015 <<
" cannot be converted to " << intType
3016 <<
"; contains a time type";
3021 return builder.createOrFold<moore::PackedToSBVOp>(loc, value);
3029 Value value, Location loc,
3031 if (value.getType() == packedType)
3034 auto &builder =
context.builder;
3035 auto intType = cast<moore::IntType>(value.getType());
3040 if (isa<moore::TimeType>(packedType) &&
3042 auto scale = moore::ConstantOp::create(builder, loc, intType,
3044 value = builder.createOrFold<moore::MulOp>(loc, value, scale);
3045 return builder.createOrFold<moore::LogicToTimeOp>(loc, value);
3053 mlir::emitError(loc) <<
"unsupported conversion: " << intType
3054 <<
" cannot be converted to " << packedType
3055 <<
"; contains a time type";
3060 return builder.createOrFold<moore::SBVToPackedOp>(loc, packedType, value);
3066 moore::ClassHandleType expectedHandleTy) {
3067 auto loc = actualHandle.getLoc();
3069 auto actualTy = actualHandle.getType();
3070 auto actualHandleTy = dyn_cast<moore::ClassHandleType>(actualTy);
3071 if (!actualHandleTy) {
3072 mlir::emitError(loc) <<
"expected a !moore.class<...> value, got "
3078 if (actualHandleTy == expectedHandleTy)
3079 return actualHandle;
3081 if (!
context.isClassDerivedFrom(actualHandleTy, expectedHandleTy)) {
3082 mlir::emitError(loc)
3083 <<
"receiver class " << actualHandleTy.getClassSym()
3084 <<
" is not the same as, or derived from, expected base class "
3085 << expectedHandleTy.getClassSym().getRootReference();
3090 auto casted = moore::ClassUpcastOp::create(
context.builder, loc,
3091 expectedHandleTy, actualHandle)
3097 Location loc,
bool fallible) {
3099 if (type == value.getType())
3104 auto dstPacked = dyn_cast<moore::PackedType>(type);
3105 auto srcPacked = dyn_cast<moore::PackedType>(value.getType());
3106 auto dstInt = dstPacked ? dstPacked.getSimpleBitVector() : moore::IntType();
3107 auto srcInt = srcPacked ? srcPacked.getSimpleBitVector() : moore::IntType();
3109 if (dstInt && srcInt) {
3117 auto resizedType = moore::IntType::get(
3118 value.getContext(), dstInt.getWidth(), srcPacked.getDomain());
3119 if (dstInt.getWidth() < srcInt.getWidth()) {
3120 value =
builder.createOrFold<moore::TruncOp>(loc, resizedType, value);
3121 }
else if (dstInt.getWidth() > srcInt.getWidth()) {
3123 value =
builder.createOrFold<moore::SExtOp>(loc, resizedType, value);
3125 value =
builder.createOrFold<moore::ZExtOp>(loc, resizedType, value);
3129 if (dstInt.getDomain() != srcInt.getDomain()) {
3131 value =
builder.createOrFold<moore::LogicToIntOp>(loc, value);
3133 value =
builder.createOrFold<moore::IntToLogicOp>(loc, value);
3142 assert(value.getType() == type);
3147 if (isa<moore::StringType>(type) &&
3148 isa<moore::FormatStringType>(value.getType())) {
3149 return builder.createOrFold<moore::FormatStringToStringOp>(loc, value);
3153 if (isa<moore::FormatStringType>(type) &&
3154 isa<moore::StringType>(value.getType())) {
3155 return builder.createOrFold<moore::FormatStringOp>(loc, value);
3160 if (isa<moore::QueueType>(type) && isa<moore::QueueType>(value.getType()) &&
3161 cast<moore::QueueType>(type).getElementType() ==
3162 cast<moore::QueueType>(value.getType()).getElementType())
3163 return builder.createOrFold<moore::QueueResizeOp>(loc, type, value);
3166 if (isa<moore::QueueType>(type) &&
3167 isa<moore::UnpackedArrayType>(value.getType())) {
3168 auto queueElType = dyn_cast<moore::QueueType>(type).getElementType();
3169 auto unpackedArrayElType =
3170 dyn_cast<moore::UnpackedArrayType>(value.getType()).getElementType();
3172 if (queueElType == unpackedArrayElType) {
3173 return builder.createOrFold<moore::QueueFromUnpackedArrayOp>(loc, type,
3179 if (dstInt && isa<moore::RealType>(value.getType())) {
3180 auto twoValInt =
builder.createOrFold<moore::RealToIntOp>(
3181 loc, dstInt.getTwoValued(), value);
3186 if (isa<moore::RealType>(type) && isa<moore::IntType>(value.getType())) {
3189 if (dyn_cast<moore::IntType>(value.getType()).getDomain() ==
3194 dyn_cast<moore::IntType>(value.getType()).getTwoValued(), value,
true,
3198 return builder.createOrFold<moore::SIntToRealOp>(loc, type, twoValInt);
3199 return builder.createOrFold<moore::UIntToRealOp>(loc, type, twoValInt);
3202 auto getBuiltinFloatType = [&](moore::RealType type) -> Type {
3204 return mlir::Float32Type::get(
builder.getContext());
3206 return mlir::Float64Type::get(
builder.getContext());
3210 if (isa<moore::TimeType>(type) && isa<moore::RealType>(value.getType())) {
3212 moore::IntType::get(
builder.getContext(), 64, Domain::TwoValued);
3214 getBuiltinFloatType(cast<moore::RealType>(value.getType()));
3215 auto scale = moore::ConstantRealOp::create(
3216 builder, loc, value.getType(),
3218 auto scaled =
builder.createOrFold<moore::MulRealOp>(loc, value, scale);
3219 auto asInt = moore::RealToIntOp::create(
builder, loc, intType, scaled);
3220 auto asLogic = moore::IntToLogicOp::create(
builder, loc, asInt);
3221 return moore::LogicToTimeOp::create(
builder, loc, asLogic);
3225 if (isa<moore::RealType>(type) && isa<moore::TimeType>(value.getType())) {
3226 auto asLogic = moore::TimeToLogicOp::create(
builder, loc, value);
3227 auto asInt = moore::LogicToIntOp::create(
builder, loc, asLogic);
3228 auto asReal = moore::UIntToRealOp::create(
builder, loc, type, asInt);
3229 Type floatType = getBuiltinFloatType(cast<moore::RealType>(type));
3230 auto scale = moore::ConstantRealOp::create(
3233 return moore::DivRealOp::create(
builder, loc, asReal, scale);
3237 if (isa<moore::StringType>(type)) {
3238 if (
auto intType = dyn_cast<moore::IntType>(value.getType())) {
3240 value = moore::LogicToIntOp::create(
builder, loc, value);
3241 return moore::IntToStringOp::create(
builder, loc, value);
3246 if (
auto intType = dyn_cast<moore::IntType>(type)) {
3247 if (isa<moore::StringType>(value.getType())) {
3248 value = moore::StringToIntOp::create(
builder, loc, intType.getTwoValued(),
3252 return moore::IntToLogicOp::create(
builder, loc, value);
3259 if (isa<moore::FormatStringType>(type)) {
3261 value, isSigned, loc);
3264 return moore::FormatStringOp::create(
builder, loc, asStr, {}, {}, {});
3267 if (isa<moore::RealType>(type) && isa<moore::RealType>(value.getType()))
3268 return builder.createOrFold<moore::ConvertRealOp>(loc, type, value);
3270 if (isa<moore::ClassHandleType>(type) &&
3271 isa<moore::ClassHandleType>(value.getType()))
3275 if (fallible && value.getType() != type)
3277 if (value.getType() != type)
3278 value = moore::ConversionOp::create(
builder, loc, type, value);
3284template <
typename OpTy>
3287 std::span<const slang::ast::Expression *const> args) {
3289 assert(args.size() == 1 &&
"real math builtin expects 1 argument");
3290 auto value =
context.convertRvalueExpression(*args[0]);
3293 return OpTy::create(
context.builder, loc, value);
3298template <
typename OpTy>
3301 std::span<const slang::ast::Expression *const> args) {
3303 assert(args.size() == 2 &&
"real math builtin expects 2 arguments");
3306 auto lhs =
context.convertRvalueExpression(*args[0], realType);
3307 auto rhs =
context.convertRvalueExpression(*args[1], realType);
3310 return OpTy::create(
context.builder, loc, lhs, rhs);
3316 auto &builder =
context.builder;
3317 auto newBlockAfter = [&](Block *after) -> Block * {
3318 auto block = std::make_unique<Block>();
3319 block->insertAfter(after);
3320 return block.release();
3323 for (
auto [destExpr, value, matched] : result.assignments) {
3324 auto lhs =
context.convertLvalueExpression(*destExpr);
3327 auto cond = moore::ToBuiltinIntOp::create(builder, loc, matched);
3329 auto *assignBlock = newBlockAfter(builder.getInsertionBlock());
3330 auto *continuedBlock = newBlockAfter(assignBlock);
3331 mlir::cf::CondBranchOp::create(builder, loc, cond, assignBlock,
3334 builder.setInsertionPointToEnd(assignBlock);
3335 moore::BlockingAssignOp::create(builder, loc, lhs, value);
3336 mlir::cf::BranchOp::create(builder, loc, continuedBlock);
3338 builder.setInsertionPointToEnd(continuedBlock);
3344 const slang::ast::SystemSubroutine &subroutine, Location loc,
3345 std::span<const slang::ast::Expression *const> args) {
3346 using ksn = slang::parsing::KnownSystemName;
3347 StringRef name = subroutine.name;
3348 auto nameId = subroutine.knownNameId;
3349 size_t numArgs = args.size();
3357 if (nameId == ksn::URandom || nameId == ksn::Random) {
3358 auto i32Ty = moore::IntType::getInt(
builder.getContext(), 32);
3359 auto minval = moore::ConstantOp::create(
builder, loc, i32Ty, 0);
3361 moore::ConstantOp::create(
builder, loc, i32Ty, APInt::getAllOnes(32));
3368 return moore::UrandomRangeBIOp::create(
builder, loc, minval, maxval, seed);
3371 if (nameId == ksn::URandomRange) {
3372 auto i32Ty = moore::IntType::getInt(
builder.getContext(), 32);
3382 minval = moore::ConstantOp::create(
builder, loc, i32Ty, 0);
3384 return moore::UrandomRangeBIOp::create(
builder, loc, minval, maxval,
3392 if (nameId == ksn::Time || nameId == ksn::STime || nameId == ksn::RealTime) {
3394 assert(numArgs == 0 &&
"time functions take no arguments");
3395 return moore::TimeBIOp::create(
builder, loc);
3402 if (nameId == ksn::Clog2) {
3404 assert(numArgs == 1 &&
"`$clog2` takes 1 argument");
3411 return moore::Clog2BIOp::create(
builder, loc, value);
3418 if (nameId == ksn::IsUnknown) {
3419 assert(numArgs == 1 &&
"`$isunknown` takes 1 argument");
3424 if (!isa<moore::IntType>(value.getType())) {
3425 if (!isa<moore::PackedType>(value.getType())) {
3426 mlir::emitError(loc) <<
"expected integer argument for `$isunknown`";
3434 auto valTy = dyn_cast<moore::IntType>(value.getType());
3438 if (nameId == ksn::OneHot0 || nameId == ksn::OneHot) {
3439 assert(numArgs == 1 &&
"`$onehot`/`$onehot0` takes 1 argument");
3443 if (!isa<moore::IntType>(value.getType())) {
3444 if (!isa<moore::PackedType>(value.getType())) {
3445 mlir::emitError(loc)
3446 <<
"expected integer argument for `$onehot`/`$onehot0`";
3454 auto valTy = dyn_cast<moore::IntType>(value.getType());
3456 mlir::emitError(loc) <<
"expected integer argument for `"
3457 << subroutine.name <<
"`";
3464 if (valTy.getDomain() == Domain::FourValued) {
3465 Value isUnknownMoore =
3468 builder.createOrFold<moore::ToBuiltinIntOp>(loc, isUnknownMoore);
3476 auto minusOne = comb::SubOp::create(
builder, loc, intVal, one);
3477 auto anded = comb::AndOp::create(
builder, loc, intVal, minusOne);
3479 Value result = comb::ICmpOp::create(
builder, loc, comb::ICmpPredicate::eq,
3480 anded, zero,
false);
3483 if (nameId == ksn::OneHot) {
3484 auto isNotZero = comb::ICmpOp::create(
3485 builder, loc, comb::ICmpPredicate::ne, intVal, zero,
false);
3486 result = comb::AndOp::create(
builder, loc, result, isNotZero);
3493 result = comb::MuxOp::create(
builder, loc, isUnknown, zeroI1, result);
3494 Value resultMoore = moore::FromBuiltinIntOp::create(
builder, loc, result);
3495 return moore::IntToLogicOp::create(
builder, loc, resultMoore).getResult();
3497 return moore::FromBuiltinIntOp::create(
builder, loc, result);
3500 if (nameId == ksn::CountOnes) {
3501 assert(numArgs == 1 &&
"`$countones` takes 1 argument");
3505 if (!isa<moore::IntType>(value.getType())) {
3506 if (!isa<moore::PackedType>(value.getType())) {
3507 mlir::emitError(loc) <<
"expected integer argument for `$countones`";
3515 auto valTy = dyn_cast<moore::IntType>(value.getType());
3517 mlir::emitError(loc) <<
"expected integer argument for `$countones`";
3525 auto builtinIntTy = cast<IntegerType>(intVal.getType());
3526 unsigned width = builtinIntTy.getWidth();
3527 unsigned resultWidth = llvm::Log2_32_Ceil(width + 1);
3528 auto i1Ty =
builder.getI1Type();
3529 unsigned padWidth = resultWidth - 1;
3531 builder.getIntegerType(padWidth), 0);
3535 Value sum = comb::ConcatOp::create(
builder, loc, ValueRange{zeros, bit0});
3537 for (
unsigned i = 1; i < width; ++i) {
3540 comb::ConcatOp::create(
builder, loc, ValueRange{zeros, bit});
3541 sum = comb::AddOp::create(
builder, loc, sum, extended);
3545 return moore::FromBuiltinIntOp::create(
builder, loc, sum);
3549 if (nameId == ksn::Ln)
3550 return convertRealMathBI<moore::LnBIOp>(*
this, loc, name, args);
3551 if (nameId == ksn::Log10)
3552 return convertRealMathBI<moore::Log10BIOp>(*
this, loc, name, args);
3553 if (nameId == ksn::Exp)
3554 return convertRealMathBI<moore::ExpBIOp>(*
this, loc, name, args);
3555 if (nameId == ksn::Sqrt)
3556 return convertRealMathBI<moore::SqrtBIOp>(*
this, loc, name, args);
3557 if (nameId == ksn::Floor)
3558 return convertRealMathBI<moore::FloorBIOp>(*
this, loc, name, args);
3559 if (nameId == ksn::Ceil)
3560 return convertRealMathBI<moore::CeilBIOp>(*
this, loc, name, args);
3561 if (nameId == ksn::Sin)
3562 return convertRealMathBI<moore::SinBIOp>(*
this, loc, name, args);
3563 if (nameId == ksn::Cos)
3564 return convertRealMathBI<moore::CosBIOp>(*
this, loc, name, args);
3565 if (nameId == ksn::Tan)
3566 return convertRealMathBI<moore::TanBIOp>(*
this, loc, name, args);
3567 if (nameId == ksn::Asin)
3568 return convertRealMathBI<moore::AsinBIOp>(*
this, loc, name, args);
3569 if (nameId == ksn::Acos)
3570 return convertRealMathBI<moore::AcosBIOp>(*
this, loc, name, args);
3571 if (nameId == ksn::Atan)
3572 return convertRealMathBI<moore::AtanBIOp>(*
this, loc, name, args);
3573 if (nameId == ksn::Sinh)
3574 return convertRealMathBI<moore::SinhBIOp>(*
this, loc, name, args);
3575 if (nameId == ksn::Cosh)
3576 return convertRealMathBI<moore::CoshBIOp>(*
this, loc, name, args);
3577 if (nameId == ksn::Tanh)
3578 return convertRealMathBI<moore::TanhBIOp>(*
this, loc, name, args);
3579 if (nameId == ksn::Asinh)
3580 return convertRealMathBI<moore::AsinhBIOp>(*
this, loc, name, args);
3581 if (nameId == ksn::Acosh)
3582 return convertRealMathBI<moore::AcoshBIOp>(*
this, loc, name, args);
3583 if (nameId == ksn::Atanh)
3584 return convertRealMathBI<moore::AtanhBIOp>(*
this, loc, name, args);
3586 if (nameId == ksn::Pow)
3587 return convertRealMathTwoBI<moore::PowRealOp>(*
this, loc, name, args);
3588 if (nameId == ksn::Atan2)
3589 return convertRealMathTwoBI<moore::Atan2BIOp>(*
this, loc, name, args);
3590 if (nameId == ksn::Hypot)
3591 return convertRealMathTwoBI<moore::HypotBIOp>(*
this, loc, name, args);
3597 if (nameId == ksn::Itor) {
3598 assert(numArgs == 1 &&
"`$itor` takes 1 argument");
3603 if (nameId == ksn::Rtoi) {
3604 assert(numArgs == 1 &&
"`$rtoi` takes 1 argument");
3605 auto intType = moore::IntType::get(
getContext(), 32, Domain::TwoValued);
3609 if (nameId == ksn::Signed || nameId == ksn::Unsigned) {
3611 assert(numArgs == 1 &&
"`$signed`/`$unsigned` take 1 argument");
3617 if (nameId == ksn::RealToBits)
3618 return convertRealMathBI<moore::RealtobitsBIOp>(*
this, loc, name, args);
3619 if (nameId == ksn::BitsToReal)
3620 return convertRealMathBI<moore::BitstorealBIOp>(*
this, loc, name, args);
3621 if (nameId == ksn::ShortrealToBits)
3622 return convertRealMathBI<moore::ShortrealtobitsBIOp>(*
this, loc, name,
3624 if (nameId == ksn::BitsToShortreal)
3625 return convertRealMathBI<moore::BitstoshortrealBIOp>(*
this, loc, name,
3628 if (nameId == ksn::Cast) {
3629 assert(numArgs == 2 &&
"`cast` takes 2 arguments");
3630 auto *dstExpr = args[0];
3635 if (
auto *assign = dstExpr->as_if<slang::ast::AssignmentExpression>())
3636 dstExpr = &assign->left();
3645 if (isa<moore::ClassHandleType>(dstType) ||
3646 isa<moore::ClassHandleType>(src.getType())) {
3647 auto i1Ty = moore::IntType::getInt(
builder.getContext(), 1);
3648 return moore::ConstantOp::create(
builder, loc, i1Ty, 0,
3652 dstType, src, args[1]->type->isSigned(), loc,
true);
3653 auto i1Ty = moore::IntType::getInt(
builder.getContext(), 1);
3655 return moore::ConstantOp::create(
builder, loc, i1Ty, 0,
3657 moore::BlockingAssignOp::create(
builder, loc, dst, converted);
3658 return moore::ConstantOp::create(
builder, loc, i1Ty, 1,
3666 if (nameId == ksn::Len) {
3668 assert(numArgs == 1 &&
"`len` takes 1 argument");
3669 auto stringType = moore::StringType::get(
getContext());
3673 return moore::StringLenOp::create(
builder, loc, value);
3676 if (nameId == ksn::Getc) {
3678 assert(numArgs == 2 &&
"`getc` takes 2 arguments");
3679 auto stringType = moore::StringType::get(
getContext());
3684 return moore::StringGetOp::create(
builder, loc, str, index);
3687 if (nameId == ksn::ToUpper) {
3689 assert(numArgs == 1 &&
"`toupper` takes 1 argument");
3690 auto stringType = moore::StringType::get(
getContext());
3694 return moore::StringToUpperOp::create(
builder, loc, value);
3697 if (nameId == ksn::ToLower) {
3699 assert(numArgs == 1 &&
"`tolower` takes 1 argument");
3700 auto stringType = moore::StringType::get(
getContext());
3704 return moore::StringToLowerOp::create(
builder, loc, value);
3707 if (nameId == ksn::Compare || nameId == ksn::ICompare) {
3710 auto stringType = moore::StringType::get(
getContext());
3715 if (nameId == ksn::Compare)
3716 return moore::StringCompareOp::create(
builder, loc, lhs, rhs);
3717 return moore::StringICompareOp::create(
builder, loc, lhs, rhs);
3720 if (nameId == ksn::Substr) {
3722 assert(numArgs == 3 &&
"`substr` takes 3 arguments");
3723 auto stringType = moore::StringType::get(
getContext());
3727 if (!str || !start || !end)
3729 return moore::StringSubstrOp::create(
builder, loc, str, start, end);
3732 if (nameId == ksn::AToI || nameId == ksn::AToHex || nameId == ksn::AToOct ||
3733 nameId == ksn::AToBin) {
3735 assert(numArgs == 1 &&
"`atoi/hex/oct/bin` takes 1 argument");
3736 auto stringType = moore::StringType::get(
getContext());
3740 auto integerType = moore::IntType::getLogic(
builder.getContext(), 32);
3743 return moore::StringAtoiOp::create(
builder, loc, integerType, str);
3745 return moore::StringAtohexOp::create(
builder, loc, integerType, str);
3747 return moore::StringAtooctOp::create(
builder, loc, integerType, str);
3749 return moore::StringAtobinOp::create(
builder, loc, integerType, str);
3751 llvm_unreachable(
"unexpected string to integer conversion");
3755 if (nameId == ksn::AToReal) {
3757 assert(numArgs == 1 &&
"`atoreal` takes 1 argument");
3758 auto stringType = moore::StringType::get(
getContext());
3763 return moore::StringAtorealOp::create(
builder, loc, realType, str);
3770 if (nameId == ksn::ArraySize) {
3772 assert(numArgs == 1 &&
"`size` takes 1 argument");
3773 if (args[0]->type->isQueue()) {
3777 return moore::QueueSizeBIOp::create(
builder, loc, value);
3779 if (args[0]->type->getCanonicalType().kind ==
3780 slang::ast::SymbolKind::DynamicArrayType) {
3784 return moore::OpenUArraySizeOp::create(
builder, loc, value);
3786 if (args[0]->type->isAssociativeArray()) {
3790 return moore::AssocArraySizeOp::create(
builder, loc, value);
3792 emitError(loc) <<
"unsupported member function `size` on type `"
3793 << args[0]->type->toString() <<
"`";
3797 if (nameId == ksn::Delete) {
3799 assert(numArgs == 1 &&
"`delete` takes 1 argument");
3800 if (args[0]->type->getCanonicalType().kind ==
3801 slang::ast::SymbolKind::DynamicArrayType) {
3805 return moore::OpenUArrayDeleteOp::create(
builder, loc, value);
3807 emitError(loc) <<
"unsupported member function `delete` on type `"
3808 << args[0]->type->toString() <<
"`";
3812 if (nameId == ksn::PopBack) {
3814 assert(numArgs == 1 &&
"`pop_back` takes 1 argument");
3815 assert(args[0]->type->isQueue() &&
"`pop_back` is only valid on queues");
3819 return moore::QueuePopBackOp::create(
builder, loc, value);
3822 if (nameId == ksn::PopFront) {
3824 assert(numArgs == 1 &&
"`pop_front` takes 1 argument");
3825 assert(args[0]->type->isQueue() &&
"`pop_front` is only valid on queues");
3829 return moore::QueuePopFrontOp::create(
builder, loc, value);
3836 if (nameId == ksn::Num) {
3837 if (args[0]->type->isAssociativeArray()) {
3838 assert(numArgs == 1 &&
"`num` takes 1 argument");
3842 return moore::AssocArraySizeOp::create(
builder, loc, value);
3844 emitError(loc) <<
"unsupported system call `" << name <<
"`";
3848 if (nameId == ksn::Exists) {
3850 assert(numArgs == 2 &&
"`exists` takes 2 arguments");
3851 assert(args[0]->type->isAssociativeArray() &&
3852 "`exists` is only valid on associative arrays");
3857 return moore::AssocArrayExistsOp::create(
builder, loc, array, key);
3864 if (nameId == ksn::First || nameId == ksn::Last || nameId == ksn::Next ||
3865 nameId == ksn::Prev) {
3866 if (args[0]->type->isAssociativeArray()) {
3867 assert(numArgs == 2 &&
"traversal methods take 2 arguments");
3872 if (nameId == ksn::First)
3873 return moore::AssocArrayFirstOp::create(
builder, loc, array, key);
3874 if (nameId == ksn::Last)
3875 return moore::AssocArrayLastOp::create(
builder, loc, array, key);
3876 if (nameId == ksn::Next)
3877 return moore::AssocArrayNextOp::create(
builder, loc, array, key);
3878 if (nameId == ksn::Prev)
3879 return moore::AssocArrayPrevOp::create(
builder, loc, array, key);
3880 llvm_unreachable(
"all traversal cases handled above");
3882 emitError(loc) <<
"unsupported system call `" << name <<
"`";
3890 if (nameId == ksn::FOpen) {
3891 assert(numArgs >= 1 && numArgs <= 2 &&
"`$fopen` takes 1 or 2 arguments");
3896 moore::FOpenModeAttr modeAttr;
3898 auto *strLit = args[1]
3899 ->unwrapImplicitConversions()
3900 .as_if<slang::ast::StringLiteral>();
3902 return emitError(loc) <<
"$fopen mode must be a string literal",
3906 llvm::StringSwitch<std::optional<moore::FOpenMode>>(
3908 .Cases({
"r",
"rb"}, moore::FOpenMode::Read)
3909 .Cases({
"w",
"wb"}, moore::FOpenMode::Write)
3910 .Cases({
"a",
"ab"}, moore::FOpenMode::Append)
3911 .Cases({
"r+",
"r+b",
"rb+"}, moore::FOpenMode::ReadUpdate)
3912 .Cases({
"w+",
"w+b",
"wb+"}, moore::FOpenMode::WriteUpdate)
3913 .Cases({
"a+",
"a+b",
"ab+"}, moore::FOpenMode::AppendUpdate)
3914 .Default(std::nullopt);
3917 return emitError(loc)
3918 <<
"invalid $fopen mode '" << strLit->getValue() <<
"'",
3920 modeAttr = moore::FOpenModeAttr::get(
getContext(), *mode);
3922 return moore::FOpenBIOp::create(
builder, loc, filename, modeAttr);
3929 if (nameId == ksn::TestPlusArgs) {
3931 assert(numArgs == 1 &&
"`$test$plusargs` takes 1 argument");
3933 args[0]->unwrapImplicitConversions().as_if<slang::ast::StringLiteral>();
3935 return emitError(loc) <<
"`$test$plusargs` argument must be a string "
3938 auto foundTy = moore::IntType::getInt(
getContext(), 1);
3939 return moore::PlusArgsTestBIOp::create(
3940 builder, loc, foundTy,
builder.getStringAttr(strLit->getValue()));
3943 if (nameId == ksn::ValuePlusArgs) {
3947 assert(numArgs == 2 &&
"`$value$plusargs` takes 2 arguments");
3949 args[0]->unwrapImplicitConversions().as_if<slang::ast::StringLiteral>();
3951 return emitError(loc) <<
"`$value$plusargs` format must be a string "
3956 const auto *valueArg = args[1];
3957 if (
const auto *assign =
3958 valueArg->as_if<slang::ast::AssignmentExpression>())
3959 valueArg = &assign->left();
3963 auto resultType = cast<moore::RefType>(lvalue.getType()).getNestedType();
3964 auto foundTy = moore::IntType::getInt(
getContext(), 1);
3965 auto op = moore::PlusArgsValueBIOp::create(
3966 builder, loc, foundTy, resultType,
3967 builder.getStringAttr(strLit->getValue()));
3968 moore::BlockingAssignOp::create(
builder, loc, lvalue, op.getResult());
3969 return op.getFound();
3972 if (nameId == ksn::FScanf) {
3974 *args[0], moore::IntType::getInt(
builder.getContext(), 32));
3978 args[1]->unwrapImplicitConversions().as_if<slang::ast::StringLiteral>();
3980 return (mlir::emitError(loc)
3981 <<
"$fscanf requires a string literal format string"),
3984 moore::ScanBeginFScanFOp::create(
builder, loc, fd).getCursor();
3991 return moore::ScanEndOp::create(
builder, loc, result->finalCursor)
3995 if (nameId == ksn::SScanf) {
4001 args[1]->unwrapImplicitConversions().as_if<slang::ast::StringLiteral>();
4003 return (mlir::emitError(loc)
4004 <<
"$sscanf requires a string literal format string"),
4007 moore::ScanBeginSScanFOp::create(
builder, loc, str).getCursor();
4014 return moore::ScanEndOp::create(
builder, loc, result->finalCursor)
4019 emitError(loc) <<
"unsupported system call `" << name <<
"`";
4025 return context.symbolTable.lookupNearestSymbolFrom(
context.intoModuleOp, sym);
4029 const moore::ClassHandleType &baseTy) {
4030 if (!actualTy || !baseTy)
4033 mlir::SymbolRefAttr actualSym = actualTy.getClassSym();
4034 mlir::SymbolRefAttr baseSym = baseTy.getClassSym();
4036 if (actualSym == baseSym)
4039 auto *op =
resolve(*
this, actualSym);
4040 auto decl = llvm::dyn_cast_or_null<moore::ClassDeclOp>(op);
4043 mlir::SymbolRefAttr curBase = decl.getBaseAttr();
4046 if (curBase == baseSym)
4048 decl = llvm::dyn_cast_or_null<moore::ClassDeclOp>(
resolve(*
this, curBase));
4053moore::ClassHandleType
4055 llvm::StringRef fieldName, Location loc) {
4057 mlir::SymbolRefAttr classSym = actualTy.getClassSym();
4061 auto *op =
resolve(*
this, classSym);
4062 auto decl = llvm::dyn_cast_or_null<moore::ClassDeclOp>(op);
4067 for (
auto &block : decl.getBody()) {
4068 for (
auto &opInBlock : block) {
4070 llvm::dyn_cast<moore::ClassPropertyDeclOp>(&opInBlock)) {
4071 if (prop.getSymName() == fieldName) {
4073 return moore::ClassHandleType::get(actualTy.getContext(), classSym);
4080 classSym = decl.getBaseAttr();
4084 mlir::emitError(loc) <<
"unknown property `" << fieldName <<
"`";
4093 const slang::ast::Expression &expr) {
4096 if (
const auto *valueRange = expr.as_if<slang::ast::ValueRangeExpression>()) {
4101 if (!insideLhs || !lowBound || !highBound)
4104 Value rangeLhs, rangeRhs;
4107 if (valueRange->left().type->isSigned() ||
4108 insideLhs.getType().isSignedInteger()) {
4109 rangeLhs = moore::SgeOp::create(
builder, loc, insideLhs, lowBound);
4111 rangeLhs = moore::UgeOp::create(
builder, loc, insideLhs, lowBound);
4114 if (valueRange->right().type->isSigned() ||
4115 insideLhs.getType().isSignedInteger()) {
4116 rangeRhs = moore::SleOp::create(
builder, loc, insideLhs, highBound);
4118 rangeRhs = moore::UleOp::create(
builder, loc, insideLhs, highBound);
4121 return moore::AndOp::create(
builder, loc, rangeLhs, rangeRhs);
4125 if (!expr.type->isIntegral()) {
4126 if (expr.type->isUnpackedArray()) {
4127 mlir::emitError(loc,
4128 "unpacked arrays in 'inside' expressions not supported");
4132 loc,
"only simple bit vectors supported in 'inside' expressions");
4139 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 Value convertRealMathTwoBI(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 two arguments.
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 LogicalResult emitScanAssignments(Context &context, const Context::ScanStringResult &result, Location loc)
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 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.
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.
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.
FailureOr< ScanStringResult > convertScanString(StringRef formatStr, Value initialCursor, std::span< const slang::ast::Expression *const > destinations, Location loc)
Convert a scan format string into a consuming chain of moore.scan.
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 materializePackedToSBVConversion(Value value, Location loc, bool fallible)
Helper function to convert a PackedType value to its simple bit vector representation,...
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.
FunctionLowering * currentFunctionLowering
The function currently being converted, if any.
std::optional< std::pair< const slang::ast::InstanceSymbol *, mlir::StringAttr > > buildHierValueKey(const slang::ast::HierarchicalValueExpression &expr)
Build a composite key for hierValueSymbols from a hierarchical value expression.
MLIRContext * getContext()
Return the MLIR context.
Location convertLocation(slang::SourceLocation loc)
Convert a slang SourceLocation into an MLIR Location.
Function lowering information.
SmallVector< const slang::ast::ValueSymbol *, 4 > capturedSymbols
The AST symbols captured by this function, determined by the capture analysis pre-pass.
mlir::FunctionOpInterface op