26#include "mlir/IR/Builders.h"
27#include "mlir/IR/BuiltinOps.h"
28#include "mlir/IR/DialectImplementation.h"
29#include "mlir/IR/ImplicitLocOpBuilder.h"
30#include "mlir/IR/Threading.h"
31#include "mlir/IR/Visitors.h"
32#include "mlir/Pass/Pass.h"
33#include "mlir/Transforms/DialectConversion.h"
34#include "llvm/ADT/Twine.h"
36#define DEBUG_TYPE "lower-sim-to-sv"
39#define GEN_PASS_DEF_LOWERSIMTOSV
40#include "circt/Conversion/Passes.h.inc"
50 return isa<ClockedTerminateOp, ClockedPauseOp, TerminateOp, PauseOp>(op);
56 return TypeSwitch<Operation *, std::pair<Value, Value>>(op)
57 .Case<ClockedTerminateOp, ClockedPauseOp>(
58 [](
auto op) -> std::pair<Value, Value> {
59 return {op.getClock(), op.getCondition()};
66struct SimConversionState {
68 bool usedSynthesisMacro =
false;
69 bool usedFileDescriptorRuntime =
false;
70 SetVector<StringAttr> dpiCallees;
73struct SimTypeConverter :
public TypeConverter {
74 explicit SimTypeConverter(MLIRContext *
context) {
75 addConversion([](Type type) {
return type; });
76 addConversion([&](OutputStreamType type) -> Type {
77 return IntegerType::get(type.getContext(), 32);
84 explicit SimConversionPattern(MLIRContext *
context, SimConversionState &state)
87 SimConversionState &state;
91DPIFunctionTypeToHWModuleType(
const DPIFunctionType &dpiFuncType) {
92 SmallVector<hw::ModulePort> hwPorts;
93 for (
auto &arg : dpiFuncType.getArguments()) {
96 case DPIDirection::Input:
97 case DPIDirection::Ref:
98 hwDir = hw::ModulePort::Direction::Input;
100 case DPIDirection::Output:
101 case DPIDirection::Return:
102 hwDir = hw::ModulePort::Direction::Output;
104 case DPIDirection::InOut:
105 hwDir = hw::ModulePort::Direction::InOut;
108 hwPorts.push_back({arg.name, arg.type, hwDir});
110 return hw::ModuleType::get(dpiFuncType.getContext(), hwPorts);
118 using SimConversionPattern<PlusArgsTestOp>::SimConversionPattern;
122 ConversionPatternRewriter &rewriter)
const final {
123 auto loc = op.getLoc();
124 auto resultType = rewriter.getIntegerType(1);
125 auto str = sv::ConstantStrOp::create(rewriter, loc, op.getFormatString());
126 auto reg = sv::RegOp::create(rewriter, loc, resultType,
127 rewriter.getStringAttr(
"_pargs"));
128 sv::InitialOp::create(rewriter, loc, [&] {
129 auto call = sv::SystemFunctionOp::create(
130 rewriter, loc, resultType,
"test$plusargs", ArrayRef<Value>{str});
131 sv::BPAssignOp::create(rewriter, loc, reg, call);
143 using SimConversionPattern<PlusArgsValueOp>::SimConversionPattern;
147 ConversionPatternRewriter &rewriter)
const final {
148 auto loc = op.getLoc();
150 auto i1ty = rewriter.getIntegerType(1);
151 auto type = op.getResult().getType();
154 rewriter.getStringAttr(
"_pargs_v"));
156 rewriter.getStringAttr(
"_pargs_f"));
158 state.usedSynthesisMacro =
true;
160 rewriter, loc,
"SYNTHESIS",
163 auto cstZ = sv::ConstantZOp::create(rewriter, loc, type);
167 sv::SVAttributeAttr::get(
168 rewriter.getContext(),
169 "This dummy assignment exists to avoid undriven lint "
170 "warnings (e.g., Verilator UNDRIVEN).",
175 auto i32ty = rewriter.getIntegerType(32);
176 auto regf = sv::RegOp::create(rewriter, loc, i32ty,
177 rewriter.getStringAttr(
"_found"));
178 auto regv = sv::RegOp::create(rewriter, loc, type,
179 rewriter.getStringAttr(
"_value"));
180 sv::InitialOp::create(rewriter, loc, [&] {
182 sv::ConstantStrOp::create(rewriter, loc, op.getFormatString());
183 auto call = sv::SystemFunctionOp::create(
184 rewriter, loc, i32ty,
"value$plusargs",
185 ArrayRef<Value>{str, regv});
186 sv::BPAssignOp::create(rewriter, loc, regf, call);
192 auto cmp = comb::ICmpOp::create(
193 rewriter, loc, comb::ICmpPredicate::ceq, readRegF, cstTrue);
201 rewriter.replaceOp(op, {readf, readv});
206template <
typename OpTy,
unsigned StreamValue>
214 ConversionPatternRewriter &rewriter)
const final {
217 rewriter.replaceOp(op, streamValue);
233 ConversionPatternRewriter &rewriter)
const final {
234 SmallVector<Type> convertedResultTypes;
235 if (failed(typeConverter->convertTypes(op.getResultTypes(),
236 convertedResultTypes)))
239 if (!llvm::equal(convertedResultTypes, adaptor.getOperands().getTypes()))
242 rewriter.replaceOp(op, adaptor.getOperands());
247static LogicalResult
convert(ClockedTerminateOp op, PatternRewriter &rewriter) {
249 rewriter.replaceOpWithNewOp<sv::FinishOp>(op, op.getVerbose());
251 rewriter.replaceOpWithNewOp<sv::FatalProceduralOp>(op, op.getVerbose());
255static LogicalResult
convert(ClockedPauseOp op, PatternRewriter &rewriter) {
256 rewriter.replaceOpWithNewOp<sv::StopOp>(op, op.getVerbose());
260static LogicalResult
convert(TerminateOp op, PatternRewriter &rewriter) {
262 rewriter.replaceOpWithNewOp<sv::FinishOp>(op, op.getVerbose());
264 rewriter.replaceOpWithNewOp<sv::FatalProceduralOp>(op, op.getVerbose());
268static LogicalResult
convert(PauseOp op, PatternRewriter &rewriter) {
269 rewriter.replaceOpWithNewOp<sv::StopOp>(op, op.getVerbose());
275 using SimConversionPattern<TriggeredOp>::SimConversionPattern;
279 ConversionPatternRewriter &rewriter)
const final {
280 auto loc = op.getLoc();
281 state.usedSynthesisMacro =
true;
284 rewriter, loc,
"SYNTHESIS", [] {},
287 seq::FromClockOp::create(rewriter, loc, adaptor.getClock());
288 auto alwaysOp = sv::AlwaysOp::create(
290 ArrayRef<sv::EventControl>{sv::EventControl::AtPosEdge},
291 ArrayRef<Value>{trigger});
293 Block *destination = alwaysOp.getBodyBlock();
294 if (
auto condition = adaptor.getCondition()) {
295 rewriter.setInsertionPointToStart(destination);
296 destination = sv::IfOp::create(rewriter, loc, condition, [] {
300 rewriter.mergeBlocks(op.getBodyBlock(), destination);
302 rewriter.eraseOp(op);
309 using SimConversionPattern<DPICallOp>::SimConversionPattern;
313 ConversionPatternRewriter &rewriter)
const final {
314 auto loc = op.getLoc();
316 state.dpiCallees.insert(op.getCalleeAttr().getAttr());
318 bool isClockedCall = !!op.getClock();
319 bool hasEnable = !!op.getEnable();
321 SmallVector<sv::RegOp> temporaries;
322 SmallVector<Value> reads;
323 for (
auto [type, result] :
324 llvm::zip(op.getResultTypes(), op.getResults())) {
325 temporaries.push_back(sv::RegOp::create(rewriter, op.getLoc(), type));
330 auto emitCall = [&]() {
331 auto call = sv::FuncCallProceduralOp::create(
332 rewriter, op.getLoc(), op.getResultTypes(), op.getCalleeAttr(),
333 adaptor.getInputs());
334 for (
auto [lhs, rhs] : llvm::zip(temporaries, call.getResults())) {
336 sv::PAssignOp::create(rewriter, op.getLoc(), lhs, rhs);
338 sv::BPAssignOp::create(rewriter, op.getLoc(), lhs, rhs);
343 seq::FromClockOp::create(rewriter, loc, adaptor.getClock());
344 sv::AlwaysOp::create(
346 ArrayRef<sv::EventControl>{sv::EventControl::AtPosEdge},
347 ArrayRef<Value>{clockCast}, [&]() {
350 sv::IfOp::create(rewriter, op.getLoc(), adaptor.getEnable(),
357 sv::AlwaysCombOp::create(rewriter, loc, [&]() {
360 auto assignXToResults = [&] {
361 for (
auto lhs : temporaries) {
362 auto xValue = sv::ConstantXOp::create(
363 rewriter, op.getLoc(), lhs.getType().getElementType());
364 sv::BPAssignOp::create(rewriter, op.getLoc(), lhs, xValue);
367 sv::IfOp::create(rewriter, op.getLoc(), adaptor.getEnable(), emitCall,
372 rewriter.replaceOp(op, reads);
382 void lower(sim::DPIFuncOp func);
386 sim::DPIFuncOp func) {
388 SmallVector<Attribute> convertedAttrs;
389 auto dpiType = func.getDpiFunctionType();
390 auto dpiArgs = dpiType.getArguments();
391 convertedAttrs.reserve(dpiArgs.size());
392 for (
auto &arg : dpiArgs) {
393 NamedAttrList newAttrs;
394 if (arg.dir == sim::DPIDirection::Return)
396 builder.getStringAttr(sv::FuncOp::getExplicitlyReturnedAttrName()),
397 builder.getUnitAttr());
398 convertedAttrs.push_back(newAttrs.getDictionary(
context));
400 return ArrayAttr::get(
context, convertedAttrs);
404 ImplicitLocOpBuilder builder(func.getLoc(), func);
405 ArrayAttr inputLocsAttr, outputLocsAttr;
408 auto moduleType = DPIFunctionTypeToHWModuleType(func.getDpiFunctionType());
410 if (func.getArgumentLocs()) {
411 SmallVector<Attribute> inputLocs, outputLocs;
412 auto hwPorts = moduleType.getPorts();
413 for (
auto [port, loc] : llvm::zip(
414 hwPorts, func.getArgumentLocsAttr().getAsRange<LocationAttr>())) {
418 inputLocsAttr = builder.getArrayAttr(inputLocs);
419 outputLocsAttr = builder.getArrayAttr(outputLocs);
422 auto svFuncDecl = sv::FuncOp::create(
423 builder, func.getSymNameAttr(), moduleType,
425 outputLocsAttr, func.getVerilogNameAttr());
427 svFuncDecl.setPrivate();
429 func.getSymNameAttr().getValue(),
"dpi_import_fragument"));
432 auto macroDecl = sv::MacroDeclOp::create(
434 func.getSymNameAttr().getValue().upper()));
435 emit::FragmentOp::create(builder, name, [&]() {
437 builder, macroDecl.getSymNameAttr(), []() {},
439 sv::FuncDPIImportOp::create(builder, func.getSymNameAttr(),
441 sv::MacroDefOp::create(builder, macroDecl.getSymNameAttr(),
"");
451 const llvm::DenseMap<StringAttr, StringAttr> &symbolToFragment,
452 const SimConversionState &state) {
453 llvm::SetVector<Attribute> fragments;
455 if (
auto exstingFragments =
456 module->getAttrOfType<ArrayAttr>(emit::getFragmentsAttrName()))
457 for (
auto fragment : exstingFragments.getAsRange<FlatSymbolRefAttr>())
458 fragments.insert(fragment);
459 for (
auto callee : state.dpiCallees) {
460 auto attr = symbolToFragment.at(callee);
461 fragments.insert(FlatSymbolRefAttr::get(attr));
463 if (state.usedFileDescriptorRuntime)
464 fragments.insert(sv::getFileDescriptorFragmentRef(module.getContext()));
465 if (!fragments.empty())
467 emit::getFragmentsAttrName(),
468 ArrayAttr::get(module.getContext(), fragments.takeVector()));
472 bool usedSynthesisMacro =
false;
474 rootOp->walk<WalkOrder::PreOrder>([&](Operation *op) {
478 if (isa<TriggeredOp>(op))
479 return WalkResult::skip();
481 auto loc = op->getLoc();
486 Block *block =
nullptr;
487 if (op->getPrevNode())
488 block = TypeSwitch<Operation *, Block *>(op->getPrevNode())
489 .Case<sv::IfDefOp, sv::IfDefProceduralOp>(
490 [&](
auto guardOp) -> Block * {
491 if (guardOp.getCond().getIdent().getAttr() ==
494 return guardOp.getElseBlock();
497 .Default([](
auto) {
return nullptr; });
501 OpBuilder builder(op);
503 block = sv::IfDefProceduralOp::create(
504 builder, loc,
"SYNTHESIS", [] {}, [] {})
507 block = sv::IfDefOp::create(
508 builder, loc,
"SYNTHESIS", [] {}, [] {})
510 usedSynthesisMacro =
true;
514 op->moveBefore(block, block->end());
523 Block *block =
nullptr;
524 if (
auto alwaysOp = dyn_cast_or_null<sv::AlwaysOp>(op->getPrevNode()))
525 if (alwaysOp.getNumConditions() == 1 &&
526 alwaysOp.getCondition(0).event == sv::EventControl::AtPosEdge)
527 if (
auto clockOp = alwaysOp.getCondition(0)
528 .value.getDefiningOp<seq::FromClockOp>())
529 if (clockOp.getInput() == clock)
530 block = alwaysOp.getBodyBlock();
534 OpBuilder builder(op);
535 clock = seq::FromClockOp::create(builder, loc, clock);
536 block = sv::AlwaysOp::create(builder, loc, sv::EventControl::AtPosEdge,
542 op->moveBefore(block, block->end());
548 Block *block =
nullptr;
549 if (
auto ifOp = dyn_cast_or_null<sv::IfOp>(op->getPrevNode()))
550 if (ifOp.getCond() == condition)
551 block = ifOp.getThenBlock();
555 OpBuilder builder(op);
556 block = sv::IfOp::create(builder, loc, condition, [] {}).getThenBlock();
560 op->moveBefore(block, block->end());
562 return WalkResult::advance();
565 return usedSynthesisMacro;
570void appendLiteralToSVFormat(SmallString<128> &formatString,
572 for (
char ch : literal) {
574 formatString +=
"%%";
576 formatString.push_back(ch);
580LogicalResult appendIntegerSpecifier(SmallString<128> &formatString,
581 bool isLeftAligned, uint8_t paddingChar,
582 std::optional<int32_t> width,
char spec) {
583 formatString.push_back(
'%');
585 formatString.push_back(
'-');
589 if (paddingChar ==
'0')
590 formatString.push_back(
'0');
591 else if (paddingChar !=
' ')
594 if (width.has_value())
595 llvm::Twine(width.value()).toVector(formatString);
597 formatString.push_back(spec);
601void appendFloatSpecifier(SmallString<128> &formatString,
bool isLeftAligned,
602 std::optional<int32_t> fieldWidth, int32_t fracDigits,
604 formatString.push_back(
'%');
606 formatString.push_back(
'-');
607 if (fieldWidth.has_value())
608 llvm::Twine(fieldWidth.value()).toVector(formatString);
609 formatString.push_back(
'.');
610 llvm::Twine(fracDigits).toVector(formatString);
611 formatString.push_back(spec);
614LogicalResult getFlattenedFormatFragments(Value input,
615 SmallVectorImpl<Value> &fragments) {
616 if (
auto concat = input.getDefiningOp<FormatStringConcatOp>()) {
617 if (failed(concat.getFlattenedInputs(fragments)))
618 return mlir::emitError(input.getLoc(),
619 "cyclic sim.fmt.concat is unsupported");
623 fragments.push_back(input);
627LogicalResult appendFormatFragmentToSVFormat(Value fragment,
628 SmallString<128> &formatString,
629 SmallVectorImpl<Value> &args,
630 OpBuilder &builder) {
631 Operation *fragmentOp = fragment.getDefiningOp();
633 return mlir::emitError(fragment.getLoc(),
634 "block argument format strings are unsupported");
636 return TypeSwitch<Operation *, LogicalResult>(fragmentOp)
637 .Case<FormatLiteralOp>([&](
auto literal) -> LogicalResult {
638 appendLiteralToSVFormat(formatString, literal.getLiteral());
641 .Case<FormatCurrentTimeOp>([&](
auto fmt) -> LogicalResult {
642 formatString +=
"%0t";
643 args.push_back(sv::TimeOp::create(builder, fmt.getLoc()));
646 .Case<FormatHierPathOp>([&](
auto hierPath) -> LogicalResult {
647 formatString += hierPath.getUseEscapes() ?
"%M" :
"%m";
650 .Case<FormatCharOp>([&](
auto fmt) -> LogicalResult {
651 formatString +=
"%c";
652 args.push_back(fmt.getValue());
655 .Case<FormatDecOp>([&](
auto fmt) -> LogicalResult {
656 if (failed(appendIntegerSpecifier(formatString, fmt.getIsLeftAligned(),
657 fmt.getPaddingChar(),
658 fmt.getSpecifierWidth(),
'd'))) {
659 return mlir::emitError(fmt.getLoc())
660 <<
"sim.fmt.dec only supports paddingChar 32 (' ') or 48 "
664 if (fmt.getIsSigned()) {
665 auto signedValue = sv::SystemFunctionOp::create(
666 builder, fmt.getLoc(), fmt.getValue().getType(),
"signed",
667 ValueRange{fmt.getValue()});
668 args.push_back(signedValue);
670 auto unsignedValue = sv::SystemFunctionOp::create(
671 builder, fmt.getLoc(), fmt.getValue().getType(),
"unsigned",
672 ValueRange{fmt.getValue()});
673 args.push_back(unsignedValue);
677 .Case<FormatHexOp>([&](
auto fmt) -> LogicalResult {
678 if (failed(appendIntegerSpecifier(
679 formatString, fmt.getIsLeftAligned(), fmt.getPaddingChar(),
680 fmt.getSpecifierWidth(),
681 fmt.getIsHexUppercase() ?
'X' :
'x'))) {
682 return mlir::emitError(fmt.getLoc())
683 <<
"sim.fmt.hex only supports paddingChar 32 (' ') or 48 "
686 args.push_back(fmt.getValue());
689 .Case<FormatOctOp>([&](
auto fmt) -> LogicalResult {
690 if (failed(appendIntegerSpecifier(formatString, fmt.getIsLeftAligned(),
691 fmt.getPaddingChar(),
692 fmt.getSpecifierWidth(),
'o'))) {
693 return mlir::emitError(fmt.getLoc())
694 <<
"sim.fmt.oct only supports paddingChar 32 (' ') or 48 "
697 args.push_back(fmt.getValue());
700 .Case<FormatBinOp>([&](
auto fmt) -> LogicalResult {
701 if (failed(appendIntegerSpecifier(formatString, fmt.getIsLeftAligned(),
702 fmt.getPaddingChar(),
703 fmt.getSpecifierWidth(),
'b'))) {
704 return mlir::emitError(fmt.getLoc())
705 <<
"sim.fmt.bin only supports paddingChar 32 (' ') or 48 "
708 args.push_back(fmt.getValue());
711 .Case<FormatScientificOp>([&](
auto fmt) -> LogicalResult {
712 appendFloatSpecifier(formatString, fmt.getIsLeftAligned(),
713 fmt.getFieldWidth(), fmt.getFracDigits(),
'e');
714 args.push_back(fmt.getValue());
717 .Case<FormatFloatOp>([&](
auto fmt) -> LogicalResult {
718 appendFloatSpecifier(formatString, fmt.getIsLeftAligned(),
719 fmt.getFieldWidth(), fmt.getFracDigits(),
'f');
720 args.push_back(fmt.getValue());
723 .Case<FormatGeneralOp>([&](
auto fmt) -> LogicalResult {
724 appendFloatSpecifier(formatString, fmt.getIsLeftAligned(),
725 fmt.getFieldWidth(), fmt.getFracDigits(),
'g');
726 args.push_back(fmt.getValue());
729 .Default([&](
auto unsupportedOp) {
730 return mlir::emitError(unsupportedOp->getLoc())
731 <<
"unsupported format fragment '"
732 << unsupportedOp->getName().getStringRef() <<
"'";
736LogicalResult lowerFormatStringToSVFormat(Value input,
737 SmallString<128> &formatString,
738 SmallVectorImpl<Value> &args,
739 OpBuilder &builder) {
740 SmallVector<Value, 8> fragments;
741 if (failed(getFlattenedFormatFragments(input, fragments)))
743 for (
auto fragment : fragments)
744 if (failed(appendFormatFragmentToSVFormat(fragment, formatString, args,
750FailureOr<Value> createFileDescriptorGetterForGetFile(GetFileOp getFileOp,
751 OpBuilder &builder) {
752 SmallString<128> formatString;
753 SmallVector<Value> args;
754 if (failed(lowerFormatStringToSVFormat(getFileOp.getFileName(), formatString,
756 getFileOp.emitError(
"cannot lower 'sim.get_file' to SystemVerilog")
757 .attachNote(getFileOp.getFileName().getLoc())
758 <<
"while lowering file name";
764 ? sv::ConstantStrOp::create(builder, getFileOp.getLoc(),
765 builder.getStringAttr(formatString))
767 : sv::SFormatFOp::create(builder, getFileOp.getLoc(),
768 builder.getStringAttr(formatString), args)
771 return sv::createProceduralFileDescriptorGetterCall(
772 builder, getFileOp.getLoc(), fileName);
775static void cleanupDeadSimFmtOps(ArrayRef<Operation *> seedOps) {
776 auto filter = [](Operation *op, OpOperand &operand) {
777 return isa<FormatStringType>(operand.get().getType()) &&
778 isa_and_present<SimDialect>(op->getDialect());
783 assert(sccs.getNumCyclicSCCs() == 0 &&
784 "Cyclic graph should have been rejected");
786 for (
OpSCC entry : sccs.reverseTopological()) {
787 auto *op = cast<Operation *>(entry);
791 op->emitWarning(
"sim format/stream op still has users after lowering; "
792 "dialect conversion will fail");
797 const TypeConverter &typeConverter,
798 SimConversionState &state) {
799 SmallVector<GetFileOp> getFileOps;
800 SmallVector<PrintFormattedProcOp> printOps;
801 SmallVector<Operation *, 8> cleanupSeeds;
802 module.walk([&](Operation *op) {
803 if (auto getFileOp = dyn_cast<GetFileOp>(op))
804 getFileOps.push_back(getFileOp);
805 if (
auto printOp = dyn_cast<PrintFormattedProcOp>(op))
806 printOps.push_back(printOp);
809 for (
auto getFileOp : getFileOps) {
810 OpBuilder builder(getFileOp);
811 auto fdOrFailure = createFileDescriptorGetterForGetFile(getFileOp, builder);
812 if (failed(fdOrFailure))
815 auto stream = mlir::UnrealizedConversionCastOp::create(
816 builder, getFileOp.getLoc(), getFileOp.getResult().getType(),
818 getFileOp.replaceAllUsesWith(stream.getResult(0));
819 state.usedFileDescriptorRuntime =
true;
820 state.usedSynthesisMacro =
true;
821 cleanupSeeds.push_back(getFileOp);
824 for (
auto printOp : printOps) {
825 OpBuilder builder(printOp);
826 SmallString<128> formatString;
827 SmallVector<Value> args;
828 if (failed(lowerFormatStringToSVFormat(printOp.getInput(), formatString,
830 printOp.emitError(
"cannot lower 'sim.proc.print' to SystemVerilog")
831 .attachNote(printOp.getInput().getLoc())
832 <<
"while lowering format string";
835 auto stream = printOp.getStream();
838 sv::WriteOp::create(builder, printOp.getLoc(), formatString, args);
840 auto fdType = typeConverter.convertType(stream.getType());
841 assert(fdType &&
"expected output stream type conversion");
842 Value fd = mlir::UnrealizedConversionCastOp::create(
843 builder, printOp.getLoc(), fdType, stream)
845 sv::FWriteOp::create(builder, printOp.getLoc(), fd, formatString, args);
847 cleanupSeeds.push_back(printOp);
850 cleanupDeadSimFmtOps(cleanupSeeds);
855struct SimToSVPass :
public circt::impl::LowerSimToSVBase<SimToSVPass> {
856 void runOnOperation()
override {
857 auto circuit = getOperation();
858 MLIRContext *
context = &getContext();
863 llvm::make_early_inc_range(circuit.getOps<
sim::DPIFuncOp>()))
864 lowerDPIFunc.lower(func);
866 std::atomic<bool> usedSynthesisMacro =
false;
867 std::atomic<bool> usedFileDescriptorRuntime =
false;
869 SimTypeConverter typeConverter(
context);
870 SimConversionState state;
872 if (failed(lowerPrintFormattedProcToSV(module, typeConverter, state)))
876 usedSynthesisMacro =
true;
878 ConversionTarget target(*
context);
879 target.addIllegalDialect<SimDialect>();
880 target.addLegalDialect<sv::SVDialect>();
881 target.addLegalDialect<hw::HWDialect>();
882 target.addLegalDialect<seq::SeqDialect>();
883 target.addLegalDialect<comb::CombDialect>();
884 target.addDynamicallyLegalOp<mlir::UnrealizedConversionCastOp>(
885 [&](mlir::UnrealizedConversionCastOp op) {
886 return typeConverter.isLegal(op);
901 auto result = applyPartialConversion(module, target, std::move(
patterns));
907 addFragments(module, lowerDPIFunc.symbolToFragment, state);
909 if (state.usedSynthesisMacro)
910 usedSynthesisMacro =
true;
911 if (state.usedFileDescriptorRuntime)
912 usedFileDescriptorRuntime =
true;
916 if (failed(mlir::failableParallelForEach(
918 return signalPassFailure();
920 if (usedSynthesisMacro) {
921 Operation *op = circuit.lookupSymbol(
"SYNTHESIS");
923 if (!isa<sv::MacroDeclOp>(op)) {
924 op->emitOpError(
"should be a macro declaration");
925 return signalPassFailure();
928 auto builder = ImplicitLocOpBuilder::atBlockBegin(
929 UnknownLoc::get(
context), circuit.getBody());
930 sv::MacroDeclOp::create(builder,
"SYNTHESIS");
934 if (usedFileDescriptorRuntime) {
935 auto builder = ImplicitLocOpBuilder::atBlockBegin(
936 UnknownLoc::get(
context), circuit.getBody());
937 sv::emitFileDescriptorRuntime(circuit, builder);
944 return std::make_unique<SimToSVPass>();
assert(baseType &&"element must be base type")
static std::unique_ptr< Context > context
static Block * getBodyBlock(FModuleLike mod)
static std::pair< Value, Value > needsClockAndConditionWrapper(Operation *op)
Check whether an op should be placed inside an always process triggered on a clock,...
static ArrayAttr buildSVPerArgumentAttrs(MLIRContext *context, sim::DPIFuncOp func)
static bool moveOpsIntoIfdefGuardsAndProcesses(Operation *rootOp)
static LogicalResult convert(ClockedTerminateOp op, PatternRewriter &rewriter)
StreamLowering< StdoutStreamOp, 0x80000001 > StdoutStreamLowering
static bool needsIfdefGuard(Operation *op)
Check whether an op should be placed inside an ifdef guard that prevents it from affecting synthesis ...
static void addFragments(hw::HWModuleOp module, const llvm::DenseMap< StringAttr, StringAttr > &symbolToFragment, const SimConversionState &state)
StreamLowering< StderrStreamOp, 0x80000002 > StderrStreamLowering
LogicalResult matchAndRewrite(DPICallOp op, OpAdaptor adaptor, ConversionPatternRewriter &rewriter) const final
LogicalResult matchAndRewrite(PlusArgsTestOp op, OpAdaptor adaptor, ConversionPatternRewriter &rewriter) const final
LogicalResult matchAndRewrite(PlusArgsValueOp op, OpAdaptor adaptor, ConversionPatternRewriter &rewriter) const final
typename OpConversionPattern< OpTy >::OpAdaptor OpAdaptor
LogicalResult matchAndRewrite(OpTy op, OpAdaptor adaptor, ConversionPatternRewriter &rewriter) const final
LogicalResult matchAndRewrite(TriggeredOp op, OpAdaptor adaptor, ConversionPatternRewriter &rewriter) const final
LogicalResult matchAndRewrite(mlir::UnrealizedConversionCastOp op, OpAdaptor adaptor, ConversionPatternRewriter &rewriter) const final
A namespace that is used to store existing names and generate new names in some scope within the IR.
void add(mlir::ModuleOp module)
StringRef newName(const Twine &name)
Return a unique name, derived from the input name, and add the new name to the internal namespace.
Signals that an operation's regions are procedural.
Iterative Tarjan SCC analysis on a sparse subgraph of MLIR operations.
create(data_type, name=None, sym_name=None)
void setSVAttributes(mlir::Operation *op, mlir::ArrayAttr attrs)
Set the SV attributes of an operation.
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
std::unique_ptr< mlir::Pass > createLowerSimToSVPass()
llvm::PointerUnion< void *, mlir::Operation *, CyclicOpSCC > OpSCC
One entry in the SCC output: a null sentinel, a trivial (non-cyclic) operation, or a cyclic group.
circt::Namespace nameSpace
void lower(sim::DPIFuncOp func)
llvm::DenseMap< StringAttr, StringAttr > symbolToFragment
LowerDPIFunc(mlir::ModuleOp module)