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"
35#include "llvm/Support/LogicalResult.h"
37#define DEBUG_TYPE "lower-sim-to-sv"
40#define GEN_PASS_DEF_LOWERSIMTOSV
41#include "circt/Conversion/Passes.h.inc"
51 return isa<ClockedTerminateOp, ClockedPauseOp, TerminateOp, PauseOp>(op);
57 return TypeSwitch<Operation *, std::pair<Value, Value>>(op)
58 .Case<ClockedTerminateOp, ClockedPauseOp>(
59 [](
auto op) -> std::pair<Value, Value> {
60 return {op.getClock(), op.getCondition()};
67struct SimConversionState {
69 bool usedSynthesisMacro =
false;
70 bool usedFileDescriptorRuntime =
false;
71 SetVector<StringAttr> dpiCallees;
74struct SimTypeConverter :
public TypeConverter {
75 explicit SimTypeConverter(MLIRContext *
context) {
76 addConversion([](Type type) {
return type; });
77 addConversion([&](OutputStreamType type) -> Type {
78 return IntegerType::get(type.getContext(), 32);
80 addConversion([&](DynamicStringType type) -> Type {
81 return hw::StringType::get(type.getContext());
88 explicit SimConversionPattern(MLIRContext *
context, SimConversionState &state)
91 SimConversionState &state;
95DPIFunctionTypeToHWModuleType(
const DPIFunctionType &dpiFuncType) {
96 SmallVector<hw::ModulePort> hwPorts;
97 for (
auto &arg : dpiFuncType.getArguments()) {
100 case DPIDirection::Input:
101 case DPIDirection::Ref:
102 hwDir = hw::ModulePort::Direction::Input;
104 case DPIDirection::Output:
105 case DPIDirection::Return:
106 hwDir = hw::ModulePort::Direction::Output;
108 case DPIDirection::InOut:
109 hwDir = hw::ModulePort::Direction::InOut;
112 hwPorts.push_back({arg.name, arg.type, hwDir});
114 return hw::ModuleType::get(dpiFuncType.getContext(), hwPorts);
122 using SimConversionPattern<PlusArgsTestOp>::SimConversionPattern;
126 ConversionPatternRewriter &rewriter)
const final {
127 auto loc = op.getLoc();
128 auto resultType = rewriter.getIntegerType(1);
129 auto str = sv::ConstantStrOp::create(rewriter, loc, op.getFormatString());
130 auto reg = sv::RegOp::create(rewriter, loc, resultType,
131 rewriter.getStringAttr(
"_pargs"));
132 sv::InitialOp::create(rewriter, loc, [&] {
133 auto call = sv::SystemFunctionOp::create(
134 rewriter, loc, resultType,
"test$plusargs", ArrayRef<Value>{str});
135 sv::BPAssignOp::create(rewriter, loc, reg, call);
147 using SimConversionPattern<PlusArgsValueOp>::SimConversionPattern;
151 ConversionPatternRewriter &rewriter)
const final {
152 auto loc = op.getLoc();
154 auto i1ty = rewriter.getIntegerType(1);
155 auto type = op.getResult().getType();
158 rewriter.getStringAttr(
"_pargs_v"));
160 rewriter.getStringAttr(
"_pargs_f"));
162 state.usedSynthesisMacro =
true;
164 rewriter, loc,
"SYNTHESIS",
167 auto cstZ = sv::ConstantZOp::create(rewriter, loc, type);
171 sv::SVAttributeAttr::get(
172 rewriter.getContext(),
173 "This dummy assignment exists to avoid undriven lint "
174 "warnings (e.g., Verilator UNDRIVEN).",
179 auto i32ty = rewriter.getIntegerType(32);
180 auto regf = sv::RegOp::create(rewriter, loc, i32ty,
181 rewriter.getStringAttr(
"_found"));
182 auto regv = sv::RegOp::create(rewriter, loc, type,
183 rewriter.getStringAttr(
"_value"));
184 sv::InitialOp::create(rewriter, loc, [&] {
186 sv::ConstantStrOp::create(rewriter, loc, op.getFormatString());
187 auto call = sv::SystemFunctionOp::create(
188 rewriter, loc, i32ty,
"value$plusargs",
189 ArrayRef<Value>{str, regv});
190 sv::BPAssignOp::create(rewriter, loc, regf, call);
196 auto cmp = comb::ICmpOp::create(
197 rewriter, loc, comb::ICmpPredicate::ceq, readRegF, cstTrue);
205 rewriter.replaceOp(op, {readf, readv});
210template <
typename OpTy,
unsigned StreamValue>
218 ConversionPatternRewriter &rewriter)
const final {
221 rewriter.replaceOp(op, streamValue);
237 ConversionPatternRewriter &rewriter)
const final {
238 SmallVector<Type> convertedResultTypes;
239 if (failed(typeConverter->convertTypes(op.getResultTypes(),
240 convertedResultTypes)))
243 if (!llvm::equal(convertedResultTypes, adaptor.getOperands().getTypes()))
246 rewriter.replaceOp(op, adaptor.getOperands());
251static LogicalResult
convert(ClockedTerminateOp op, PatternRewriter &rewriter) {
253 rewriter.replaceOpWithNewOp<sv::FinishOp>(op, op.getVerbose());
255 rewriter.replaceOpWithNewOp<sv::FatalProceduralOp>(op, op.getVerbose());
259static LogicalResult
convert(ClockedPauseOp op, PatternRewriter &rewriter) {
260 rewriter.replaceOpWithNewOp<sv::StopOp>(op, op.getVerbose());
264static LogicalResult
convert(TerminateOp op, PatternRewriter &rewriter) {
266 rewriter.replaceOpWithNewOp<sv::FinishOp>(op, op.getVerbose());
268 rewriter.replaceOpWithNewOp<sv::FatalProceduralOp>(op, op.getVerbose());
272static LogicalResult
convert(PauseOp op, PatternRewriter &rewriter) {
273 rewriter.replaceOpWithNewOp<sv::StopOp>(op, op.getVerbose());
279 using SimConversionPattern<TriggeredOp>::SimConversionPattern;
283 ConversionPatternRewriter &rewriter)
const final {
284 auto loc = op.getLoc();
285 state.usedSynthesisMacro =
true;
288 rewriter, loc,
"SYNTHESIS", [] {},
291 seq::FromClockOp::create(rewriter, loc, adaptor.getClock());
292 auto alwaysOp = sv::AlwaysOp::create(
294 ArrayRef<sv::EventControl>{sv::EventControl::AtPosEdge},
295 ArrayRef<Value>{trigger});
297 Block *destination = alwaysOp.getBodyBlock();
298 if (
auto condition = adaptor.getCondition()) {
299 rewriter.setInsertionPointToStart(destination);
300 destination = sv::IfOp::create(rewriter, loc, condition, [] {
304 rewriter.mergeBlocks(op.getBodyBlock(), destination);
306 rewriter.eraseOp(op);
317 ConversionPatternRewriter &rewriter)
const final {
318 Value fd = adaptor.getStream();
319 if (!fd.getType().isInteger(32))
320 return rewriter.notifyMatchFailure(op,
"expected converted i32 stream");
321 rewriter.replaceOpWithNewOp<sv::FFlushOp>(op, fd);
328 using SimConversionPattern<DPICallOp>::SimConversionPattern;
332 ConversionPatternRewriter &rewriter)
const final {
333 auto loc = op.getLoc();
335 state.dpiCallees.insert(op.getCalleeAttr().getAttr());
337 bool isClockedCall = !!op.getClock();
338 bool hasEnable = !!op.getEnable();
340 SmallVector<sv::RegOp> temporaries;
341 SmallVector<Value> reads;
342 for (
auto [type, result] :
343 llvm::zip(op.getResultTypes(), op.getResults())) {
344 temporaries.push_back(sv::RegOp::create(rewriter, op.getLoc(), type));
349 auto emitCall = [&]() {
350 auto call = sv::FuncCallProceduralOp::create(
351 rewriter, op.getLoc(), op.getResultTypes(), op.getCalleeAttr(),
352 adaptor.getInputs());
353 for (
auto [lhs, rhs] : llvm::zip(temporaries, call.getResults())) {
355 sv::PAssignOp::create(rewriter, op.getLoc(), lhs, rhs);
357 sv::BPAssignOp::create(rewriter, op.getLoc(), lhs, rhs);
362 seq::FromClockOp::create(rewriter, loc, adaptor.getClock());
363 sv::AlwaysOp::create(
365 ArrayRef<sv::EventControl>{sv::EventControl::AtPosEdge},
366 ArrayRef<Value>{clockCast}, [&]() {
369 sv::IfOp::create(rewriter, op.getLoc(), adaptor.getEnable(),
376 sv::AlwaysCombOp::create(rewriter, loc, [&]() {
379 auto assignXToResults = [&] {
380 for (
auto lhs : temporaries) {
381 auto xValue = sv::ConstantXOp::create(
382 rewriter, op.getLoc(), lhs.getType().getElementType());
383 sv::BPAssignOp::create(rewriter, op.getLoc(), lhs, xValue);
386 sv::IfOp::create(rewriter, op.getLoc(), adaptor.getEnable(), emitCall,
391 rewriter.replaceOp(op, reads);
402 ConversionPatternRewriter &rewriter)
const final {
403 rewriter.replaceOpWithNewOp<sv::ConstantStrOp>(op, op.getLiteralAttr());
414 ConversionPatternRewriter &rewriter)
const final {
415 auto inputs = adaptor.getInputs();
416 if (inputs.empty()) {
417 rewriter.replaceOpWithNewOp<sv::ConstantStrOp>(
418 op, rewriter.getStringAttr(
""));
422 rewriter.replaceOpWithNewOp<sv::ConcatStrOp>(op, inputs);
432 void lower(sim::DPIFuncOp func);
436 sim::DPIFuncOp func) {
438 SmallVector<Attribute> convertedAttrs;
439 auto dpiType = func.getDpiFunctionType();
440 auto dpiArgs = dpiType.getArguments();
441 convertedAttrs.reserve(dpiArgs.size());
442 for (
auto &arg : dpiArgs) {
443 NamedAttrList newAttrs;
444 if (arg.dir == sim::DPIDirection::Return)
446 builder.getStringAttr(sv::FuncOp::getExplicitlyReturnedAttrName()),
447 builder.getUnitAttr());
448 convertedAttrs.push_back(newAttrs.getDictionary(
context));
450 return ArrayAttr::get(
context, convertedAttrs);
454 ImplicitLocOpBuilder builder(func.getLoc(), func);
455 ArrayAttr inputLocsAttr, outputLocsAttr;
458 auto moduleType = DPIFunctionTypeToHWModuleType(func.getDpiFunctionType());
460 if (func.getArgumentLocs()) {
461 SmallVector<Attribute> inputLocs, outputLocs;
462 auto hwPorts = moduleType.getPorts();
463 for (
auto [port, loc] : llvm::zip(
464 hwPorts, func.getArgumentLocsAttr().getAsRange<LocationAttr>())) {
468 inputLocsAttr = builder.getArrayAttr(inputLocs);
469 outputLocsAttr = builder.getArrayAttr(outputLocs);
472 auto svFuncDecl = sv::FuncOp::create(
473 builder, func.getSymNameAttr(), moduleType,
475 outputLocsAttr, func.getVerilogNameAttr());
477 svFuncDecl.setPrivate();
479 func.getSymNameAttr().getValue(),
"dpi_import_fragument"));
482 auto macroDecl = sv::MacroDeclOp::create(
484 func.getSymNameAttr().getValue().upper()));
485 emit::FragmentOp::create(builder, name, [&]() {
487 builder, macroDecl.getSymNameAttr(), []() {},
489 sv::FuncDPIImportOp::create(builder, func.getSymNameAttr(),
491 sv::MacroDefOp::create(builder, macroDecl.getSymNameAttr(),
"");
501 const llvm::DenseMap<StringAttr, StringAttr> &symbolToFragment,
502 const SimConversionState &state) {
503 llvm::SetVector<Attribute> fragments;
505 if (
auto exstingFragments =
506 module->getAttrOfType<ArrayAttr>(emit::getFragmentsAttrName()))
507 for (
auto fragment : exstingFragments.getAsRange<FlatSymbolRefAttr>())
508 fragments.insert(fragment);
509 for (
auto callee : state.dpiCallees) {
510 auto attr = symbolToFragment.at(callee);
511 fragments.insert(FlatSymbolRefAttr::get(attr));
513 if (state.usedFileDescriptorRuntime)
514 fragments.insert(sv::getFileDescriptorFragmentRef(module.getContext()));
515 if (!fragments.empty())
517 emit::getFragmentsAttrName(),
518 ArrayAttr::get(module.getContext(), fragments.takeVector()));
522 bool usedSynthesisMacro =
false;
524 rootOp->walk<WalkOrder::PreOrder>([&](Operation *op) {
528 if (isa<TriggeredOp>(op))
529 return WalkResult::skip();
531 auto loc = op->getLoc();
536 Block *block =
nullptr;
537 if (op->getPrevNode())
538 block = TypeSwitch<Operation *, Block *>(op->getPrevNode())
539 .Case<sv::IfDefOp, sv::IfDefProceduralOp>(
540 [&](
auto guardOp) -> Block * {
541 if (guardOp.getCond().getIdent().getAttr() ==
544 return guardOp.getElseBlock();
547 .Default([](
auto) {
return nullptr; });
551 OpBuilder builder(op);
553 block = sv::IfDefProceduralOp::create(
554 builder, loc,
"SYNTHESIS", [] {}, [] {})
557 block = sv::IfDefOp::create(
558 builder, loc,
"SYNTHESIS", [] {}, [] {})
560 usedSynthesisMacro =
true;
564 op->moveBefore(block, block->end());
573 Block *block =
nullptr;
574 if (
auto alwaysOp = dyn_cast_or_null<sv::AlwaysOp>(op->getPrevNode()))
575 if (alwaysOp.getNumConditions() == 1 &&
576 alwaysOp.getCondition(0).event == sv::EventControl::AtPosEdge)
577 if (
auto clockOp = alwaysOp.getCondition(0)
578 .value.getDefiningOp<seq::FromClockOp>())
579 if (clockOp.getInput() == clock)
580 block = alwaysOp.getBodyBlock();
584 OpBuilder builder(op);
585 clock = seq::FromClockOp::create(builder, loc, clock);
586 block = sv::AlwaysOp::create(builder, loc, sv::EventControl::AtPosEdge,
592 op->moveBefore(block, block->end());
598 Block *block =
nullptr;
599 if (
auto ifOp = dyn_cast_or_null<sv::IfOp>(op->getPrevNode()))
600 if (ifOp.getCond() == condition)
601 block = ifOp.getThenBlock();
605 OpBuilder builder(op);
606 block = sv::IfOp::create(builder, loc, condition, [] {}).getThenBlock();
610 op->moveBefore(block, block->end());
612 return WalkResult::advance();
615 return usedSynthesisMacro;
620void appendLiteralToSVFormat(SmallString<128> &formatString,
622 for (
char ch : literal) {
624 formatString +=
"%%";
626 formatString.push_back(ch);
630LogicalResult appendPaddedSpecifier(SmallString<128> &formatString,
631 bool isLeftAligned, uint8_t paddingChar,
632 std::optional<int32_t> width,
char spec) {
633 formatString.push_back(
'%');
635 formatString.push_back(
'-');
639 if (paddingChar ==
'0')
640 formatString.push_back(
'0');
641 else if (paddingChar !=
' ')
644 if (width.has_value())
645 llvm::Twine(width.value()).toVector(formatString);
647 formatString.push_back(spec);
651void appendFloatSpecifier(SmallString<128> &formatString,
bool isLeftAligned,
652 std::optional<int32_t> fieldWidth, int32_t fracDigits,
654 formatString.push_back(
'%');
656 formatString.push_back(
'-');
657 if (fieldWidth.has_value())
658 llvm::Twine(fieldWidth.value()).toVector(formatString);
659 formatString.push_back(
'.');
660 llvm::Twine(fracDigits).toVector(formatString);
661 formatString.push_back(spec);
664LogicalResult getFlattenedFormatFragments(Value input,
665 SmallVectorImpl<Value> &fragments) {
666 if (
auto concat = input.getDefiningOp<FormatStringConcatOp>()) {
667 if (failed(concat.getFlattenedInputs(fragments)))
668 return mlir::emitError(input.getLoc(),
669 "cyclic sim.fmt.concat is unsupported");
673 fragments.push_back(input);
677LogicalResult appendFormatFragmentToSVFormat(Value fragment,
678 SmallString<128> &formatString,
679 SmallVectorImpl<Value> &args,
680 OpBuilder &builder) {
681 Operation *fragmentOp = fragment.getDefiningOp();
683 return mlir::emitError(fragment.getLoc(),
684 "block argument format strings are unsupported");
686 return TypeSwitch<Operation *, LogicalResult>(fragmentOp)
687 .Case<FormatLiteralOp>([&](
auto literal) -> LogicalResult {
688 appendLiteralToSVFormat(formatString, literal.getLiteral());
691 .Case<FormatStringOp>([&](
auto fmt) -> LogicalResult {
692 if (failed(appendPaddedSpecifier(formatString, fmt.getIsLeftAligned(),
693 fmt.getPaddingChar(),
694 fmt.getSpecifierWidth(),
's'))) {
695 return mlir::emitError(fmt.getLoc())
696 <<
"sim.fmt.string only supports paddingChar 32 (' ') or 48 "
699 args.push_back(mlir::UnrealizedConversionCastOp::create(
700 builder, fmt.getLoc(),
701 hw::StringType::get(builder.getContext()),
706 .Case<FormatCurrentTimeOp>([&](
auto fmt) -> LogicalResult {
707 formatString +=
"%0t";
708 args.push_back(sv::TimeOp::create(builder, fmt.getLoc()));
711 .Case<FormatHierPathOp>([&](
auto hierPath) -> LogicalResult {
712 formatString += hierPath.getUseEscapes() ?
"%M" :
"%m";
715 .Case<FormatCharOp>([&](
auto fmt) -> LogicalResult {
716 formatString +=
"%c";
717 args.push_back(fmt.getValue());
720 .Case<FormatDecOp>([&](
auto fmt) -> LogicalResult {
721 if (failed(appendPaddedSpecifier(formatString, fmt.getIsLeftAligned(),
722 fmt.getPaddingChar(),
723 fmt.getSpecifierWidth(),
'd'))) {
724 return mlir::emitError(fmt.getLoc())
725 <<
"sim.fmt.dec only supports paddingChar 32 (' ') or 48 "
729 if (fmt.getIsSigned()) {
730 auto signedValue = sv::SystemFunctionOp::create(
731 builder, fmt.getLoc(), fmt.getValue().getType(),
"signed",
732 ValueRange{fmt.getValue()});
733 args.push_back(signedValue);
735 auto unsignedValue = sv::SystemFunctionOp::create(
736 builder, fmt.getLoc(), fmt.getValue().getType(),
"unsigned",
737 ValueRange{fmt.getValue()});
738 args.push_back(unsignedValue);
742 .Case<FormatHexOp>([&](
auto fmt) -> LogicalResult {
743 if (failed(appendPaddedSpecifier(
744 formatString, fmt.getIsLeftAligned(), fmt.getPaddingChar(),
745 fmt.getSpecifierWidth(),
746 fmt.getIsHexUppercase() ?
'X' :
'x'))) {
747 return mlir::emitError(fmt.getLoc())
748 <<
"sim.fmt.hex only supports paddingChar 32 (' ') or 48 "
751 args.push_back(fmt.getValue());
754 .Case<FormatOctOp>([&](
auto fmt) -> LogicalResult {
755 if (failed(appendPaddedSpecifier(formatString, fmt.getIsLeftAligned(),
756 fmt.getPaddingChar(),
757 fmt.getSpecifierWidth(),
'o'))) {
758 return mlir::emitError(fmt.getLoc())
759 <<
"sim.fmt.oct only supports paddingChar 32 (' ') or 48 "
762 args.push_back(fmt.getValue());
765 .Case<FormatBinOp>([&](
auto fmt) -> LogicalResult {
766 if (failed(appendPaddedSpecifier(formatString, fmt.getIsLeftAligned(),
767 fmt.getPaddingChar(),
768 fmt.getSpecifierWidth(),
'b'))) {
769 return mlir::emitError(fmt.getLoc())
770 <<
"sim.fmt.bin only supports paddingChar 32 (' ') or 48 "
773 args.push_back(fmt.getValue());
776 .Case<FormatScientificOp>([&](
auto fmt) -> LogicalResult {
777 appendFloatSpecifier(formatString, fmt.getIsLeftAligned(),
778 fmt.getFieldWidth(), fmt.getFracDigits(),
'e');
779 args.push_back(fmt.getValue());
782 .Case<FormatFloatOp>([&](
auto fmt) -> LogicalResult {
783 appendFloatSpecifier(formatString, fmt.getIsLeftAligned(),
784 fmt.getFieldWidth(), fmt.getFracDigits(),
'f');
785 args.push_back(fmt.getValue());
788 .Case<FormatGeneralOp>([&](
auto fmt) -> LogicalResult {
789 appendFloatSpecifier(formatString, fmt.getIsLeftAligned(),
790 fmt.getFieldWidth(), fmt.getFracDigits(),
'g');
791 args.push_back(fmt.getValue());
794 .Default([&](
auto unsupportedOp) {
795 return mlir::emitError(unsupportedOp->getLoc())
796 <<
"unsupported format fragment '"
797 << unsupportedOp->getName().getStringRef() <<
"'";
801LogicalResult lowerFormatStringToSVFormat(Value input,
802 SmallString<128> &formatString,
803 SmallVectorImpl<Value> &args,
805 bool &requiresFormatting) {
806 SmallVector<Value, 8> fragments;
807 if (failed(getFlattenedFormatFragments(input, fragments)))
809 requiresFormatting =
false;
810 for (
auto fragment : fragments) {
811 if (failed(appendFormatFragmentToSVFormat(fragment, formatString, args,
816 if (!isa<FormatLiteralOp>(fragment.getDefiningOp()))
817 requiresFormatting =
true;
822FailureOr<Value> createFileDescriptorGetterForGetFile(GetFileOp getFileOp,
823 OpBuilder &builder) {
824 SmallString<128> formatString;
825 SmallVector<Value> args;
826 bool requiresFormatting =
false;
827 if (failed(lowerFormatStringToSVFormat(getFileOp.getFileName(), formatString,
828 args, builder, requiresFormatting))) {
829 getFileOp.emitError(
"cannot lower 'sim.get_file' to SystemVerilog")
830 .attachNote(getFileOp.getFileName().getLoc())
831 <<
"while lowering file name";
837 ? sv::SFormatFOp::create(builder, getFileOp.getLoc(),
838 builder.getStringAttr(formatString), args)
840 : sv::ConstantStrOp::create(builder, getFileOp.getLoc(),
841 builder.getStringAttr(formatString))
844 return sv::createProceduralFileDescriptorGetterCall(
845 builder, getFileOp.getLoc(), fileName);
848static void cleanupDeadSimFmtOps(ArrayRef<Operation *> seedOps) {
849 auto filter = [](Operation *op, OpOperand &operand) {
850 return isa<FormatStringType>(operand.get().getType()) &&
851 isa_and_present<SimDialect>(op->getDialect());
856 assert(sccs.getNumCyclicSCCs() == 0 &&
857 "Cyclic graph should have been rejected");
859 for (
OpSCC entry : sccs.reverseTopological()) {
860 auto *op = cast<Operation *>(entry);
864 op->emitWarning(
"sim format/stream op still has users after lowering; "
865 "dialect conversion will fail");
870 const TypeConverter &typeConverter,
871 SimConversionState &state) {
872 SmallVector<GetFileOp> getFileOps;
873 SmallVector<PrintFormattedProcOp> printOps;
874 SmallVector<FormatToStringOp> formatToStringOps;
875 SmallVector<Operation *, 8> cleanupSeeds;
876 module.walk([&](Operation *op) {
877 if (auto getFileOp = dyn_cast<GetFileOp>(op))
878 getFileOps.push_back(getFileOp);
879 if (
auto printOp = dyn_cast<PrintFormattedProcOp>(op))
880 printOps.push_back(printOp);
881 if (
auto formatToStringOp = dyn_cast<FormatToStringOp>(op))
882 formatToStringOps.push_back(formatToStringOp);
885 for (
auto getFileOp : getFileOps) {
886 OpBuilder builder(getFileOp);
887 auto fdOrFailure = createFileDescriptorGetterForGetFile(getFileOp, builder);
888 if (failed(fdOrFailure))
891 auto stream = mlir::UnrealizedConversionCastOp::create(
892 builder, getFileOp.getLoc(), getFileOp.getResult().getType(),
894 getFileOp.replaceAllUsesWith(stream.getResult(0));
895 state.usedFileDescriptorRuntime =
true;
896 state.usedSynthesisMacro =
true;
897 cleanupSeeds.push_back(getFileOp);
900 for (
auto printOp : printOps) {
901 OpBuilder builder(printOp);
902 SmallString<128> formatString;
903 SmallVector<Value> args;
904 bool requiresFormatting =
false;
905 if (failed(lowerFormatStringToSVFormat(printOp.getInput(), formatString,
907 requiresFormatting))) {
908 printOp.emitError(
"cannot lower 'sim.proc.print' to SystemVerilog")
909 .attachNote(printOp.getInput().getLoc())
910 <<
"while lowering format string";
913 auto stream = printOp.getStream();
916 sv::WriteOp::create(builder, printOp.getLoc(), formatString, args);
918 auto fdType = typeConverter.convertType(stream.getType());
919 assert(fdType &&
"expected output stream type conversion");
920 Value fd = mlir::UnrealizedConversionCastOp::create(
921 builder, printOp.getLoc(), fdType, stream)
923 sv::FWriteOp::create(builder, printOp.getLoc(), fd, formatString, args);
925 cleanupSeeds.push_back(printOp);
928 for (
auto op : formatToStringOps) {
929 OpBuilder builder(op);
930 SmallString<128> formatStr;
931 SmallVector<Value> args;
932 bool requiresFormatting =
false;
933 if (failed(lowerFormatStringToSVFormat(op.getFmtstring(), formatStr, args,
934 builder, requiresFormatting)))
936 "cannot lower 'sim.string.format_to_string' to SystemVerilog");
939 if (requiresFormatting)
940 svResult = sv::SFormatFOp::create(builder, op.getLoc(),
941 builder.getStringAttr(formatStr), args);
943 svResult = sv::ConstantStrOp::create(builder, op.getLoc(),
944 builder.getStringAttr(formatStr));
946 auto cast = mlir::UnrealizedConversionCastOp::create(
947 builder, op.getLoc(), op.getType(), svResult);
948 op.replaceAllUsesWith(cast.getResult(0));
949 cleanupSeeds.push_back(op);
952 cleanupDeadSimFmtOps(cleanupSeeds);
957struct SimToSVPass :
public circt::impl::LowerSimToSVBase<SimToSVPass> {
958 void runOnOperation()
override {
959 auto circuit = getOperation();
960 MLIRContext *
context = &getContext();
965 llvm::make_early_inc_range(circuit.getOps<
sim::DPIFuncOp>()))
966 lowerDPIFunc.lower(func);
968 std::atomic<bool> usedSynthesisMacro =
false;
969 std::atomic<bool> usedFileDescriptorRuntime =
false;
971 SimTypeConverter typeConverter(
context);
972 SimConversionState state;
974 if (failed(lowerPrintFormattedProcToSV(module, typeConverter, state)))
978 usedSynthesisMacro =
true;
980 ConversionTarget target(*
context);
981 target.addIllegalDialect<SimDialect>();
982 target.addLegalDialect<sv::SVDialect>();
983 target.addLegalDialect<hw::HWDialect>();
984 target.addLegalDialect<seq::SeqDialect>();
985 target.addLegalDialect<comb::CombDialect>();
986 target.addDynamicallyLegalOp<mlir::UnrealizedConversionCastOp>(
987 [&](mlir::UnrealizedConversionCastOp op) {
988 return typeConverter.isLegal(op);
1006 auto result = applyPartialConversion(module, target, std::move(
patterns));
1012 addFragments(module, lowerDPIFunc.symbolToFragment, state);
1014 if (state.usedSynthesisMacro)
1015 usedSynthesisMacro =
true;
1016 if (state.usedFileDescriptorRuntime)
1017 usedFileDescriptorRuntime =
true;
1021 if (failed(mlir::failableParallelForEach(
1023 return signalPassFailure();
1025 if (usedSynthesisMacro) {
1026 Operation *op = circuit.lookupSymbol(
"SYNTHESIS");
1028 if (!isa<sv::MacroDeclOp>(op)) {
1029 op->emitOpError(
"should be a macro declaration");
1030 return signalPassFailure();
1033 auto builder = ImplicitLocOpBuilder::atBlockBegin(
1034 UnknownLoc::get(
context), circuit.getBody());
1035 sv::MacroDeclOp::create(builder,
"SYNTHESIS");
1039 if (usedFileDescriptorRuntime) {
1040 auto builder = ImplicitLocOpBuilder::atBlockBegin(
1041 UnknownLoc::get(
context), circuit.getBody());
1042 sv::emitFileDescriptorRuntime(circuit, builder);
1049 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(FlushOp 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(StringConcatOp op, OpAdaptor adaptor, ConversionPatternRewriter &rewriter) const final
LogicalResult matchAndRewrite(StringConstantOp 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.
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.
bool isInProceduralRegion(Operation *op)
Returns true if op has a parent marked as a procedural region that is closer than any parent marked a...
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)