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>(derefType)) {
295 mlir::emitError(loc) <<
"unsupported expression: element select into "
296 << expr.value().type->toString() <<
"\n";
301 if (isa<moore::AssocArrayType>(derefType)) {
302 auto assocArray = cast<moore::AssocArrayType>(derefType);
303 auto expectedIndexType = assocArray.getIndexType();
309 if (givenIndex.getType() != expectedIndexType) {
311 <<
"Incorrect index type: expected index type of "
312 << expectedIndexType <<
" but was given " << givenIndex.getType();
316 return moore::AssocArrayExtractRefOp::create(
317 builder, loc, moore::RefType::get(cast<moore::UnpackedType>(type)),
320 return moore::AssocArrayExtractOp::create(builder, loc, type, value,
325 if (isa<moore::StringType>(derefType)) {
327 mlir::emitError(loc) <<
"string index assignment not supported";
332 auto i32Type = moore::IntType::getInt(builder.getContext(), 32);
338 return moore::StringGetOp::create(builder, loc, value, index);
342 isLvalue ? moore::RefType::get(cast<moore::UnpackedType>(type)) : type;
343 auto range = expr.value().type->getFixedRange();
344 if (
auto *constValue = expr.selector().getConstant();
345 constValue && constValue->isInteger()) {
346 assert(!constValue->hasUnknown());
347 assert(constValue->size() <= 32);
349 auto lowBit = constValue->integer().as<uint32_t>().value();
351 return llvm::TypeSwitch<Type, Value>(derefType)
352 .Case<moore::QueueType>([&](moore::QueueType) {
354 <<
"Unexpected LValue extract on Queue Type!";
358 return moore::ExtractRefOp::create(builder, loc, resultType,
360 range.translateIndex(lowBit));
363 return llvm::TypeSwitch<Type, Value>(derefType)
364 .Case<moore::QueueType>([&](moore::QueueType) {
366 <<
"Unexpected RValue extract on Queue Type!";
370 return moore::ExtractOp::create(builder, loc, resultType, value,
371 range.translateIndex(lowBit));
378 llvm::scope_exit restoreQueue([&] { context.
currentQueue = savedQueue; });
379 if (isa<moore::QueueType>(derefType)) {
382 if (isa<moore::RefType>(value.getType())) {
383 context.
currentQueue = moore::ReadOp::create(builder, loc, value);
394 return llvm::TypeSwitch<Type, Value>(derefType)
395 .Case<moore::QueueType>([&](moore::QueueType) {
396 return moore::DynQueueRefElementOp::create(builder, loc, resultType,
400 return moore::DynExtractRefOp::create(builder, loc, resultType,
405 return llvm::TypeSwitch<Type, Value>(derefType)
406 .Case<moore::QueueType>([&](moore::QueueType) {
407 return moore::DynQueueExtractOp::create(builder, loc, resultType,
408 value, lowBit, lowBit);
411 return moore::DynExtractOp::create(builder, loc, resultType, value,
418 Value visit(
const slang::ast::NullLiteral &expr) {
420 if (isa<moore::ClassHandleType, moore::ChandleType, moore::EventType,
421 moore::NullType>(type))
422 return moore::NullOp::create(builder, loc);
423 mlir::emitError(loc) <<
"No null value definition found for value of type "
429 Value visit(
const slang::ast::RangeSelectExpression &expr) {
431 auto value = convertLvalueOrRvalueExpression(expr.value());
435 auto derefType = value.getType();
437 derefType = cast<moore::RefType>(derefType).getNestedType();
439 if (isa<moore::QueueType>(derefType)) {
440 return handleQueueRangeSelectExpressions(expr, type, value);
442 return handleArrayRangeSelectExpressions(expr, type, value);
447 Value handleQueueRangeSelectExpressions(
448 const slang::ast::RangeSelectExpression &expr, Type type, Value value) {
450 llvm::scope_exit restoreQueue([&] { context.
currentQueue = savedQueue; });
456 isLvalue ? moore::RefType::get(cast<moore::UnpackedType>(type)) : type;
459 mlir::emitError(loc) <<
"queue lvalue range selections are not supported";
462 return moore::DynQueueExtractOp::create(builder, loc, resultType, value,
468 Value handleArrayRangeSelectExpressions(
469 const slang::ast::RangeSelectExpression &expr, Type type, Value value) {
470 std::optional<int32_t> constLeft;
471 std::optional<int32_t> constRight;
472 if (
auto *constant = expr.left().getConstant())
473 constLeft = constant->integer().as<int32_t>();
474 if (
auto *constant = expr.right().getConstant())
475 constRight = constant->integer().as<int32_t>();
481 <<
"unsupported expression: range select with non-constant bounds";
501 int32_t offsetConst = 0;
502 auto range = expr.value().type->getFixedRange();
504 using slang::ast::RangeSelectionKind;
505 if (expr.getSelectionKind() == RangeSelectionKind::Simple) {
510 assert(constRight &&
"constness checked in slang");
511 offsetConst = *constRight;
522 offsetConst = *constLeft;
533 int32_t offsetAdd = 0;
538 if (expr.getSelectionKind() == RangeSelectionKind::IndexedDown &&
539 range.isDescending()) {
540 assert(constRight &&
"constness checked in slang");
541 offsetAdd = 1 - *constRight;
547 if (expr.getSelectionKind() == RangeSelectionKind::IndexedUp &&
548 !range.isDescending()) {
549 assert(constRight &&
"constness checked in slang");
550 offsetAdd = *constRight - 1;
554 if (offsetAdd != 0) {
556 offsetDyn = moore::AddOp::create(
557 builder, loc, offsetDyn,
558 moore::ConstantOp::create(
559 builder, loc, cast<moore::IntType>(offsetDyn.getType()),
563 offsetConst += offsetAdd;
574 isLvalue ? moore::RefType::get(cast<moore::UnpackedType>(type)) : type;
579 return moore::DynExtractRefOp::create(builder, loc, resultType, value,
582 return moore::DynExtractOp::create(builder, loc, resultType, value,
586 offsetConst = range.translateIndex(offsetConst);
588 return moore::ExtractRefOp::create(builder, loc, resultType, value,
591 return moore::ExtractOp::create(builder, loc, resultType, value,
598 Value visit(
const slang::ast::ConcatenationExpression &expr) {
599 SmallVector<Value> operands;
600 if (expr.type->isString()) {
601 for (
auto *operand : expr.operands()) {
602 assert(!isLvalue &&
"checked by Slang");
603 auto value = convertLvalueOrRvalueExpression(*operand);
607 moore::StringType::get(context.
getContext()), value,
false,
611 operands.push_back(value);
613 return moore::StringConcatOp::create(builder, loc, operands);
615 if (expr.type->isQueue()) {
616 return handleQueueConcat(expr);
619 if (expr.type->isUnpackedArray()) {
620 assert(!isLvalue &&
"checked by Slang");
621 auto loweredType = context.
convertType(*expr.type, loc);
626 if (
auto arrayType = dyn_cast<moore::UnpackedArrayType>(loweredType))
628 else if (
auto openType =
629 dyn_cast<moore::OpenUnpackedArrayType>(loweredType))
634 SmallVector<Value> operands;
635 for (
auto *operand : expr.operands()) {
636 if (operand->type->isVoid())
641 operands.push_back(value);
644 auto arrayType = moore::UnpackedArrayType::get(
646 return moore::ArrayCreateOp::create(builder, loc, arrayType, operands);
649 for (
auto *operand : expr.operands()) {
653 if (operand->type->isVoid())
655 auto value = convertLvalueOrRvalueExpression(*operand);
662 operands.push_back(value);
665 return moore::ConcatRefOp::create(builder, loc, operands);
667 return moore::ConcatOp::create(builder, loc, operands);
674 Value handleQueueConcat(
const slang::ast::ConcatenationExpression &expr) {
675 SmallVector<Value> operands;
678 cast<moore::QueueType>(context.
convertType(*expr.type, loc));
690 Value contigElements;
692 for (
auto *operand : expr.operands()) {
693 bool isSingleElement =
698 if (!isSingleElement && contigElements) {
699 operands.push_back(moore::ReadOp::create(builder, loc, contigElements));
703 assert(!isLvalue &&
"checked by Slang");
704 auto value = convertLvalueOrRvalueExpression(*operand);
712 moore::RefType::get(context.
getContext(), queueType);
714 if (!contigElements) {
716 moore::VariableOp::create(builder, loc, queueRefType, {}, {});
718 moore::QueuePushBackOp::create(builder, loc, contigElements, value);
726 if (!(isa<moore::QueueType>(value.getType()) &&
727 cast<moore::QueueType>(value.getType()).getElementType() ==
733 operands.push_back(value);
736 if (contigElements) {
737 operands.push_back(moore::ReadOp::create(builder, loc, contigElements));
740 return moore::QueueConcatOp::create(builder, loc, queueType, operands);
744 Value visit(
const slang::ast::MemberAccessExpression &expr) {
749 auto *valueType = expr.value().type.get();
750 auto memberName = builder.getStringAttr(expr.member.name);
756 if (valueType->isVirtualInterface()) {
757 auto memberType = dyn_cast<moore::UnpackedType>(type);
760 <<
"unsupported virtual interface member type: " << type;
763 auto resultRefType = moore::RefType::get(memberType);
771 auto memberRef = moore::StructExtractOp::create(
772 builder, loc, resultRefType, memberName, base);
775 return moore::ReadOp::create(builder, loc, memberRef);
779 if (valueType->isStruct()) {
781 isLvalue ? moore::RefType::get(cast<moore::UnpackedType>(type))
783 auto value = convertLvalueOrRvalueExpression(expr.value());
788 return moore::StructExtractRefOp::create(builder, loc, resultType,
790 return moore::StructExtractOp::create(builder, loc, resultType,
795 if (valueType->isPackedUnion() || valueType->isUnpackedUnion()) {
797 isLvalue ? moore::RefType::get(cast<moore::UnpackedType>(type))
799 auto value = convertLvalueOrRvalueExpression(expr.value());
804 return moore::UnionExtractRefOp::create(builder, loc, resultType,
806 return moore::UnionExtractOp::create(builder, loc, type, memberName,
811 if (valueType->isClass()) {
815 auto targetTy = cast<moore::ClassHandleType>(valTy);
827 if (expr.member.kind != slang::ast::SymbolKind::Parameter) {
833 moore::ClassHandleType upcastTargetTy =
847 auto fieldSym = mlir::FlatSymbolRefAttr::get(builder.getContext(),
849 auto fieldRefTy = moore::RefType::get(cast<moore::UnpackedType>(type));
853 Value fieldRef = moore::ClassPropertyRefOp::create(
854 builder, loc, fieldRefTy, baseVal, fieldSym);
857 return isLvalue ? fieldRef
858 : moore::ReadOp::create(builder, loc, fieldRef);
861 slang::ConstantValue constVal;
862 if (
auto param = expr.member.as_if<slang::ast::ParameterSymbol>()) {
863 constVal = param->getValue();
868 mlir::emitError(loc) <<
"Parameter " << expr.member.name
869 <<
" has no constant value";
873 mlir::emitError(loc,
"expression of type ")
874 << valueType->toString() <<
" has no member fields";
886struct RvalueExprVisitor :
public ExprVisitor {
888 : ExprVisitor(
context, loc, false) {}
889 using ExprVisitor::visit;
892 Value visit(
const slang::ast::LValueReferenceExpression &expr) {
893 assert(!
context.lvalueStack.empty() &&
"parent assignments push lvalue");
894 auto lvalue =
context.lvalueStack.back();
895 return moore::ReadOp::create(builder, loc, lvalue);
899 Value visit(
const slang::ast::NamedValueExpression &expr) {
901 if (
auto value =
context.valueSymbols.lookup(&expr.symbol)) {
902 if (isa<moore::RefType>(value.getType())) {
903 auto readOp = moore::ReadOp::create(builder, loc, value);
904 if (
context.rvalueReadCallback)
905 context.rvalueReadCallback(readOp);
906 value = readOp.getResult();
912 if (
auto globalOp =
context.globalVariables.lookup(&expr.symbol)) {
913 auto value = moore::GetGlobalVariableOp::create(builder, loc, globalOp);
914 return moore::ReadOp::create(builder, loc, value);
918 if (
auto *
const property =
919 expr.symbol.as_if<slang::ast::ClassPropertySymbol>()) {
921 return moore::ReadOp::create(builder, loc, fieldRef).getResult();
928 if (
auto access =
context.virtualIfaceMembers.lookup(&expr.symbol);
930 auto type =
context.convertType(*expr.type);
933 auto memberType = dyn_cast<moore::UnpackedType>(type);
936 <<
"unsupported virtual interface member type: " << type;
940 Value base = materializeSymbolRvalue(*access.base);
942 auto d = mlir::emitError(loc,
"unknown name `")
943 << access.base->name <<
"`";
944 d.attachNote(
context.convertLocation(access.base->location))
945 <<
"no rvalue generated for virtual interface base";
949 auto fieldName = access.fieldName
951 : builder.getStringAttr(expr.symbol.name);
952 auto memberRefType = moore::RefType::get(memberType);
953 auto memberRef = moore::StructExtractOp::create(
954 builder, loc, memberRefType, fieldName, base);
955 auto readOp = moore::ReadOp::create(builder, loc, memberRef);
956 if (
context.rvalueReadCallback)
957 context.rvalueReadCallback(readOp);
958 return readOp.getResult();
962 auto constant =
context.evaluateConstant(expr);
963 if (
auto value =
context.materializeConstant(constant, *expr.type, loc))
968 auto d = mlir::emitError(loc,
"unknown name `") << expr.symbol.name <<
"`";
969 d.attachNote(
context.convertLocation(expr.symbol.location))
970 <<
"no rvalue generated for " << slang::ast::toString(expr.symbol.kind);
975 Value visit(
const slang::ast::HierarchicalValueExpression &expr) {
976 auto hierLoc =
context.convertLocation(expr.symbol.location);
982 if (!expr.ref.path.empty()) {
983 if (
auto *inst = expr.ref.path.front()
984 .symbol->as_if<slang::ast::InstanceSymbol>()) {
986 expr.symbol.getParentScope()->getContainingInstance();
987 if (&inst->body == symbolBody ||
988 (symbolBody && inst->body.getDeclaringDefinition() ==
989 symbolBody->getDeclaringDefinition())) {
990 if (
auto value =
context.valueSymbols.lookup(&expr.symbol)) {
991 if (isa<moore::RefType>(value.getType())) {
992 auto readOp = moore::ReadOp::create(builder, hierLoc, value);
993 if (
context.rvalueReadCallback)
994 context.rvalueReadCallback(readOp);
995 value = readOp.getResult();
1005 if (
auto value =
context.resolveCapturedValue(expr.symbol)) {
1006 if (isa<moore::RefType>(value.getType())) {
1007 auto readOp = moore::ReadOp::create(builder, hierLoc, value);
1008 if (
context.rvalueReadCallback)
1009 context.rvalueReadCallback(readOp);
1010 value = readOp.getResult();
1019 if (
auto key =
context.buildHierValueKey(expr)) {
1020 if (
auto it =
context.hierValueSymbols.find(*key);
1021 it !=
context.hierValueSymbols.end()) {
1022 auto value = it->second;
1023 if (isa<moore::RefType>(value.getType())) {
1024 auto readOp = moore::ReadOp::create(builder, hierLoc, value);
1025 if (
context.rvalueReadCallback)
1026 context.rvalueReadCallback(readOp);
1027 value = readOp.getResult();
1034 if (
auto value =
context.valueSymbols.lookup(&expr.symbol)) {
1035 if (isa<moore::RefType>(value.getType())) {
1036 auto readOp = moore::ReadOp::create(builder, hierLoc, value);
1037 if (
context.rvalueReadCallback)
1038 context.rvalueReadCallback(readOp);
1039 value = readOp.getResult();
1045 if (isa<moore::RefType>(value.getType())) {
1046 auto readOp = moore::ReadOp::create(builder, hierLoc, value);
1047 if (
context.rvalueReadCallback)
1048 context.rvalueReadCallback(readOp);
1049 return readOp.getResult();
1057 slang::ConstantValue constant;
1058 switch (expr.symbol.kind) {
1059 case slang::ast::SymbolKind::Parameter:
1060 constant = expr.symbol.as<slang::ast::ParameterSymbol>().getValue(
1063 case slang::ast::SymbolKind::Specparam:
1064 constant = expr.symbol.as<slang::ast::SpecparamSymbol>().getValue(
1067 case slang::ast::SymbolKind::EnumValue:
1068 constant = expr.symbol.as<slang::ast::EnumValueSymbol>().getValue(
1072 constant =
context.evaluateConstant(expr);
1075 if (
auto value =
context.materializeConstant(constant, *expr.type, loc))
1080 auto d = mlir::emitError(loc,
"unknown hierarchical name `")
1081 << expr.symbol.name <<
"`";
1082 d.attachNote(hierLoc) <<
"no rvalue generated for "
1083 << slang::ast::toString(expr.symbol.kind);
1089 Value visit(
const slang::ast::ArbitrarySymbolExpression &expr) {
1090 const auto &canonTy = expr.type->getCanonicalType();
1091 if (
const auto *vi = canonTy.as_if<slang::ast::VirtualInterfaceType>()) {
1092 auto value =
context.materializeVirtualInterfaceValue(*vi, loc);
1098 mlir::emitError(loc) <<
"unsupported arbitrary symbol expression of type "
1099 << expr.type->toString();
1104 Value visit(
const slang::ast::ConversionExpression &expr) {
1105 auto type =
context.convertType(*expr.type);
1108 return context.convertRvalueExpression(expr.operand(), type);
1112 Value visit(
const slang::ast::AssignmentExpression &expr) {
1113 auto lhs =
context.convertLvalueExpression(expr.left());
1118 context.lvalueStack.push_back(lhs);
1119 auto rhs =
context.convertRvalueExpression(
1120 expr.right(), cast<moore::RefType>(lhs.getType()).getNestedType());
1121 context.lvalueStack.pop_back();
1128 if (!expr.isNonBlocking()) {
1129 if (expr.timingControl)
1130 if (failed(
context.convertTimingControl(*expr.timingControl)))
1132 auto assignOp = moore::BlockingAssignOp::create(builder, loc, lhs, rhs);
1133 if (
context.variableAssignCallback)
1134 context.variableAssignCallback(assignOp);
1139 if (expr.timingControl) {
1141 if (
auto *ctrl = expr.timingControl->as_if<slang::ast::DelayControl>()) {
1142 auto delay =
context.convertRvalueExpression(
1143 ctrl->expr, moore::TimeType::get(builder.getContext()));
1146 auto assignOp = moore::DelayedNonBlockingAssignOp::create(
1147 builder, loc, lhs, rhs, delay);
1148 if (
context.variableAssignCallback)
1149 context.variableAssignCallback(assignOp);
1154 auto loc =
context.convertLocation(expr.timingControl->sourceRange);
1155 mlir::emitError(loc)
1156 <<
"unsupported non-blocking assignment timing control: "
1157 << slang::ast::toString(expr.timingControl->kind);
1160 auto assignOp = moore::NonBlockingAssignOp::create(builder, loc, lhs, rhs);
1161 if (
context.variableAssignCallback)
1162 context.variableAssignCallback(assignOp);
1168 template <
class ConcreteOp>
1169 Value createReduction(Value arg,
bool invert) {
1170 arg =
context.convertToSimpleBitVector(arg);
1173 Value result = ConcreteOp::create(builder, loc, arg);
1175 result = moore::NotOp::create(builder, loc, result);
1180 Value createIncrement(Value arg,
bool isInc,
bool isPost) {
1181 auto preValue = moore::ReadOp::create(builder, loc, arg);
1187 postValue = moore::NotOp::create(builder, loc, preValue).getResult();
1190 auto one = moore::ConstantOp::create(
1191 builder, loc, cast<moore::IntType>(preValue.getType()), 1);
1193 isInc ? moore::AddOp::create(builder, loc, preValue, one).getResult()
1194 : moore::SubOp::create(builder, loc, preValue, one).getResult();
1196 moore::BlockingAssignOp::create(builder, loc, arg, postValue);
1197 if (
context.variableAssignCallback)
1198 context.variableAssignCallback(assignOp);
1207 Value createRealIncrement(Value arg,
bool isInc,
bool isPost) {
1208 Value preValue = moore::ReadOp::create(builder, loc, arg);
1211 bool isTime = isa<moore::TimeType>(preValue.getType());
1213 preValue =
context.materializeConversion(
1214 moore::RealType::get(
context.getContext(), moore::RealWidth::f64),
1215 preValue,
false, loc);
1217 moore::RealType realTy =
1218 llvm::dyn_cast<moore::RealType>(preValue.getType());
1223 if (realTy.getWidth() == moore::RealWidth::f32) {
1224 oneAttr = builder.getFloatAttr(builder.getF32Type(), 1.0);
1225 }
else if (realTy.getWidth() == moore::RealWidth::f64) {
1227 oneAttr = builder.getFloatAttr(builder.getF64Type(), oneVal);
1229 mlir::emitError(loc) <<
"cannot construct increment for " << realTy;
1232 auto one = moore::ConstantRealOp::create(builder, loc, oneAttr);
1236 ? moore::AddRealOp::create(builder, loc, preValue, one).getResult()
1237 : moore::SubRealOp::create(builder, loc, preValue, one).getResult();
1240 postValue =
context.materializeConversion(
1241 moore::TimeType::get(
context.getContext()), postValue,
false, loc);
1244 moore::BlockingAssignOp::create(builder, loc, arg, postValue);
1246 if (
context.variableAssignCallback)
1247 context.variableAssignCallback(assignOp);
1254 Value visitRealUOp(
const slang::ast::UnaryExpression &expr) {
1255 Type opFTy =
context.convertType(*expr.operand().type);
1257 using slang::ast::UnaryOperator;
1259 if (expr.op == UnaryOperator::Preincrement ||
1260 expr.op == UnaryOperator::Predecrement ||
1261 expr.op == UnaryOperator::Postincrement ||
1262 expr.op == UnaryOperator::Postdecrement)
1263 arg =
context.convertLvalueExpression(expr.operand());
1265 arg =
context.convertRvalueExpression(expr.operand(), opFTy);
1270 if (isa<moore::TimeType>(arg.getType()))
1271 arg =
context.materializeConversion(
1272 moore::RealType::get(
context.getContext(), moore::RealWidth::f64),
1277 case UnaryOperator::Plus:
1279 case UnaryOperator::Minus:
1280 return moore::NegRealOp::create(builder, loc, arg);
1282 case UnaryOperator::Preincrement:
1283 return createRealIncrement(arg,
true,
false);
1284 case UnaryOperator::Predecrement:
1285 return createRealIncrement(arg,
false,
false);
1286 case UnaryOperator::Postincrement:
1287 return createRealIncrement(arg,
true,
true);
1288 case UnaryOperator::Postdecrement:
1289 return createRealIncrement(arg,
false,
true);
1291 case UnaryOperator::LogicalNot:
1292 arg =
context.convertToBool(arg);
1295 return moore::NotOp::create(builder, loc, arg);
1298 mlir::emitError(loc) <<
"Unary operator " << slang::ast::toString(expr.op)
1299 <<
" not supported with real values!\n";
1305 Value visit(
const slang::ast::UnaryExpression &expr) {
1307 const auto *floatType =
1308 expr.operand().type->as_if<slang::ast::FloatingType>();
1311 return visitRealUOp(expr);
1313 using slang::ast::UnaryOperator;
1315 if (expr.op == UnaryOperator::Preincrement ||
1316 expr.op == UnaryOperator::Predecrement ||
1317 expr.op == UnaryOperator::Postincrement ||
1318 expr.op == UnaryOperator::Postdecrement)
1319 arg =
context.convertLvalueExpression(expr.operand());
1321 arg =
context.convertRvalueExpression(expr.operand());
1328 case UnaryOperator::Plus:
1329 return context.convertToSimpleBitVector(arg);
1331 case UnaryOperator::Minus:
1332 arg =
context.convertToSimpleBitVector(arg);
1335 return moore::NegOp::create(builder, loc, arg);
1337 case UnaryOperator::BitwiseNot:
1338 arg =
context.convertToSimpleBitVector(arg);
1341 return moore::NotOp::create(builder, loc, arg);
1343 case UnaryOperator::BitwiseAnd:
1344 return createReduction<moore::ReduceAndOp>(arg,
false);
1345 case UnaryOperator::BitwiseOr:
1346 return createReduction<moore::ReduceOrOp>(arg,
false);
1347 case UnaryOperator::BitwiseXor:
1348 return createReduction<moore::ReduceXorOp>(arg,
false);
1349 case UnaryOperator::BitwiseNand:
1350 return createReduction<moore::ReduceAndOp>(arg,
true);
1351 case UnaryOperator::BitwiseNor:
1352 return createReduction<moore::ReduceOrOp>(arg,
true);
1353 case UnaryOperator::BitwiseXnor:
1354 return createReduction<moore::ReduceXorOp>(arg,
true);
1356 case UnaryOperator::LogicalNot:
1357 arg =
context.convertToBool(arg);
1360 return moore::NotOp::create(builder, loc, arg);
1362 case UnaryOperator::Preincrement:
1363 return createIncrement(arg,
true,
false);
1364 case UnaryOperator::Predecrement:
1365 return createIncrement(arg,
false,
false);
1366 case UnaryOperator::Postincrement:
1367 return createIncrement(arg,
true,
true);
1368 case UnaryOperator::Postdecrement:
1369 return createIncrement(arg,
false,
true);
1372 mlir::emitError(loc,
"unsupported unary operator");
1377 Value buildLogicalBOp(slang::ast::BinaryOperator op, Value lhs, Value rhs,
1378 std::optional<Domain> domain = std::nullopt) {
1379 using slang::ast::BinaryOperator;
1383 lhs =
context.convertToBool(lhs, domain.value());
1384 rhs =
context.convertToBool(rhs, domain.value());
1386 lhs =
context.convertToBool(lhs);
1387 rhs =
context.convertToBool(rhs);
1394 case BinaryOperator::LogicalAnd:
1395 return moore::AndOp::create(builder, loc, lhs, rhs);
1397 case BinaryOperator::LogicalOr:
1398 return moore::OrOp::create(builder, loc, lhs, rhs);
1400 case BinaryOperator::LogicalImplication: {
1402 auto notLHS = moore::NotOp::create(builder, loc, lhs);
1403 return moore::OrOp::create(builder, loc, notLHS, rhs);
1406 case BinaryOperator::LogicalEquivalence: {
1408 auto notLHS = moore::NotOp::create(builder, loc, lhs);
1409 auto notRHS = moore::NotOp::create(builder, loc, rhs);
1410 auto both = moore::AndOp::create(builder, loc, lhs, rhs);
1411 auto notBoth = moore::AndOp::create(builder, loc, notLHS, notRHS);
1412 return moore::OrOp::create(builder, loc, both, notBoth);
1416 llvm_unreachable(
"not a logical BinaryOperator");
1420 Value visitHandleBOp(
const slang::ast::BinaryExpression &expr) {
1422 auto lhs =
context.convertRvalueExpression(expr.left());
1425 auto rhs =
context.convertRvalueExpression(expr.right());
1429 using slang::ast::BinaryOperator;
1432 case BinaryOperator::Equality:
1433 return moore::HandleEqOp::create(builder, loc, lhs, rhs);
1434 case BinaryOperator::Inequality:
1435 return moore::HandleNeOp::create(builder, loc, lhs, rhs);
1436 case BinaryOperator::CaseEquality:
1437 return moore::HandleCaseEqOp::create(builder, loc, lhs, rhs);
1438 case BinaryOperator::CaseInequality:
1439 return moore::HandleCaseNeOp::create(builder, loc, lhs, rhs);
1442 mlir::emitError(loc)
1443 <<
"Binary operator " << slang::ast::toString(expr.op)
1444 <<
" not supported with class handle valued operands!\n";
1449 Value visitRealBOp(
const slang::ast::BinaryExpression &expr) {
1451 auto lhs =
context.convertRvalueExpression(expr.left());
1454 auto rhs =
context.convertRvalueExpression(expr.right());
1458 if (isa<moore::TimeType>(lhs.getType()) ||
1459 isa<moore::TimeType>(rhs.getType())) {
1460 lhs =
context.materializeConversion(
1461 moore::RealType::get(
context.getContext(), moore::RealWidth::f64),
1463 rhs =
context.materializeConversion(
1464 moore::RealType::get(
context.getContext(), moore::RealWidth::f64),
1468 using slang::ast::BinaryOperator;
1470 case BinaryOperator::Add:
1471 return moore::AddRealOp::create(builder, loc, lhs, rhs);
1472 case BinaryOperator::Subtract:
1473 return moore::SubRealOp::create(builder, loc, lhs, rhs);
1474 case BinaryOperator::Multiply:
1475 return moore::MulRealOp::create(builder, loc, lhs, rhs);
1476 case BinaryOperator::Divide:
1477 return moore::DivRealOp::create(builder, loc, lhs, rhs);
1478 case BinaryOperator::Power:
1479 return moore::PowRealOp::create(builder, loc, lhs, rhs);
1481 case BinaryOperator::Equality:
1482 return moore::EqRealOp::create(builder, loc, lhs, rhs);
1483 case BinaryOperator::Inequality:
1484 return moore::NeRealOp::create(builder, loc, lhs, rhs);
1486 case BinaryOperator::GreaterThan:
1487 return moore::FgtOp::create(builder, loc, lhs, rhs);
1488 case BinaryOperator::LessThan:
1489 return moore::FltOp::create(builder, loc, lhs, rhs);
1490 case BinaryOperator::GreaterThanEqual:
1491 return moore::FgeOp::create(builder, loc, lhs, rhs);
1492 case BinaryOperator::LessThanEqual:
1493 return moore::FleOp::create(builder, loc, lhs, rhs);
1495 case BinaryOperator::LogicalAnd:
1496 case BinaryOperator::LogicalOr:
1497 case BinaryOperator::LogicalImplication:
1498 case BinaryOperator::LogicalEquivalence:
1499 return buildLogicalBOp(expr.op, lhs, rhs);
1502 mlir::emitError(loc) <<
"Binary operator "
1503 << slang::ast::toString(expr.op)
1504 <<
" not supported with real valued operands!\n";
1511 template <
class ConcreteOp>
1512 Value createBinary(Value lhs, Value rhs) {
1513 lhs =
context.convertToSimpleBitVector(lhs);
1516 rhs =
context.convertToSimpleBitVector(rhs);
1519 return ConcreteOp::create(builder, loc, lhs, rhs);
1523 Value visit(
const slang::ast::BinaryExpression &expr) {
1524 if (expr.left().kind == slang::ast::ExpressionKind::TypeReference &&
1525 expr.right().kind == slang::ast::ExpressionKind::TypeReference) {
1527 expr.left().as<slang::ast::TypeReferenceExpression>().targetType;
1529 expr.right().as<slang::ast::TypeReferenceExpression>().targetType;
1530 bool value = lhsType.isMatching(rhsType);
1532 using slang::ast::BinaryOperator;
1534 case BinaryOperator::Equality:
1535 case BinaryOperator::CaseEquality:
1537 case BinaryOperator::Inequality:
1538 case BinaryOperator::CaseInequality:
1542 mlir::emitError(loc,
"unsupported type reference binary operator");
1546 auto type = moore::IntType::get(
context.getContext(), 1,
1547 moore::Domain::TwoValued);
1548 return moore::ConstantOp::create(builder, loc, type, value,
1553 const auto *rhsFloatType =
1554 expr.right().type->as_if<slang::ast::FloatingType>();
1555 const auto *lhsFloatType =
1556 expr.left().type->as_if<slang::ast::FloatingType>();
1559 if (rhsFloatType || lhsFloatType)
1560 return visitRealBOp(expr);
1563 const auto rhsIsClass = expr.right().type->isClass();
1564 const auto lhsIsClass = expr.left().type->isClass();
1565 const auto rhsIsChandle = expr.right().type->isCHandle();
1566 const auto lhsIsChandle = expr.left().type->isCHandle();
1568 if (rhsIsClass || lhsIsClass || rhsIsChandle || lhsIsChandle)
1569 return visitHandleBOp(expr);
1571 auto lhs =
context.convertRvalueExpression(expr.left());
1574 auto rhs =
context.convertRvalueExpression(expr.right());
1579 Domain domain = Domain::TwoValued;
1580 if (expr.type->isFourState() || expr.left().type->isFourState() ||
1581 expr.right().type->isFourState())
1582 domain = Domain::FourValued;
1584 using slang::ast::BinaryOperator;
1586 case BinaryOperator::Add:
1587 return createBinary<moore::AddOp>(lhs, rhs);
1588 case BinaryOperator::Subtract:
1589 return createBinary<moore::SubOp>(lhs, rhs);
1590 case BinaryOperator::Multiply:
1591 return createBinary<moore::MulOp>(lhs, rhs);
1592 case BinaryOperator::Divide:
1593 if (expr.type->isSigned())
1594 return createBinary<moore::DivSOp>(lhs, rhs);
1596 return createBinary<moore::DivUOp>(lhs, rhs);
1597 case BinaryOperator::Mod:
1598 if (expr.type->isSigned())
1599 return createBinary<moore::ModSOp>(lhs, rhs);
1601 return createBinary<moore::ModUOp>(lhs, rhs);
1602 case BinaryOperator::Power: {
1607 auto rhsCast =
context.materializeConversion(
1608 lhs.getType(), rhs, expr.right().type->isSigned(), rhs.getLoc());
1609 if (expr.type->isSigned())
1610 return createBinary<moore::PowSOp>(lhs, rhsCast);
1612 return createBinary<moore::PowUOp>(lhs, rhsCast);
1615 case BinaryOperator::BinaryAnd:
1616 return createBinary<moore::AndOp>(lhs, rhs);
1617 case BinaryOperator::BinaryOr:
1618 return createBinary<moore::OrOp>(lhs, rhs);
1619 case BinaryOperator::BinaryXor:
1620 return createBinary<moore::XorOp>(lhs, rhs);
1621 case BinaryOperator::BinaryXnor: {
1622 auto result = createBinary<moore::XorOp>(lhs, rhs);
1625 return moore::NotOp::create(builder, loc, result);
1628 case BinaryOperator::Equality:
1629 if (isa<moore::UnpackedArrayType>(lhs.getType()))
1630 return moore::UArrayCmpOp::create(
1631 builder, loc, moore::UArrayCmpPredicate::eq, lhs, rhs);
1632 else if (isa<moore::StringType>(lhs.getType()))
1633 return moore::StringCmpOp::create(
1634 builder, loc, moore::StringCmpPredicate::eq, lhs, rhs);
1635 else if (isa<moore::QueueType>(lhs.getType()))
1636 return moore::QueueCmpOp::create(
1637 builder, loc, moore::UArrayCmpPredicate::eq, lhs, rhs);
1639 return createBinary<moore::EqOp>(lhs, rhs);
1640 case BinaryOperator::Inequality:
1641 if (isa<moore::UnpackedArrayType>(lhs.getType()))
1642 return moore::UArrayCmpOp::create(
1643 builder, loc, moore::UArrayCmpPredicate::ne, lhs, rhs);
1644 else if (isa<moore::StringType>(lhs.getType()))
1645 return moore::StringCmpOp::create(
1646 builder, loc, moore::StringCmpPredicate::ne, lhs, rhs);
1647 else if (isa<moore::QueueType>(lhs.getType()))
1648 return moore::QueueCmpOp::create(
1649 builder, loc, moore::UArrayCmpPredicate::ne, lhs, rhs);
1651 return createBinary<moore::NeOp>(lhs, rhs);
1652 case BinaryOperator::CaseEquality:
1653 return createBinary<moore::CaseEqOp>(lhs, rhs);
1654 case BinaryOperator::CaseInequality:
1655 return createBinary<moore::CaseNeOp>(lhs, rhs);
1656 case BinaryOperator::WildcardEquality:
1657 return createBinary<moore::WildcardEqOp>(lhs, rhs);
1658 case BinaryOperator::WildcardInequality:
1659 return createBinary<moore::WildcardNeOp>(lhs, rhs);
1661 case BinaryOperator::GreaterThanEqual:
1662 if (expr.left().type->isSigned())
1663 return createBinary<moore::SgeOp>(lhs, rhs);
1664 else if (isa<moore::StringType>(lhs.getType()))
1665 return moore::StringCmpOp::create(
1666 builder, loc, moore::StringCmpPredicate::ge, lhs, rhs);
1668 return createBinary<moore::UgeOp>(lhs, rhs);
1669 case BinaryOperator::GreaterThan:
1670 if (expr.left().type->isSigned())
1671 return createBinary<moore::SgtOp>(lhs, rhs);
1672 else if (isa<moore::StringType>(lhs.getType()))
1673 return moore::StringCmpOp::create(
1674 builder, loc, moore::StringCmpPredicate::gt, lhs, rhs);
1676 return createBinary<moore::UgtOp>(lhs, rhs);
1677 case BinaryOperator::LessThanEqual:
1678 if (expr.left().type->isSigned())
1679 return createBinary<moore::SleOp>(lhs, rhs);
1680 else if (isa<moore::StringType>(lhs.getType()))
1681 return moore::StringCmpOp::create(
1682 builder, loc, moore::StringCmpPredicate::le, lhs, rhs);
1684 return createBinary<moore::UleOp>(lhs, rhs);
1685 case BinaryOperator::LessThan:
1686 if (expr.left().type->isSigned())
1687 return createBinary<moore::SltOp>(lhs, rhs);
1688 else if (isa<moore::StringType>(lhs.getType()))
1689 return moore::StringCmpOp::create(
1690 builder, loc, moore::StringCmpPredicate::lt, lhs, rhs);
1692 return createBinary<moore::UltOp>(lhs, rhs);
1694 case BinaryOperator::LogicalAnd:
1695 case BinaryOperator::LogicalOr:
1696 case BinaryOperator::LogicalImplication:
1697 case BinaryOperator::LogicalEquivalence:
1698 return buildLogicalBOp(expr.op, lhs, rhs, domain);
1700 case BinaryOperator::LogicalShiftLeft:
1701 return createBinary<moore::ShlOp>(lhs, rhs);
1702 case BinaryOperator::LogicalShiftRight:
1703 return createBinary<moore::ShrOp>(lhs, rhs);
1704 case BinaryOperator::ArithmeticShiftLeft:
1705 return createBinary<moore::ShlOp>(lhs, rhs);
1706 case BinaryOperator::ArithmeticShiftRight: {
1709 lhs =
context.convertToSimpleBitVector(lhs);
1710 rhs =
context.convertToSimpleBitVector(rhs);
1713 if (expr.type->isSigned())
1714 return moore::AShrOp::create(builder, loc, lhs, rhs);
1715 return moore::ShrOp::create(builder, loc, lhs, rhs);
1719 mlir::emitError(loc,
"unsupported binary operator");
1724 Value visit(
const slang::ast::UnbasedUnsizedIntegerLiteral &expr) {
1725 return context.materializeSVInt(expr.getValue(), *expr.type, loc);
1729 Value visit(
const slang::ast::IntegerLiteral &expr) {
1730 return context.materializeSVInt(expr.getValue(), *expr.type, loc);
1734 Value visit(
const slang::ast::TimeLiteral &expr) {
1739 double value = std::round(expr.getValue() * scale);
1749 static constexpr uint64_t limit =
1750 (std::numeric_limits<uint64_t>::max() >> 11) << 11;
1751 if (value > limit) {
1752 mlir::emitError(loc) <<
"time value is larger than " << limit <<
" fs";
1756 return moore::ConstantTimeOp::create(builder, loc,
1757 static_cast<uint64_t
>(value));
1761 Value visit(
const slang::ast::ReplicationExpression &expr) {
1762 auto type =
context.convertType(*expr.type);
1763 auto value =
context.convertRvalueExpression(expr.concat());
1766 return moore::ReplicateOp::create(builder, loc, type, value);
1770 Value visit(
const slang::ast::InsideExpression &expr) {
1771 auto lhs =
context.convertToSimpleBitVector(
1772 context.convertRvalueExpression(expr.left()));
1777 SmallVector<Value> conditions;
1780 for (
const auto *listExpr : expr.rangeList()) {
1781 auto cond =
context.convertInsideCheck(lhs, loc, *listExpr);
1785 conditions.push_back(cond);
1789 auto result = conditions.back();
1790 conditions.pop_back();
1791 while (!conditions.empty()) {
1792 result = moore::OrOp::create(builder, loc, conditions.back(), result);
1793 conditions.pop_back();
1799 Value visit(
const slang::ast::ConditionalExpression &expr) {
1800 auto type =
context.convertType(*expr.type);
1803 if (expr.conditions.size() > 1) {
1804 mlir::emitError(loc)
1805 <<
"unsupported conditional expression with more than one condition";
1808 const auto &cond = expr.conditions[0];
1810 mlir::emitError(loc) <<
"unsupported conditional expression with pattern";
1814 context.convertToBool(
context.convertRvalueExpression(*cond.expr));
1817 auto conditionalOp =
1818 moore::ConditionalOp::create(builder, loc, type, value);
1821 auto &trueBlock = conditionalOp.getTrueRegion().emplaceBlock();
1822 auto &falseBlock = conditionalOp.getFalseRegion().emplaceBlock();
1824 OpBuilder::InsertionGuard g(builder);
1827 builder.setInsertionPointToStart(&trueBlock);
1828 auto trueValue =
context.convertRvalueExpression(expr.left(), type);
1831 moore::YieldOp::create(builder, loc, trueValue);
1834 builder.setInsertionPointToStart(&falseBlock);
1835 auto falseValue =
context.convertRvalueExpression(expr.right(), type);
1838 moore::YieldOp::create(builder, loc, falseValue);
1840 return conditionalOp.getResult();
1844 Value visit(
const slang::ast::CallExpression &expr) {
1846 auto constant =
context.evaluateConstant(expr);
1847 if (
auto value =
context.materializeConstant(constant, *expr.type, loc))
1851 [&](
auto &subroutine) {
return visitCall(expr, subroutine); },
1857 std::pair<Value, moore::ClassHandleType>
1858 getMethodReceiverTypeHandle(
const slang::ast::CallExpression &expr) {
1860 moore::ClassHandleType handleTy;
1864 if (
const slang::ast::Expression *recvExpr = expr.thisClass()) {
1865 thisRef =
context.convertRvalueExpression(*recvExpr);
1870 thisRef =
context.getImplicitThisRef();
1872 mlir::emitError(loc) <<
"method '" << expr.getSubroutineName()
1873 <<
"' called without an object";
1877 handleTy = cast<moore::ClassHandleType>(thisRef.getType());
1878 return {thisRef, handleTy};
1882 mlir::CallOpInterface
1883 buildMethodCall(
const slang::ast::SubroutineSymbol *subroutine,
1885 moore::ClassHandleType actualHandleTy, Value actualThisRef,
1886 SmallVector<Value> &arguments,
1887 SmallVector<Type> &resultTypes) {
1890 auto funcTy = cast<FunctionType>(lowering->
op.getFunctionType());
1891 auto expected0 = funcTy.getInput(0);
1892 auto expectedHdlTy = cast<moore::ClassHandleType>(expected0);
1895 auto implicitThisRef =
context.materializeConversion(
1896 expectedHdlTy, actualThisRef,
false, actualThisRef.getLoc());
1899 SmallVector<Value> explicitArguments;
1900 explicitArguments.reserve(arguments.size() + 1);
1901 explicitArguments.push_back(implicitThisRef);
1902 explicitArguments.append(arguments.begin(), arguments.end());
1905 const bool isVirtual =
1906 (subroutine->flags & slang::ast::MethodFlags::Virtual) != 0;
1909 auto calleeSym = lowering->
op.getNameAttr().getValue();
1910 if (isa<moore::CoroutineOp>(lowering->
op.getOperation()))
1911 return moore::CallCoroutineOp::create(builder, loc, resultTypes,
1912 calleeSym, explicitArguments);
1913 return mlir::func::CallOp::create(builder, loc, resultTypes, calleeSym,
1917 auto funcName = subroutine->name;
1918 auto method = moore::VTableLoadMethodOp::create(
1919 builder, loc, funcTy, actualThisRef,
1920 SymbolRefAttr::get(
context.getContext(), funcName));
1921 return mlir::func::CallIndirectOp::create(builder, loc, method,
1926 Value visitCall(
const slang::ast::CallExpression &expr,
1927 const slang::ast::SubroutineSymbol *subroutine) {
1929 const bool isMethod = (subroutine->thisVar !=
nullptr);
1931 auto *lowering =
context.declareFunction(*subroutine);
1935 if (isa<moore::DPIFuncOp>(lowering->
op.getOperation())) {
1936 SmallVector<Value> operands;
1937 SmallVector<Value> resultTargets;
1939 for (
auto [callArg, declArg] :
1940 llvm::zip(expr.arguments(), subroutine->getArguments())) {
1941 auto *actual = callArg;
1942 if (
const auto *assign =
1943 actual->as_if<slang::ast::AssignmentExpression>())
1944 actual = &assign->left();
1946 auto argType =
context.convertType(declArg->getType());
1950 switch (declArg->direction) {
1951 case slang::ast::ArgumentDirection::In: {
1952 auto value =
context.convertRvalueExpression(*actual, argType);
1955 operands.push_back(value);
1958 case slang::ast::ArgumentDirection::Out: {
1959 auto lvalue =
context.convertLvalueExpression(*actual);
1962 resultTargets.push_back(lvalue);
1965 case slang::ast::ArgumentDirection::InOut:
1966 case slang::ast::ArgumentDirection::Ref: {
1967 auto lvalue =
context.convertLvalueExpression(*actual);
1970 auto value =
context.convertRvalueExpression(*actual, argType);
1973 operands.push_back(value);
1974 resultTargets.push_back(lvalue);
1980 SmallVector<Type> resultTypes(
1981 cast<FunctionType>(lowering->
op.getFunctionType()).getResults());
1982 auto callOp = moore::FuncDPICallOp::create(
1983 builder, loc, resultTypes,
1984 SymbolRefAttr::get(lowering->
op.getNameAttr()), operands);
1986 unsigned resultIndex = 0;
1987 unsigned targetIndex = 0;
1988 for (
const auto *declArg : subroutine->getArguments()) {
1989 auto argType =
context.convertType(declArg->getType());
1993 switch (declArg->direction) {
1994 case slang::ast::ArgumentDirection::Out:
1995 case slang::ast::ArgumentDirection::InOut:
1996 case slang::ast::ArgumentDirection::Ref: {
1997 auto lvalue = resultTargets[targetIndex++];
1998 auto refTy = dyn_cast<moore::RefType>(lvalue.getType());
2000 lowering->
op->emitError(
2001 "expected DPI output target to be moore::RefType");
2004 auto converted =
context.materializeConversion(
2005 refTy.getNestedType(), callOp->getResult(resultIndex++),
2006 declArg->getType().isSigned(), loc);
2009 moore::BlockingAssignOp::create(builder, loc, lvalue, converted);
2017 if (!subroutine->getReturnType().isVoid())
2018 return callOp->getResult(resultIndex);
2020 return mlir::UnrealizedConversionCastOp::create(
2021 builder, loc, moore::VoidType::get(
context.getContext()),
2029 SmallVector<Value> arguments;
2030 for (
auto [callArg, declArg] :
2031 llvm::zip(expr.arguments(), subroutine->getArguments())) {
2035 auto *expr = callArg;
2036 if (
const auto *assign = expr->as_if<slang::ast::AssignmentExpression>())
2037 expr = &assign->left();
2040 auto type =
context.convertType(declArg->getType());
2041 if (declArg->direction == slang::ast::ArgumentDirection::In) {
2042 value =
context.convertRvalueExpression(*expr, type);
2044 Value lvalue =
context.convertLvalueExpression(*expr);
2045 auto unpackedType = dyn_cast<moore::UnpackedType>(type);
2049 context.materializeConversion(moore::RefType::get(unpackedType),
2050 lvalue, expr->type->isSigned(), loc);
2054 arguments.push_back(value);
2061 for (
auto *sym : lowering->capturedSymbols) {
2062 Value val =
context.valueSymbols.lookup(sym);
2064 mlir::emitError(loc) <<
"failed to resolve captured variable `"
2065 << sym->name <<
"` at call site";
2068 arguments.push_back(val);
2072 SmallVector<Type> resultTypes(
2073 cast<FunctionType>(lowering->
op.getFunctionType()).getResults().begin(),
2074 cast<FunctionType>(lowering->
op.getFunctionType()).getResults().end());
2076 mlir::CallOpInterface callOp;
2080 auto [thisRef, tyHandle] = getMethodReceiverTypeHandle(expr);
2081 callOp = buildMethodCall(subroutine, lowering, tyHandle, thisRef,
2082 arguments, resultTypes);
2083 }
else if (isa<moore::CoroutineOp>(lowering->
op.getOperation())) {
2085 auto coroutine = cast<moore::CoroutineOp>(lowering->
op.getOperation());
2087 moore::CallCoroutineOp::create(builder, loc, coroutine, arguments);
2090 auto funcOp = cast<mlir::func::FuncOp>(lowering->
op.getOperation());
2091 callOp = mlir::func::CallOp::create(builder, loc, funcOp, arguments);
2094 auto result = resultTypes.size() > 0 ? callOp->getOpResult(0) : Value{};
2098 if (resultTypes.size() == 0)
2099 return mlir::UnrealizedConversionCastOp::create(
2100 builder, loc, moore::VoidType::get(
context.getContext()),
2108 Value visitCall(
const slang::ast::CallExpression &expr,
2109 const slang::ast::CallExpression::SystemCallInfo &info) {
2110 using ksn = slang::parsing::KnownSystemName;
2111 const auto &subroutine = *
info.subroutine;
2112 auto nameId = subroutine.knownNameId;
2124 return context.convertAssertionCallExpression(expr, info, loc);
2129 auto args = expr.arguments();
2137 if (nameId == ksn::SFormatF) {
2139 auto fmtValue =
context.convertFormatString(
2140 expr.arguments(), loc, moore::IntFormat::Decimal,
false);
2141 if (failed(fmtValue))
2143 return fmtValue.value();
2147 auto result =
context.convertSystemCall(subroutine, loc, args);
2151 auto ty =
context.convertType(*expr.type);
2155 bool isSigned = expr.type->isSigned();
2156 if (nameId == ksn::CountOnes || nameId == ksn::IsUnknown ||
2157 nameId == ksn::OneHot || nameId == ksn::OneHot0)
2159 return context.materializeConversion(ty, result, isSigned, loc);
2163 Value visit(
const slang::ast::StringLiteral &expr) {
2164 auto type =
context.convertType(*expr.type);
2165 return moore::ConstantStringOp::create(builder, loc, type, expr.getValue());
2169 Value visit(
const slang::ast::RealLiteral &expr) {
2170 auto fTy = mlir::Float64Type::get(
context.getContext());
2171 auto attr = mlir::FloatAttr::get(fTy, expr.getValue());
2172 return moore::ConstantRealOp::create(builder, loc, attr).getResult();
2177 FailureOr<SmallVector<Value>>
2178 convertElements(
const slang::ast::AssignmentPatternExpressionBase &expr,
2179 std::variant<Type, ArrayRef<Type>> expectedTypes,
2180 unsigned replCount) {
2181 const auto &elts = expr.elements();
2182 const size_t elementCount = elts.size();
2185 const bool hasBroadcast =
2186 std::holds_alternative<Type>(expectedTypes) &&
2187 static_cast<bool>(std::get<Type>(expectedTypes));
2189 const bool hasPerElem =
2190 std::holds_alternative<ArrayRef<Type>>(expectedTypes) &&
2191 !std::get<ArrayRef<Type>>(expectedTypes).empty();
2195 auto types = std::get<ArrayRef<Type>>(expectedTypes);
2196 if (types.size() != elementCount) {
2197 mlir::emitError(loc)
2198 <<
"assignment pattern arity mismatch: expected " << types.size()
2199 <<
" elements, got " << elementCount;
2204 SmallVector<Value> converted;
2205 converted.reserve(elementCount * std::max(1u, replCount));
2208 if (!hasBroadcast && !hasPerElem) {
2210 for (
const auto *elementExpr : elts) {
2211 Value v =
context.convertRvalueExpression(*elementExpr);
2214 converted.push_back(v);
2216 }
else if (hasBroadcast) {
2218 Type want = std::get<Type>(expectedTypes);
2219 for (
const auto *elementExpr : elts) {
2220 Value v = want ?
context.convertRvalueExpression(*elementExpr, want)
2221 :
context.convertRvalueExpression(*elementExpr);
2224 converted.push_back(v);
2227 auto types = std::get<ArrayRef<Type>>(expectedTypes);
2228 for (
size_t i = 0; i < elementCount; ++i) {
2229 Type want = types[i];
2230 const auto *elementExpr = elts[i];
2231 Value v = want ?
context.convertRvalueExpression(*elementExpr, want)
2232 :
context.convertRvalueExpression(*elementExpr);
2235 converted.push_back(v);
2239 for (
unsigned i = 1; i < replCount; ++i)
2240 converted.append(converted.begin(), converted.begin() + elementCount);
2246 Value visitAssignmentPattern(
2247 const slang::ast::AssignmentPatternExpressionBase &expr,
2248 unsigned replCount = 1) {
2249 auto type =
context.convertType(*expr.type);
2250 const auto &elts = expr.elements();
2253 if (
auto intType = dyn_cast<moore::IntType>(type)) {
2254 auto elements = convertElements(expr, {}, replCount);
2256 if (failed(elements))
2259 assert(intType.getWidth() == elements->size());
2260 std::reverse(elements->begin(), elements->end());
2261 return moore::ConcatOp::create(builder, loc, intType, *elements);
2265 if (
auto structType = dyn_cast<moore::StructType>(type)) {
2266 SmallVector<Type> expectedTy;
2267 expectedTy.reserve(structType.getMembers().size());
2268 for (
auto member : structType.getMembers())
2269 expectedTy.push_back(member.type);
2271 FailureOr<SmallVector<Value>> elements;
2272 if (expectedTy.size() == elts.size())
2273 elements = convertElements(expr, expectedTy, replCount);
2275 elements = convertElements(expr, {}, replCount);
2277 if (failed(elements))
2280 assert(structType.getMembers().size() == elements->size());
2281 return moore::StructCreateOp::create(builder, loc, structType, *elements);
2285 if (
auto structType = dyn_cast<moore::UnpackedStructType>(type)) {
2286 SmallVector<Type> expectedTy;
2287 expectedTy.reserve(structType.getMembers().size());
2288 for (
auto member : structType.getMembers())
2289 expectedTy.push_back(member.type);
2291 FailureOr<SmallVector<Value>> elements;
2292 if (expectedTy.size() == elts.size())
2293 elements = convertElements(expr, expectedTy, replCount);
2295 elements = convertElements(expr, {}, replCount);
2297 if (failed(elements))
2300 assert(structType.getMembers().size() == elements->size());
2302 return moore::StructCreateOp::create(builder, loc, structType, *elements);
2306 if (
auto arrayType = dyn_cast<moore::ArrayType>(type)) {
2308 convertElements(expr, arrayType.getElementType(), replCount);
2310 if (failed(elements))
2313 assert(arrayType.getSize() == elements->size());
2314 return moore::ArrayCreateOp::create(builder, loc, arrayType, *elements);
2318 if (
auto arrayType = dyn_cast<moore::UnpackedArrayType>(type)) {
2320 convertElements(expr, arrayType.getElementType(), replCount);
2322 if (failed(elements))
2325 assert(arrayType.getSize() == elements->size());
2326 return moore::ArrayCreateOp::create(builder, loc, arrayType, *elements);
2330 if (
auto openType = dyn_cast<moore::OpenUnpackedArrayType>(type)) {
2332 convertElements(expr, openType.getElementType(), replCount);
2334 if (failed(elements))
2337 auto arrayType = moore::UnpackedArrayType::get(
2338 context.getContext(), elements->size(), openType.getElementType());
2339 return moore::ArrayCreateOp::create(builder, loc, arrayType, *elements);
2342 mlir::emitError(loc) <<
"unsupported assignment pattern with type " << type;
2346 Value visit(
const slang::ast::SimpleAssignmentPatternExpression &expr) {
2347 return visitAssignmentPattern(expr);
2350 Value visit(
const slang::ast::StructuredAssignmentPatternExpression &expr) {
2351 return visitAssignmentPattern(expr);
2354 Value visit(
const slang::ast::ReplicatedAssignmentPatternExpression &expr) {
2356 context.evaluateConstant(expr.count()).integer().as<
unsigned>();
2357 assert(count &&
"Slang guarantees constant non-zero replication count");
2358 return visitAssignmentPattern(expr, *count);
2361 Value visit(
const slang::ast::StreamingConcatenationExpression &expr) {
2362 SmallVector<Value> operands;
2363 for (
auto stream : expr.streams()) {
2364 auto operandLoc =
context.convertLocation(stream.operand->sourceRange);
2365 if (!stream.constantWithWidth.has_value() && stream.withExpr) {
2366 mlir::emitError(operandLoc)
2367 <<
"Moore only support streaming "
2368 "concatenation with fixed size 'with expression'";
2372 if (stream.constantWithWidth.has_value()) {
2373 value =
context.convertRvalueExpression(*stream.withExpr);
2374 auto type = cast<moore::UnpackedType>(value.getType());
2375 auto intType = moore::IntType::get(
2376 context.getContext(), type.getBitSize().value(), type.getDomain());
2378 value =
context.materializeConversion(intType, value,
false, loc);
2380 value =
context.convertRvalueExpression(*stream.operand);
2383 value =
context.convertToSimpleBitVector(value);
2386 operands.push_back(value);
2390 if (operands.size() == 1) {
2393 value = operands.front();
2395 value = moore::ConcatOp::create(builder, loc, operands).getResult();
2398 if (expr.getSliceSize() == 0) {
2402 auto type = cast<moore::IntType>(value.getType());
2403 SmallVector<Value> slicedOperands;
2404 auto iterMax = type.getWidth() / expr.getSliceSize();
2405 auto remainSize = type.getWidth() % expr.getSliceSize();
2407 for (
size_t i = 0; i < iterMax; i++) {
2408 auto extractResultType = moore::IntType::get(
2409 context.getContext(), expr.getSliceSize(), type.getDomain());
2411 auto extracted = moore::ExtractOp::create(builder, loc, extractResultType,
2412 value, i * expr.getSliceSize());
2413 slicedOperands.push_back(extracted);
2417 auto extractResultType = moore::IntType::get(
2418 context.getContext(), remainSize, type.getDomain());
2421 moore::ExtractOp::create(builder, loc, extractResultType, value,
2422 iterMax * expr.getSliceSize());
2423 slicedOperands.push_back(extracted);
2426 return moore::ConcatOp::create(builder, loc, slicedOperands);
2429 Value visit(
const slang::ast::AssertionInstanceExpression &expr) {
2430 return context.convertAssertionExpression(expr.body, loc);
2433 Value visit(
const slang::ast::UnboundedLiteral &expr) {
2435 "slang checks $ only used within queue index expression");
2439 moore::QueueSizeBIOp::create(builder, loc,
context.getIndexedQueue());
2440 auto one = moore::ConstantOp::create(builder, loc, queueSize.getType(), 1);
2441 auto lastElement = moore::SubOp::create(builder, loc, queueSize, one);
2458 Value visit(
const slang::ast::NewClassExpression &expr) {
2459 auto type =
context.convertType(*expr.type);
2460 auto classTy = dyn_cast<moore::ClassHandleType>(type);
2466 if (!classTy && expr.isSuperClass) {
2467 newObj =
context.getImplicitThisRef();
2468 if (!newObj || !newObj.getType() ||
2469 !isa<moore::ClassHandleType>(newObj.getType())) {
2470 mlir::emitError(loc) <<
"implicit this ref was not set while "
2471 "converting new class function";
2474 auto thisType = cast<moore::ClassHandleType>(newObj.getType());
2476 cast<moore::ClassDeclOp>(*
context.symbolTable.lookupNearestSymbolFrom(
2477 context.intoModuleOp, thisType.getClassSym()));
2478 auto baseClassSym = classDecl.getBase();
2479 classTy = circt::moore::ClassHandleType::get(
context.getContext(),
2480 baseClassSym.value());
2483 newObj = moore::ClassNewOp::create(builder, loc, classTy, {});
2486 const auto *constructor = expr.constructorCall();
2491 if (
const auto *callConstructor =
2492 constructor->as_if<slang::ast::CallExpression>())
2493 if (
const auto *subroutine =
2494 std::get_if<const slang::ast::SubroutineSymbol *>(
2495 &callConstructor->subroutine)) {
2496 if (!(*subroutine)->thisVar) {
2497 mlir::emitError(loc)
2498 <<
"unsupported constructor call without `this` argument";
2502 llvm::SaveAndRestore saveThis(
context.currentThisRef, newObj);
2503 if (!visitCall(*callConstructor, *subroutine))
2511 template <
typename T>
2512 Value visit(T &&node) {
2513 mlir::emitError(loc,
"unsupported expression: ")
2514 << slang::ast::toString(node.kind);
2518 Value visitInvalid(
const slang::ast::Expression &expr) {
2519 mlir::emitError(loc,
"invalid expression");
2530struct LvalueExprVisitor :
public ExprVisitor {
2532 : ExprVisitor(
context, loc, true) {}
2533 using ExprVisitor::visit;
2536 Value visit(
const slang::ast::NamedValueExpression &expr) {
2538 if (
auto value =
context.valueSymbols.lookup(&expr.symbol))
2542 if (
auto globalOp =
context.globalVariables.lookup(&expr.symbol))
2543 return moore::GetGlobalVariableOp::create(builder, loc, globalOp);
2545 if (
auto *
const property =
2546 expr.symbol.as_if<slang::ast::ClassPropertySymbol>()) {
2550 if (
auto access =
context.virtualIfaceMembers.lookup(&expr.symbol);
2552 auto type =
context.convertType(*expr.type);
2555 auto memberType = dyn_cast<moore::UnpackedType>(type);
2557 mlir::emitError(loc)
2558 <<
"unsupported virtual interface member type: " << type;
2562 Value base = materializeSymbolRvalue(*access.base);
2564 auto d = mlir::emitError(loc,
"unknown name `")
2565 << access.base->name <<
"`";
2566 d.attachNote(
context.convertLocation(access.base->location))
2567 <<
"no rvalue generated for virtual interface base";
2571 auto fieldName = access.fieldName
2573 : builder.getStringAttr(expr.symbol.name);
2574 auto memberRefType = moore::RefType::get(memberType);
2575 return moore::StructExtractOp::create(builder, loc, memberRefType,
2579 auto d = mlir::emitError(loc,
"unknown name `") << expr.symbol.name <<
"`";
2580 d.attachNote(
context.convertLocation(expr.symbol.location))
2581 <<
"no lvalue generated for " << slang::ast::toString(expr.symbol.kind);
2586 Value visit(
const slang::ast::HierarchicalValueExpression &expr) {
2589 if (!expr.ref.path.empty()) {
2590 if (
auto *inst = expr.ref.path.front()
2591 .symbol->as_if<slang::ast::InstanceSymbol>()) {
2593 expr.symbol.getParentScope()->getContainingInstance();
2594 if (&inst->body == symbolBody ||
2595 (symbolBody && inst->body.getDeclaringDefinition() ==
2596 symbolBody->getDeclaringDefinition())) {
2597 if (
auto value =
context.valueSymbols.lookup(&expr.symbol))
2604 if (
auto value =
context.resolveCapturedValue(expr.symbol))
2610 if (
auto key =
context.buildHierValueKey(expr)) {
2611 if (
auto it =
context.hierValueSymbols.find(*key);
2612 it !=
context.hierValueSymbols.end())
2617 if (
auto value =
context.valueSymbols.lookup(&expr.symbol))
2624 if (
auto globalOp =
context.globalVariables.lookup(&expr.symbol))
2625 return moore::GetGlobalVariableOp::create(builder, loc, globalOp);
2629 auto d = mlir::emitError(loc,
"unknown hierarchical name `")
2630 << expr.symbol.name <<
"`";
2631 d.attachNote(
context.convertLocation(expr.symbol.location))
2632 <<
"no lvalue generated for " << slang::ast::toString(expr.symbol.kind);
2636 Value visit(
const slang::ast::StreamingConcatenationExpression &expr) {
2637 SmallVector<Value> operands;
2638 for (
auto stream : expr.streams()) {
2639 auto operandLoc =
context.convertLocation(stream.operand->sourceRange);
2640 if (!stream.constantWithWidth.has_value() && stream.withExpr) {
2641 mlir::emitError(operandLoc)
2642 <<
"Moore only support streaming "
2643 "concatenation with fixed size 'with expression'";
2647 if (stream.constantWithWidth.has_value()) {
2648 value =
context.convertLvalueExpression(*stream.withExpr);
2649 auto type = cast<moore::UnpackedType>(
2650 cast<moore::RefType>(value.getType()).getNestedType());
2651 auto intType = moore::RefType::get(moore::IntType::get(
2652 context.getContext(), type.getBitSize().value(), type.getDomain()));
2654 value =
context.materializeConversion(intType, value,
false, loc);
2656 value =
context.convertLvalueExpression(*stream.operand);
2661 operands.push_back(value);
2664 if (operands.size() == 1) {
2667 value = operands.front();
2669 value = moore::ConcatRefOp::create(builder, loc, operands).getResult();
2672 if (expr.getSliceSize() == 0) {
2676 auto type = cast<moore::IntType>(
2677 cast<moore::RefType>(value.getType()).getNestedType());
2678 SmallVector<Value> slicedOperands;
2679 auto widthSum = type.getWidth();
2680 auto domain = type.getDomain();
2681 auto iterMax = widthSum / expr.getSliceSize();
2682 auto remainSize = widthSum % expr.getSliceSize();
2684 for (
size_t i = 0; i < iterMax; i++) {
2685 auto extractResultType = moore::RefType::get(moore::IntType::get(
2686 context.getContext(), expr.getSliceSize(), domain));
2688 auto extracted = moore::ExtractRefOp::create(
2689 builder, loc, extractResultType, value, i * expr.getSliceSize());
2690 slicedOperands.push_back(extracted);
2694 auto extractResultType = moore::RefType::get(
2695 moore::IntType::get(
context.getContext(), remainSize, domain));
2698 moore::ExtractRefOp::create(builder, loc, extractResultType, value,
2699 iterMax * expr.getSliceSize());
2700 slicedOperands.push_back(extracted);
2703 return moore::ConcatRefOp::create(builder, loc, slicedOperands);
2707 template <
typename T>
2708 Value visit(T &&node) {
2709 return context.convertRvalueExpression(node);
2712 Value visitInvalid(
const slang::ast::Expression &expr) {
2713 mlir::emitError(loc,
"invalid expression");
2723Value Context::resolveCapturedValue(
const slang::ast::ValueSymbol &sym) {
2731std::optional<std::pair<const slang::ast::InstanceSymbol *, mlir::StringAttr>>
2733 const slang::ast::HierarchicalValueExpression &expr) {
2734 if (expr.ref.path.empty())
2735 return std::nullopt;
2737 const slang::ast::InstanceSymbol *firstInst =
nullptr;
2738 SmallVector<StringRef, 4> names;
2739 for (
auto &elem : expr.ref.path) {
2740 if (
auto *inst = elem.symbol->as_if<slang::ast::InstanceSymbol>()) {
2744 names.push_back(inst->name);
2748 names.push_back(expr.symbol.name);
2749 std::string hierName = llvm::join(names,
".");
2752 return std::nullopt;
2753 return std::make_pair(firstInst,
builder.getStringAttr(hierName));
2761 Type requiredType) {
2763 auto value = expr.visit(RvalueExprVisitor(*
this, loc));
2764 if (value && requiredType)
2772 return expr.visit(LvalueExprVisitor(*
this, loc));
2780 if (
auto type = dyn_cast_or_null<moore::IntType>(value.getType()))
2781 if (type.getBitSize() == 1)
2783 if (
auto type = dyn_cast_or_null<moore::UnpackedType>(value.getType()))
2784 return moore::BoolCastOp::create(
builder, value.getLoc(), value);
2785 mlir::emitError(value.getLoc(),
"expression of type ")
2786 << value.getType() <<
" cannot be cast to a boolean";
2792 const slang::ast::Type &astType,
2794 const auto *floatType = astType.as_if<slang::ast::FloatingType>();
2798 if (svreal.isShortReal() &&
2799 floatType->floatKind == slang::ast::FloatingType::ShortReal) {
2800 attr = FloatAttr::get(
builder.getF32Type(), svreal.shortReal().v);
2801 }
else if (svreal.isReal() &&
2802 floatType->floatKind == slang::ast::FloatingType::Real) {
2803 attr = FloatAttr::get(
builder.getF64Type(), svreal.real().v);
2805 mlir::emitError(loc) <<
"invalid real constant";
2809 return moore::ConstantRealOp::create(
builder, loc, attr);
2814 const slang::ast::Type &astType,
2816 if (!astType.isString())
2818 const std::string &str = stringLiteral.str();
2819 auto intTy = moore::IntType::getInt(
getContext(),
2820 static_cast<unsigned>(str.size() * 8));
2822 moore::ConstantStringOp::create(
builder, loc, intTy, str).getResult();
2823 return moore::IntToStringOp::create(
builder, loc, immInt).getResult();
2828 const slang::ast::Type &astType, Location loc) {
2833 bool typeIsFourValued =
false;
2834 if (
auto unpackedType = dyn_cast<moore::UnpackedType>(type))
2838 auto intType = moore::IntType::get(
getContext(), fvint.getBitWidth(),
2839 fvint.hasUnknown() || typeIsFourValued
2842 auto result = moore::ConstantOp::create(
builder, loc, intType, fvint);
2847 const slang::ConstantValue &constant,
2848 const slang::ast::FixedSizeUnpackedArrayType &astType, Location loc) {
2855 if (astType.elementType.isString()) {
2856 auto arrayType = dyn_cast<moore::UnpackedArrayType>(type);
2860 SmallVector<Value> elemVals;
2861 for (
const auto &elem : constant.elements()) {
2862 if (!elem.isString())
2867 elemVals.push_back(value);
2869 if (elemVals.size() != arrayType.getSize())
2871 return moore::ArrayCreateOp::create(
builder, loc, arrayType, elemVals);
2876 if (astType.elementType.isIntegral())
2877 bitWidth = astType.elementType.getBitWidth();
2881 bool typeIsFourValued =
false;
2884 if (
auto unpackedType = dyn_cast<moore::UnpackedType>(type))
2895 auto intType = moore::IntType::get(
getContext(), bitWidth, domain);
2897 auto arrType = moore::UnpackedArrayType::get(
2898 getContext(), constant.elements().size(), intType);
2900 llvm::SmallVector<mlir::Value> elemVals;
2901 moore::ConstantOp constOp;
2903 mlir::OpBuilder::InsertionGuard guard(
builder);
2906 for (
auto elem : constant.elements()) {
2908 constOp = moore::ConstantOp::create(
builder, loc, intType, fvInt);
2909 elemVals.push_back(constOp.getResult());
2914 auto arrayOp = moore::ArrayCreateOp::create(
builder, loc, arrType, elemVals);
2916 return arrayOp.getResult();
2920 const slang::ast::Type &type, Location loc) {
2922 if (
auto *arr = type.as_if<slang::ast::FixedSizeUnpackedArrayType>())
2924 if (constant.isInteger())
2926 if (constant.isReal() || constant.isShortReal())
2928 if (constant.isString())
2936 using slang::ast::EvalFlags;
2937 slang::ast::EvalContext evalContext(
2939 slang::ast::LookupLocation::max),
2940 EvalFlags::CacheResults | EvalFlags::SpecparamsAllowed);
2941 return expr.eval(evalContext);
2950 auto type = moore::IntType::get(
getContext(), 1, domain);
2957 if (isa<moore::IntType>(value.getType()))
2964 if (
auto packed = dyn_cast<moore::PackedType>(value.getType()))
2965 if (
auto sbvType = packed.getSimpleBitVector())
2968 mlir::emitError(value.getLoc()) <<
"expression of type " << value.getType()
2969 <<
" cannot be cast to a simple bit vector";
2977 Location loc,
bool fallible) {
2978 if (isa<moore::IntType>(value.getType()))
2981 auto &builder =
context.builder;
2982 auto packedType = cast<moore::PackedType>(value.getType());
2983 auto intType = packedType.getSimpleBitVector();
2988 if (isa<moore::TimeType>(packedType) &&
2990 value = builder.createOrFold<moore::TimeToLogicOp>(loc, value);
2991 auto scale = moore::ConstantOp::create(builder, loc, intType,
2993 return builder.createOrFold<moore::DivUOp>(loc, value, scale);
2999 if (packedType.containsTimeType()) {
3001 mlir::emitError(loc) <<
"unsupported conversion: " << packedType
3002 <<
" cannot be converted to " << intType
3003 <<
"; contains a time type";
3008 return builder.createOrFold<moore::PackedToSBVOp>(loc, value);
3016 Value value, Location loc,
3018 if (value.getType() == packedType)
3021 auto &builder =
context.builder;
3022 auto intType = cast<moore::IntType>(value.getType());
3027 if (isa<moore::TimeType>(packedType) &&
3029 auto scale = moore::ConstantOp::create(builder, loc, intType,
3031 value = builder.createOrFold<moore::MulOp>(loc, value, scale);
3032 return builder.createOrFold<moore::LogicToTimeOp>(loc, value);
3040 mlir::emitError(loc) <<
"unsupported conversion: " << intType
3041 <<
" cannot be converted to " << packedType
3042 <<
"; contains a time type";
3047 return builder.createOrFold<moore::SBVToPackedOp>(loc, packedType, value);
3053 moore::ClassHandleType expectedHandleTy) {
3054 auto loc = actualHandle.getLoc();
3056 auto actualTy = actualHandle.getType();
3057 auto actualHandleTy = dyn_cast<moore::ClassHandleType>(actualTy);
3058 if (!actualHandleTy) {
3059 mlir::emitError(loc) <<
"expected a !moore.class<...> value, got "
3065 if (actualHandleTy == expectedHandleTy)
3066 return actualHandle;
3068 if (!
context.isClassDerivedFrom(actualHandleTy, expectedHandleTy)) {
3069 mlir::emitError(loc)
3070 <<
"receiver class " << actualHandleTy.getClassSym()
3071 <<
" is not the same as, or derived from, expected base class "
3072 << expectedHandleTy.getClassSym().getRootReference();
3077 auto casted = moore::ClassUpcastOp::create(
context.builder, loc,
3078 expectedHandleTy, actualHandle)
3084 Location loc,
bool fallible) {
3086 if (type == value.getType())
3091 auto dstPacked = dyn_cast<moore::PackedType>(type);
3092 auto srcPacked = dyn_cast<moore::PackedType>(value.getType());
3093 auto dstInt = dstPacked ? dstPacked.getSimpleBitVector() : moore::IntType();
3094 auto srcInt = srcPacked ? srcPacked.getSimpleBitVector() : moore::IntType();
3096 if (dstInt && srcInt) {
3104 auto resizedType = moore::IntType::get(
3105 value.getContext(), dstInt.getWidth(), srcPacked.getDomain());
3106 if (dstInt.getWidth() < srcInt.getWidth()) {
3107 value =
builder.createOrFold<moore::TruncOp>(loc, resizedType, value);
3108 }
else if (dstInt.getWidth() > srcInt.getWidth()) {
3110 value =
builder.createOrFold<moore::SExtOp>(loc, resizedType, value);
3112 value =
builder.createOrFold<moore::ZExtOp>(loc, resizedType, value);
3116 if (dstInt.getDomain() != srcInt.getDomain()) {
3118 value =
builder.createOrFold<moore::LogicToIntOp>(loc, value);
3120 value =
builder.createOrFold<moore::IntToLogicOp>(loc, value);
3129 assert(value.getType() == type);
3134 if (isa<moore::StringType>(type) &&
3135 isa<moore::FormatStringType>(value.getType())) {
3136 return builder.createOrFold<moore::FormatStringToStringOp>(loc, value);
3140 if (isa<moore::FormatStringType>(type) &&
3141 isa<moore::StringType>(value.getType())) {
3142 return builder.createOrFold<moore::FormatStringOp>(loc, value);
3147 if (isa<moore::QueueType>(type) && isa<moore::QueueType>(value.getType()) &&
3148 cast<moore::QueueType>(type).getElementType() ==
3149 cast<moore::QueueType>(value.getType()).getElementType())
3150 return builder.createOrFold<moore::QueueResizeOp>(loc, type, value);
3153 if (isa<moore::QueueType>(type) &&
3154 isa<moore::UnpackedArrayType>(value.getType())) {
3155 auto queueElType = dyn_cast<moore::QueueType>(type).getElementType();
3156 auto unpackedArrayElType =
3157 dyn_cast<moore::UnpackedArrayType>(value.getType()).getElementType();
3159 if (queueElType == unpackedArrayElType) {
3160 return builder.createOrFold<moore::QueueFromUnpackedArrayOp>(loc, type,
3166 if (dstInt && isa<moore::RealType>(value.getType())) {
3167 auto twoValInt =
builder.createOrFold<moore::RealToIntOp>(
3168 loc, dstInt.getTwoValued(), value);
3173 if (isa<moore::RealType>(type) && isa<moore::IntType>(value.getType())) {
3176 if (dyn_cast<moore::IntType>(value.getType()).getDomain() ==
3181 dyn_cast<moore::IntType>(value.getType()).getTwoValued(), value,
true,
3185 return builder.createOrFold<moore::SIntToRealOp>(loc, type, twoValInt);
3186 return builder.createOrFold<moore::UIntToRealOp>(loc, type, twoValInt);
3189 auto getBuiltinFloatType = [&](moore::RealType type) -> Type {
3191 return mlir::Float32Type::get(
builder.getContext());
3193 return mlir::Float64Type::get(
builder.getContext());
3197 if (isa<moore::TimeType>(type) && isa<moore::RealType>(value.getType())) {
3199 moore::IntType::get(
builder.getContext(), 64, Domain::TwoValued);
3201 getBuiltinFloatType(cast<moore::RealType>(value.getType()));
3202 auto scale = moore::ConstantRealOp::create(
3203 builder, loc, value.getType(),
3205 auto scaled =
builder.createOrFold<moore::MulRealOp>(loc, value, scale);
3206 auto asInt = moore::RealToIntOp::create(
builder, loc, intType, scaled);
3207 auto asLogic = moore::IntToLogicOp::create(
builder, loc, asInt);
3208 return moore::LogicToTimeOp::create(
builder, loc, asLogic);
3212 if (isa<moore::RealType>(type) && isa<moore::TimeType>(value.getType())) {
3213 auto asLogic = moore::TimeToLogicOp::create(
builder, loc, value);
3214 auto asInt = moore::LogicToIntOp::create(
builder, loc, asLogic);
3215 auto asReal = moore::UIntToRealOp::create(
builder, loc, type, asInt);
3216 Type floatType = getBuiltinFloatType(cast<moore::RealType>(type));
3217 auto scale = moore::ConstantRealOp::create(
3220 return moore::DivRealOp::create(
builder, loc, asReal, scale);
3224 if (isa<moore::StringType>(type)) {
3225 if (
auto intType = dyn_cast<moore::IntType>(value.getType())) {
3227 value = moore::LogicToIntOp::create(
builder, loc, value);
3228 return moore::IntToStringOp::create(
builder, loc, value);
3233 if (
auto intType = dyn_cast<moore::IntType>(type)) {
3234 if (isa<moore::StringType>(value.getType())) {
3235 value = moore::StringToIntOp::create(
builder, loc, intType.getTwoValued(),
3239 return moore::IntToLogicOp::create(
builder, loc, value);
3246 if (isa<moore::FormatStringType>(type)) {
3248 value, isSigned, loc);
3251 return moore::FormatStringOp::create(
builder, loc, asStr, {}, {}, {});
3254 if (isa<moore::RealType>(type) && isa<moore::RealType>(value.getType()))
3255 return builder.createOrFold<moore::ConvertRealOp>(loc, type, value);
3257 if (isa<moore::ClassHandleType>(type) &&
3258 isa<moore::ClassHandleType>(value.getType()))
3262 if (fallible && value.getType() != type)
3264 if (value.getType() != type)
3265 value = moore::ConversionOp::create(
builder, loc, type, value);
3271template <
typename OpTy>
3274 std::span<const slang::ast::Expression *const> args) {
3276 assert(args.size() == 1 &&
"real math builtin expects 1 argument");
3277 auto value =
context.convertRvalueExpression(*args[0]);
3280 return OpTy::create(
context.builder, loc, value);
3286 auto &builder =
context.builder;
3287 auto newBlockAfter = [&](Block *after) -> Block * {
3288 auto block = std::make_unique<Block>();
3289 block->insertAfter(after);
3290 return block.release();
3293 for (
auto [destExpr, value, matched] : result.assignments) {
3294 auto lhs =
context.convertLvalueExpression(*destExpr);
3297 auto cond = moore::ToBuiltinIntOp::create(builder, loc, matched);
3299 auto *assignBlock = newBlockAfter(builder.getInsertionBlock());
3300 auto *continuedBlock = newBlockAfter(assignBlock);
3301 mlir::cf::CondBranchOp::create(builder, loc, cond, assignBlock,
3304 builder.setInsertionPointToEnd(assignBlock);
3305 moore::BlockingAssignOp::create(builder, loc, lhs, value);
3306 mlir::cf::BranchOp::create(builder, loc, continuedBlock);
3308 builder.setInsertionPointToEnd(continuedBlock);
3314 const slang::ast::SystemSubroutine &subroutine, Location loc,
3315 std::span<const slang::ast::Expression *const> args) {
3316 using ksn = slang::parsing::KnownSystemName;
3317 StringRef name = subroutine.name;
3318 auto nameId = subroutine.knownNameId;
3319 size_t numArgs = args.size();
3327 if (nameId == ksn::URandom || nameId == ksn::Random) {
3328 auto i32Ty = moore::IntType::getInt(
builder.getContext(), 32);
3329 auto minval = moore::ConstantOp::create(
builder, loc, i32Ty, 0);
3331 moore::ConstantOp::create(
builder, loc, i32Ty, APInt::getAllOnes(32));
3338 return moore::UrandomRangeBIOp::create(
builder, loc, minval, maxval, seed);
3341 if (nameId == ksn::URandomRange) {
3342 auto i32Ty = moore::IntType::getInt(
builder.getContext(), 32);
3352 minval = moore::ConstantOp::create(
builder, loc, i32Ty, 0);
3354 return moore::UrandomRangeBIOp::create(
builder, loc, minval, maxval,
3362 if (nameId == ksn::Time || nameId == ksn::STime || nameId == ksn::RealTime) {
3364 assert(numArgs == 0 &&
"time functions take no arguments");
3365 return moore::TimeBIOp::create(
builder, loc);
3372 if (nameId == ksn::Clog2) {
3374 assert(numArgs == 1 &&
"`$clog2` takes 1 argument");
3381 return moore::Clog2BIOp::create(
builder, loc, value);
3388 if (nameId == ksn::IsUnknown) {
3389 assert(numArgs == 1 &&
"`$isunknown` takes 1 argument");
3394 if (!isa<moore::IntType>(value.getType())) {
3395 if (!isa<moore::PackedType>(value.getType())) {
3396 mlir::emitError(loc) <<
"expected integer argument for `$isunknown`";
3404 auto valTy = dyn_cast<moore::IntType>(value.getType());
3408 if (nameId == ksn::OneHot0 || nameId == ksn::OneHot) {
3409 assert(numArgs == 1 &&
"`$onehot`/`$onehot0` takes 1 argument");
3413 if (!isa<moore::IntType>(value.getType())) {
3414 if (!isa<moore::PackedType>(value.getType())) {
3415 mlir::emitError(loc)
3416 <<
"expected integer argument for `$onehot`/`$onehot0`";
3424 auto valTy = dyn_cast<moore::IntType>(value.getType());
3426 mlir::emitError(loc) <<
"expected integer argument for `"
3427 << subroutine.name <<
"`";
3434 if (valTy.getDomain() == Domain::FourValued) {
3435 Value isUnknownMoore =
3438 builder.createOrFold<moore::ToBuiltinIntOp>(loc, isUnknownMoore);
3446 auto minusOne = comb::SubOp::create(
builder, loc, intVal, one);
3447 auto anded = comb::AndOp::create(
builder, loc, intVal, minusOne);
3449 Value result = comb::ICmpOp::create(
builder, loc, comb::ICmpPredicate::eq,
3450 anded, zero,
false);
3453 if (nameId == ksn::OneHot) {
3454 auto isNotZero = comb::ICmpOp::create(
3455 builder, loc, comb::ICmpPredicate::ne, intVal, zero,
false);
3456 result = comb::AndOp::create(
builder, loc, result, isNotZero);
3463 result = comb::MuxOp::create(
builder, loc, isUnknown, zeroI1, result);
3464 Value resultMoore = moore::FromBuiltinIntOp::create(
builder, loc, result);
3465 return moore::IntToLogicOp::create(
builder, loc, resultMoore).getResult();
3467 return moore::FromBuiltinIntOp::create(
builder, loc, result);
3470 if (nameId == ksn::CountOnes) {
3471 assert(numArgs == 1 &&
"`$countones` takes 1 argument");
3475 if (!isa<moore::IntType>(value.getType())) {
3476 if (!isa<moore::PackedType>(value.getType())) {
3477 mlir::emitError(loc) <<
"expected integer argument for `$countones`";
3485 auto valTy = dyn_cast<moore::IntType>(value.getType());
3487 mlir::emitError(loc) <<
"expected integer argument for `$countones`";
3495 auto builtinIntTy = cast<IntegerType>(intVal.getType());
3496 unsigned width = builtinIntTy.getWidth();
3497 unsigned resultWidth = llvm::Log2_32_Ceil(width + 1);
3498 auto i1Ty =
builder.getI1Type();
3499 unsigned padWidth = resultWidth - 1;
3501 builder.getIntegerType(padWidth), 0);
3505 Value sum = comb::ConcatOp::create(
builder, loc, ValueRange{zeros, bit0});
3507 for (
unsigned i = 1; i < width; ++i) {
3510 comb::ConcatOp::create(
builder, loc, ValueRange{zeros, bit});
3511 sum = comb::AddOp::create(
builder, loc, sum, extended);
3515 return moore::FromBuiltinIntOp::create(
builder, loc, sum);
3519 if (nameId == ksn::Ln)
3520 return convertRealMathBI<moore::LnBIOp>(*
this, loc, name, args);
3521 if (nameId == ksn::Log10)
3522 return convertRealMathBI<moore::Log10BIOp>(*
this, loc, name, args);
3523 if (nameId == ksn::Exp)
3524 return convertRealMathBI<moore::ExpBIOp>(*
this, loc, name, args);
3525 if (nameId == ksn::Sqrt)
3526 return convertRealMathBI<moore::SqrtBIOp>(*
this, loc, name, args);
3527 if (nameId == ksn::Floor)
3528 return convertRealMathBI<moore::FloorBIOp>(*
this, loc, name, args);
3529 if (nameId == ksn::Ceil)
3530 return convertRealMathBI<moore::CeilBIOp>(*
this, loc, name, args);
3531 if (nameId == ksn::Sin)
3532 return convertRealMathBI<moore::SinBIOp>(*
this, loc, name, args);
3533 if (nameId == ksn::Cos)
3534 return convertRealMathBI<moore::CosBIOp>(*
this, loc, name, args);
3535 if (nameId == ksn::Tan)
3536 return convertRealMathBI<moore::TanBIOp>(*
this, loc, name, args);
3537 if (nameId == ksn::Asin)
3538 return convertRealMathBI<moore::AsinBIOp>(*
this, loc, name, args);
3539 if (nameId == ksn::Acos)
3540 return convertRealMathBI<moore::AcosBIOp>(*
this, loc, name, args);
3541 if (nameId == ksn::Atan)
3542 return convertRealMathBI<moore::AtanBIOp>(*
this, loc, name, args);
3543 if (nameId == ksn::Sinh)
3544 return convertRealMathBI<moore::SinhBIOp>(*
this, loc, name, args);
3545 if (nameId == ksn::Cosh)
3546 return convertRealMathBI<moore::CoshBIOp>(*
this, loc, name, args);
3547 if (nameId == ksn::Tanh)
3548 return convertRealMathBI<moore::TanhBIOp>(*
this, loc, name, args);
3549 if (nameId == ksn::Asinh)
3550 return convertRealMathBI<moore::AsinhBIOp>(*
this, loc, name, args);
3551 if (nameId == ksn::Acosh)
3552 return convertRealMathBI<moore::AcoshBIOp>(*
this, loc, name, args);
3553 if (nameId == ksn::Atanh)
3554 return convertRealMathBI<moore::AtanhBIOp>(*
this, loc, name, args);
3560 if (nameId == ksn::Signed || nameId == ksn::Unsigned) {
3562 assert(numArgs == 1 &&
"`$signed`/`$unsigned` take 1 argument");
3568 if (nameId == ksn::RealToBits)
3569 return convertRealMathBI<moore::RealtobitsBIOp>(*
this, loc, name, args);
3570 if (nameId == ksn::BitsToReal)
3571 return convertRealMathBI<moore::BitstorealBIOp>(*
this, loc, name, args);
3572 if (nameId == ksn::ShortrealToBits)
3573 return convertRealMathBI<moore::ShortrealtobitsBIOp>(*
this, loc, name,
3575 if (nameId == ksn::BitsToShortreal)
3576 return convertRealMathBI<moore::BitstoshortrealBIOp>(*
this, loc, name,
3579 if (nameId == ksn::Cast) {
3580 assert(numArgs == 2 &&
"`cast` takes 2 arguments");
3581 auto *dstExpr = args[0];
3586 if (
auto *assign = dstExpr->as_if<slang::ast::AssignmentExpression>())
3587 dstExpr = &assign->left();
3596 if (isa<moore::ClassHandleType>(dstType) ||
3597 isa<moore::ClassHandleType>(src.getType())) {
3598 auto i1Ty = moore::IntType::getInt(
builder.getContext(), 1);
3599 return moore::ConstantOp::create(
builder, loc, i1Ty, 0,
3603 dstType, src, args[1]->type->isSigned(), loc,
true);
3604 auto i1Ty = moore::IntType::getInt(
builder.getContext(), 1);
3606 return moore::ConstantOp::create(
builder, loc, i1Ty, 0,
3608 moore::BlockingAssignOp::create(
builder, loc, dst, converted);
3609 return moore::ConstantOp::create(
builder, loc, i1Ty, 1,
3617 if (nameId == ksn::Len) {
3619 assert(numArgs == 1 &&
"`len` takes 1 argument");
3620 auto stringType = moore::StringType::get(
getContext());
3624 return moore::StringLenOp::create(
builder, loc, value);
3627 if (nameId == ksn::Getc) {
3629 assert(numArgs == 2 &&
"`getc` takes 2 arguments");
3630 auto stringType = moore::StringType::get(
getContext());
3635 return moore::StringGetOp::create(
builder, loc, str, index);
3638 if (nameId == ksn::ToUpper) {
3640 assert(numArgs == 1 &&
"`toupper` takes 1 argument");
3641 auto stringType = moore::StringType::get(
getContext());
3645 return moore::StringToUpperOp::create(
builder, loc, value);
3648 if (nameId == ksn::ToLower) {
3650 assert(numArgs == 1 &&
"`tolower` takes 1 argument");
3651 auto stringType = moore::StringType::get(
getContext());
3655 return moore::StringToLowerOp::create(
builder, loc, value);
3658 if (nameId == ksn::Compare || nameId == ksn::ICompare) {
3661 auto stringType = moore::StringType::get(
getContext());
3666 if (nameId == ksn::Compare)
3667 return moore::StringCompareOp::create(
builder, loc, lhs, rhs);
3668 return moore::StringICompareOp::create(
builder, loc, lhs, rhs);
3671 if (nameId == ksn::Substr) {
3673 assert(numArgs == 3 &&
"`substr` takes 3 arguments");
3674 auto stringType = moore::StringType::get(
getContext());
3678 if (!str || !start || !end)
3680 return moore::StringSubstrOp::create(
builder, loc, str, start, end);
3683 if (nameId == ksn::AToI || nameId == ksn::AToHex || nameId == ksn::AToOct ||
3684 nameId == ksn::AToBin) {
3686 assert(numArgs == 1 &&
"`atoi/hex/oct/bin` takes 1 argument");
3687 auto stringType = moore::StringType::get(
getContext());
3691 auto integerType = moore::IntType::getLogic(
builder.getContext(), 32);
3694 return moore::StringAtoiOp::create(
builder, loc, integerType, str);
3696 return moore::StringAtohexOp::create(
builder, loc, integerType, str);
3698 return moore::StringAtooctOp::create(
builder, loc, integerType, str);
3700 return moore::StringAtobinOp::create(
builder, loc, integerType, str);
3702 llvm_unreachable(
"unexpected string to integer conversion");
3706 if (nameId == ksn::AToReal) {
3708 assert(numArgs == 1 &&
"`atoreal` takes 1 argument");
3709 auto stringType = moore::StringType::get(
getContext());
3714 return moore::StringAtorealOp::create(
builder, loc, realType, str);
3721 if (nameId == ksn::ArraySize) {
3723 assert(numArgs == 1 &&
"`size` takes 1 argument");
3724 if (args[0]->type->isQueue()) {
3728 return moore::QueueSizeBIOp::create(
builder, loc, value);
3730 if (args[0]->type->getCanonicalType().kind ==
3731 slang::ast::SymbolKind::DynamicArrayType) {
3735 return moore::OpenUArraySizeOp::create(
builder, loc, value);
3737 if (args[0]->type->isAssociativeArray()) {
3741 return moore::AssocArraySizeOp::create(
builder, loc, value);
3743 emitError(loc) <<
"unsupported member function `size` on type `"
3744 << args[0]->type->toString() <<
"`";
3748 if (nameId == ksn::Delete) {
3750 assert(numArgs == 1 &&
"`delete` takes 1 argument");
3751 if (args[0]->type->getCanonicalType().kind ==
3752 slang::ast::SymbolKind::DynamicArrayType) {
3756 return moore::OpenUArrayDeleteOp::create(
builder, loc, value);
3758 emitError(loc) <<
"unsupported member function `delete` on type `"
3759 << args[0]->type->toString() <<
"`";
3763 if (nameId == ksn::PopBack) {
3765 assert(numArgs == 1 &&
"`pop_back` takes 1 argument");
3766 assert(args[0]->type->isQueue() &&
"`pop_back` is only valid on queues");
3770 return moore::QueuePopBackOp::create(
builder, loc, value);
3773 if (nameId == ksn::PopFront) {
3775 assert(numArgs == 1 &&
"`pop_front` takes 1 argument");
3776 assert(args[0]->type->isQueue() &&
"`pop_front` is only valid on queues");
3780 return moore::QueuePopFrontOp::create(
builder, loc, value);
3787 if (nameId == ksn::Num) {
3788 if (args[0]->type->isAssociativeArray()) {
3789 assert(numArgs == 1 &&
"`num` takes 1 argument");
3793 return moore::AssocArraySizeOp::create(
builder, loc, value);
3795 emitError(loc) <<
"unsupported system call `" << name <<
"`";
3799 if (nameId == ksn::Exists) {
3801 assert(numArgs == 2 &&
"`exists` takes 2 arguments");
3802 assert(args[0]->type->isAssociativeArray() &&
3803 "`exists` is only valid on associative arrays");
3808 return moore::AssocArrayExistsOp::create(
builder, loc, array, key);
3815 if (nameId == ksn::First || nameId == ksn::Last || nameId == ksn::Next ||
3816 nameId == ksn::Prev) {
3817 if (args[0]->type->isAssociativeArray()) {
3818 assert(numArgs == 2 &&
"traversal methods take 2 arguments");
3823 if (nameId == ksn::First)
3824 return moore::AssocArrayFirstOp::create(
builder, loc, array, key);
3825 if (nameId == ksn::Last)
3826 return moore::AssocArrayLastOp::create(
builder, loc, array, key);
3827 if (nameId == ksn::Next)
3828 return moore::AssocArrayNextOp::create(
builder, loc, array, key);
3829 if (nameId == ksn::Prev)
3830 return moore::AssocArrayPrevOp::create(
builder, loc, array, key);
3831 llvm_unreachable(
"all traversal cases handled above");
3833 emitError(loc) <<
"unsupported system call `" << name <<
"`";
3841 if (nameId == ksn::FOpen) {
3842 assert(numArgs >= 1 && numArgs <= 2 &&
"`$fopen` takes 1 or 2 arguments");
3847 moore::FOpenModeAttr modeAttr;
3849 auto *strLit = args[1]
3850 ->unwrapImplicitConversions()
3851 .as_if<slang::ast::StringLiteral>();
3853 return emitError(loc) <<
"$fopen mode must be a string literal",
3857 llvm::StringSwitch<std::optional<moore::FOpenMode>>(
3859 .Cases({
"r",
"rb"}, moore::FOpenMode::Read)
3860 .Cases({
"w",
"wb"}, moore::FOpenMode::Write)
3861 .Cases({
"a",
"ab"}, moore::FOpenMode::Append)
3862 .Cases({
"r+",
"r+b",
"rb+"}, moore::FOpenMode::ReadUpdate)
3863 .Cases({
"w+",
"w+b",
"wb+"}, moore::FOpenMode::WriteUpdate)
3864 .Cases({
"a+",
"a+b",
"ab+"}, moore::FOpenMode::AppendUpdate)
3865 .Default(std::nullopt);
3868 return emitError(loc)
3869 <<
"invalid $fopen mode '" << strLit->getValue() <<
"'",
3871 modeAttr = moore::FOpenModeAttr::get(
getContext(), *mode);
3873 return moore::FOpenBIOp::create(
builder, loc, filename, modeAttr);
3880 if (nameId == ksn::TestPlusArgs) {
3882 assert(numArgs == 1 &&
"`$test$plusargs` takes 1 argument");
3884 args[0]->unwrapImplicitConversions().as_if<slang::ast::StringLiteral>();
3886 return emitError(loc) <<
"`$test$plusargs` argument must be a string "
3889 auto foundTy = moore::IntType::getInt(
getContext(), 1);
3890 return moore::PlusArgsTestBIOp::create(
3891 builder, loc, foundTy,
builder.getStringAttr(strLit->getValue()));
3894 if (nameId == ksn::ValuePlusArgs) {
3898 assert(numArgs == 2 &&
"`$value$plusargs` takes 2 arguments");
3900 args[0]->unwrapImplicitConversions().as_if<slang::ast::StringLiteral>();
3902 return emitError(loc) <<
"`$value$plusargs` format must be a string "
3907 const auto *valueArg = args[1];
3908 if (
const auto *assign =
3909 valueArg->as_if<slang::ast::AssignmentExpression>())
3910 valueArg = &assign->left();
3914 auto resultType = cast<moore::RefType>(lvalue.getType()).getNestedType();
3915 auto foundTy = moore::IntType::getInt(
getContext(), 1);
3916 auto op = moore::PlusArgsValueBIOp::create(
3917 builder, loc, foundTy, resultType,
3918 builder.getStringAttr(strLit->getValue()));
3919 moore::BlockingAssignOp::create(
builder, loc, lvalue, op.getResult());
3920 return op.getFound();
3923 if (nameId == ksn::FScanf) {
3925 *args[0], moore::IntType::getInt(
builder.getContext(), 32));
3929 args[1]->unwrapImplicitConversions().as_if<slang::ast::StringLiteral>();
3931 return (mlir::emitError(loc)
3932 <<
"$fscanf requires a string literal format string"),
3935 moore::ScanBeginFScanFOp::create(
builder, loc, fd).getCursor();
3942 return moore::ScanEndOp::create(
builder, loc, result->finalCursor)
3946 if (nameId == ksn::SScanf) {
3952 args[1]->unwrapImplicitConversions().as_if<slang::ast::StringLiteral>();
3954 return (mlir::emitError(loc)
3955 <<
"$sscanf requires a string literal format string"),
3958 moore::ScanBeginSScanFOp::create(
builder, loc, str).getCursor();
3965 return moore::ScanEndOp::create(
builder, loc, result->finalCursor)
3970 emitError(loc) <<
"unsupported system call `" << name <<
"`";
3976 return context.symbolTable.lookupNearestSymbolFrom(
context.intoModuleOp, sym);
3980 const moore::ClassHandleType &baseTy) {
3981 if (!actualTy || !baseTy)
3984 mlir::SymbolRefAttr actualSym = actualTy.getClassSym();
3985 mlir::SymbolRefAttr baseSym = baseTy.getClassSym();
3987 if (actualSym == baseSym)
3990 auto *op =
resolve(*
this, actualSym);
3991 auto decl = llvm::dyn_cast_or_null<moore::ClassDeclOp>(op);
3994 mlir::SymbolRefAttr curBase = decl.getBaseAttr();
3997 if (curBase == baseSym)
3999 decl = llvm::dyn_cast_or_null<moore::ClassDeclOp>(
resolve(*
this, curBase));
4004moore::ClassHandleType
4006 llvm::StringRef fieldName, Location loc) {
4008 mlir::SymbolRefAttr classSym = actualTy.getClassSym();
4012 auto *op =
resolve(*
this, classSym);
4013 auto decl = llvm::dyn_cast_or_null<moore::ClassDeclOp>(op);
4018 for (
auto &block : decl.getBody()) {
4019 for (
auto &opInBlock : block) {
4021 llvm::dyn_cast<moore::ClassPropertyDeclOp>(&opInBlock)) {
4022 if (prop.getSymName() == fieldName) {
4024 return moore::ClassHandleType::get(actualTy.getContext(), classSym);
4031 classSym = decl.getBaseAttr();
4035 mlir::emitError(loc) <<
"unknown property `" << fieldName <<
"`";
4044 const slang::ast::Expression &expr) {
4047 if (
const auto *valueRange = expr.as_if<slang::ast::ValueRangeExpression>()) {
4052 if (!insideLhs || !lowBound || !highBound)
4055 Value rangeLhs, rangeRhs;
4058 if (valueRange->left().type->isSigned() ||
4059 insideLhs.getType().isSignedInteger()) {
4060 rangeLhs = moore::SgeOp::create(
builder, loc, insideLhs, lowBound);
4062 rangeLhs = moore::UgeOp::create(
builder, loc, insideLhs, lowBound);
4065 if (valueRange->right().type->isSigned() ||
4066 insideLhs.getType().isSignedInteger()) {
4067 rangeRhs = moore::SleOp::create(
builder, loc, insideLhs, highBound);
4069 rangeRhs = moore::UleOp::create(
builder, loc, insideLhs, highBound);
4072 return moore::AndOp::create(
builder, loc, rangeLhs, rangeRhs);
4076 if (!expr.type->isIntegral()) {
4077 if (expr.type->isUnpackedArray()) {
4078 mlir::emitError(loc,
4079 "unpacked arrays in 'inside' expressions not supported");
4083 loc,
"only simple bit vectors supported in 'inside' expressions");
4090 return moore::WildcardEqOp::create(
builder, loc, insideLhs, value);
assert(baseType &&"element must be base type")
static std::unique_ptr< Context > context
static Value convertRealMathBI(Context &context, Location loc, StringRef name, std::span< const slang::ast::Expression *const > args)
Helper function to convert real math builtin functions that take exactly one argument.
static mlir::Value maybeUpcastHandle(Context &context, mlir::Value actualHandle, moore::ClassHandleType expectedHandleTy)
Check whether the actual handle is a subclass of another handle type and return a properly upcast ver...
static mlir::Operation * resolve(Context &context, mlir::SymbolRefAttr sym)
static Value lookupExpandedInterfaceMember(Context &context, const slang::ast::HierarchicalValueExpression &expr)
Resolve a hierarchical value that refers to a member of an expanded interface instance.
static Value visitClassProperty(Context &context, const slang::ast::ClassPropertySymbol &expr)
static Value materializeSBVToPackedConversion(Context &context, moore::PackedType packedType, Value value, Location loc, bool fallible)
Create the necessary operations to convert from a simple bit vector IntType to an equivalent PackedTy...
static Value materializePackedToSBVConversion(Context &context, Value value, Location loc, bool fallible)
Create the necessary operations to convert from a PackedType to the corresponding simple bit vector I...
static 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 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