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);
221template <
typename RangeT>
223 assert(type.hasFixedRange());
224 const slang::ConstantRange &cstRange = type.getFixedRange();
225 if (cstRange.left < cstRange.right)
226 std::reverse(std::begin(range), std::end(range));
237 ExprVisitor(
Context &context, Location loc,
bool isLvalue)
238 : context(context), loc(loc), builder(context.builder),
239 isLvalue(isLvalue) {}
245 Value convertLvalueOrRvalueExpression(
const slang::ast::Expression &expr) {
253 Value materializeSymbolRvalue(
const slang::ast::ValueSymbol &sym) {
255 if (isa<moore::RefType>(value.getType())) {
256 auto readOp = moore::ReadOp::create(builder, loc, value);
259 return readOp.getResult();
265 auto ref = moore::GetGlobalVariableOp::create(builder, loc, globalOp);
266 auto readOp = moore::ReadOp::create(builder, loc, ref);
269 return readOp.getResult();
272 if (
auto *
const property = sym.as_if<slang::ast::ClassPropertySymbol>()) {
274 auto readOp = moore::ReadOp::create(builder, loc, fieldRef);
277 return readOp.getResult();
283 Value visit(
const slang::ast::NewArrayExpression &expr) {
288 if (expr.initExpr()) {
290 <<
"unsupported expression: array `new` with initializer\n";
295 expr.sizeExpr(), context.
convertType(*expr.sizeExpr().type));
299 return moore::OpenUArrayCreateOp::create(builder, loc, type, initialSize);
303 Value visit(
const slang::ast::ElementSelectExpression &expr) {
305 auto value = convertLvalueOrRvalueExpression(expr.value());
310 auto derefType = value.getType();
312 derefType = cast<moore::RefType>(derefType).getNestedType();
314 if (!isa<moore::IntType, moore::ArrayType, moore::UnpackedArrayType,
315 moore::QueueType, moore::AssocArrayType, moore::StringType,
316 moore::OpenUnpackedArrayType, moore::StructType, moore::UnionType>(
318 mlir::emitError(loc) <<
"unsupported expression: element select into "
319 << expr.value().type->toString() <<
"\n";
323 if (!isLvalue && isa<moore::StructType, moore::UnionType>(derefType)) {
327 derefType = value.getType();
331 if (isa<moore::AssocArrayType>(derefType)) {
332 auto assocArray = cast<moore::AssocArrayType>(derefType);
333 auto expectedIndexType = assocArray.getIndexType();
339 if (givenIndex.getType() != expectedIndexType) {
341 <<
"Incorrect index type: expected index type of "
342 << expectedIndexType <<
" but was given " << givenIndex.getType();
346 return moore::AssocArrayExtractRefOp::create(
347 builder, loc, moore::RefType::get(cast<moore::UnpackedType>(type)),
350 return moore::AssocArrayExtractOp::create(builder, loc, type, value,
355 if (isa<moore::StringType>(derefType)) {
357 mlir::emitError(loc) <<
"string index assignment not supported";
362 auto i32Type = moore::IntType::getInt(builder.getContext(), 32);
368 return moore::StringGetOp::create(builder, loc, value, index);
372 isLvalue ? moore::RefType::get(cast<moore::UnpackedType>(type)) : type;
373 auto range = expr.value().type->getFixedRange();
374 if (
auto *constValue = expr.selector().getConstant();
375 constValue && constValue->isInteger()) {
376 assert(!constValue->hasUnknown());
377 assert(constValue->size() <= 32);
379 auto lowBit = constValue->integer().as<uint32_t>().value();
381 return llvm::TypeSwitch<Type, Value>(derefType)
382 .Case<moore::QueueType>([&](moore::QueueType) {
384 <<
"Unexpected LValue extract on Queue Type!";
388 return moore::ExtractRefOp::create(builder, loc, resultType,
390 range.translateIndex(lowBit));
393 return llvm::TypeSwitch<Type, Value>(derefType)
394 .Case<moore::QueueType>([&](moore::QueueType) {
396 <<
"Unexpected RValue extract on Queue Type!";
400 return moore::ExtractOp::create(builder, loc, resultType, value,
401 range.translateIndex(lowBit));
408 llvm::scope_exit restoreQueue([&] { context.
currentQueue = savedQueue; });
409 if (isa<moore::QueueType>(derefType)) {
412 if (isa<moore::RefType>(value.getType())) {
413 context.
currentQueue = moore::ReadOp::create(builder, loc, value);
424 return llvm::TypeSwitch<Type, Value>(derefType)
425 .Case<moore::QueueType>([&](moore::QueueType) {
426 return moore::DynQueueRefElementOp::create(builder, loc, resultType,
430 return moore::DynExtractRefOp::create(builder, loc, resultType,
435 return llvm::TypeSwitch<Type, Value>(derefType)
436 .Case<moore::QueueType>([&](moore::QueueType) {
437 return moore::DynQueueExtractOp::create(builder, loc, resultType,
438 value, lowBit, lowBit);
441 return moore::DynExtractOp::create(builder, loc, resultType, value,
448 Value visit(
const slang::ast::NullLiteral &expr) {
450 if (isa<moore::ClassHandleType, moore::ChandleType, moore::EventType,
451 moore::NullType>(type))
452 return moore::NullOp::create(builder, loc);
453 mlir::emitError(loc) <<
"No null value definition found for value of type "
459 Value visit(
const slang::ast::RangeSelectExpression &expr) {
461 auto value = convertLvalueOrRvalueExpression(expr.value());
465 auto derefType = value.getType();
467 derefType = cast<moore::RefType>(derefType).getNestedType();
469 if (isa<moore::QueueType>(derefType)) {
470 return handleQueueRangeSelectExpressions(expr, type, value);
472 if (!isLvalue && isa<moore::StructType, moore::UnionType>(derefType)) {
478 return handleArrayRangeSelectExpressions(expr, type, value);
483 Value handleQueueRangeSelectExpressions(
484 const slang::ast::RangeSelectExpression &expr, Type type, Value value) {
486 llvm::scope_exit restoreQueue([&] { context.
currentQueue = savedQueue; });
492 isLvalue ? moore::RefType::get(cast<moore::UnpackedType>(type)) : type;
495 mlir::emitError(loc) <<
"queue lvalue range selections are not supported";
498 return moore::DynQueueExtractOp::create(builder, loc, resultType, value,
504 Value handleArrayRangeSelectExpressions(
505 const slang::ast::RangeSelectExpression &expr, Type type, Value value) {
506 std::optional<int32_t> constLeft;
507 std::optional<int32_t> constRight;
508 if (
auto *constant = expr.left().getConstant())
509 constLeft = constant->integer().as<int32_t>();
510 if (
auto *constant = expr.right().getConstant())
511 constRight = constant->integer().as<int32_t>();
517 <<
"unsupported expression: range select with non-constant bounds";
537 int32_t offsetConst = 0;
538 auto range = expr.value().type->getFixedRange();
540 using slang::ast::RangeSelectionKind;
541 if (expr.getSelectionKind() == RangeSelectionKind::Simple) {
546 assert(constRight &&
"constness checked in slang");
547 offsetConst = *constRight;
558 offsetConst = *constLeft;
569 int32_t offsetAdd = 0;
574 if (expr.getSelectionKind() == RangeSelectionKind::IndexedDown &&
575 range.isDescending()) {
576 assert(constRight &&
"constness checked in slang");
577 offsetAdd = 1 - *constRight;
583 if (expr.getSelectionKind() == RangeSelectionKind::IndexedUp &&
584 !range.isDescending()) {
585 assert(constRight &&
"constness checked in slang");
586 offsetAdd = *constRight - 1;
590 if (offsetAdd != 0) {
592 offsetDyn = moore::AddOp::create(
593 builder, loc, offsetDyn,
594 moore::ConstantOp::create(
595 builder, loc, cast<moore::IntType>(offsetDyn.getType()),
599 offsetConst += offsetAdd;
610 isLvalue ? moore::RefType::get(cast<moore::UnpackedType>(type)) : type;
615 return moore::DynExtractRefOp::create(builder, loc, resultType, value,
618 return moore::DynExtractOp::create(builder, loc, resultType, value,
622 offsetConst = range.translateIndex(offsetConst);
624 return moore::ExtractRefOp::create(builder, loc, resultType, value,
627 return moore::ExtractOp::create(builder, loc, resultType, value,
634 Value visit(
const slang::ast::ConcatenationExpression &expr) {
635 SmallVector<Value> operands;
636 if (expr.type->isString()) {
637 for (
auto *operand : expr.operands()) {
638 assert(!isLvalue &&
"checked by Slang");
639 auto value = convertLvalueOrRvalueExpression(*operand);
643 moore::StringType::get(context.
getContext()), value,
false,
647 operands.push_back(value);
649 return moore::StringConcatOp::create(builder, loc, operands);
651 if (expr.type->isQueue()) {
652 return handleQueueConcat(expr);
655 if (expr.type->isUnpackedArray()) {
656 assert(!isLvalue &&
"checked by Slang");
657 auto loweredType = context.
convertType(*expr.type, loc);
662 if (
auto arrayType = dyn_cast<moore::UnpackedArrayType>(loweredType))
664 else if (
auto openType =
665 dyn_cast<moore::OpenUnpackedArrayType>(loweredType))
670 SmallVector<Value> operands;
671 for (
auto *operand : expr.operands()) {
672 if (operand->type->isVoid())
677 operands.push_back(value);
680 auto arrayType = moore::UnpackedArrayType::get(
682 return moore::ArrayCreateOp::create(builder, loc, arrayType, operands);
685 for (
auto *operand : expr.operands()) {
689 if (operand->type->isVoid())
691 auto value = convertLvalueOrRvalueExpression(*operand);
698 operands.push_back(value);
701 return moore::ConcatRefOp::create(builder, loc, operands);
703 return moore::ConcatOp::create(builder, loc, operands);
710 Value handleQueueConcat(
const slang::ast::ConcatenationExpression &expr) {
711 SmallVector<Value> operands;
714 cast<moore::QueueType>(context.
convertType(*expr.type, loc));
726 Value contigElements;
728 for (
auto *operand : expr.operands()) {
729 bool isSingleElement =
734 if (!isSingleElement && contigElements) {
735 operands.push_back(moore::ReadOp::create(builder, loc, contigElements));
739 assert(!isLvalue &&
"checked by Slang");
740 auto value = convertLvalueOrRvalueExpression(*operand);
748 moore::RefType::get(context.
getContext(), queueType);
750 if (!contigElements) {
752 moore::VariableOp::create(builder, loc, queueRefType, {}, {});
754 moore::QueuePushBackOp::create(builder, loc, contigElements, value);
762 if (!(isa<moore::QueueType>(value.getType()) &&
763 cast<moore::QueueType>(value.getType()).getElementType() ==
771 operands.push_back(value);
774 if (contigElements) {
775 operands.push_back(moore::ReadOp::create(builder, loc, contigElements));
778 return moore::QueueConcatOp::create(builder, loc, queueType, operands);
782 Value visit(
const slang::ast::MemberAccessExpression &expr) {
787 auto *valueType = expr.value().type.get();
788 auto memberName = builder.getStringAttr(expr.member.name);
794 if (valueType->isVirtualInterface()) {
795 auto memberType = dyn_cast<moore::UnpackedType>(type);
798 <<
"unsupported virtual interface member type: " << type;
801 auto resultRefType = moore::RefType::get(memberType);
809 auto memberRef = moore::StructExtractOp::create(
810 builder, loc, resultRefType, memberName, base);
813 return moore::ReadOp::create(builder, loc, memberRef);
817 if (valueType->isStruct()) {
819 isLvalue ? moore::RefType::get(cast<moore::UnpackedType>(type))
821 auto value = convertLvalueOrRvalueExpression(expr.value());
826 return moore::StructExtractRefOp::create(builder, loc, resultType,
828 return moore::StructExtractOp::create(builder, loc, resultType,
833 if (valueType->isPackedUnion() || valueType->isUnpackedUnion()) {
835 isLvalue ? moore::RefType::get(cast<moore::UnpackedType>(type))
837 auto value = convertLvalueOrRvalueExpression(expr.value());
842 return moore::UnionExtractRefOp::create(builder, loc, resultType,
844 return moore::UnionExtractOp::create(builder, loc, type, memberName,
849 if (valueType->isClass()) {
853 auto targetTy = cast<moore::ClassHandleType>(valTy);
865 if (expr.member.kind != slang::ast::SymbolKind::Parameter) {
871 moore::ClassHandleType upcastTargetTy =
885 auto fieldSym = mlir::FlatSymbolRefAttr::get(builder.getContext(),
887 auto fieldRefTy = moore::RefType::get(cast<moore::UnpackedType>(type));
891 Value fieldRef = moore::ClassPropertyRefOp::create(
892 builder, loc, fieldRefTy, baseVal, fieldSym);
895 return isLvalue ? fieldRef
896 : moore::ReadOp::create(builder, loc, fieldRef);
899 slang::ConstantValue constVal;
900 if (
auto param = expr.member.as_if<slang::ast::ParameterSymbol>()) {
901 constVal = param->getValue();
906 mlir::emitError(loc) <<
"Parameter " << expr.member.name
907 <<
" has no constant value";
911 mlir::emitError(loc,
"expression of type ")
912 << valueType->toString() <<
" has no member fields";
924struct RvalueExprVisitor :
public ExprVisitor {
926 : ExprVisitor(
context, loc, false) {}
927 using ExprVisitor::visit;
930 Value visit(
const slang::ast::LValueReferenceExpression &expr) {
931 assert(!
context.lvalueStack.empty() &&
"parent assignments push lvalue");
932 auto lvalue =
context.lvalueStack.back();
933 return moore::ReadOp::create(builder, loc, lvalue);
937 Value visit(
const slang::ast::NamedValueExpression &expr) {
939 if (
auto value =
context.valueSymbols.lookup(&expr.symbol)) {
940 if (isa<moore::RefType>(value.getType())) {
941 auto readOp = moore::ReadOp::create(builder, loc, value);
942 if (
context.rvalueReadCallback)
943 context.rvalueReadCallback(readOp);
944 value = readOp.getResult();
950 if (
auto globalOp =
context.globalVariables.lookup(&expr.symbol)) {
951 auto value = moore::GetGlobalVariableOp::create(builder, loc, globalOp);
952 return moore::ReadOp::create(builder, loc, value);
956 if (
auto *
const property =
957 expr.symbol.as_if<slang::ast::ClassPropertySymbol>()) {
959 return moore::ReadOp::create(builder, loc, fieldRef).getResult();
966 if (
auto access =
context.virtualIfaceMembers.lookup(&expr.symbol);
968 auto type =
context.convertType(*expr.type);
971 auto memberType = dyn_cast<moore::UnpackedType>(type);
974 <<
"unsupported virtual interface member type: " << type;
978 Value base = materializeSymbolRvalue(*access.base);
980 auto d = mlir::emitError(loc,
"unknown name `")
981 << access.base->name <<
"`";
982 d.attachNote(
context.convertLocation(access.base->location))
983 <<
"no rvalue generated for virtual interface base";
987 auto fieldName = access.fieldName
989 : builder.getStringAttr(expr.symbol.name);
990 auto memberRefType = moore::RefType::get(memberType);
991 auto memberRef = moore::StructExtractOp::create(
992 builder, loc, memberRefType, fieldName, base);
993 auto readOp = moore::ReadOp::create(builder, loc, memberRef);
994 if (
context.rvalueReadCallback)
995 context.rvalueReadCallback(readOp);
996 return readOp.getResult();
1000 auto constant =
context.evaluateConstant(expr);
1001 if (
auto value =
context.materializeConstant(constant, *expr.type, loc))
1006 auto d = mlir::emitError(loc,
"unknown name `") << expr.symbol.name <<
"`";
1007 d.attachNote(
context.convertLocation(expr.symbol.location))
1008 <<
"no rvalue generated for " << slang::ast::toString(expr.symbol.kind);
1013 Value visit(
const slang::ast::HierarchicalValueExpression &expr) {
1014 auto hierLoc =
context.convertLocation(expr.symbol.location);
1020 if (!expr.ref.path.empty()) {
1021 if (
auto *inst = expr.ref.path.front()
1022 .symbol->as_if<slang::ast::InstanceSymbol>()) {
1024 expr.symbol.getParentScope()->getContainingInstance();
1025 if (&inst->body == symbolBody ||
1026 (symbolBody && inst->body.getDeclaringDefinition() ==
1027 symbolBody->getDeclaringDefinition())) {
1028 if (
auto value =
context.valueSymbols.lookup(&expr.symbol)) {
1029 if (isa<moore::RefType>(value.getType())) {
1030 auto readOp = moore::ReadOp::create(builder, hierLoc, value);
1031 if (
context.rvalueReadCallback)
1032 context.rvalueReadCallback(readOp);
1033 value = readOp.getResult();
1043 if (
auto value =
context.resolveCapturedValue(expr.symbol)) {
1044 if (isa<moore::RefType>(value.getType())) {
1045 auto readOp = moore::ReadOp::create(builder, hierLoc, value);
1046 if (
context.rvalueReadCallback)
1047 context.rvalueReadCallback(readOp);
1048 value = readOp.getResult();
1057 if (
auto key =
context.buildHierValueKey(expr)) {
1058 if (
auto it =
context.hierValueSymbols.find(*key);
1059 it !=
context.hierValueSymbols.end()) {
1060 auto value = it->second;
1061 if (isa<moore::RefType>(value.getType())) {
1062 auto readOp = moore::ReadOp::create(builder, hierLoc, value);
1063 if (
context.rvalueReadCallback)
1064 context.rvalueReadCallback(readOp);
1065 value = readOp.getResult();
1072 if (
auto value =
context.valueSymbols.lookup(&expr.symbol)) {
1073 if (isa<moore::RefType>(value.getType())) {
1074 auto readOp = moore::ReadOp::create(builder, hierLoc, value);
1075 if (
context.rvalueReadCallback)
1076 context.rvalueReadCallback(readOp);
1077 value = readOp.getResult();
1083 if (isa<moore::RefType>(value.getType())) {
1084 auto readOp = moore::ReadOp::create(builder, hierLoc, value);
1085 if (
context.rvalueReadCallback)
1086 context.rvalueReadCallback(readOp);
1087 return readOp.getResult();
1095 slang::ConstantValue constant;
1096 switch (expr.symbol.kind) {
1097 case slang::ast::SymbolKind::Parameter:
1098 constant = expr.symbol.as<slang::ast::ParameterSymbol>().getValue(
1101 case slang::ast::SymbolKind::Specparam:
1102 constant = expr.symbol.as<slang::ast::SpecparamSymbol>().getValue(
1105 case slang::ast::SymbolKind::EnumValue:
1106 constant = expr.symbol.as<slang::ast::EnumValueSymbol>().getValue(
1110 constant =
context.evaluateConstant(expr);
1113 if (
auto value =
context.materializeConstant(constant, *expr.type, loc))
1118 auto d = mlir::emitError(loc,
"unknown hierarchical name `")
1119 << expr.symbol.name <<
"`";
1120 d.attachNote(hierLoc) <<
"no rvalue generated for "
1121 << slang::ast::toString(expr.symbol.kind);
1127 Value visit(
const slang::ast::ArbitrarySymbolExpression &expr) {
1128 const auto &canonTy = expr.type->getCanonicalType();
1129 if (
const auto *vi = canonTy.as_if<slang::ast::VirtualInterfaceType>()) {
1130 auto value =
context.materializeVirtualInterfaceValue(*vi, loc);
1136 mlir::emitError(loc) <<
"unsupported arbitrary symbol expression of type "
1137 << expr.type->toString();
1142 Value visit(
const slang::ast::ConversionExpression &expr) {
1143 auto type =
context.convertType(*expr.type);
1146 return context.convertRvalueExpression(expr.operand(), type);
1150 Value visit(
const slang::ast::AssignmentExpression &expr) {
1151 auto lhs =
context.convertLvalueExpression(expr.left());
1156 context.lvalueStack.push_back(lhs);
1157 auto rhs =
context.convertRvalueExpression(
1158 expr.right(), cast<moore::RefType>(lhs.getType()).getNestedType());
1159 context.lvalueStack.pop_back();
1166 if (!expr.isNonBlocking()) {
1167 if (expr.timingControl)
1168 if (failed(
context.convertTimingControl(*expr.timingControl)))
1170 auto assignOp = moore::BlockingAssignOp::create(builder, loc, lhs, rhs);
1171 if (
context.variableAssignCallback)
1172 context.variableAssignCallback(assignOp);
1177 if (expr.timingControl) {
1179 if (
auto *ctrl = expr.timingControl->as_if<slang::ast::DelayControl>()) {
1180 auto delay =
context.convertRvalueExpression(
1181 ctrl->expr, moore::TimeType::get(builder.getContext()));
1184 auto assignOp = moore::DelayedNonBlockingAssignOp::create(
1185 builder, loc, lhs, rhs, delay);
1186 if (
context.variableAssignCallback)
1187 context.variableAssignCallback(assignOp);
1192 auto loc =
context.convertLocation(expr.timingControl->sourceRange);
1193 mlir::emitError(loc)
1194 <<
"unsupported non-blocking assignment timing control: "
1195 << slang::ast::toString(expr.timingControl->kind);
1198 auto assignOp = moore::NonBlockingAssignOp::create(builder, loc, lhs, rhs);
1199 if (
context.variableAssignCallback)
1200 context.variableAssignCallback(assignOp);
1206 template <
class ConcreteOp>
1207 Value createReduction(Value arg,
bool invert) {
1208 arg =
context.convertToSimpleBitVector(arg);
1211 Value result = ConcreteOp::create(builder, loc, arg);
1213 result = moore::NotOp::create(builder, loc, result);
1218 Value createIncrement(Value arg,
bool isInc,
bool isPost) {
1219 auto preValue = moore::ReadOp::create(builder, loc, arg);
1225 postValue = moore::NotOp::create(builder, loc, preValue).getResult();
1228 auto one = moore::ConstantOp::create(
1229 builder, loc, cast<moore::IntType>(preValue.getType()), 1);
1231 isInc ? moore::AddOp::create(builder, loc, preValue, one).getResult()
1232 : moore::SubOp::create(builder, loc, preValue, one).getResult();
1234 moore::BlockingAssignOp::create(builder, loc, arg, postValue);
1235 if (
context.variableAssignCallback)
1236 context.variableAssignCallback(assignOp);
1245 Value createRealIncrement(Value arg,
bool isInc,
bool isPost) {
1246 Value preValue = moore::ReadOp::create(builder, loc, arg);
1249 bool isTime = isa<moore::TimeType>(preValue.getType());
1251 preValue =
context.materializeConversion(
1252 moore::RealType::get(
context.getContext(), moore::RealWidth::f64),
1253 preValue,
false, loc);
1255 moore::RealType realTy =
1256 llvm::dyn_cast<moore::RealType>(preValue.getType());
1261 if (realTy.getWidth() == moore::RealWidth::f32) {
1262 oneAttr = builder.getFloatAttr(builder.getF32Type(), 1.0);
1263 }
else if (realTy.getWidth() == moore::RealWidth::f64) {
1265 oneAttr = builder.getFloatAttr(builder.getF64Type(), oneVal);
1267 mlir::emitError(loc) <<
"cannot construct increment for " << realTy;
1270 auto one = moore::ConstantRealOp::create(builder, loc, oneAttr);
1274 ? moore::AddRealOp::create(builder, loc, preValue, one).getResult()
1275 : moore::SubRealOp::create(builder, loc, preValue, one).getResult();
1278 postValue =
context.materializeConversion(
1279 moore::TimeType::get(
context.getContext()), postValue,
false, loc);
1282 moore::BlockingAssignOp::create(builder, loc, arg, postValue);
1284 if (
context.variableAssignCallback)
1285 context.variableAssignCallback(assignOp);
1292 Value visitRealUOp(
const slang::ast::UnaryExpression &expr) {
1293 Type opFTy =
context.convertType(*expr.operand().type);
1295 using slang::ast::UnaryOperator;
1297 if (expr.op == UnaryOperator::Preincrement ||
1298 expr.op == UnaryOperator::Predecrement ||
1299 expr.op == UnaryOperator::Postincrement ||
1300 expr.op == UnaryOperator::Postdecrement)
1301 arg =
context.convertLvalueExpression(expr.operand());
1303 arg =
context.convertRvalueExpression(expr.operand(), opFTy);
1308 if (isa<moore::TimeType>(arg.getType()))
1309 arg =
context.materializeConversion(
1310 moore::RealType::get(
context.getContext(), moore::RealWidth::f64),
1315 case UnaryOperator::Plus:
1317 case UnaryOperator::Minus:
1318 return moore::NegRealOp::create(builder, loc, arg);
1320 case UnaryOperator::Preincrement:
1321 return createRealIncrement(arg,
true,
false);
1322 case UnaryOperator::Predecrement:
1323 return createRealIncrement(arg,
false,
false);
1324 case UnaryOperator::Postincrement:
1325 return createRealIncrement(arg,
true,
true);
1326 case UnaryOperator::Postdecrement:
1327 return createRealIncrement(arg,
false,
true);
1329 case UnaryOperator::LogicalNot:
1330 arg =
context.convertToBool(arg);
1333 return moore::NotOp::create(builder, loc, arg);
1336 mlir::emitError(loc) <<
"Unary operator " << slang::ast::toString(expr.op)
1337 <<
" not supported with real values!\n";
1343 Value visit(
const slang::ast::UnaryExpression &expr) {
1345 const auto *floatType =
1346 expr.operand().type->as_if<slang::ast::FloatingType>();
1349 return visitRealUOp(expr);
1351 using slang::ast::UnaryOperator;
1353 if (expr.op == UnaryOperator::Preincrement ||
1354 expr.op == UnaryOperator::Predecrement ||
1355 expr.op == UnaryOperator::Postincrement ||
1356 expr.op == UnaryOperator::Postdecrement)
1357 arg =
context.convertLvalueExpression(expr.operand());
1359 arg =
context.convertRvalueExpression(expr.operand());
1366 case UnaryOperator::Plus:
1367 return context.convertToSimpleBitVector(arg);
1369 case UnaryOperator::Minus:
1370 arg =
context.convertToSimpleBitVector(arg);
1373 return moore::NegOp::create(builder, loc, arg);
1375 case UnaryOperator::BitwiseNot:
1376 arg =
context.convertToSimpleBitVector(arg);
1379 return moore::NotOp::create(builder, loc, arg);
1381 case UnaryOperator::BitwiseAnd:
1382 return createReduction<moore::ReduceAndOp>(arg,
false);
1383 case UnaryOperator::BitwiseOr:
1384 return createReduction<moore::ReduceOrOp>(arg,
false);
1385 case UnaryOperator::BitwiseXor:
1386 return createReduction<moore::ReduceXorOp>(arg,
false);
1387 case UnaryOperator::BitwiseNand:
1388 return createReduction<moore::ReduceAndOp>(arg,
true);
1389 case UnaryOperator::BitwiseNor:
1390 return createReduction<moore::ReduceOrOp>(arg,
true);
1391 case UnaryOperator::BitwiseXnor:
1392 return createReduction<moore::ReduceXorOp>(arg,
true);
1394 case UnaryOperator::LogicalNot:
1395 arg =
context.convertToBool(arg);
1398 return moore::NotOp::create(builder, loc, arg);
1400 case UnaryOperator::Preincrement:
1401 return createIncrement(arg,
true,
false);
1402 case UnaryOperator::Predecrement:
1403 return createIncrement(arg,
false,
false);
1404 case UnaryOperator::Postincrement:
1405 return createIncrement(arg,
true,
true);
1406 case UnaryOperator::Postdecrement:
1407 return createIncrement(arg,
false,
true);
1410 mlir::emitError(loc,
"unsupported unary operator");
1415 Value buildLogicalBOp(slang::ast::BinaryOperator op, Value lhs, Value rhs,
1416 std::optional<Domain> domain = std::nullopt) {
1417 using slang::ast::BinaryOperator;
1421 lhs =
context.convertToBool(lhs, domain.value());
1422 rhs =
context.convertToBool(rhs, domain.value());
1424 lhs =
context.convertToBool(lhs);
1425 rhs =
context.convertToBool(rhs);
1432 case BinaryOperator::LogicalAnd:
1433 return moore::AndOp::create(builder, loc, lhs, rhs);
1435 case BinaryOperator::LogicalOr:
1436 return moore::OrOp::create(builder, loc, lhs, rhs);
1438 case BinaryOperator::LogicalImplication: {
1440 auto notLHS = moore::NotOp::create(builder, loc, lhs);
1441 return moore::OrOp::create(builder, loc, notLHS, rhs);
1444 case BinaryOperator::LogicalEquivalence: {
1446 auto notLHS = moore::NotOp::create(builder, loc, lhs);
1447 auto notRHS = moore::NotOp::create(builder, loc, rhs);
1448 auto both = moore::AndOp::create(builder, loc, lhs, rhs);
1449 auto notBoth = moore::AndOp::create(builder, loc, notLHS, notRHS);
1450 return moore::OrOp::create(builder, loc, both, notBoth);
1454 llvm_unreachable(
"not a logical BinaryOperator");
1458 Value visitHandleBOp(
const slang::ast::BinaryExpression &expr) {
1460 auto lhs =
context.convertRvalueExpression(expr.left());
1463 auto rhs =
context.convertRvalueExpression(expr.right());
1467 using slang::ast::BinaryOperator;
1470 case BinaryOperator::Equality:
1471 return moore::HandleEqOp::create(builder, loc, lhs, rhs);
1472 case BinaryOperator::Inequality:
1473 return moore::HandleNeOp::create(builder, loc, lhs, rhs);
1474 case BinaryOperator::CaseEquality:
1475 return moore::HandleCaseEqOp::create(builder, loc, lhs, rhs);
1476 case BinaryOperator::CaseInequality:
1477 return moore::HandleCaseNeOp::create(builder, loc, lhs, rhs);
1480 mlir::emitError(loc)
1481 <<
"Binary operator " << slang::ast::toString(expr.op)
1482 <<
" not supported with class handle valued operands!\n";
1487 Value visitRealBOp(
const slang::ast::BinaryExpression &expr) {
1489 auto lhs =
context.convertRvalueExpression(expr.left());
1492 auto rhs =
context.convertRvalueExpression(expr.right());
1496 if (isa<moore::TimeType>(lhs.getType()) ||
1497 isa<moore::TimeType>(rhs.getType())) {
1498 lhs =
context.materializeConversion(
1499 moore::RealType::get(
context.getContext(), moore::RealWidth::f64),
1501 rhs =
context.materializeConversion(
1502 moore::RealType::get(
context.getContext(), moore::RealWidth::f64),
1506 using slang::ast::BinaryOperator;
1508 case BinaryOperator::Add:
1509 return moore::AddRealOp::create(builder, loc, lhs, rhs);
1510 case BinaryOperator::Subtract:
1511 return moore::SubRealOp::create(builder, loc, lhs, rhs);
1512 case BinaryOperator::Multiply:
1513 return moore::MulRealOp::create(builder, loc, lhs, rhs);
1514 case BinaryOperator::Divide:
1515 return moore::DivRealOp::create(builder, loc, lhs, rhs);
1516 case BinaryOperator::Power:
1517 return moore::PowRealOp::create(builder, loc, lhs, rhs);
1519 case BinaryOperator::Equality:
1520 return moore::EqRealOp::create(builder, loc, lhs, rhs);
1521 case BinaryOperator::Inequality:
1522 return moore::NeRealOp::create(builder, loc, lhs, rhs);
1524 case BinaryOperator::GreaterThan:
1525 return moore::FgtOp::create(builder, loc, lhs, rhs);
1526 case BinaryOperator::LessThan:
1527 return moore::FltOp::create(builder, loc, lhs, rhs);
1528 case BinaryOperator::GreaterThanEqual:
1529 return moore::FgeOp::create(builder, loc, lhs, rhs);
1530 case BinaryOperator::LessThanEqual:
1531 return moore::FleOp::create(builder, loc, lhs, rhs);
1533 case BinaryOperator::LogicalAnd:
1534 case BinaryOperator::LogicalOr:
1535 case BinaryOperator::LogicalImplication:
1536 case BinaryOperator::LogicalEquivalence: {
1537 Domain domain = Domain::TwoValued;
1538 if (expr.left().type->isFourState() || expr.right().type->isFourState())
1539 domain = Domain::FourValued;
1540 return buildLogicalBOp(expr.op, lhs, rhs, domain);
1544 mlir::emitError(loc) <<
"Binary operator "
1545 << slang::ast::toString(expr.op)
1546 <<
" not supported with real valued operands!\n";
1553 template <
class ConcreteOp>
1554 Value createBinary(Value lhs, Value rhs) {
1555 lhs =
context.convertToSimpleBitVector(lhs);
1558 rhs =
context.convertToSimpleBitVector(rhs);
1561 return ConcreteOp::create(builder, loc, lhs, rhs);
1565 Value visit(
const slang::ast::BinaryExpression &expr) {
1566 if (expr.left().kind == slang::ast::ExpressionKind::TypeReference &&
1567 expr.right().kind == slang::ast::ExpressionKind::TypeReference) {
1569 expr.left().as<slang::ast::TypeReferenceExpression>().targetType;
1571 expr.right().as<slang::ast::TypeReferenceExpression>().targetType;
1572 bool value = lhsType.isMatching(rhsType);
1574 using slang::ast::BinaryOperator;
1576 case BinaryOperator::Equality:
1577 case BinaryOperator::CaseEquality:
1579 case BinaryOperator::Inequality:
1580 case BinaryOperator::CaseInequality:
1584 mlir::emitError(loc,
"unsupported type reference binary operator");
1588 auto type = moore::IntType::get(
context.getContext(), 1,
1589 moore::Domain::TwoValued);
1590 return moore::ConstantOp::create(builder, loc, type, value,
1595 const auto *rhsFloatType =
1596 expr.right().type->as_if<slang::ast::FloatingType>();
1597 const auto *lhsFloatType =
1598 expr.left().type->as_if<slang::ast::FloatingType>();
1601 if (rhsFloatType || lhsFloatType)
1602 return visitRealBOp(expr);
1605 const auto rhsIsClass = expr.right().type->isClass();
1606 const auto lhsIsClass = expr.left().type->isClass();
1607 const auto rhsIsChandle = expr.right().type->isCHandle();
1608 const auto lhsIsChandle = expr.left().type->isCHandle();
1610 if (rhsIsClass || lhsIsClass || rhsIsChandle || lhsIsChandle)
1611 return visitHandleBOp(expr);
1613 auto lhs =
context.convertRvalueExpression(expr.left());
1616 auto rhs =
context.convertRvalueExpression(expr.right());
1621 Domain domain = Domain::TwoValued;
1622 if (expr.type->isFourState() || expr.left().type->isFourState() ||
1623 expr.right().type->isFourState())
1624 domain = Domain::FourValued;
1626 using slang::ast::BinaryOperator;
1628 case BinaryOperator::Add:
1629 return createBinary<moore::AddOp>(lhs, rhs);
1630 case BinaryOperator::Subtract:
1631 return createBinary<moore::SubOp>(lhs, rhs);
1632 case BinaryOperator::Multiply:
1633 return createBinary<moore::MulOp>(lhs, rhs);
1634 case BinaryOperator::Divide:
1635 if (expr.type->isSigned())
1636 return createBinary<moore::DivSOp>(lhs, rhs);
1638 return createBinary<moore::DivUOp>(lhs, rhs);
1639 case BinaryOperator::Mod:
1640 if (expr.type->isSigned())
1641 return createBinary<moore::ModSOp>(lhs, rhs);
1643 return createBinary<moore::ModUOp>(lhs, rhs);
1644 case BinaryOperator::Power: {
1649 auto rhsCast =
context.materializeConversion(
1650 lhs.getType(), rhs, expr.right().type->isSigned(), rhs.getLoc());
1651 if (expr.type->isSigned())
1652 return createBinary<moore::PowSOp>(lhs, rhsCast);
1654 return createBinary<moore::PowUOp>(lhs, rhsCast);
1657 case BinaryOperator::BinaryAnd:
1658 return createBinary<moore::AndOp>(lhs, rhs);
1659 case BinaryOperator::BinaryOr:
1660 return createBinary<moore::OrOp>(lhs, rhs);
1661 case BinaryOperator::BinaryXor:
1662 return createBinary<moore::XorOp>(lhs, rhs);
1663 case BinaryOperator::BinaryXnor: {
1664 auto result = createBinary<moore::XorOp>(lhs, rhs);
1667 return moore::NotOp::create(builder, loc, result);
1670 case BinaryOperator::Equality:
1671 if (isa<moore::UnpackedArrayType>(lhs.getType()))
1672 return moore::UArrayCmpOp::create(
1673 builder, loc, moore::UArrayCmpPredicate::eq, lhs, rhs);
1674 else if (isa<moore::StringType>(lhs.getType()))
1675 return moore::StringCmpOp::create(
1676 builder, loc, moore::StringCmpPredicate::eq, lhs, rhs);
1677 else if (isa<moore::QueueType>(lhs.getType()))
1678 return moore::QueueCmpOp::create(
1679 builder, loc, moore::UArrayCmpPredicate::eq, lhs, rhs);
1681 return createBinary<moore::EqOp>(lhs, rhs);
1682 case BinaryOperator::Inequality:
1683 if (isa<moore::UnpackedArrayType>(lhs.getType()))
1684 return moore::UArrayCmpOp::create(
1685 builder, loc, moore::UArrayCmpPredicate::ne, lhs, rhs);
1686 else if (isa<moore::StringType>(lhs.getType()))
1687 return moore::StringCmpOp::create(
1688 builder, loc, moore::StringCmpPredicate::ne, lhs, rhs);
1689 else if (isa<moore::QueueType>(lhs.getType()))
1690 return moore::QueueCmpOp::create(
1691 builder, loc, moore::UArrayCmpPredicate::ne, lhs, rhs);
1693 return createBinary<moore::NeOp>(lhs, rhs);
1694 case BinaryOperator::CaseEquality:
1695 return createBinary<moore::CaseEqOp>(lhs, rhs);
1696 case BinaryOperator::CaseInequality:
1697 return createBinary<moore::CaseNeOp>(lhs, rhs);
1698 case BinaryOperator::WildcardEquality:
1699 return createBinary<moore::WildcardEqOp>(lhs, rhs);
1700 case BinaryOperator::WildcardInequality:
1701 return createBinary<moore::WildcardNeOp>(lhs, rhs);
1703 case BinaryOperator::GreaterThanEqual:
1704 if (expr.left().type->isSigned())
1705 return createBinary<moore::SgeOp>(lhs, rhs);
1706 else if (isa<moore::StringType>(lhs.getType()))
1707 return moore::StringCmpOp::create(
1708 builder, loc, moore::StringCmpPredicate::ge, lhs, rhs);
1710 return createBinary<moore::UgeOp>(lhs, rhs);
1711 case BinaryOperator::GreaterThan:
1712 if (expr.left().type->isSigned())
1713 return createBinary<moore::SgtOp>(lhs, rhs);
1714 else if (isa<moore::StringType>(lhs.getType()))
1715 return moore::StringCmpOp::create(
1716 builder, loc, moore::StringCmpPredicate::gt, lhs, rhs);
1718 return createBinary<moore::UgtOp>(lhs, rhs);
1719 case BinaryOperator::LessThanEqual:
1720 if (expr.left().type->isSigned())
1721 return createBinary<moore::SleOp>(lhs, rhs);
1722 else if (isa<moore::StringType>(lhs.getType()))
1723 return moore::StringCmpOp::create(
1724 builder, loc, moore::StringCmpPredicate::le, lhs, rhs);
1726 return createBinary<moore::UleOp>(lhs, rhs);
1727 case BinaryOperator::LessThan:
1728 if (expr.left().type->isSigned())
1729 return createBinary<moore::SltOp>(lhs, rhs);
1730 else if (isa<moore::StringType>(lhs.getType()))
1731 return moore::StringCmpOp::create(
1732 builder, loc, moore::StringCmpPredicate::lt, lhs, rhs);
1734 return createBinary<moore::UltOp>(lhs, rhs);
1736 case BinaryOperator::LogicalAnd:
1737 case BinaryOperator::LogicalOr:
1738 case BinaryOperator::LogicalImplication:
1739 case BinaryOperator::LogicalEquivalence:
1740 return buildLogicalBOp(expr.op, lhs, rhs, domain);
1742 case BinaryOperator::LogicalShiftLeft:
1743 return createBinary<moore::ShlOp>(lhs, rhs);
1744 case BinaryOperator::LogicalShiftRight:
1745 return createBinary<moore::ShrOp>(lhs, rhs);
1746 case BinaryOperator::ArithmeticShiftLeft:
1747 return createBinary<moore::ShlOp>(lhs, rhs);
1748 case BinaryOperator::ArithmeticShiftRight: {
1751 lhs =
context.convertToSimpleBitVector(lhs);
1752 rhs =
context.convertToSimpleBitVector(rhs);
1755 if (expr.type->isSigned())
1756 return moore::AShrOp::create(builder, loc, lhs, rhs);
1757 return moore::ShrOp::create(builder, loc, lhs, rhs);
1761 mlir::emitError(loc,
"unsupported binary operator");
1766 Value visit(
const slang::ast::UnbasedUnsizedIntegerLiteral &expr) {
1767 return context.materializeSVInt(expr.getValue(), *expr.type, loc);
1771 Value visit(
const slang::ast::IntegerLiteral &expr) {
1772 return context.materializeSVInt(expr.getValue(), *expr.type, loc);
1776 Value visit(
const slang::ast::TimeLiteral &expr) {
1781 double value = std::round(expr.getValue() * scale);
1791 static constexpr uint64_t limit =
1792 (std::numeric_limits<uint64_t>::max() >> 11) << 11;
1793 if (value > limit) {
1794 mlir::emitError(loc) <<
"time value is larger than " << limit <<
" fs";
1798 return moore::ConstantTimeOp::create(builder, loc,
1799 static_cast<uint64_t
>(value));
1803 Value visit(
const slang::ast::ReplicationExpression &expr) {
1804 auto type =
context.convertType(*expr.type);
1805 auto value =
context.convertRvalueExpression(expr.concat());
1808 return moore::ReplicateOp::create(builder, loc, type, value);
1812 Value visit(
const slang::ast::InsideExpression &expr) {
1813 auto lhs =
context.convertToSimpleBitVector(
1814 context.convertRvalueExpression(expr.left()));
1819 SmallVector<Value> conditions;
1822 for (
const auto *listExpr : expr.rangeList()) {
1823 auto cond =
context.convertInsideCheck(lhs, loc, *listExpr);
1827 conditions.push_back(cond);
1831 auto result = conditions.back();
1832 conditions.pop_back();
1833 while (!conditions.empty()) {
1834 result = moore::OrOp::create(builder, loc, conditions.back(), result);
1835 conditions.pop_back();
1841 Value visit(
const slang::ast::ConditionalExpression &expr) {
1842 auto type =
context.convertType(*expr.type);
1845 if (expr.conditions.size() > 1) {
1846 mlir::emitError(loc)
1847 <<
"unsupported conditional expression with more than one condition";
1850 const auto &cond = expr.conditions[0];
1852 mlir::emitError(loc) <<
"unsupported conditional expression with pattern";
1856 context.convertToBool(
context.convertRvalueExpression(*cond.expr));
1859 auto conditionalOp =
1860 moore::ConditionalOp::create(builder, loc, type, value);
1863 auto &trueBlock = conditionalOp.getTrueRegion().emplaceBlock();
1864 auto &falseBlock = conditionalOp.getFalseRegion().emplaceBlock();
1866 OpBuilder::InsertionGuard g(builder);
1869 builder.setInsertionPointToStart(&trueBlock);
1870 auto trueValue =
context.convertRvalueExpression(expr.left(), type);
1873 moore::YieldOp::create(builder, loc, trueValue);
1876 builder.setInsertionPointToStart(&falseBlock);
1877 auto falseValue =
context.convertRvalueExpression(expr.right(), type);
1880 moore::YieldOp::create(builder, loc, falseValue);
1882 return conditionalOp.getResult();
1886 Value visit(
const slang::ast::CallExpression &expr) {
1888 auto constant =
context.evaluateConstant(expr);
1889 if (
auto value =
context.materializeConstant(constant, *expr.type, loc))
1893 [&](
auto &subroutine) {
return visitCall(expr, subroutine); },
1899 std::pair<Value, moore::ClassHandleType>
1900 getMethodReceiverTypeHandle(
const slang::ast::CallExpression &expr) {
1902 moore::ClassHandleType handleTy;
1906 if (
const slang::ast::Expression *recvExpr = expr.thisClass()) {
1907 thisRef =
context.convertRvalueExpression(*recvExpr);
1912 thisRef =
context.getImplicitThisRef();
1914 mlir::emitError(loc) <<
"method '" << expr.getSubroutineName()
1915 <<
"' called without an object";
1919 handleTy = cast<moore::ClassHandleType>(thisRef.getType());
1920 return {thisRef, handleTy};
1924 mlir::CallOpInterface
1925 buildMethodCall(
const slang::ast::SubroutineSymbol *subroutine,
1927 moore::ClassHandleType actualHandleTy, Value actualThisRef,
1928 SmallVector<Value> &arguments,
1929 SmallVector<Type> &resultTypes) {
1932 auto funcTy = cast<FunctionType>(lowering->
op.getFunctionType());
1933 auto expected0 = funcTy.getInput(0);
1934 auto expectedHdlTy = cast<moore::ClassHandleType>(expected0);
1937 auto implicitThisRef =
context.materializeConversion(
1938 expectedHdlTy, actualThisRef,
false, actualThisRef.getLoc());
1941 SmallVector<Value> explicitArguments;
1942 explicitArguments.reserve(arguments.size() + 1);
1943 explicitArguments.push_back(implicitThisRef);
1944 explicitArguments.append(arguments.begin(), arguments.end());
1947 const bool isVirtual =
1948 (subroutine->flags & slang::ast::MethodFlags::Virtual) != 0;
1951 auto calleeSym = lowering->
op.getNameAttr().getValue();
1952 if (isa<moore::CoroutineOp>(lowering->
op.getOperation()))
1953 return moore::CallCoroutineOp::create(builder, loc, resultTypes,
1954 calleeSym, explicitArguments);
1955 return mlir::func::CallOp::create(builder, loc, resultTypes, calleeSym,
1959 auto funcName = subroutine->name;
1960 auto method = moore::VTableLoadMethodOp::create(
1961 builder, loc, funcTy, actualThisRef,
1962 SymbolRefAttr::get(
context.getContext(), funcName));
1963 return mlir::func::CallIndirectOp::create(builder, loc, method,
1968 Value visitCall(
const slang::ast::CallExpression &expr,
1969 const slang::ast::SubroutineSymbol *subroutine) {
1971 const bool isMethod = (subroutine->thisVar !=
nullptr);
1973 auto *lowering =
context.declareFunction(*subroutine);
1977 if (isa<moore::DPIFuncOp>(lowering->
op.getOperation())) {
1978 SmallVector<Value> operands;
1979 SmallVector<Value> resultTargets;
1981 for (
auto [callArg, declArg] :
1982 llvm::zip(expr.arguments(), subroutine->getArguments())) {
1983 auto *actual = callArg;
1984 if (
const auto *assign =
1985 actual->as_if<slang::ast::AssignmentExpression>())
1986 actual = &assign->left();
1988 auto argType =
context.convertType(declArg->getType());
1992 switch (declArg->direction) {
1993 case slang::ast::ArgumentDirection::In: {
1994 auto value =
context.convertRvalueExpression(*actual, argType);
1997 operands.push_back(value);
2000 case slang::ast::ArgumentDirection::Out: {
2001 auto lvalue =
context.convertLvalueExpression(*actual);
2004 resultTargets.push_back(lvalue);
2007 case slang::ast::ArgumentDirection::InOut:
2008 case slang::ast::ArgumentDirection::Ref: {
2009 auto lvalue =
context.convertLvalueExpression(*actual);
2012 auto value =
context.convertRvalueExpression(*actual, argType);
2015 operands.push_back(value);
2016 resultTargets.push_back(lvalue);
2022 SmallVector<Type> resultTypes(
2023 cast<FunctionType>(lowering->
op.getFunctionType()).getResults());
2024 auto callOp = moore::FuncDPICallOp::create(
2025 builder, loc, resultTypes,
2026 SymbolRefAttr::get(lowering->
op.getNameAttr()), operands);
2028 unsigned resultIndex = 0;
2029 unsigned targetIndex = 0;
2030 for (
const auto *declArg : subroutine->getArguments()) {
2031 auto argType =
context.convertType(declArg->getType());
2035 switch (declArg->direction) {
2036 case slang::ast::ArgumentDirection::Out:
2037 case slang::ast::ArgumentDirection::InOut:
2038 case slang::ast::ArgumentDirection::Ref: {
2039 auto lvalue = resultTargets[targetIndex++];
2040 auto refTy = dyn_cast<moore::RefType>(lvalue.getType());
2042 lowering->
op->emitError(
2043 "expected DPI output target to be moore::RefType");
2046 auto converted =
context.materializeConversion(
2047 refTy.getNestedType(), callOp->getResult(resultIndex++),
2048 declArg->getType().isSigned(), loc);
2051 moore::BlockingAssignOp::create(builder, loc, lvalue, converted);
2059 if (!subroutine->getReturnType().isVoid())
2060 return callOp->getResult(resultIndex);
2062 return mlir::UnrealizedConversionCastOp::create(
2063 builder, loc, moore::VoidType::get(
context.getContext()),
2071 SmallVector<Value> arguments;
2072 for (
auto [callArg, declArg] :
2073 llvm::zip(expr.arguments(), subroutine->getArguments())) {
2077 auto *expr = callArg;
2078 if (
const auto *assign = expr->as_if<slang::ast::AssignmentExpression>())
2079 expr = &assign->left();
2082 auto type =
context.convertType(declArg->getType());
2083 if (declArg->direction == slang::ast::ArgumentDirection::In) {
2084 value =
context.convertRvalueExpression(*expr, type);
2086 Value lvalue =
context.convertLvalueExpression(*expr);
2087 auto unpackedType = dyn_cast<moore::UnpackedType>(type);
2091 context.materializeConversion(moore::RefType::get(unpackedType),
2092 lvalue, expr->type->isSigned(), loc);
2096 arguments.push_back(value);
2103 for (
auto *sym : lowering->capturedSymbols) {
2104 Value val =
context.valueSymbols.lookup(sym);
2106 mlir::emitError(loc) <<
"failed to resolve captured variable `"
2107 << sym->name <<
"` at call site";
2110 arguments.push_back(val);
2114 SmallVector<Type> resultTypes(
2115 cast<FunctionType>(lowering->
op.getFunctionType()).getResults().begin(),
2116 cast<FunctionType>(lowering->
op.getFunctionType()).getResults().end());
2118 mlir::CallOpInterface callOp;
2122 auto [thisRef, tyHandle] = getMethodReceiverTypeHandle(expr);
2123 callOp = buildMethodCall(subroutine, lowering, tyHandle, thisRef,
2124 arguments, resultTypes);
2125 }
else if (isa<moore::CoroutineOp>(lowering->
op.getOperation())) {
2127 auto coroutine = cast<moore::CoroutineOp>(lowering->
op.getOperation());
2129 moore::CallCoroutineOp::create(builder, loc, coroutine, arguments);
2132 auto funcOp = cast<mlir::func::FuncOp>(lowering->
op.getOperation());
2133 callOp = mlir::func::CallOp::create(builder, loc, funcOp, arguments);
2136 auto result = resultTypes.size() > 0 ? callOp->getOpResult(0) : Value{};
2140 if (resultTypes.size() == 0)
2141 return mlir::UnrealizedConversionCastOp::create(
2142 builder, loc, moore::VoidType::get(
context.getContext()),
2150 Value visitCall(
const slang::ast::CallExpression &expr,
2151 const slang::ast::CallExpression::SystemCallInfo &info) {
2152 using ksn = slang::parsing::KnownSystemName;
2153 const auto &subroutine = *
info.subroutine;
2154 auto nameId = subroutine.knownNameId;
2165 return context.convertSampledValueCallExpression(expr, info, loc);
2170 auto args = expr.arguments();
2178 if (nameId == ksn::SFormatF) {
2180 auto fmtValue =
context.convertFormatString(
2181 expr.arguments(), loc, moore::IntFormat::Decimal,
false);
2182 if (failed(fmtValue))
2184 return fmtValue.value();
2188 auto result =
context.convertSystemCall(subroutine, loc, args);
2192 auto ty =
context.convertType(*expr.type);
2196 bool isSigned = expr.type->isSigned();
2197 if (nameId == ksn::CountOnes || nameId == ksn::IsUnknown ||
2198 nameId == ksn::OneHot || nameId == ksn::OneHot0)
2200 return context.materializeConversion(ty, result, isSigned, loc);
2204 Value visit(
const slang::ast::StringLiteral &expr) {
2205 auto type =
context.convertType(*expr.type);
2206 return moore::ConstantStringOp::create(builder, loc, type, expr.getValue());
2210 Value visit(
const slang::ast::RealLiteral &expr) {
2211 auto fTy = mlir::Float64Type::get(
context.getContext());
2212 auto attr = mlir::FloatAttr::get(fTy, expr.getValue());
2213 return moore::ConstantRealOp::create(builder, loc, attr).getResult();
2218 FailureOr<SmallVector<Value>>
2219 convertElements(
const slang::ast::AssignmentPatternExpressionBase &expr,
2220 std::variant<Type, ArrayRef<Type>> expectedTypes,
2221 unsigned replCount) {
2222 const auto &elts = expr.elements();
2223 const size_t elementCount = elts.size();
2226 const bool hasBroadcast =
2227 std::holds_alternative<Type>(expectedTypes) &&
2228 static_cast<bool>(std::get<Type>(expectedTypes));
2230 const bool hasPerElem =
2231 std::holds_alternative<ArrayRef<Type>>(expectedTypes) &&
2232 !std::get<ArrayRef<Type>>(expectedTypes).empty();
2236 auto types = std::get<ArrayRef<Type>>(expectedTypes);
2237 if (types.size() != elementCount) {
2238 mlir::emitError(loc)
2239 <<
"assignment pattern arity mismatch: expected " << types.size()
2240 <<
" elements, got " << elementCount;
2245 SmallVector<Value> converted;
2246 converted.reserve(elementCount * std::max(1u, replCount));
2249 if (!hasBroadcast && !hasPerElem) {
2251 for (
const auto *elementExpr : elts) {
2252 Value v =
context.convertRvalueExpression(*elementExpr);
2255 converted.push_back(v);
2257 }
else if (hasBroadcast) {
2259 Type want = std::get<Type>(expectedTypes);
2260 for (
const auto *elementExpr : elts) {
2261 Value v = want ?
context.convertRvalueExpression(*elementExpr, want)
2262 :
context.convertRvalueExpression(*elementExpr);
2265 converted.push_back(v);
2268 auto types = std::get<ArrayRef<Type>>(expectedTypes);
2269 for (
size_t i = 0; i < elementCount; ++i) {
2270 Type want = types[i];
2271 const auto *elementExpr = elts[i];
2272 Value v = want ?
context.convertRvalueExpression(*elementExpr, want)
2273 :
context.convertRvalueExpression(*elementExpr);
2276 converted.push_back(v);
2280 for (
unsigned i = 1; i < replCount; ++i)
2281 converted.append(converted.begin(), converted.begin() + elementCount);
2287 Value visitAssignmentPattern(
2288 const slang::ast::AssignmentPatternExpressionBase &expr,
2289 unsigned replCount = 1) {
2290 auto type =
context.convertType(*expr.type);
2291 const auto &elts = expr.elements();
2294 if (
auto intType = dyn_cast<moore::IntType>(type)) {
2295 auto elements = convertElements(expr, {}, replCount);
2297 if (failed(elements))
2300 assert(intType.getWidth() == elements->size());
2302 return moore::ConcatOp::create(builder, loc, intType, *elements);
2306 if (
auto structType = dyn_cast<moore::StructType>(type)) {
2307 SmallVector<Type> expectedTy;
2308 expectedTy.reserve(structType.getMembers().size());
2309 for (
auto member : structType.getMembers())
2310 expectedTy.push_back(member.type);
2312 FailureOr<SmallVector<Value>> elements;
2313 if (expectedTy.size() == elts.size())
2314 elements = convertElements(expr, expectedTy, replCount);
2316 elements = convertElements(expr, {}, replCount);
2318 if (failed(elements))
2321 assert(structType.getMembers().size() == elements->size());
2322 return moore::StructCreateOp::create(builder, loc, structType, *elements);
2326 if (
auto structType = dyn_cast<moore::UnpackedStructType>(type)) {
2327 SmallVector<Type> expectedTy;
2328 expectedTy.reserve(structType.getMembers().size());
2329 for (
auto member : structType.getMembers())
2330 expectedTy.push_back(member.type);
2332 FailureOr<SmallVector<Value>> elements;
2333 if (expectedTy.size() == elts.size())
2334 elements = convertElements(expr, expectedTy, replCount);
2336 elements = convertElements(expr, {}, replCount);
2338 if (failed(elements))
2341 assert(structType.getMembers().size() == elements->size());
2343 return moore::StructCreateOp::create(builder, loc, structType, *elements);
2347 if (
auto arrayType = dyn_cast<moore::ArrayType>(type)) {
2349 convertElements(expr, arrayType.getElementType(), replCount);
2351 if (failed(elements))
2354 assert(arrayType.getSize() == elements->size());
2356 return moore::ArrayCreateOp::create(builder, loc, arrayType, *elements);
2360 if (
auto arrayType = dyn_cast<moore::UnpackedArrayType>(type)) {
2362 convertElements(expr, arrayType.getElementType(), replCount);
2364 if (failed(elements))
2367 assert(arrayType.getSize() == elements->size());
2368 return moore::ArrayCreateOp::create(builder, loc, arrayType, *elements);
2372 if (
auto openType = dyn_cast<moore::OpenUnpackedArrayType>(type)) {
2374 convertElements(expr, openType.getElementType(), replCount);
2376 if (failed(elements))
2379 auto arrayType = moore::UnpackedArrayType::get(
2380 context.getContext(), elements->size(), openType.getElementType());
2381 return moore::ArrayCreateOp::create(builder, loc, arrayType, *elements);
2384 mlir::emitError(loc) <<
"unsupported assignment pattern with type " << type;
2388 Value visit(
const slang::ast::SimpleAssignmentPatternExpression &expr) {
2389 return visitAssignmentPattern(expr);
2392 Value visit(
const slang::ast::StructuredAssignmentPatternExpression &expr) {
2393 return visitAssignmentPattern(expr);
2396 Value visit(
const slang::ast::ReplicatedAssignmentPatternExpression &expr) {
2398 context.evaluateConstant(expr.count()).integer().as<
unsigned>();
2399 assert(count &&
"Slang guarantees constant non-zero replication count");
2400 return visitAssignmentPattern(expr, *count);
2403 Value visit(
const slang::ast::StreamingConcatenationExpression &expr) {
2404 SmallVector<Value> operands;
2405 for (
auto stream : expr.streams()) {
2406 auto operandLoc =
context.convertLocation(stream.operand->sourceRange);
2407 if (!stream.constantWithWidth.has_value() && stream.withExpr) {
2408 mlir::emitError(operandLoc)
2409 <<
"Moore only support streaming "
2410 "concatenation with fixed size 'with expression'";
2414 if (stream.constantWithWidth.has_value()) {
2415 value =
context.convertRvalueExpression(*stream.withExpr);
2416 auto type = cast<moore::UnpackedType>(value.getType());
2417 auto intType = moore::IntType::get(
2418 context.getContext(), type.getBitSize().value(), type.getDomain());
2420 value =
context.materializeConversion(intType, value,
false, loc);
2422 value =
context.convertRvalueExpression(*stream.operand);
2425 value =
context.convertToSimpleBitVector(value);
2428 operands.push_back(value);
2432 if (operands.size() == 1) {
2435 value = operands.front();
2437 value = moore::ConcatOp::create(builder, loc, operands).getResult();
2440 if (expr.getSliceSize() == 0) {
2444 auto type = cast<moore::IntType>(value.getType());
2445 SmallVector<Value> slicedOperands;
2446 auto iterMax = type.getWidth() / expr.getSliceSize();
2447 auto remainSize = type.getWidth() % expr.getSliceSize();
2449 for (
size_t i = 0; i < iterMax; i++) {
2450 auto extractResultType = moore::IntType::get(
2451 context.getContext(), expr.getSliceSize(), type.getDomain());
2453 auto extracted = moore::ExtractOp::create(builder, loc, extractResultType,
2454 value, i * expr.getSliceSize());
2455 slicedOperands.push_back(extracted);
2459 auto extractResultType = moore::IntType::get(
2460 context.getContext(), remainSize, type.getDomain());
2463 moore::ExtractOp::create(builder, loc, extractResultType, value,
2464 iterMax * expr.getSliceSize());
2465 slicedOperands.push_back(extracted);
2468 return moore::ConcatOp::create(builder, loc, slicedOperands);
2471 Value visit(
const slang::ast::AssertionInstanceExpression &expr) {
2472 return context.convertAssertionExpression(expr.body, loc);
2475 Value visit(
const slang::ast::UnboundedLiteral &expr) {
2477 "slang checks $ only used within queue index expression");
2481 moore::QueueSizeBIOp::create(builder, loc,
context.getIndexedQueue());
2482 auto one = moore::ConstantOp::create(builder, loc, queueSize.getType(), 1);
2483 auto lastElement = moore::SubOp::create(builder, loc, queueSize, one);
2500 Value visit(
const slang::ast::NewClassExpression &expr) {
2501 auto type =
context.convertType(*expr.type);
2502 auto classTy = dyn_cast<moore::ClassHandleType>(type);
2508 if (!classTy && expr.isSuperClass) {
2509 newObj =
context.getImplicitThisRef();
2510 if (!newObj || !newObj.getType() ||
2511 !isa<moore::ClassHandleType>(newObj.getType())) {
2512 mlir::emitError(loc) <<
"implicit this ref was not set while "
2513 "converting new class function";
2516 auto thisType = cast<moore::ClassHandleType>(newObj.getType());
2518 cast<moore::ClassDeclOp>(*
context.symbolTable.lookupNearestSymbolFrom(
2519 context.intoModuleOp, thisType.getClassSym()));
2520 auto baseClassSym = classDecl.getBase();
2521 classTy = circt::moore::ClassHandleType::get(
context.getContext(),
2522 baseClassSym.value());
2525 newObj = moore::ClassNewOp::create(builder, loc, classTy, {});
2528 const auto *constructor = expr.constructorCall();
2533 if (
const auto *callConstructor =
2534 constructor->as_if<slang::ast::CallExpression>())
2535 if (
const auto *subroutine =
2536 std::get_if<const slang::ast::SubroutineSymbol *>(
2537 &callConstructor->subroutine)) {
2538 if (!(*subroutine)->thisVar) {
2539 mlir::emitError(loc)
2540 <<
"unsupported constructor call without `this` argument";
2544 llvm::SaveAndRestore saveThis(
context.currentThisRef, newObj);
2545 if (!visitCall(*callConstructor, *subroutine))
2553 template <
typename T>
2554 Value visit(T &&node) {
2555 mlir::emitError(loc,
"unsupported expression: ")
2556 << slang::ast::toString(node.kind);
2560 Value visitInvalid(
const slang::ast::Expression &expr) {
2561 mlir::emitError(loc,
"invalid expression");
2572struct LvalueExprVisitor :
public ExprVisitor {
2574 : ExprVisitor(
context, loc, true) {}
2575 using ExprVisitor::visit;
2578 Value visit(
const slang::ast::NamedValueExpression &expr) {
2580 if (
auto value =
context.valueSymbols.lookup(&expr.symbol))
2584 if (
auto globalOp =
context.globalVariables.lookup(&expr.symbol))
2585 return moore::GetGlobalVariableOp::create(builder, loc, globalOp);
2587 if (
auto *
const property =
2588 expr.symbol.as_if<slang::ast::ClassPropertySymbol>()) {
2592 if (
auto access =
context.virtualIfaceMembers.lookup(&expr.symbol);
2594 auto type =
context.convertType(*expr.type);
2597 auto memberType = dyn_cast<moore::UnpackedType>(type);
2599 mlir::emitError(loc)
2600 <<
"unsupported virtual interface member type: " << type;
2604 Value base = materializeSymbolRvalue(*access.base);
2606 auto d = mlir::emitError(loc,
"unknown name `")
2607 << access.base->name <<
"`";
2608 d.attachNote(
context.convertLocation(access.base->location))
2609 <<
"no rvalue generated for virtual interface base";
2613 auto fieldName = access.fieldName
2615 : builder.getStringAttr(expr.symbol.name);
2616 auto memberRefType = moore::RefType::get(memberType);
2617 return moore::StructExtractOp::create(builder, loc, memberRefType,
2621 auto d = mlir::emitError(loc,
"unknown name `") << expr.symbol.name <<
"`";
2622 d.attachNote(
context.convertLocation(expr.symbol.location))
2623 <<
"no lvalue generated for " << slang::ast::toString(expr.symbol.kind);
2628 Value visit(
const slang::ast::HierarchicalValueExpression &expr) {
2631 if (!expr.ref.path.empty()) {
2632 if (
auto *inst = expr.ref.path.front()
2633 .symbol->as_if<slang::ast::InstanceSymbol>()) {
2635 expr.symbol.getParentScope()->getContainingInstance();
2636 if (&inst->body == symbolBody ||
2637 (symbolBody && inst->body.getDeclaringDefinition() ==
2638 symbolBody->getDeclaringDefinition())) {
2639 if (
auto value =
context.valueSymbols.lookup(&expr.symbol))
2646 if (
auto value =
context.resolveCapturedValue(expr.symbol))
2652 if (
auto key =
context.buildHierValueKey(expr)) {
2653 if (
auto it =
context.hierValueSymbols.find(*key);
2654 it !=
context.hierValueSymbols.end())
2659 if (
auto value =
context.valueSymbols.lookup(&expr.symbol))
2666 if (
auto globalOp =
context.globalVariables.lookup(&expr.symbol))
2667 return moore::GetGlobalVariableOp::create(builder, loc, globalOp);
2671 auto d = mlir::emitError(loc,
"unknown hierarchical name `")
2672 << expr.symbol.name <<
"`";
2673 d.attachNote(
context.convertLocation(expr.symbol.location))
2674 <<
"no lvalue generated for " << slang::ast::toString(expr.symbol.kind);
2678 Value visit(
const slang::ast::StreamingConcatenationExpression &expr) {
2679 SmallVector<Value> operands;
2680 for (
auto stream : expr.streams()) {
2681 auto operandLoc =
context.convertLocation(stream.operand->sourceRange);
2682 if (!stream.constantWithWidth.has_value() && stream.withExpr) {
2683 mlir::emitError(operandLoc)
2684 <<
"Moore only support streaming "
2685 "concatenation with fixed size 'with expression'";
2689 if (stream.constantWithWidth.has_value()) {
2690 value =
context.convertLvalueExpression(*stream.withExpr);
2691 auto type = cast<moore::UnpackedType>(
2692 cast<moore::RefType>(value.getType()).getNestedType());
2693 auto intType = moore::RefType::get(moore::IntType::get(
2694 context.getContext(), type.getBitSize().value(), type.getDomain()));
2696 value =
context.materializeConversion(intType, value,
false, loc);
2698 value =
context.convertLvalueExpression(*stream.operand);
2703 operands.push_back(value);
2706 if (operands.size() == 1) {
2709 value = operands.front();
2711 value = moore::ConcatRefOp::create(builder, loc, operands).getResult();
2714 if (expr.getSliceSize() == 0) {
2718 auto type = cast<moore::IntType>(
2719 cast<moore::RefType>(value.getType()).getNestedType());
2720 SmallVector<Value> slicedOperands;
2721 auto widthSum = type.getWidth();
2722 auto domain = type.getDomain();
2723 auto iterMax = widthSum / expr.getSliceSize();
2724 auto remainSize = widthSum % expr.getSliceSize();
2726 for (
size_t i = 0; i < iterMax; i++) {
2727 auto extractResultType = moore::RefType::get(moore::IntType::get(
2728 context.getContext(), expr.getSliceSize(), domain));
2730 auto extracted = moore::ExtractRefOp::create(
2731 builder, loc, extractResultType, value, i * expr.getSliceSize());
2732 slicedOperands.push_back(extracted);
2736 auto extractResultType = moore::RefType::get(
2737 moore::IntType::get(
context.getContext(), remainSize, domain));
2740 moore::ExtractRefOp::create(builder, loc, extractResultType, value,
2741 iterMax * expr.getSliceSize());
2742 slicedOperands.push_back(extracted);
2745 return moore::ConcatRefOp::create(builder, loc, slicedOperands);
2749 template <
typename T>
2750 Value visit(T &&node) {
2751 return context.convertRvalueExpression(node);
2754 Value visitInvalid(
const slang::ast::Expression &expr) {
2755 mlir::emitError(loc,
"invalid expression");
2765Value Context::resolveCapturedValue(
const slang::ast::ValueSymbol &sym) {
2773std::optional<std::pair<const slang::ast::InstanceSymbol *, mlir::StringAttr>>
2775 const slang::ast::HierarchicalValueExpression &expr) {
2776 if (expr.ref.path.empty())
2777 return std::nullopt;
2779 const slang::ast::InstanceSymbol *firstInst =
nullptr;
2780 SmallVector<StringRef, 4> names;
2781 for (
auto &elem : expr.ref.path) {
2782 if (
auto *inst = elem.symbol->as_if<slang::ast::InstanceSymbol>()) {
2786 names.push_back(inst->name);
2790 names.push_back(expr.symbol.name);
2791 std::string hierName = llvm::join(names,
".");
2794 return std::nullopt;
2795 return std::make_pair(firstInst,
builder.getStringAttr(hierName));
2803 Type requiredType) {
2805 auto value = expr.visit(RvalueExprVisitor(*
this, loc));
2806 if (value && requiredType)
2814 return expr.visit(LvalueExprVisitor(*
this, loc));
2822 if (
auto type = dyn_cast_or_null<moore::IntType>(value.getType()))
2823 if (type.getBitSize() == 1)
2825 if (
auto type = dyn_cast_or_null<moore::UnpackedType>(value.getType()))
2826 return moore::BoolCastOp::create(
builder, value.getLoc(), value);
2827 mlir::emitError(value.getLoc(),
"expression of type ")
2828 << value.getType() <<
" cannot be cast to a boolean";
2834 const slang::ast::Type &astType,
2836 const auto *floatType = astType.as_if<slang::ast::FloatingType>();
2840 if (svreal.isShortReal() &&
2841 floatType->floatKind == slang::ast::FloatingType::ShortReal) {
2842 attr = FloatAttr::get(
builder.getF32Type(), svreal.shortReal().v);
2843 }
else if (svreal.isReal() &&
2844 floatType->floatKind == slang::ast::FloatingType::Real) {
2845 attr = FloatAttr::get(
builder.getF64Type(), svreal.real().v);
2847 mlir::emitError(loc) <<
"invalid real constant";
2851 return moore::ConstantRealOp::create(
builder, loc, attr);
2856 const slang::ast::Type &astType,
2858 if (!astType.isString())
2860 const std::string &str = stringLiteral.str();
2861 auto intTy = moore::IntType::getInt(
getContext(),
2862 static_cast<unsigned>(str.size() * 8));
2864 moore::ConstantStringOp::create(
builder, loc, intTy, str).getResult();
2865 return moore::IntToStringOp::create(
builder, loc, immInt).getResult();
2870 const slang::ast::Type &astType, Location loc) {
2875 bool typeIsFourValued =
false;
2876 if (
auto unpackedType = dyn_cast<moore::UnpackedType>(type))
2880 auto intType = moore::IntType::get(
getContext(), fvint.getBitWidth(),
2881 fvint.hasUnknown() || typeIsFourValued
2884 auto result = moore::ConstantOp::create(
builder, loc, intType, fvint);
2889 const slang::ConstantValue &constant,
2890 const slang::ast::FixedSizeUnpackedArrayType &astType, Location loc) {
2897 if (astType.elementType.isString()) {
2898 auto arrayType = dyn_cast<moore::UnpackedArrayType>(type);
2902 SmallVector<Value> elemVals;
2903 for (
const auto &elem : constant.elements()) {
2904 if (!elem.isString())
2909 elemVals.push_back(value);
2911 if (elemVals.size() != arrayType.getSize())
2913 return moore::ArrayCreateOp::create(
builder, loc, arrayType, elemVals);
2918 if (astType.elementType.isIntegral())
2919 bitWidth = astType.elementType.getBitWidth();
2923 bool typeIsFourValued =
false;
2926 if (
auto unpackedType = dyn_cast<moore::UnpackedType>(type))
2937 auto intType = moore::IntType::get(
getContext(), bitWidth, domain);
2939 auto arrType = moore::UnpackedArrayType::get(
2940 getContext(), constant.elements().size(), intType);
2942 llvm::SmallVector<mlir::Value> elemVals;
2943 moore::ConstantOp constOp;
2945 mlir::OpBuilder::InsertionGuard guard(
builder);
2948 for (
auto elem : constant.elements()) {
2950 constOp = moore::ConstantOp::create(
builder, loc, intType, fvInt);
2951 elemVals.push_back(constOp.getResult());
2956 auto arrayOp = moore::ArrayCreateOp::create(
builder, loc, arrType, elemVals);
2958 return arrayOp.getResult();
2962 const slang::ast::Type &type, Location loc) {
2964 if (
auto *arr = type.as_if<slang::ast::FixedSizeUnpackedArrayType>())
2966 if (constant.isInteger())
2968 if (constant.isReal() || constant.isShortReal())
2970 if (constant.isString())
2978 using slang::ast::EvalFlags;
2979 slang::ast::EvalContext evalContext(
2981 slang::ast::LookupLocation::max),
2982 EvalFlags::CacheResults | EvalFlags::SpecparamsAllowed);
2983 return expr.eval(evalContext);
2992 auto type = moore::IntType::get(
getContext(), 1, domain);
2999 if (isa<moore::IntType>(value.getType()))
3006 if (
auto packed = dyn_cast<moore::PackedType>(value.getType()))
3007 if (
auto sbvType = packed.getSimpleBitVector())
3010 mlir::emitError(value.getLoc()) <<
"expression of type " << value.getType()
3011 <<
" cannot be cast to a simple bit vector";
3017 if (isa<moore::IntType>(value.getType()))
3020 auto packedType = cast<moore::PackedType>(value.getType());
3021 auto intType = packedType.getSimpleBitVector();
3026 if (isa<moore::TimeType>(packedType) &&
3028 value =
builder.createOrFold<moore::TimeToLogicOp>(loc, value);
3029 auto scale = moore::ConstantOp::create(
builder, loc, intType,
3031 return builder.createOrFold<moore::DivUOp>(loc, value, scale);
3037 if (packedType.containsTimeType()) {
3039 mlir::emitError(loc) <<
"unsupported conversion: " << packedType
3040 <<
" cannot be converted to " << intType
3041 <<
"; contains a time type";
3046 return builder.createOrFold<moore::PackedToSBVOp>(loc, value);
3054 Value value, Location loc,
3056 if (value.getType() == packedType)
3059 auto &builder =
context.builder;
3060 auto intType = cast<moore::IntType>(value.getType());
3065 if (isa<moore::TimeType>(packedType) &&
3067 auto scale = moore::ConstantOp::create(builder, loc, intType,
3069 value = builder.createOrFold<moore::MulOp>(loc, value, scale);
3070 return builder.createOrFold<moore::LogicToTimeOp>(loc, value);
3078 mlir::emitError(loc) <<
"unsupported conversion: " << intType
3079 <<
" cannot be converted to " << packedType
3080 <<
"; contains a time type";
3085 return builder.createOrFold<moore::SBVToPackedOp>(loc, packedType, value);
3091 moore::ClassHandleType expectedHandleTy) {
3092 auto loc = actualHandle.getLoc();
3094 auto actualTy = actualHandle.getType();
3095 auto actualHandleTy = dyn_cast<moore::ClassHandleType>(actualTy);
3096 if (!actualHandleTy) {
3097 mlir::emitError(loc) <<
"expected a !moore.class<...> value, got "
3103 if (actualHandleTy == expectedHandleTy)
3104 return actualHandle;
3106 if (!
context.isClassDerivedFrom(actualHandleTy, expectedHandleTy)) {
3107 mlir::emitError(loc)
3108 <<
"receiver class " << actualHandleTy.getClassSym()
3109 <<
" is not the same as, or derived from, expected base class "
3110 << expectedHandleTy.getClassSym().getRootReference();
3115 auto casted = moore::ClassUpcastOp::create(
context.builder, loc,
3116 expectedHandleTy, actualHandle)
3122 Location loc,
bool fallible) {
3124 if (type == value.getType())
3129 if (isa<moore::NullType>(value.getType())) {
3130 if (isa<moore::ChandleType>(type))
3131 return moore::NullChandleOp::create(
builder, loc);
3132 if (
auto classType = dyn_cast<moore::ClassHandleType>(type))
3133 return moore::NullClassOp::create(
builder, loc, classType);
3134 if (type == moore::IntType::getInt(value.getContext(), 1))
3135 return moore::ConstantOp::create(
builder, loc, cast<moore::IntType>(type),
3141 auto dstPacked = dyn_cast<moore::PackedType>(type);
3142 auto srcPacked = dyn_cast<moore::PackedType>(value.getType());
3143 auto dstInt = dstPacked ? dstPacked.getSimpleBitVector() : moore::IntType();
3144 auto srcInt = srcPacked ? srcPacked.getSimpleBitVector() : moore::IntType();
3146 if (dstInt && srcInt) {
3154 auto resizedType = moore::IntType::get(
3155 value.getContext(), dstInt.getWidth(), srcPacked.getDomain());
3156 if (dstInt.getWidth() < srcInt.getWidth()) {
3157 value =
builder.createOrFold<moore::TruncOp>(loc, resizedType, value);
3158 }
else if (dstInt.getWidth() > srcInt.getWidth()) {
3160 value =
builder.createOrFold<moore::SExtOp>(loc, resizedType, value);
3162 value =
builder.createOrFold<moore::ZExtOp>(loc, resizedType, value);
3166 if (dstInt.getDomain() != srcInt.getDomain()) {
3168 value =
builder.createOrFold<moore::LogicToIntOp>(loc, value);
3170 value =
builder.createOrFold<moore::IntToLogicOp>(loc, value);
3179 assert(value.getType() == type);
3184 if (isa<moore::StringType>(type) &&
3185 isa<moore::FormatStringType>(value.getType())) {
3186 return builder.createOrFold<moore::FormatStringToStringOp>(loc, value);
3190 if (isa<moore::FormatStringType>(type) &&
3191 isa<moore::StringType>(value.getType())) {
3192 return builder.createOrFold<moore::FormatStringOp>(loc, value);
3197 if (isa<moore::QueueType>(type) && isa<moore::QueueType>(value.getType()) &&
3198 cast<moore::QueueType>(type).getElementType() ==
3199 cast<moore::QueueType>(value.getType()).getElementType())
3200 return builder.createOrFold<moore::QueueResizeOp>(loc, type, value);
3203 if (isa<moore::QueueType>(type) &&
3204 isa<moore::UnpackedArrayType>(value.getType())) {
3205 auto queueElType = dyn_cast<moore::QueueType>(type).getElementType();
3206 auto unpackedArrayElType =
3207 dyn_cast<moore::UnpackedArrayType>(value.getType()).getElementType();
3209 if (queueElType == unpackedArrayElType) {
3210 return builder.createOrFold<moore::QueueFromUnpackedArrayOp>(loc, type,
3215 auto srcUArray = dyn_cast<moore::UnpackedArrayType>(value.getType());
3216 auto dstOpenUArray = dyn_cast<moore::OpenUnpackedArrayType>(type);
3217 if (srcUArray && dstOpenUArray) {
3218 auto openUnpackedArrayElType = dstOpenUArray.getElementType();
3219 auto unpackedArrayElType = srcUArray.getElementType();
3221 if (openUnpackedArrayElType == unpackedArrayElType)
3222 return builder.createOrFold<moore::OpenUArrayFromUnpackedArrayOp>(
3226 if (dstInt && isa<moore::RealType>(value.getType())) {
3227 auto twoValInt =
builder.createOrFold<moore::RealToIntOp>(
3228 loc, dstInt.getTwoValued(), value);
3233 if (isa<moore::RealType>(type) && isa<moore::IntType>(value.getType())) {
3236 if (dyn_cast<moore::IntType>(value.getType()).getDomain() ==
3241 dyn_cast<moore::IntType>(value.getType()).getTwoValued(), value,
true,
3245 return builder.createOrFold<moore::SIntToRealOp>(loc, type, twoValInt);
3246 return builder.createOrFold<moore::UIntToRealOp>(loc, type, twoValInt);
3249 auto getBuiltinFloatType = [&](moore::RealType type) -> Type {
3251 return mlir::Float32Type::get(
builder.getContext());
3253 return mlir::Float64Type::get(
builder.getContext());
3257 if (isa<moore::TimeType>(type) && isa<moore::RealType>(value.getType())) {
3259 moore::IntType::get(
builder.getContext(), 64, Domain::TwoValued);
3261 getBuiltinFloatType(cast<moore::RealType>(value.getType()));
3262 auto scale = moore::ConstantRealOp::create(
3263 builder, loc, value.getType(),
3265 auto scaled =
builder.createOrFold<moore::MulRealOp>(loc, value, scale);
3266 auto asInt = moore::RealToIntOp::create(
builder, loc, intType, scaled);
3267 auto asLogic = moore::IntToLogicOp::create(
builder, loc, asInt);
3268 return moore::LogicToTimeOp::create(
builder, loc, asLogic);
3272 if (isa<moore::RealType>(type) && isa<moore::TimeType>(value.getType())) {
3273 auto asLogic = moore::TimeToLogicOp::create(
builder, loc, value);
3274 auto asInt = moore::LogicToIntOp::create(
builder, loc, asLogic);
3275 auto asReal = moore::UIntToRealOp::create(
builder, loc, type, asInt);
3276 Type floatType = getBuiltinFloatType(cast<moore::RealType>(type));
3277 auto scale = moore::ConstantRealOp::create(
3280 return moore::DivRealOp::create(
builder, loc, asReal, scale);
3284 if (isa<moore::StringType>(type)) {
3285 if (
auto intType = dyn_cast<moore::IntType>(value.getType())) {
3287 value = moore::LogicToIntOp::create(
builder, loc, value);
3288 return moore::IntToStringOp::create(
builder, loc, value);
3293 if (
auto intType = dyn_cast<moore::IntType>(type)) {
3294 if (isa<moore::StringType>(value.getType())) {
3295 value = moore::StringToIntOp::create(
builder, loc, intType.getTwoValued(),
3299 return moore::IntToLogicOp::create(
builder, loc, value);
3306 if (isa<moore::FormatStringType>(type)) {
3308 value, isSigned, loc);
3311 return moore::FormatStringOp::create(
builder, loc, asStr, {}, {}, {});
3314 if (isa<moore::RealType>(type) && isa<moore::RealType>(value.getType()))
3315 return builder.createOrFold<moore::ConvertRealOp>(loc, type, value);
3317 if (isa<moore::ClassHandleType>(type) &&
3318 isa<moore::ClassHandleType>(value.getType()))
3322 mlir::emitError(loc) <<
"unsupported conversion from " << value.getType()
3329template <
typename OpTy>
3332 std::span<const slang::ast::Expression *const> args) {
3334 assert(args.size() == 1 &&
"real math builtin expects 1 argument");
3335 auto value =
context.convertRvalueExpression(*args[0]);
3338 return OpTy::create(
context.builder, loc, value);
3343template <
typename OpTy>
3346 std::span<const slang::ast::Expression *const> args) {
3348 assert(args.size() == 2 &&
"real math builtin expects 2 arguments");
3351 auto lhs =
context.convertRvalueExpression(*args[0], realType);
3352 auto rhs =
context.convertRvalueExpression(*args[1], realType);
3355 return OpTy::create(
context.builder, loc, lhs, rhs);
3361 auto &builder =
context.builder;
3362 auto newBlockAfter = [&](Block *after) -> Block * {
3363 auto block = std::make_unique<Block>();
3364 block->insertAfter(after);
3365 return block.release();
3368 for (
auto [destExpr, value, matched] : result.assignments) {
3369 auto lhs =
context.convertLvalueExpression(*destExpr);
3372 auto cond = moore::ToBuiltinIntOp::create(builder, loc, matched);
3374 auto *assignBlock = newBlockAfter(builder.getInsertionBlock());
3375 auto *continuedBlock = newBlockAfter(assignBlock);
3376 mlir::cf::CondBranchOp::create(builder, loc, cond, assignBlock,
3379 builder.setInsertionPointToEnd(assignBlock);
3380 moore::BlockingAssignOp::create(builder, loc, lhs, value);
3381 mlir::cf::BranchOp::create(builder, loc, continuedBlock);
3383 builder.setInsertionPointToEnd(continuedBlock);
3413 slang::parsing::KnownSystemName method,
3415 using ksn = slang::parsing::KnownSystemName;
3416 const auto &enumType = type.getCanonicalType().as<slang::ast::EnumType>();
3420 bool isName = method == ksn::Name;
3424 auto valueType = dyn_cast_or_null<moore::PackedType>(
convertType(enumType));
3427 auto posType = moore::IntType::getInt(
getContext(), 32);
3429 isName ? Type(moore::StringType::get(
getContext())) : Type(valueType);
3433 OpBuilder::InsertionGuard guard(
builder);
3439 builder.setInsertionPoint(it->second);
3444 StringRef typeName = type.name;
3445 auto helperName = StringAttr::get(
3446 getContext(), Twine(
"enum.") + slang::parsing::toString(method) +
"." +
3447 (typeName.empty() ?
"anon" : typeName));
3449 SmallVector<Type> argTypes{valueType};
3451 argTypes.push_back(posType);
3453 mlir::func::FuncOp::create(
builder, helperLoc, helperName,
3454 builder.getFunctionType(argTypes, resultType));
3455 SymbolTable::setSymbolVisibility(funcOp, SymbolTable::Visibility::Private);
3463 auto &bodyRegion = funcOp.getBody();
3464 auto *entryBlock = funcOp.addEntryBlock();
3465 auto value = entryBlock->getArgument(0);
3466 builder.setInsertionPointToEnd(entryBlock);
3467 SmallVector<Value> enumerandValues;
3468 for (
const auto &enumerand : enumType.values()) {
3473 enumerandValues.push_back(constant);
3481 auto tableType = moore::ArrayType::get(enumerandValues.size(), valueType);
3482 table = moore::ArrayCreateOp::create(
3483 builder, helperLoc, tableType,
3484 SmallVector<Value>(llvm::reverse(enumerandValues)));
3491 auto *matchBlock = &bodyRegion.emplaceBlock();
3492 matchBlock->addArgument(isName ? resultType : Type(posType), helperLoc);
3496 for (
auto [position, enumerand] : llvm::enumerate(enumType.values())) {
3498 auto matches = moore::CaseEqOp::create(
builder, enumerandLoc, value,
3499 enumerandValues[position]);
3501 moore::ToBuiltinIntOp::create(
builder, enumerandLoc, matches);
3506 moore::IntType::getInt(
getContext(), enumerand.name.size() * 8);
3507 auto bytes = moore::ConstantStringOp::create(
builder, enumerandLoc,
3508 intType, enumerand.name);
3509 matchResult = moore::IntToStringOp::create(
builder, enumerandLoc, bytes);
3511 matchResult = moore::ConstantOp::create(
builder, enumerandLoc, posType,
3512 static_cast<int64_t
>(position));
3515 auto *mismatchBlock = &bodyRegion.emplaceBlock();
3516 mlir::cf::CondBranchOp::create(
builder, enumerandLoc, condition, matchBlock,
3517 ValueRange{matchResult}, mismatchBlock,
3519 builder.setInsertionPointToEnd(mismatchBlock);
3527 auto intType = moore::IntType::getInt(
getContext(), 0);
3529 moore::ConstantStringOp::create(
builder, helperLoc, intType,
"");
3530 Value
empty = moore::IntToStringOp::create(
builder, helperLoc, bytes);
3531 mlir::cf::BranchOp::create(
builder, helperLoc, matchBlock,
empty);
3537 mlir::func::ReturnOp::create(
builder, helperLoc, fallback);
3540 builder.setInsertionPointToEnd(matchBlock);
3541 Value result = matchBlock->getArgument(0);
3548 moore::ConstantOp::create(
builder, helperLoc, posType,
3549 static_cast<int64_t
>(enumerandValues.size()));
3550 Value step = moore::ModUOp::create(
builder, helperLoc,
3551 funcOp.getArgument(1), numValues);
3552 if (method == ksn::Prev)
3553 step = moore::SubOp::create(
builder, helperLoc, numValues, step);
3554 Value offset = moore::AddOp::create(
builder, helperLoc, result, step);
3556 moore::ModUOp::create(
builder, helperLoc, offset, numValues);
3557 result = moore::DynExtractOp::create(
builder, helperLoc, valueType, table,
3560 mlir::func::ReturnOp::create(
builder, helperLoc, result);
3564 matchBlock->moveBefore(&bodyRegion, bodyRegion.end());
3569 const slang::ast::SystemSubroutine &subroutine, Location loc,
3570 std::span<const slang::ast::Expression *const> args) {
3571 using ksn = slang::parsing::KnownSystemName;
3572 StringRef name = subroutine.name;
3573 auto nameId = subroutine.knownNameId;
3574 size_t numArgs = args.size();
3582 if (nameId == ksn::URandom || nameId == ksn::Random) {
3583 auto i32Ty = moore::IntType::getInt(
builder.getContext(), 32);
3584 auto minval = moore::ConstantOp::create(
builder, loc, i32Ty, 0);
3586 moore::ConstantOp::create(
builder, loc, i32Ty, APInt::getAllOnes(32));
3593 return moore::UrandomRangeBIOp::create(
builder, loc, minval, maxval, seed);
3596 if (nameId == ksn::URandomRange) {
3597 auto i32Ty = moore::IntType::getInt(
builder.getContext(), 32);
3607 minval = moore::ConstantOp::create(
builder, loc, i32Ty, 0);
3609 return moore::UrandomRangeBIOp::create(
builder, loc, minval, maxval,
3617 if (nameId == ksn::Time || nameId == ksn::STime || nameId == ksn::RealTime) {
3619 assert(numArgs == 0 &&
"time functions take no arguments");
3620 return moore::TimeBIOp::create(
builder, loc);
3627 if (nameId == ksn::Clog2) {
3629 assert(numArgs == 1 &&
"`$clog2` takes 1 argument");
3636 return moore::Clog2BIOp::create(
builder, loc, value);
3643 if (nameId == ksn::IsUnknown) {
3644 assert(numArgs == 1 &&
"`$isunknown` takes 1 argument");
3649 if (!isa<moore::IntType>(value.getType())) {
3650 if (!isa<moore::PackedType>(value.getType())) {
3651 mlir::emitError(loc) <<
"expected integer argument for `$isunknown`";
3659 auto valTy = dyn_cast<moore::IntType>(value.getType());
3663 if (nameId == ksn::OneHot0 || nameId == ksn::OneHot) {
3664 assert(numArgs == 1 &&
"`$onehot`/`$onehot0` takes 1 argument");
3668 if (!isa<moore::IntType>(value.getType())) {
3669 if (!isa<moore::PackedType>(value.getType())) {
3670 mlir::emitError(loc)
3671 <<
"expected integer argument for `$onehot`/`$onehot0`";
3679 auto valTy = dyn_cast<moore::IntType>(value.getType());
3681 mlir::emitError(loc) <<
"expected integer argument for `"
3682 << subroutine.name <<
"`";
3689 if (valTy.getDomain() == Domain::FourValued) {
3690 Value isUnknownMoore =
3693 builder.createOrFold<moore::ToBuiltinIntOp>(loc, isUnknownMoore);
3701 auto minusOne = comb::SubOp::create(
builder, loc, intVal, one);
3702 auto anded = comb::AndOp::create(
builder, loc, intVal, minusOne);
3704 Value result = comb::ICmpOp::create(
builder, loc, comb::ICmpPredicate::eq,
3705 anded, zero,
false);
3708 if (nameId == ksn::OneHot) {
3709 auto isNotZero = comb::ICmpOp::create(
3710 builder, loc, comb::ICmpPredicate::ne, intVal, zero,
false);
3711 result = comb::AndOp::create(
builder, loc, result, isNotZero);
3718 result = comb::MuxOp::create(
builder, loc, isUnknown, zeroI1, result);
3719 Value resultMoore = moore::FromBuiltinIntOp::create(
builder, loc, result);
3720 return moore::IntToLogicOp::create(
builder, loc, resultMoore).getResult();
3722 return moore::FromBuiltinIntOp::create(
builder, loc, result);
3725 if (nameId == ksn::CountOnes) {
3726 assert(numArgs == 1 &&
"`$countones` takes 1 argument");
3730 if (!isa<moore::IntType>(value.getType())) {
3731 if (!isa<moore::PackedType>(value.getType())) {
3732 mlir::emitError(loc) <<
"expected integer argument for `$countones`";
3740 auto valTy = dyn_cast<moore::IntType>(value.getType());
3742 mlir::emitError(loc) <<
"expected integer argument for `$countones`";
3750 auto builtinIntTy = cast<IntegerType>(intVal.getType());
3751 unsigned width = builtinIntTy.getWidth();
3752 unsigned resultWidth = llvm::Log2_32_Ceil(width + 1);
3753 auto i1Ty =
builder.getI1Type();
3754 unsigned padWidth = resultWidth - 1;
3756 builder.getIntegerType(padWidth), 0);
3760 Value sum = comb::ConcatOp::create(
builder, loc, ValueRange{zeros, bit0});
3762 for (
unsigned i = 1; i < width; ++i) {
3765 comb::ConcatOp::create(
builder, loc, ValueRange{zeros, bit});
3766 sum = comb::AddOp::create(
builder, loc, sum, extended);
3770 return moore::FromBuiltinIntOp::create(
builder, loc, sum);
3774 if (nameId == ksn::Ln)
3775 return convertRealMathBI<moore::LnBIOp>(*
this, loc, name, args);
3776 if (nameId == ksn::Log10)
3777 return convertRealMathBI<moore::Log10BIOp>(*
this, loc, name, args);
3778 if (nameId == ksn::Exp)
3779 return convertRealMathBI<moore::ExpBIOp>(*
this, loc, name, args);
3780 if (nameId == ksn::Sqrt)
3781 return convertRealMathBI<moore::SqrtBIOp>(*
this, loc, name, args);
3782 if (nameId == ksn::Floor)
3783 return convertRealMathBI<moore::FloorBIOp>(*
this, loc, name, args);
3784 if (nameId == ksn::Ceil)
3785 return convertRealMathBI<moore::CeilBIOp>(*
this, loc, name, args);
3786 if (nameId == ksn::Sin)
3787 return convertRealMathBI<moore::SinBIOp>(*
this, loc, name, args);
3788 if (nameId == ksn::Cos)
3789 return convertRealMathBI<moore::CosBIOp>(*
this, loc, name, args);
3790 if (nameId == ksn::Tan)
3791 return convertRealMathBI<moore::TanBIOp>(*
this, loc, name, args);
3792 if (nameId == ksn::Asin)
3793 return convertRealMathBI<moore::AsinBIOp>(*
this, loc, name, args);
3794 if (nameId == ksn::Acos)
3795 return convertRealMathBI<moore::AcosBIOp>(*
this, loc, name, args);
3796 if (nameId == ksn::Atan)
3797 return convertRealMathBI<moore::AtanBIOp>(*
this, loc, name, args);
3798 if (nameId == ksn::Sinh)
3799 return convertRealMathBI<moore::SinhBIOp>(*
this, loc, name, args);
3800 if (nameId == ksn::Cosh)
3801 return convertRealMathBI<moore::CoshBIOp>(*
this, loc, name, args);
3802 if (nameId == ksn::Tanh)
3803 return convertRealMathBI<moore::TanhBIOp>(*
this, loc, name, args);
3804 if (nameId == ksn::Asinh)
3805 return convertRealMathBI<moore::AsinhBIOp>(*
this, loc, name, args);
3806 if (nameId == ksn::Acosh)
3807 return convertRealMathBI<moore::AcoshBIOp>(*
this, loc, name, args);
3808 if (nameId == ksn::Atanh)
3809 return convertRealMathBI<moore::AtanhBIOp>(*
this, loc, name, args);
3811 if (nameId == ksn::Pow)
3812 return convertRealMathTwoBI<moore::PowRealOp>(*
this, loc, name, args);
3813 if (nameId == ksn::Atan2)
3814 return convertRealMathTwoBI<moore::Atan2BIOp>(*
this, loc, name, args);
3815 if (nameId == ksn::Hypot)
3816 return convertRealMathTwoBI<moore::HypotBIOp>(*
this, loc, name, args);
3822 if (nameId == ksn::Itor) {
3823 assert(numArgs == 1 &&
"`$itor` takes 1 argument");
3828 if (nameId == ksn::Rtoi) {
3829 assert(numArgs == 1 &&
"`$rtoi` takes 1 argument");
3830 auto intType = moore::IntType::get(
getContext(), 32, Domain::TwoValued);
3834 if (nameId == ksn::Signed || nameId == ksn::Unsigned) {
3836 assert(numArgs == 1 &&
"`$signed`/`$unsigned` take 1 argument");
3842 if (nameId == ksn::RealToBits)
3843 return convertRealMathBI<moore::RealtobitsBIOp>(*
this, loc, name, args);
3844 if (nameId == ksn::BitsToReal)
3845 return convertRealMathBI<moore::BitstorealBIOp>(*
this, loc, name, args);
3846 if (nameId == ksn::ShortrealToBits)
3847 return convertRealMathBI<moore::ShortrealtobitsBIOp>(*
this, loc, name,
3849 if (nameId == ksn::BitsToShortreal)
3850 return convertRealMathBI<moore::BitstoshortrealBIOp>(*
this, loc, name,
3853 if (nameId == ksn::Cast) {
3854 assert(numArgs == 2 &&
"`cast` takes 2 arguments");
3855 auto *dstExpr = args[0];
3860 if (
auto *assign = dstExpr->as_if<slang::ast::AssignmentExpression>())
3861 dstExpr = &assign->left();
3870 if (isa<moore::ClassHandleType>(dstType) ||
3871 isa<moore::ClassHandleType>(src.getType())) {
3872 auto i1Ty = moore::IntType::getInt(
builder.getContext(), 1);
3873 return moore::ConstantOp::create(
builder, loc, i1Ty, 0,
3877 dstType, src, args[1]->type->isSigned(), loc,
true);
3878 auto i1Ty = moore::IntType::getInt(
builder.getContext(), 1);
3880 return moore::ConstantOp::create(
builder, loc, i1Ty, 0,
3882 moore::BlockingAssignOp::create(
builder, loc, dst, converted);
3883 return moore::ConstantOp::create(
builder, loc, i1Ty, 1,
3891 if (nameId == ksn::Len) {
3893 assert(numArgs == 1 &&
"`len` takes 1 argument");
3894 auto stringType = moore::StringType::get(
getContext());
3898 return moore::StringLenOp::create(
builder, loc, value);
3901 if (nameId == ksn::Getc) {
3903 assert(numArgs == 2 &&
"`getc` takes 2 arguments");
3904 auto stringType = moore::StringType::get(
getContext());
3909 return moore::StringGetOp::create(
builder, loc, str, index);
3912 if (nameId == ksn::ToUpper) {
3914 assert(numArgs == 1 &&
"`toupper` takes 1 argument");
3915 auto stringType = moore::StringType::get(
getContext());
3919 return moore::StringToUpperOp::create(
builder, loc, value);
3922 if (nameId == ksn::ToLower) {
3924 assert(numArgs == 1 &&
"`tolower` takes 1 argument");
3925 auto stringType = moore::StringType::get(
getContext());
3929 return moore::StringToLowerOp::create(
builder, loc, value);
3932 if (nameId == ksn::Compare || nameId == ksn::ICompare) {
3935 auto stringType = moore::StringType::get(
getContext());
3940 if (nameId == ksn::Compare)
3941 return moore::StringCompareOp::create(
builder, loc, lhs, rhs);
3942 return moore::StringICompareOp::create(
builder, loc, lhs, rhs);
3945 if (nameId == ksn::Substr) {
3947 assert(numArgs == 3 &&
"`substr` takes 3 arguments");
3948 auto stringType = moore::StringType::get(
getContext());
3952 if (!str || !start || !end)
3954 return moore::StringSubstrOp::create(
builder, loc, str, start, end);
3957 if (nameId == ksn::AToI || nameId == ksn::AToHex || nameId == ksn::AToOct ||
3958 nameId == ksn::AToBin) {
3960 assert(numArgs == 1 &&
"`atoi/hex/oct/bin` takes 1 argument");
3961 auto stringType = moore::StringType::get(
getContext());
3965 auto integerType = moore::IntType::getLogic(
builder.getContext(), 32);
3968 return moore::StringAtoiOp::create(
builder, loc, integerType, str);
3970 return moore::StringAtohexOp::create(
builder, loc, integerType, str);
3972 return moore::StringAtooctOp::create(
builder, loc, integerType, str);
3974 return moore::StringAtobinOp::create(
builder, loc, integerType, str);
3976 llvm_unreachable(
"unexpected string to integer conversion");
3980 if (nameId == ksn::AToReal) {
3982 assert(numArgs == 1 &&
"`atoreal` takes 1 argument");
3983 auto stringType = moore::StringType::get(
getContext());
3988 return moore::StringAtorealOp::create(
builder, loc, realType, str);
3995 if (nameId == ksn::ArraySize) {
3997 assert(numArgs == 1 &&
"`size` takes 1 argument");
3998 if (args[0]->type->isQueue()) {
4002 return moore::QueueSizeBIOp::create(
builder, loc, value);
4004 if (args[0]->type->getCanonicalType().kind ==
4005 slang::ast::SymbolKind::DynamicArrayType) {
4009 return moore::OpenUArraySizeOp::create(
builder, loc, value);
4011 if (args[0]->type->isAssociativeArray()) {
4015 return moore::AssocArraySizeOp::create(
builder, loc, value);
4017 emitError(loc) <<
"unsupported member function `size` on type `"
4018 << args[0]->type->toString() <<
"`";
4022 if (nameId == ksn::Delete) {
4024 assert(numArgs == 1 &&
"`delete` takes 1 argument");
4025 if (args[0]->type->getCanonicalType().kind ==
4026 slang::ast::SymbolKind::DynamicArrayType) {
4030 return moore::OpenUArrayDeleteOp::create(
builder, loc, value);
4032 emitError(loc) <<
"unsupported member function `delete` on type `"
4033 << args[0]->type->toString() <<
"`";
4037 if (nameId == ksn::PopBack) {
4039 assert(numArgs == 1 &&
"`pop_back` takes 1 argument");
4040 assert(args[0]->type->isQueue() &&
"`pop_back` is only valid on queues");
4044 return moore::QueuePopBackOp::create(
builder, loc, value);
4047 if (nameId == ksn::PopFront) {
4049 assert(numArgs == 1 &&
"`pop_front` takes 1 argument");
4050 assert(args[0]->type->isQueue() &&
"`pop_front` is only valid on queues");
4054 return moore::QueuePopFrontOp::create(
builder, loc, value);
4061 if (nameId == ksn::Num) {
4062 if (args[0]->type->isAssociativeArray()) {
4063 assert(numArgs == 1 &&
"`num` takes 1 argument");
4067 return moore::AssocArraySizeOp::create(
builder, loc, value);
4069 emitError(loc) <<
"unsupported system call `" << name <<
"`";
4073 if (nameId == ksn::Exists) {
4075 assert(numArgs == 2 &&
"`exists` takes 2 arguments");
4076 assert(args[0]->type->isAssociativeArray() &&
4077 "`exists` is only valid on associative arrays");
4082 return moore::AssocArrayExistsOp::create(
builder, loc, array, key);
4085 if ((nameId == ksn::First || nameId == ksn::Last || nameId == ksn::Next ||
4086 nameId == ksn::Prev) &&
4087 args[0]->type->isAssociativeArray()) {
4088 assert(numArgs == 2 &&
"traversal methods take 2 arguments");
4093 if (nameId == ksn::First)
4094 return moore::AssocArrayFirstOp::create(
builder, loc, array, key);
4095 if (nameId == ksn::Last)
4096 return moore::AssocArrayLastOp::create(
builder, loc, array, key);
4097 if (nameId == ksn::Next)
4098 return moore::AssocArrayNextOp::create(
builder, loc, array, key);
4099 if (nameId == ksn::Prev)
4100 return moore::AssocArrayPrevOp::create(
builder, loc, array, key);
4101 llvm_unreachable(
"all traversal cases handled above");
4108 if (nameId == ksn::FOpen) {
4109 assert(numArgs >= 1 && numArgs <= 2 &&
"`$fopen` takes 1 or 2 arguments");
4114 moore::FOpenModeAttr modeAttr;
4116 auto *strLit = args[1]
4117 ->unwrapImplicitConversions()
4118 .as_if<slang::ast::StringLiteral>();
4120 return emitError(loc) <<
"$fopen mode must be a string literal",
4124 llvm::StringSwitch<std::optional<moore::FOpenMode>>(
4126 .Cases({
"r",
"rb"}, moore::FOpenMode::Read)
4127 .Cases({
"w",
"wb"}, moore::FOpenMode::Write)
4128 .Cases({
"a",
"ab"}, moore::FOpenMode::Append)
4129 .Cases({
"r+",
"r+b",
"rb+"}, moore::FOpenMode::ReadUpdate)
4130 .Cases({
"w+",
"w+b",
"wb+"}, moore::FOpenMode::WriteUpdate)
4131 .Cases({
"a+",
"a+b",
"ab+"}, moore::FOpenMode::AppendUpdate)
4132 .Default(std::nullopt);
4135 return emitError(loc)
4136 <<
"invalid $fopen mode '" << strLit->getValue() <<
"'",
4138 modeAttr = moore::FOpenModeAttr::get(
getContext(), *mode);
4140 return moore::FOpenBIOp::create(
builder, loc, filename, modeAttr);
4147 if (nameId == ksn::TestPlusArgs) {
4149 assert(numArgs == 1 &&
"`$test$plusargs` takes 1 argument");
4151 args[0]->unwrapImplicitConversions().as_if<slang::ast::StringLiteral>();
4153 return emitError(loc) <<
"`$test$plusargs` argument must be a string "
4156 auto foundTy = moore::IntType::getInt(
getContext(), 1);
4157 return moore::PlusArgsTestBIOp::create(
4158 builder, loc, foundTy,
builder.getStringAttr(strLit->getValue()));
4161 if (nameId == ksn::ValuePlusArgs) {
4165 assert(numArgs == 2 &&
"`$value$plusargs` takes 2 arguments");
4167 args[0]->unwrapImplicitConversions().as_if<slang::ast::StringLiteral>();
4169 return emitError(loc) <<
"`$value$plusargs` format must be a string "
4174 const auto *valueArg = args[1];
4175 if (
const auto *assign =
4176 valueArg->as_if<slang::ast::AssignmentExpression>())
4177 valueArg = &assign->left();
4181 auto resultType = cast<moore::RefType>(lvalue.getType()).getNestedType();
4182 auto foundTy = moore::IntType::getInt(
getContext(), 1);
4183 auto op = moore::PlusArgsValueBIOp::create(
4184 builder, loc, foundTy, resultType,
4185 builder.getStringAttr(strLit->getValue()));
4186 moore::BlockingAssignOp::create(
builder, loc, lvalue, op.getResult());
4187 return op.getFound();
4190 if (nameId == ksn::FScanf) {
4192 *args[0], moore::IntType::getInt(
builder.getContext(), 32));
4196 args[1]->unwrapImplicitConversions().as_if<slang::ast::StringLiteral>();
4198 return (mlir::emitError(loc)
4199 <<
"$fscanf requires a string literal format string"),
4202 moore::ScanBeginFScanFOp::create(
builder, loc, fd).getCursor();
4209 return moore::ScanEndOp::create(
builder, loc, result->finalCursor)
4213 if (nameId == ksn::SScanf) {
4219 args[1]->unwrapImplicitConversions().as_if<slang::ast::StringLiteral>();
4221 return (mlir::emitError(loc)
4222 <<
"$sscanf requires a string literal format string"),
4225 moore::ScanBeginSScanFOp::create(
builder, loc, str).getCursor();
4232 return moore::ScanEndOp::create(
builder, loc, result->finalCursor)
4241 assert(!(nameId == ksn::First || nameId == ksn::Last || nameId == ksn::Num) ||
4242 !args[0]->type->isEnum());
4244 if (nameId == ksn::Name && args[0]->type->isEnum()) {
4245 assert(numArgs == 1 &&
"`name` takes 1 argument");
4252 return mlir::func::CallOp::create(
builder, loc, helper, ValueRange{value})
4256 if ((nameId == ksn::Next || nameId == ksn::Prev) && args[0]->type->isEnum()) {
4257 assert(numArgs >= 1 && numArgs <= 2 &&
"`next`/`prev` take 1 or 2 args");
4263 auto posType = moore::IntType::getInt(
getContext(), 32);
4268 count = moore::ConstantOp::create(
builder, loc, posType, 1);
4275 return mlir::func::CallOp::create(
builder, loc, helper,
4276 ValueRange{value, count})
4281 emitError(loc) <<
"unsupported system call `" << name <<
"`";
4287 return context.symbolTable.lookupNearestSymbolFrom(
context.intoModuleOp, sym);
4291 const moore::ClassHandleType &baseTy) {
4292 if (!actualTy || !baseTy)
4295 mlir::SymbolRefAttr actualSym = actualTy.getClassSym();
4296 mlir::SymbolRefAttr baseSym = baseTy.getClassSym();
4298 if (actualSym == baseSym)
4301 auto *op =
resolve(*
this, actualSym);
4302 auto decl = llvm::dyn_cast_or_null<moore::ClassDeclOp>(op);
4305 mlir::SymbolRefAttr curBase = decl.getBaseAttr();
4308 if (curBase == baseSym)
4310 decl = llvm::dyn_cast_or_null<moore::ClassDeclOp>(
resolve(*
this, curBase));
4315moore::ClassHandleType
4317 llvm::StringRef fieldName, Location loc) {
4319 mlir::SymbolRefAttr classSym = actualTy.getClassSym();
4323 auto *op =
resolve(*
this, classSym);
4324 auto decl = llvm::dyn_cast_or_null<moore::ClassDeclOp>(op);
4329 for (
auto &block : decl.getBody()) {
4330 for (
auto &opInBlock : block) {
4332 llvm::dyn_cast<moore::ClassPropertyDeclOp>(&opInBlock)) {
4333 if (prop.getSymName() == fieldName) {
4335 return moore::ClassHandleType::get(actualTy.getContext(), classSym);
4342 classSym = decl.getBaseAttr();
4346 mlir::emitError(loc) <<
"unknown property `" << fieldName <<
"`";
4355 const slang::ast::Expression &expr) {
4358 if (
const auto *valueRange = expr.as_if<slang::ast::ValueRangeExpression>()) {
4363 if (!insideLhs || !lowBound || !highBound)
4366 Value rangeLhs, rangeRhs;
4369 if (valueRange->left().type->isSigned() ||
4370 insideLhs.getType().isSignedInteger()) {
4371 rangeLhs = moore::SgeOp::create(
builder, loc, insideLhs, lowBound);
4373 rangeLhs = moore::UgeOp::create(
builder, loc, insideLhs, lowBound);
4376 if (valueRange->right().type->isSigned() ||
4377 insideLhs.getType().isSignedInteger()) {
4378 rangeRhs = moore::SleOp::create(
builder, loc, insideLhs, highBound);
4380 rangeRhs = moore::UleOp::create(
builder, loc, insideLhs, highBound);
4383 return moore::AndOp::create(
builder, loc, rangeLhs, rangeRhs);
4387 if (!expr.type->isIntegral()) {
4388 if (expr.type->isUnpackedArray()) {
4389 mlir::emitError(loc,
4390 "unpacked arrays in 'inside' expressions not supported");
4394 loc,
"only simple bit vectors supported in 'inside' expressions");
4401 return moore::WildcardEqOp::create(
builder, loc, insideLhs, value);
assert(baseType &&"element must be base type")
static std::unique_ptr< Context > context
static Value convertRealMathBI(Context &context, Location loc, StringRef name, std::span< const slang::ast::Expression *const > args)
Helper function to convert real math builtin functions that take exactly one argument.
static Value convertRealMathTwoBI(Context &context, Location loc, StringRef name, std::span< const slang::ast::Expression *const > args)
Helper function to convert real math builtin functions that take exactly two arguments.
static mlir::Value maybeUpcastHandle(Context &context, mlir::Value actualHandle, moore::ClassHandleType expectedHandleTy)
Check whether the actual handle is a subclass of another handle type and return a properly upcast ver...
static mlir::Operation * resolve(Context &context, mlir::SymbolRefAttr sym)
static Value lookupExpandedInterfaceMember(Context &context, const slang::ast::HierarchicalValueExpression &expr)
Resolve a hierarchical value that refers to a member of an expanded interface instance.
static void ensureDescendingOrder(RangeT &range, const slang::ast::Type &type)
Ensures that the given range is in "descending" order.
static Value visitClassProperty(Context &context, const slang::ast::ClassPropertySymbol &expr)
static Value materializeSBVToPackedConversion(Context &context, moore::PackedType packedType, Value value, Location loc, bool fallible)
Create the necessary operations to convert from a simple bit vector IntType to an equivalent PackedTy...
static LogicalResult emitScanAssignments(Context &context, const Context::ScanStringResult &result, Location loc)
static Value getIsUnknown(OpBuilder &builder, Location loc, Value value, moore::IntType valTy, MLIRContext *ctx)
Check if a Moore integer value contains any unknown (x/z) bits.
static uint64_t getTimeScaleInFemtoseconds(Context &context)
Get the currently active timescale as an integer number of femtoseconds.
static Value coerceToBuiltinInt(OpBuilder &builder, Location loc, Value value, moore::IntType valTy)
Coerce a Moore integer value to a builtin integer, handling four-valued inputs by first mapping x/z t...
static FVInt convertSVIntToFVInt(const slang::SVInt &svint)
Convert a Slang SVInt to a CIRCT FVInt.
static InstancePath empty
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.
DenseMap< std::pair< const slang::ast::EnumType *, slang::parsing::KnownSystemName >, mlir::func::FuncOp > enumHelpers
Helper functions generated for the enum built-in methods, keyed by the canonical enum type and the me...
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
mlir::func::FuncOp getOrCreateEnumHelper(const slang::ast::Type &type, slang::parsing::KnownSystemName method, Location loc)
Get the helper function implementing one of the name, next, and prev built-in methods for the given e...
moore::ClassHandleType getAncestorClassWithProperty(const moore::ClassHandleType &actualTy, StringRef fieldName, Location loc)
Tries to find the closest base class of actualTy that carries a property with name fieldName.
Value materializePackedToSBVConversion(Value value, Location loc, bool fallible)
Helper function to convert a PackedType value to its simple bit vector representation,...
Value convertRvalueExpression(const slang::ast::Expression &expr, Type requiredType={})
Value convertToSimpleBitVector(Value value)
Helper function to convert a value to its simple bit vector representation, if it has one.
Value materializeString(const slang::ConstantValue &string, const slang::ast::Type &astType, Location loc)
Helper function to materialize a string as an SSA value.
const slang::SourceManager & sourceManager
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.
std::map< LocationKey, Operation * > orderedRootOps
The top-level operations ordered by their Slang source location.
FunctionLowering * currentFunctionLowering
The function currently being converted, if any.
mlir::ModuleOp intoModuleOp
SymbolTable symbolTable
A symbol table of the MLIR module we are emitting into.
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
static LocationKey get(const slang::SourceLocation &loc, const slang::SourceManager &mgr)