10#include "slang/ast/Compilation.h"
11#include "slang/ast/symbols/ClassSymbols.h"
12#include "llvm/ADT/ScopeExit.h"
15using namespace ImportVerilog;
22 SmallString<64> &prefix) {
23 if (symbol.kind != slang::ast::SymbolKind::Package)
26 if (!symbol.name.empty()) {
27 prefix += symbol.name;
44 BaseVisitor(
Context &context, Location loc)
45 : context(context), loc(loc), builder(context.builder) {}
48 LogicalResult visit(
const slang::ast::EmptyMemberSymbol &) {
54 LogicalResult visit(
const slang::ast::TransparentMemberSymbol &) {
59 LogicalResult visit(
const slang::ast::ClassType &classdecl) {
67 LogicalResult visit(
const slang::ast::GenericClassDefSymbol &) {
72 LogicalResult visit(
const slang::ast::TypeAliasType &) {
return success(); }
73 LogicalResult visit(
const slang::ast::ForwardingTypedefSymbol &) {
78 LogicalResult visit(
const slang::ast::ExplicitImportSymbol &) {
81 LogicalResult visit(
const slang::ast::WildcardImportSymbol &) {
86 LogicalResult visit(
const slang::ast::TypeParameterSymbol &) {
91 LogicalResult visit(
const slang::ast::ElabSystemTaskSymbol &) {
96 LogicalResult visit(
const slang::ast::ParameterSymbol ¶m) {
97 visitParameter(param);
101 LogicalResult visit(
const slang::ast::SpecparamSymbol ¶m) {
102 visitParameter(param);
106 template <
class Node>
107 void visitParameter(
const Node ¶m) {
117 if (builder.getInsertionBlock()->getParentOp() == context.
intoModuleOp)
118 context.
orderedRootOps.insert({param.location, value.getDefiningOp()});
122 SmallString<64> paramName;
124 paramName += param.name;
126 debug::VariableOp::create(builder, loc, builder.getStringAttr(paramName),
137struct RootVisitor :
public BaseVisitor {
138 using BaseVisitor::BaseVisitor;
139 using BaseVisitor::visit;
142 LogicalResult visit(
const slang::ast::PackageSymbol &package) {
143 return context.convertPackage(package);
147 LogicalResult visit(
const slang::ast::SubroutineSymbol &subroutine) {
148 return context.convertFunction(subroutine);
152 LogicalResult visit(
const slang::ast::VariableSymbol &var) {
153 return context.convertGlobalVariable(var);
157 template <
typename T>
158 LogicalResult visit(T &&node) {
159 mlir::emitError(loc,
"unsupported construct: ")
160 << slang::ast::toString(node.kind);
171struct PackageVisitor :
public BaseVisitor {
172 using BaseVisitor::BaseVisitor;
173 using BaseVisitor::visit;
176 LogicalResult visit(
const slang::ast::SubroutineSymbol &subroutine) {
177 return context.convertFunction(subroutine);
181 LogicalResult visit(
const slang::ast::VariableSymbol &var) {
182 return context.convertGlobalVariable(var);
186 template <
typename T>
187 LogicalResult visit(T &&node) {
188 mlir::emitError(loc,
"unsupported package member: ")
189 << slang::ast::toString(node.kind);
199static moore::ProcedureKind
202 case slang::ast::ProceduralBlockKind::Always:
203 return moore::ProcedureKind::Always;
204 case slang::ast::ProceduralBlockKind::AlwaysComb:
205 return moore::ProcedureKind::AlwaysComb;
206 case slang::ast::ProceduralBlockKind::AlwaysLatch:
207 return moore::ProcedureKind::AlwaysLatch;
208 case slang::ast::ProceduralBlockKind::AlwaysFF:
209 return moore::ProcedureKind::AlwaysFF;
210 case slang::ast::ProceduralBlockKind::Initial:
211 return moore::ProcedureKind::Initial;
212 case slang::ast::ProceduralBlockKind::Final:
213 return moore::ProcedureKind::Final;
215 llvm_unreachable(
"all procedure kinds handled");
220 case slang::ast::NetType::Supply0:
221 return moore::NetKind::Supply0;
222 case slang::ast::NetType::Supply1:
223 return moore::NetKind::Supply1;
224 case slang::ast::NetType::Tri:
225 return moore::NetKind::Tri;
226 case slang::ast::NetType::TriAnd:
227 return moore::NetKind::TriAnd;
228 case slang::ast::NetType::TriOr:
229 return moore::NetKind::TriOr;
230 case slang::ast::NetType::TriReg:
231 return moore::NetKind::TriReg;
232 case slang::ast::NetType::Tri0:
233 return moore::NetKind::Tri0;
234 case slang::ast::NetType::Tri1:
235 return moore::NetKind::Tri1;
236 case slang::ast::NetType::UWire:
237 return moore::NetKind::UWire;
238 case slang::ast::NetType::Wire:
239 return moore::NetKind::Wire;
240 case slang::ast::NetType::WAnd:
241 return moore::NetKind::WAnd;
242 case slang::ast::NetType::WOr:
243 return moore::NetKind::WOr;
244 case slang::ast::NetType::Interconnect:
245 return moore::NetKind::Interconnect;
246 case slang::ast::NetType::UserDefined:
247 return moore::NetKind::UserDefined;
248 case slang::ast::NetType::Unknown:
249 return moore::NetKind::Unknown;
251 llvm_unreachable(
"all net kinds handled");
255struct ModuleVisitor :
public BaseVisitor {
256 using BaseVisitor::visit;
260 StringRef blockNamePrefix;
262 ModuleVisitor(
Context &
context, Location loc, StringRef blockNamePrefix =
"")
263 : BaseVisitor(
context, loc), blockNamePrefix(blockNamePrefix) {}
266 LogicalResult visit(
const slang::ast::PortSymbol &) {
return success(); }
267 LogicalResult visit(
const slang::ast::MultiPortSymbol &) {
return success(); }
270 LogicalResult visit(
const slang::ast::GenvarSymbol &genvarNode) {
275 LogicalResult visit(
const slang::ast::DefParamSymbol &) {
return success(); }
279 LogicalResult visit(
const slang::ast::TypeParameterSymbol &) {
284 LogicalResult visit(
const slang::ast::InstanceSymbol &instNode) {
285 using slang::ast::ArgumentDirection;
286 using slang::ast::AssignmentExpression;
287 using slang::ast::MultiPortSymbol;
288 using slang::ast::PortSymbol;
290 auto *moduleLowering =
context.convertModuleHeader(&instNode.body);
293 auto module = moduleLowering->op;
294 auto moduleType =
module.getModuleType();
297 SymbolTable::setSymbolVisibility(module, SymbolTable::Visibility::Private);
304 portValues.reserve(moduleType.getNumPorts());
306 for (
const auto *con : instNode.getPortConnections()) {
307 const auto *expr = con->getExpression();
312 auto *port = con->port.as_if<PortSymbol>();
313 if (
auto *existingPort =
314 moduleLowering->portsBySyntaxNode.lookup(port->getSyntax()))
317 switch (port->direction) {
318 case ArgumentDirection::In: {
319 auto refType = moore::RefType::get(
320 cast<moore::UnpackedType>(
context.convertType(port->getType())));
322 if (
const auto *net =
323 port->internalSymbol->as_if<slang::ast::NetSymbol>()) {
324 auto netOp = moore::NetOp::create(
325 builder, loc, refType,
326 StringAttr::get(builder.getContext(), net->name),
328 auto readOp = moore::ReadOp::create(builder, loc, netOp);
329 portValues.insert({port, readOp});
330 }
else if (
const auto *var =
332 ->as_if<slang::ast::VariableSymbol>()) {
333 auto varOp = moore::VariableOp::create(
334 builder, loc, refType,
335 StringAttr::get(builder.getContext(), var->name),
nullptr);
336 auto readOp = moore::ReadOp::create(builder, loc, varOp);
337 portValues.insert({port, readOp});
339 return mlir::emitError(loc)
340 <<
"unsupported internal symbol for unconnected port `"
341 << port->name <<
"`";
348 case ArgumentDirection::Out:
353 return mlir::emitError(loc)
354 <<
"unsupported port `" << port->name <<
"` ("
355 << slang::ast::toString(port->kind) <<
")";
361 if (
const auto *assign = expr->as_if<AssignmentExpression>())
362 expr = &assign->left();
367 if (
auto *port = con->port.as_if<PortSymbol>()) {
369 auto value = (port->direction == ArgumentDirection::In)
370 ?
context.convertRvalueExpression(*expr)
371 :
context.convertLvalueExpression(*expr);
374 if (
auto *existingPort =
375 moduleLowering->portsBySyntaxNode.lookup(con->port.getSyntax()))
377 portValues.insert({port, value});
384 if (
const auto *multiPort = con->port.as_if<MultiPortSymbol>()) {
386 auto value =
context.convertLvalueExpression(*expr);
390 for (
const auto *port :
llvm::reverse(multiPort->ports)) {
391 if (
auto *existingPort = moduleLowering->portsBySyntaxNode.lookup(
392 con->port.getSyntax()))
394 unsigned width = port->getType().getBitWidth();
395 auto sliceType =
context.convertType(port->getType());
398 Value slice = moore::ExtractRefOp::create(
400 moore::RefType::get(cast<moore::UnpackedType>(sliceType)), value,
403 if (port->direction == ArgumentDirection::In)
404 slice = moore::ReadOp::create(builder, loc, slice);
405 portValues.insert({port, slice});
411 mlir::emitError(loc) <<
"unsupported instance port `" << con->port.name
412 <<
"` (" << slang::ast::toString(con->port.kind)
418 SmallVector<Value> inputValues;
419 SmallVector<Value> outputValues;
420 inputValues.reserve(moduleType.getNumInputs());
421 outputValues.reserve(moduleType.getNumOutputs());
423 for (
auto &port : moduleLowering->ports) {
424 auto value = portValues.lookup(&port.ast);
425 if (port.ast.direction == ArgumentDirection::Out)
426 outputValues.push_back(value);
428 inputValues.push_back(value);
432 for (
auto [value, type] :
433 llvm::zip(inputValues, moduleType.getInputTypes()))
435 value =
context.materializeConversion(type, value, false, value.
getLoc());
439 for (
const auto &hierPath :
context.hierPaths[&instNode.body])
440 if (auto hierValue =
context.valueSymbols.lookup(hierPath.valueSym);
441 hierPath.hierName && hierPath.direction == ArgumentDirection::In)
442 inputValues.push_back(hierValue);
445 auto inputNames = builder.getArrayAttr(moduleType.getInputNames());
446 auto outputNames = builder.getArrayAttr(moduleType.getOutputNames());
447 auto inst = moore::InstanceOp::create(
448 builder, loc, moduleType.getOutputTypes(),
449 builder.getStringAttr(Twine(blockNamePrefix) + instNode.name),
450 FlatSymbolRefAttr::get(module.getSymNameAttr()), inputValues,
451 inputNames, outputNames);
454 for (
const auto &hierPath :
context.hierPaths[&instNode.body])
455 if (hierPath.idx && hierPath.direction == ArgumentDirection::
Out)
456 context.valueSymbols.insert(hierPath.valueSym,
457 inst->getResult(*hierPath.idx));
460 for (
auto [lvalue, output] :
llvm::zip(outputValues, inst.getOutputs())) {
463 Value rvalue = output;
464 auto dstType = cast<moore::RefType>(lvalue.getType()).getNestedType();
466 rvalue =
context.materializeConversion(dstType, rvalue,
false, loc);
467 moore::ContinuousAssignOp::create(builder, loc, lvalue, rvalue);
474 LogicalResult visit(
const slang::ast::VariableSymbol &varNode) {
475 auto loweredType =
context.convertType(*varNode.getDeclaredType());
480 if (
const auto *init = varNode.getInitializer()) {
481 initial =
context.convertRvalueExpression(*init, loweredType);
486 auto varOp = moore::VariableOp::create(
488 moore::RefType::get(cast<moore::UnpackedType>(loweredType)),
489 builder.getStringAttr(Twine(blockNamePrefix) + varNode.name), initial);
490 context.valueSymbols.insert(&varNode, varOp);
495 LogicalResult visit(
const slang::ast::NetSymbol &netNode) {
496 auto loweredType =
context.convertType(*netNode.getDeclaredType());
501 if (
const auto *init = netNode.getInitializer()) {
502 assignment =
context.convertRvalueExpression(*init, loweredType);
508 if (netkind == moore::NetKind::Interconnect ||
509 netkind == moore::NetKind::UserDefined ||
510 netkind == moore::NetKind::Unknown)
511 return mlir::emitError(loc,
"unsupported net kind `")
512 << netNode.netType.name <<
"`";
514 auto netOp = moore::NetOp::create(
516 moore::RefType::get(cast<moore::UnpackedType>(loweredType)),
517 builder.getStringAttr(Twine(blockNamePrefix) + netNode.name), netkind,
519 context.valueSymbols.insert(&netNode, netOp);
524 LogicalResult visit(
const slang::ast::ContinuousAssignSymbol &assignNode) {
526 assignNode.getAssignment().as<slang::ast::AssignmentExpression>();
527 auto lhs =
context.convertLvalueExpression(expr.left());
531 auto rhs =
context.convertRvalueExpression(
532 expr.right(), cast<moore::RefType>(lhs.getType()).getNestedType());
537 if (
auto *timingCtrl = assignNode.getDelay()) {
538 auto *ctrl = timingCtrl->as_if<slang::ast::DelayControl>();
539 assert(ctrl &&
"slang guarantees this to be a simple delay");
540 auto delay =
context.convertRvalueExpression(
541 ctrl->expr, moore::TimeType::get(builder.getContext()));
544 moore::DelayedContinuousAssignOp::create(builder, loc, lhs, rhs, delay);
549 moore::ContinuousAssignOp::create(builder, loc, lhs, rhs);
554 LogicalResult convertProcedure(moore::ProcedureKind kind,
555 const slang::ast::Statement &body) {
556 if (body.as_if<slang::ast::ConcurrentAssertionStatement>())
557 return context.convertStatement(body);
558 auto procOp = moore::ProcedureOp::create(builder, loc, kind);
559 OpBuilder::InsertionGuard guard(builder);
560 builder.setInsertionPointToEnd(&procOp.getBody().emplaceBlock());
561 Context::ValueSymbolScope scope(
context.valueSymbols);
562 if (failed(
context.convertStatement(body)))
564 if (builder.getBlock())
565 moore::ReturnOp::create(builder, loc);
569 LogicalResult visit(
const slang::ast::ProceduralBlockSymbol &procNode) {
572 if (
context.options.lowerAlwaysAtStarAsComb) {
573 auto *stmt = procNode.getBody().as_if<slang::ast::TimedStatement>();
574 if (procNode.procedureKind == slang::ast::ProceduralBlockKind::Always &&
576 stmt->timing.kind == slang::ast::TimingControlKind::ImplicitEvent)
577 return convertProcedure(moore::ProcedureKind::AlwaysComb, stmt->stmt);
585 LogicalResult visit(
const slang::ast::GenerateBlockSymbol &genNode) {
587 if (genNode.isUninstantiated)
591 SmallString<64> prefix = blockNamePrefix;
592 if (!genNode.name.empty() ||
593 genNode.getParentScope()->asSymbol().kind !=
594 slang::ast::SymbolKind::GenerateBlockArray) {
595 prefix += genNode.getExternalName();
600 for (
auto &member : genNode.members())
601 if (failed(member.visit(ModuleVisitor(
context, loc, prefix))))
607 LogicalResult visit(
const slang::ast::GenerateBlockArraySymbol &genArrNode) {
610 SmallString<64> prefix = blockNamePrefix;
611 prefix += genArrNode.getExternalName();
613 auto prefixBaseLen = prefix.size();
616 for (
const auto *entry : genArrNode.entries) {
618 prefix.resize(prefixBaseLen);
619 if (entry->arrayIndex)
620 prefix += entry->arrayIndex->toString();
622 Twine(entry->constructIndex).toVector(prefix);
626 if (failed(entry->asSymbol().visit(ModuleVisitor(
context, loc, prefix))))
638 LogicalResult visit(
const slang::ast::StatementBlockSymbol &) {
644 LogicalResult visit(
const slang::ast::SequenceSymbol &seqNode) {
650 LogicalResult visit(
const slang::ast::PropertySymbol &propNode) {
655 LogicalResult visit(
const slang::ast::SubroutineSymbol &subroutine) {
656 return context.convertFunction(subroutine);
660 template <
typename T>
661 LogicalResult visit(T &&node) {
662 mlir::emitError(loc,
"unsupported module member: ")
663 << slang::ast::toString(node.kind);
675LogicalResult Context::convertCompilation() {
681 timeScale = root.getTimeScale().value_or(slang::TimeScale());
682 llvm::scope_exit timeScaleGuard([&] {
timeScale = prevTimeScale; });
686 for (
auto *inst : root.topInstances)
693 for (
auto *unit : root.compilationUnits) {
694 for (
const auto &member : unit->members()) {
696 if (failed(member.visit(RootVisitor(*
this, loc))))
702 SmallVector<const slang::ast::InstanceSymbol *> topInstances;
703 for (
auto *inst : root.topInstances)
709 auto *
module = moduleWorklist.front();
718 auto &block = varOp.getInitRegion().emplaceBlock();
719 OpBuilder::InsertionGuard guard(
builder);
720 builder.setInsertionPointToEnd(&block);
725 moore::YieldOp::create(
builder, varOp.getLoc(), value);
738 using slang::ast::ArgumentDirection;
739 using slang::ast::MultiPortSymbol;
740 using slang::ast::ParameterSymbol;
741 using slang::ast::PortSymbol;
742 using slang::ast::TypeParameterSymbol;
747 timeScale =
module->getTimeScale().value_or(slang::TimeScale());
748 llvm::scope_exit timeScaleGuard([&] {
timeScale = prevTimeScale; });
750 auto parameters =
module->getParameters();
751 bool hasModuleSame =
false;
755 for (
auto const &existingModule :
modules) {
756 if (module->getDeclaringDefinition() ==
757 existingModule.getFirst()->getDeclaringDefinition()) {
758 auto moduleParameters = existingModule.getFirst()->getParameters();
759 hasModuleSame =
true;
760 for (
auto it1 = parameters.begin(), it2 = moduleParameters.begin();
761 it1 != parameters.end() && it2 != moduleParameters.end();
764 if (it1 == parameters.end() || it2 == moduleParameters.end()) {
765 hasModuleSame =
false;
768 const auto *para1 = (*it1)->symbol.as_if<ParameterSymbol>();
769 const auto *para2 = (*it2)->symbol.as_if<ParameterSymbol>();
771 if ((para1 ==
nullptr) ^ (para2 ==
nullptr)) {
772 hasModuleSame =
false;
776 if (para1 !=
nullptr) {
777 hasModuleSame = para1->getValue() == para2->getValue();
780 if (para1 ==
nullptr) {
782 (*it1)->symbol.as<TypeParameterSymbol>().getTypeAlias());
784 (*it2)->symbol.as<TypeParameterSymbol>().getTypeAlias());
785 hasModuleSame = para1Type == para2Type;
791 module = existingModule.first;
800 slot = std::make_unique<ModuleLowering>();
801 auto &lowering = *slot;
804 OpBuilder::InsertionGuard g(
builder);
809 auto kind =
module->getDefinition().definitionKind;
810 if (kind != slang::ast::DefinitionKind::Module &&
811 kind != slang::ast::DefinitionKind::Program) {
812 mlir::emitError(loc) <<
"unsupported definition: "
813 <<
module->getDefinition().getKindString();
818 auto block = std::make_unique<Block>();
819 SmallVector<hw::ModulePort> modulePorts;
822 unsigned int outputIdx = 0, inputIdx = 0;
823 for (
auto *symbol :
module->getPortList()) {
824 auto handlePort = [&](const PortSymbol &port) {
825 auto portLoc = convertLocation(port.location);
829 auto portName =
builder.getStringAttr(port.name);
831 if (port.direction == ArgumentDirection::Out) {
837 if (port.direction != ArgumentDirection::In)
838 type = moore::RefType::get(cast<moore::UnpackedType>(type));
840 arg = block->addArgument(type, portLoc);
843 lowering.ports.push_back({port, portLoc, arg});
847 if (
const auto *port = symbol->as_if<PortSymbol>()) {
848 if (failed(handlePort(*port)))
850 }
else if (
const auto *multiPort = symbol->as_if<MultiPortSymbol>()) {
851 for (
auto *port : multiPort->ports)
852 if (failed(handlePort(*port)))
856 <<
"unsupported module port `" << symbol->name <<
"` ("
857 << slang::ast::toString(symbol->kind) <<
")";
863 for (
auto &hierPath : hierPaths[module]) {
864 auto hierType =
convertType(hierPath.valueSym->getType());
868 if (
auto hierName = hierPath.hierName) {
870 hierType = moore::RefType::get(cast<moore::UnpackedType>(hierType));
871 if (hierPath.direction == ArgumentDirection::Out) {
872 hierPath.idx = outputIdx++;
875 hierPath.idx = inputIdx++;
878 block->addArgument(hierType, hierLoc);
882 auto moduleType = hw::ModuleType::get(getContext(), modulePorts);
886 auto it = orderedRootOps.upper_bound(module->location);
887 if (it == orderedRootOps.end())
888 builder.setInsertionPointToEnd(intoModuleOp.getBody());
890 builder.setInsertionPoint(it->second);
894 moore::SVModuleOp::create(builder, loc, module->name, moduleType);
895 orderedRootOps.insert(it, {
module->location, moduleOp});
896 moduleOp.getBodyRegion().push_back(block.release());
897 lowering.op = moduleOp;
901 symbolTable.insert(moduleOp);
904 moduleWorklist.push(module);
907 for (
const auto &port : lowering.ports)
908 lowering.portsBySyntaxNode.insert({port.ast.getSyntax(), &port.ast});
917 auto &lowering = *
modules[module];
918 OpBuilder::InsertionGuard g(
builder);
919 builder.setInsertionPointToEnd(lowering.op.getBody());
926 timeScale =
module->getTimeScale().value_or(slang::TimeScale());
927 llvm::scope_exit timeScaleGuard([&] {
timeScale = prevTimeScale; });
933 if (hierPath.direction == slang::ast::ArgumentDirection::In && hierPath.idx)
935 lowering.op.getBody()->getArgument(*hierPath.idx));
938 for (
auto &member :
module->members()) {
939 auto loc = convertLocation(member.location);
940 if (failed(member.visit(ModuleVisitor(*
this, loc))))
947 SmallVector<Value> outputs;
948 for (
auto &port : lowering.ports) {
950 if (
auto *expr = port.ast.getInternalExpr()) {
951 value = convertLvalueExpression(*expr);
952 }
else if (port.ast.internalSymbol) {
953 if (
const auto *sym =
954 port.ast.internalSymbol->as_if<slang::ast::ValueSymbol>())
955 value = valueSymbols.lookup(sym);
958 return mlir::emitError(port.loc,
"unsupported port: `")
960 <<
"` does not map to an internal symbol or expression";
963 if (port.ast.direction == slang::ast::ArgumentDirection::Out) {
964 if (isa<moore::RefType>(value.getType()))
965 value = moore::ReadOp::create(builder, value.getLoc(), value);
966 outputs.push_back(value);
972 Value portArg = port.arg;
973 if (port.ast.direction != slang::ast::ArgumentDirection::In)
974 portArg = moore::ReadOp::create(builder, port.loc, port.arg);
975 moore::ContinuousAssignOp::create(builder, port.loc, value, portArg);
980 for (
auto &hierPath : hierPaths[module])
981 if (auto hierValue = valueSymbols.lookup(hierPath.valueSym))
982 if (hierPath.direction == slang::ast::ArgumentDirection::
Out)
983 outputs.push_back(hierValue);
985 moore::OutputOp::create(builder, lowering.op.getLoc(), outputs);
995 timeScale = package.getTimeScale().value_or(slang::TimeScale());
996 llvm::scope_exit timeScaleGuard([&] {
timeScale = prevTimeScale; });
998 OpBuilder::InsertionGuard g(
builder);
1001 for (
auto &member : package.members()) {
1003 if (failed(member.visit(PackageVisitor(*
this, loc))))
1014 auto &lowering =
functions[&subroutine];
1018 return lowering.get();
1021 if (!subroutine.thisVar) {
1023 SmallString<64> name;
1025 name += subroutine.name;
1027 SmallVector<Type, 1> noThis = {};
1034 const slang::ast::Type &thisTy = subroutine.thisVar->getType();
1035 moore::ClassDeclOp ownerDecl;
1037 if (
auto *classTy = thisTy.as_if<slang::ast::ClassType>()) {
1038 auto &ownerLowering =
classes[classTy];
1039 ownerDecl = ownerLowering->op;
1041 mlir::emitError(loc) <<
"expected 'this' to be a class type, got "
1042 << thisTy.toString();
1047 SmallString<64> qualName;
1048 qualName += ownerDecl.getSymName();
1050 qualName += subroutine.name;
1053 SmallVector<Type, 1> extraParams;
1055 auto classSym = mlir::FlatSymbolRefAttr::get(ownerDecl.getSymNameAttr());
1056 auto handleTy = moore::ClassHandleType::get(
getContext(), classSym);
1057 extraParams.push_back(handleTy);
1068 const slang::ast::SubroutineSymbol &subroutine,
1069 llvm::SmallVectorImpl<Type> &extraParams) {
1070 using slang::ast::ArgumentDirection;
1072 SmallVector<Type> inputTypes;
1073 inputTypes.append(extraParams.begin(), extraParams.end());
1074 SmallVector<Type, 1> outputTypes;
1076 for (
const auto *arg : subroutine.getArguments()) {
1077 auto type =
context.convertType(arg->getType());
1080 if (arg->direction == ArgumentDirection::In) {
1081 inputTypes.push_back(type);
1083 inputTypes.push_back(
1084 moore::RefType::get(cast<moore::UnpackedType>(type)));
1088 const auto &returnType = subroutine.getReturnType();
1089 if (!returnType.isVoid()) {
1090 auto type =
context.convertType(returnType);
1093 outputTypes.push_back(type);
1097 FunctionType::get(
context.getContext(), inputTypes, outputTypes);
1107 mlir::StringRef qualifiedName,
1108 llvm::SmallVectorImpl<Type> &extraParams) {
1110 std::unique_ptr<FunctionLowering> lowering =
1111 std::make_unique<FunctionLowering>();
1115 OpBuilder::InsertionGuard g(
builder);
1120 builder.setInsertionPoint(it->second);
1125 auto funcOp = mlir::func::FuncOp::create(
builder, loc, qualifiedName, funcTy);
1127 SymbolTable::setSymbolVisibility(funcOp, SymbolTable::Visibility::Private);
1129 lowering->op = funcOp;
1134 functions[&subroutine] = std::move(lowering);
1143 ArrayRef<Value> captures) {
1144 if (captures.empty())
1147 mlir::ModuleOp
module = callee->getParentOfType<mlir::ModuleOp>();
1149 return callee.emitError(
"expected callee to be nested under ModuleOp");
1151 auto usesOpt = mlir::SymbolTable::getSymbolUses(callee, module);
1153 return callee.emitError(
"failed to compute symbol uses");
1156 SmallVector<mlir::func::CallOp, 8> callSites;
1157 callSites.reserve(std::distance(usesOpt->begin(), usesOpt->end()));
1158 for (
const mlir::SymbolTable::SymbolUse &use : *usesOpt) {
1159 if (
auto call = llvm::dyn_cast<mlir::func::CallOp>(use.getUser()))
1160 callSites.push_back(call);
1162 if (callSites.empty())
1165 Block &entry = callee.getBody().front();
1166 const unsigned numCaps = captures.size();
1167 const unsigned numEntryArgs = entry.getNumArguments();
1168 if (numEntryArgs < numCaps)
1169 return callee.emitError(
"entry block has fewer args than captures");
1170 const unsigned capArgStart = numEntryArgs - numCaps;
1173 auto fTy = callee.getFunctionType();
1175 for (
auto call : callSites) {
1176 SmallVector<Value> newOperands(call.getArgOperands().begin(),
1177 call.getArgOperands().end());
1179 const bool inSameFunc = callee->isProperAncestor(call);
1182 for (
unsigned i = 0; i < numCaps; ++i)
1183 newOperands.push_back(entry.getArgument(capArgStart + i));
1186 newOperands.append(captures.begin(), captures.end());
1190 auto flatRef = mlir::FlatSymbolRefAttr::get(callee);
1191 auto newCall = mlir::func::CallOp::create(
1192 b, call.getLoc(), fTy.getResults(), flatRef, newOperands);
1193 call->replaceAllUsesWith(newCall.getOperation());
1206 timeScale = subroutine.getTimeScale().value_or(slang::TimeScale());
1207 llvm::scope_exit timeScaleGuard([&] {
timeScale = prevTimeScale; });
1216 if (lowering->capturesFinalized || lowering->isConverting)
1219 const bool isMethod = (subroutine.thisVar !=
nullptr);
1224 SmallVector<moore::VariableOp> argVariables;
1225 auto &block = lowering->op.getBody().emplaceBlock();
1231 auto thisType = lowering->op.getFunctionType().getInput(0);
1232 auto thisArg = block.addArgument(thisType, thisLoc);
1239 auto inputs = lowering->op.getFunctionType().getInputs();
1240 auto astArgs = subroutine.getArguments();
1241 auto valInputs = llvm::ArrayRef<Type>(inputs).drop_front(isMethod ? 1 : 0);
1243 for (
auto [astArg, type] : llvm::zip(astArgs, valInputs)) {
1245 auto blockArg = block.addArgument(type, loc);
1247 if (isa<moore::RefType>(type)) {
1250 OpBuilder::InsertionGuard g(
builder);
1251 builder.setInsertionPointToEnd(&block);
1253 auto shadowArg = moore::VariableOp::create(
1254 builder, loc, moore::RefType::get(cast<moore::UnpackedType>(type)),
1255 StringAttr{}, blockArg);
1257 argVariables.push_back(shadowArg);
1262 OpBuilder::InsertionGuard g(
builder);
1263 builder.setInsertionPointToEnd(&block);
1266 if (subroutine.returnValVar) {
1267 auto type =
convertType(*subroutine.returnValVar->getDeclaredType());
1270 returnVar = moore::VariableOp::create(
1271 builder, lowering->op.getLoc(),
1272 moore::RefType::get(cast<moore::UnpackedType>(type)), StringAttr{},
1274 valueSymbols.insert(subroutine.returnValVar, returnVar);
1280 llvm::scope_exit prevRCbGuard([&] {
1287 mlir::Value ref = rop.getInput();
1290 mlir::Type ty = ref.getType();
1291 if (!ty || !(isa<moore::RefType>(ty)))
1295 mlir::Region *defReg = ref.getParentRegion();
1296 if (defReg && lowering->op.getBody().isAncestor(defReg))
1300 if (lowering->captureIndex.count(ref))
1304 auto [it, inserted] =
1305 lowering->captureIndex.try_emplace(ref, lowering->captures.size());
1307 lowering->captures.push_back(ref);
1315 mlir::Value dstRef =
1316 llvm::TypeSwitch<mlir::Operation *, mlir::Value>(op)
1317 .Case<moore::BlockingAssignOp, moore::NonBlockingAssignOp,
1318 moore::DelayedNonBlockingAssignOp>(
1319 [](
auto op) {
return op.getDst(); })
1320 .Default([](
auto) -> mlir::Value {
return {}; });
1323 mlir::Type ty = dstRef.getType();
1324 if (!ty || !(isa<moore::RefType>(ty)))
1328 mlir::Region *defReg = dstRef.getParentRegion();
1329 if (defReg && lowering->op.getBody().isAncestor(defReg))
1333 if (lowering->captureIndex.count(dstRef))
1337 auto [it, inserted] =
1338 lowering->captureIndex.try_emplace(dstRef, lowering->captures.size());
1340 lowering->captures.push_back(dstRef);
1349 llvm::scope_exit restoreThis([&] {
currentThisRef = savedThis; });
1351 lowering->isConverting =
true;
1352 llvm::scope_exit convertingGuard([&] { lowering->isConverting =
false; });
1369 if (returnVar && !subroutine.getReturnType().isVoid()) {
1371 moore::ReadOp::create(
builder, returnVar.getLoc(), returnVar);
1372 mlir::func::ReturnOp::create(
builder, lowering->op.getLoc(), read);
1374 mlir::func::ReturnOp::create(
builder, lowering->op.getLoc(),
1378 if (returnVar && returnVar.use_empty())
1379 returnVar.getDefiningOp()->erase();
1381 for (
auto var : argVariables) {
1382 if (llvm::all_of(var->getUsers(),
1383 [](
auto *user) { return isa<moore::ReadOp>(user); })) {
1384 for (
auto *user : llvm::make_early_inc_range(var->getUsers())) {
1385 user->getResult(0).replaceAllUsesWith(var.getInitial());
1392 lowering->capturesFinalized =
true;
1404 SmallVector<Type> newInputs(lowering.
op.getFunctionType().getInputs().begin(),
1405 lowering.
op.getFunctionType().getInputs().end());
1407 for (Value cap : lowering.
captures) {
1409 Type capTy = cap.getType();
1410 if (!isa<moore::RefType>(capTy)) {
1411 return lowering.
op.emitError(
1412 "expected captured value to be a ref-like type");
1414 newInputs.push_back(capTy);
1418 auto newFuncTy = FunctionType::get(
1419 ctx, newInputs, lowering.
op.getFunctionType().getResults());
1420 lowering.
op.setFunctionType(newFuncTy);
1423 Block &entry = lowering.
op.getBody().front();
1424 SmallVector<Value> capArgs;
1425 capArgs.reserve(lowering.
captures.size());
1427 llvm::ArrayRef<Type>(newInputs).take_back(lowering.
captures.size())) {
1428 capArgs.push_back(entry.addArgument(t, lowering.
op.getLoc()));
1434 Value arg = capArgs[idx];
1435 cap.replaceUsesWithIf(arg, [&](OpOperand &use) {
1436 return lowering.
op->isProperAncestor(use.getOwner());
1447mlir::StringAttr fullyQualifiedClassName(
Context &ctx,
1448 const slang::ast::Type &ty) {
1449 SmallString<64> name;
1450 SmallVector<llvm::StringRef, 8> parts;
1452 const slang::ast::Scope *scope = ty.getParentScope();
1454 const auto &sym = scope->asSymbol();
1456 case slang::ast::SymbolKind::Root:
1459 case slang::ast::SymbolKind::InstanceBody:
1460 case slang::ast::SymbolKind::Instance:
1461 case slang::ast::SymbolKind::Package:
1462 case slang::ast::SymbolKind::ClassType:
1463 if (!sym.name.empty())
1464 parts.push_back(sym.name);
1469 scope = sym.getParentScope();
1472 for (
auto p :
llvm::reverse(parts)) {
1477 return mlir::StringAttr::get(ctx.
getContext(), name);
1482std::pair<mlir::SymbolRefAttr, mlir::ArrayAttr>
1484 const slang::ast::ClassType &cls) {
1488 mlir::SymbolRefAttr base;
1489 if (
const auto *b = cls.getBaseClass())
1490 base = mlir::SymbolRefAttr::get(fullyQualifiedClassName(
context, *b));
1493 SmallVector<mlir::Attribute> impls;
1494 if (
auto ifaces = cls.getDeclaredInterfaces(); !ifaces.empty()) {
1495 impls.reserve(ifaces.size());
1496 for (
const auto *iface : ifaces)
1497 impls.push_back(
mlir::FlatSymbolRefAttr::
get(
1498 fullyQualifiedClassName(
context, *iface)));
1501 mlir::ArrayAttr implArr =
1502 impls.empty() ? mlir::ArrayAttr() :
mlir::ArrayAttr::
get(ctx, impls);
1504 return {base, implArr};
1509struct ClassDeclVisitor {
1515 :
context(ctx), builder(ctx.builder), classLowering(lowering) {}
1517 LogicalResult
run(
const slang::ast::ClassType &classAST) {
1518 if (!classLowering.
op.getBody().empty())
1521 OpBuilder::InsertionGuard ig(builder);
1523 Block *body = &classLowering.
op.getBody().emplaceBlock();
1524 builder.setInsertionPointToEnd(body);
1526 llvm::SmallVector<const slang::ast::Symbol *, 8> delayedSymbols;
1529 for (
const auto &mem : classAST.members()) {
1530 if (
const auto *proto = mem.as_if<slang::ast::ClassPropertySymbol>()) {
1531 if (failed(proto->visit(*
this)))
1535 delayedSymbols.push_back(&mem);
1541 for (
const auto *sym : delayedSymbols) {
1542 if (failed(sym->visit(*
this)))
1550 LogicalResult visit(
const slang::ast::ClassPropertySymbol &prop) {
1552 auto ty =
context.convertType(prop.getType());
1556 if (prop.lifetime == slang::ast::VariableLifetime::Automatic) {
1557 moore::ClassPropertyDeclOp::create(builder, loc, prop.name, ty);
1565 if (!
context.globalVariables.lookup(&prop))
1566 return context.convertGlobalVariable(prop);
1572 LogicalResult visit(
const slang::ast::ParameterSymbol &) {
return success(); }
1576 LogicalResult visit(
const slang::ast::TypeParameterSymbol &) {
1582 LogicalResult visit(
const slang::ast::TypeAliasType &) {
return success(); }
1585 LogicalResult visit(
const slang::ast::SubroutineSymbol &fn) {
1586 if (fn.flags & slang::ast::MethodFlags::BuiltIn) {
1587 static bool remarkEmitted =
false;
1591 mlir::emitRemark(classLowering.
op.getLoc())
1592 <<
"Class builtin functions (needed for randomization, constraints, "
1593 "and covergroups) are not yet supported and will be dropped "
1595 remarkEmitted =
true;
1599 const mlir::UnitAttr isVirtual =
1600 (fn.flags & slang::ast::MethodFlags::Virtual)
1601 ? UnitAttr::get(
context.getContext())
1608 if (fn.flags & slang::ast::MethodFlags::Pure) {
1610 SmallVector<Type, 1> extraParams;
1612 mlir::FlatSymbolRefAttr::get(classLowering.
op.getSymNameAttr());
1614 moore::ClassHandleType::get(
context.getContext(), classSym);
1615 extraParams.push_back(handleTy);
1619 mlir::emitError(loc) <<
"Invalid function signature for " << fn.name;
1623 moore::ClassMethodDeclOp::create(builder, loc, fn.name, funcTy,
nullptr);
1627 auto *lowering =
context.declareFunction(fn);
1631 if (failed(
context.convertFunction(fn)))
1634 if (!lowering->capturesFinalized)
1642 FunctionType fnTy = lowering->op.getFunctionType();
1644 moore::ClassMethodDeclOp::create(builder, loc, fn.name, fnTy,
1645 SymbolRefAttr::get(lowering->op));
1662 LogicalResult visit(
const slang::ast::MethodPrototypeSymbol &fn) {
1663 const auto *externImpl = fn.getSubroutine();
1667 <<
"Didn't find an implementation matching the forward declaration "
1672 return visit(*externImpl);
1676 LogicalResult visit(
const slang::ast::GenericClassDefSymbol &) {
1681 LogicalResult visit(
const slang::ast::ClassType &cls) {
1682 return context.convertClassDeclaration(cls);
1686 LogicalResult visit(
const slang::ast::TransparentMemberSymbol &) {
1691 LogicalResult visit(
const slang::ast::EmptyMemberSymbol &) {
1696 template <
typename T>
1697 LogicalResult visit(T &&node) {
1698 Location loc = UnknownLoc::get(
context.getContext());
1699 if constexpr (
requires { node.location; })
1701 mlir::emitError(loc) <<
"unsupported construct in ClassType members: "
1702 << slang::ast::toString(node.kind);
1708 return context.convertLocation(sloc);
1715 auto &lowering =
classes[&cls];
1717 return lowering.get();
1718 lowering = std::make_unique<ClassLowering>();
1723 OpBuilder::InsertionGuard g(
builder);
1728 builder.setInsertionPoint(it->second);
1730 auto symName = fullyQualifiedClassName(*
this, cls);
1733 if (
const auto *maybeBaseClass = cls.getBaseClass())
1734 if (
const auto *baseClass = maybeBaseClass->as_if<slang::ast::ClassType>())
1735 if (!
classes.contains(baseClass) &&
1737 mlir::emitError(loc) <<
"Failed to convert base class "
1738 << baseClass->name <<
" of class " << cls.name;
1742 auto [base, impls] = buildBaseAndImplementsAttrs(*
this, cls);
1744 moore::ClassDeclOp::create(
builder, loc, symName, base, impls);
1746 SymbolTable::setSymbolVisibility(classDeclOp,
1747 SymbolTable::Visibility::Public);
1749 lowering->op = classDeclOp;
1752 return lowering.get();
1760 timeScale = classdecl.getTimeScale().value_or(slang::TimeScale());
1761 llvm::scope_exit timeScaleGuard([&] {
timeScale = prevTimeScale; });
1764 if (
classes.contains(&classdecl))
1767 if (classdecl.getBaseClass()) {
1768 if (
const auto *baseClassDecl =
1769 classdecl.getBaseClass()->as_if<slang::ast::ClassType>()) {
1776 if (failed(ClassDeclVisitor(*
this, *lowering).run(classdecl)))
1789 OpBuilder::InsertionGuard g(
builder);
1794 builder.setInsertionPoint(it->second);
1798 SmallString<64> symName;
1802 if (
const auto *classVar = var.as_if<slang::ast::ClassPropertySymbol>()) {
1803 if (
const auto *parentScope = classVar->getParentScope()) {
1804 if (
const auto *parentClass =
1805 parentScope->asSymbol().as_if<slang::ast::ClassType>())
1806 symName = fullyQualifiedClassName(*
this, *parentClass);
1808 mlir::emitError(loc)
1809 <<
"Could not access parent class of class property "
1814 mlir::emitError(loc) <<
"Could not get parent scope of class property "
1819 symName += var.name;
1822 symName += var.name;
1831 auto varOp = moore::GlobalVariableOp::create(
builder, loc, symName,
1832 cast<moore::UnpackedType>(type));
1839 if (var.getInitializer())
assert(baseType &&"element must be base type")
static std::unique_ptr< Context > context
static FIRRTLBaseType convertType(FIRRTLBaseType type)
Returns null type if no conversion is needed.
static Location convertLocation(MLIRContext *context, const slang::SourceManager &sourceManager, slang::SourceLocation loc)
Convert a slang SourceLocation to an MLIR Location.
static Location getLoc(DefSlot slot)
static moore::ProcedureKind convertProcedureKind(slang::ast::ProceduralBlockKind kind)
static FunctionType getFunctionSignature(Context &context, const slang::ast::SubroutineSymbol &subroutine, llvm::SmallVectorImpl< Type > &extraParams)
Helper function to generate the function signature from a SubroutineSymbol and optional extra argumen...
static void guessNamespacePrefix(const slang::ast::Symbol &symbol, SmallString< 64 > &prefix)
static LogicalResult rewriteCallSitesToPassCaptures(mlir::func::FuncOp callee, ArrayRef< Value > captures)
Special case handling for recursive functions with captures; this function fixes the in-body call of ...
static moore::NetKind convertNetKind(slang::ast::NetType::NetKind kind)
Direction get(bool isOutput)
Returns an output direction if isOutput is true, otherwise returns an input direction.
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
int run(Type[Generator] generator=CppGenerator, cmdline_args=sys.argv)
bool debugInfo
Generate debug information in the form of debug dialect ops in the IR.
circt::moore::ClassDeclOp op
A helper class to facilitate the conversion from a Slang AST to MLIR operations.
LogicalResult convertFunction(const slang::ast::SubroutineSymbol &subroutine)
Convert a function.
FunctionLowering * declareCallableImpl(const slang::ast::SubroutineSymbol &subroutine, mlir::StringRef qualifiedName, llvm::SmallVectorImpl< Type > &extraParams)
Helper function to extract the commonalities in lowering of functions and methods.
ModuleLowering * convertModuleHeader(const slang::ast::InstanceBodySymbol *module)
Convert a module and its ports to an empty module op in the IR.
Value materializeConstant(const slang::ConstantValue &constant, const slang::ast::Type &type, Location loc)
Helper function to materialize a ConstantValue as an SSA value.
LogicalResult convertModuleBody(const slang::ast::InstanceBodySymbol *module)
Convert a module's body to the corresponding IR ops.
LogicalResult convertClassDeclaration(const slang::ast::ClassType &classdecl)
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.
std::queue< const slang::ast::InstanceBodySymbol * > moduleWorklist
A list of modules for which the header has been created, but the body has not been converted yet.
LogicalResult convertGlobalVariable(const slang::ast::VariableSymbol &var)
Convert a variable to a moore.global_variable operation.
DenseMap< const slang::ast::ClassType *, std::unique_ptr< ClassLowering > > classes
Classes that have already been converted.
std::function< void(moore::ReadOp)> rvalueReadCallback
A listener called for every variable or net being read.
std::map< slang::SourceLocation, Operation * > orderedRootOps
The top-level operations ordered by their Slang source location.
Type convertType(const slang::ast::Type &type, LocationAttr loc={})
Convert a slang type into an MLIR type.
DenseMap< const slang::ast::SubroutineSymbol *, std::unique_ptr< FunctionLowering > > functions
Functions that have already been converted.
slang::TimeScale timeScale
The time scale currently in effect.
LogicalResult finalizeFunctionBodyCaptures(FunctionLowering &lowering)
ClassLowering * declareClass(const slang::ast::ClassType &cls)
ValueSymbols valueSymbols
std::function< void(mlir::Operation *)> variableAssignCallback
A listener called for every variable or net being assigned.
ValueSymbols::ScopeTy ValueSymbolScope
const ImportVerilogOptions & options
Value convertRvalueExpression(const slang::ast::Expression &expr, Type requiredType={})
LogicalResult traverseInstanceBody(const slang::ast::Symbol &symbol)
Value currentThisRef
Variable to track the value of the current function's implicit this reference.
mlir::ModuleOp intoModuleOp
SymbolTable symbolTable
A symbol table of the MLIR module we are emitting into.
DenseMap< const slang::ast::InstanceBodySymbol *, SmallVector< HierPathInfo > > hierPaths
Collect all hierarchical names used for the per module/instance.
FunctionLowering * declareFunction(const slang::ast::SubroutineSymbol &subroutine)
Convert a function and its arguments to a function declaration in the IR.
LogicalResult convertPackage(const slang::ast::PackageSymbol &package)
Convert a package and its contents.
MLIRContext * getContext()
Return the MLIR context.
LogicalResult convertStatement(const slang::ast::Statement &stmt)
SmallVector< const slang::ast::ValueSymbol * > globalVariableWorklist
A list of global variables that still need their initializers to be converted.
DenseMap< const slang::ast::InstanceBodySymbol *, std::unique_ptr< ModuleLowering > > modules
How we have lowered modules to MLIR.
Location convertLocation(slang::SourceLocation loc)
Convert a slang SourceLocation into an MLIR Location.
Function lowering information.
llvm::DenseMap< Value, unsigned > captureIndex
llvm::SmallVector< Value, 4 > captures
Module lowering information.