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);
85 explicit SimConversionPattern(MLIRContext *
context, SimConversionState &state)
88 SimConversionState &state;
92DPIFunctionTypeToHWModuleType(
const DPIFunctionType &dpiFuncType) {
93 SmallVector<hw::ModulePort> hwPorts;
94 for (
auto &arg : dpiFuncType.getArguments()) {
97 case DPIDirection::Input:
98 case DPIDirection::Ref:
99 hwDir = hw::ModulePort::Direction::Input;
101 case DPIDirection::Output:
102 case DPIDirection::Return:
103 hwDir = hw::ModulePort::Direction::Output;
105 case DPIDirection::InOut:
106 hwDir = hw::ModulePort::Direction::InOut;
109 hwPorts.push_back({arg.name, arg.type, hwDir});
111 return hw::ModuleType::get(dpiFuncType.getContext(), hwPorts);
119 using SimConversionPattern<PlusArgsTestOp>::SimConversionPattern;
123 ConversionPatternRewriter &rewriter)
const final {
124 auto loc = op.getLoc();
125 auto resultType = rewriter.getIntegerType(1);
126 auto str = sv::ConstantStrOp::create(rewriter, loc, op.getFormatString());
127 auto reg = sv::RegOp::create(rewriter, loc, resultType,
128 rewriter.getStringAttr(
"_pargs"));
129 sv::InitialOp::create(rewriter, loc, [&] {
130 auto call = sv::SystemFunctionOp::create(
131 rewriter, loc, resultType,
"test$plusargs", ArrayRef<Value>{str});
132 sv::BPAssignOp::create(rewriter, loc, reg, call);
144 using SimConversionPattern<PlusArgsValueOp>::SimConversionPattern;
148 ConversionPatternRewriter &rewriter)
const final {
149 auto loc = op.getLoc();
151 auto i1ty = rewriter.getIntegerType(1);
152 auto type = op.getResult().getType();
155 rewriter.getStringAttr(
"_pargs_v"));
157 rewriter.getStringAttr(
"_pargs_f"));
159 state.usedSynthesisMacro =
true;
161 rewriter, loc,
"SYNTHESIS",
164 auto cstZ = sv::ConstantZOp::create(rewriter, loc, type);
168 sv::SVAttributeAttr::get(
169 rewriter.getContext(),
170 "This dummy assignment exists to avoid undriven lint "
171 "warnings (e.g., Verilator UNDRIVEN).",
176 auto i32ty = rewriter.getIntegerType(32);
177 auto regf = sv::RegOp::create(rewriter, loc, i32ty,
178 rewriter.getStringAttr(
"_found"));
179 auto regv = sv::RegOp::create(rewriter, loc, type,
180 rewriter.getStringAttr(
"_value"));
181 sv::InitialOp::create(rewriter, loc, [&] {
183 sv::ConstantStrOp::create(rewriter, loc, op.getFormatString());
184 auto call = sv::SystemFunctionOp::create(
185 rewriter, loc, i32ty,
"value$plusargs",
186 ArrayRef<Value>{str, regv});
187 sv::BPAssignOp::create(rewriter, loc, regf, call);
193 auto cmp = comb::ICmpOp::create(
194 rewriter, loc, comb::ICmpPredicate::ceq, readRegF, cstTrue);
202 rewriter.replaceOp(op, {readf, readv});
207template <
typename OpTy,
unsigned StreamValue>
215 ConversionPatternRewriter &rewriter)
const final {
218 rewriter.replaceOp(op, streamValue);
234 ConversionPatternRewriter &rewriter)
const final {
235 SmallVector<Type> convertedResultTypes;
236 if (failed(typeConverter->convertTypes(op.getResultTypes(),
237 convertedResultTypes)))
240 if (!llvm::equal(convertedResultTypes, adaptor.getOperands().getTypes()))
243 rewriter.replaceOp(op, adaptor.getOperands());
248static LogicalResult
convert(ClockedTerminateOp op, PatternRewriter &rewriter) {
250 rewriter.replaceOpWithNewOp<sv::FinishOp>(op, op.getVerbose());
252 rewriter.replaceOpWithNewOp<sv::FatalProceduralOp>(op, op.getVerbose());
256static LogicalResult
convert(ClockedPauseOp op, PatternRewriter &rewriter) {
257 rewriter.replaceOpWithNewOp<sv::StopOp>(op, op.getVerbose());
261static LogicalResult
convert(TerminateOp op, PatternRewriter &rewriter) {
263 rewriter.replaceOpWithNewOp<sv::FinishOp>(op, op.getVerbose());
265 rewriter.replaceOpWithNewOp<sv::FatalProceduralOp>(op, op.getVerbose());
269static LogicalResult
convert(PauseOp op, PatternRewriter &rewriter) {
270 rewriter.replaceOpWithNewOp<sv::StopOp>(op, op.getVerbose());
276 using SimConversionPattern<TriggeredOp>::SimConversionPattern;
280 ConversionPatternRewriter &rewriter)
const final {
281 auto loc = op.getLoc();
282 state.usedSynthesisMacro =
true;
285 rewriter, loc,
"SYNTHESIS", [] {},
288 seq::FromClockOp::create(rewriter, loc, adaptor.getClock());
289 auto alwaysOp = sv::AlwaysOp::create(
291 ArrayRef<sv::EventControl>{sv::EventControl::AtPosEdge},
292 ArrayRef<Value>{trigger});
294 Block *destination = alwaysOp.getBodyBlock();
295 if (
auto condition = adaptor.getCondition()) {
296 rewriter.setInsertionPointToStart(destination);
297 destination = sv::IfOp::create(rewriter, loc, condition, [] {
301 rewriter.mergeBlocks(op.getBodyBlock(), destination);
303 rewriter.eraseOp(op);
314 ConversionPatternRewriter &rewriter)
const final {
315 Value fd = adaptor.getStream();
316 if (!fd.getType().isInteger(32))
317 return rewriter.notifyMatchFailure(op,
"expected converted i32 stream");
318 rewriter.replaceOpWithNewOp<sv::FFlushOp>(op, fd);
325 using SimConversionPattern<DPICallOp>::SimConversionPattern;
329 ConversionPatternRewriter &rewriter)
const final {
330 auto loc = op.getLoc();
332 state.dpiCallees.insert(op.getCalleeAttr().getAttr());
334 bool isClockedCall = !!op.getClock();
335 bool hasEnable = !!op.getEnable();
337 SmallVector<sv::RegOp> temporaries;
338 SmallVector<Value> reads;
339 for (
auto [type, result] :
340 llvm::zip(op.getResultTypes(), op.getResults())) {
341 temporaries.push_back(sv::RegOp::create(rewriter, op.getLoc(), type));
346 auto emitCall = [&]() {
347 auto call = sv::FuncCallProceduralOp::create(
348 rewriter, op.getLoc(), op.getResultTypes(), op.getCalleeAttr(),
349 adaptor.getInputs());
350 for (
auto [lhs, rhs] : llvm::zip(temporaries, call.getResults())) {
352 sv::PAssignOp::create(rewriter, op.getLoc(), lhs, rhs);
354 sv::BPAssignOp::create(rewriter, op.getLoc(), lhs, rhs);
359 seq::FromClockOp::create(rewriter, loc, adaptor.getClock());
360 sv::AlwaysOp::create(
362 ArrayRef<sv::EventControl>{sv::EventControl::AtPosEdge},
363 ArrayRef<Value>{clockCast}, [&]() {
366 sv::IfOp::create(rewriter, op.getLoc(), adaptor.getEnable(),
373 sv::AlwaysCombOp::create(rewriter, loc, [&]() {
376 auto assignXToResults = [&] {
377 for (
auto lhs : temporaries) {
378 auto xValue = sv::ConstantXOp::create(
379 rewriter, op.getLoc(), lhs.getType().getElementType());
380 sv::BPAssignOp::create(rewriter, op.getLoc(), lhs, xValue);
383 sv::IfOp::create(rewriter, op.getLoc(), adaptor.getEnable(), emitCall,
388 rewriter.replaceOp(op, reads);
398 void lower(sim::DPIFuncOp func);
402 sim::DPIFuncOp func) {
404 SmallVector<Attribute> convertedAttrs;
405 auto dpiType = func.getDpiFunctionType();
406 auto dpiArgs = dpiType.getArguments();
407 convertedAttrs.reserve(dpiArgs.size());
408 for (
auto &arg : dpiArgs) {
409 NamedAttrList newAttrs;
410 if (arg.dir == sim::DPIDirection::Return)
412 builder.getStringAttr(sv::FuncOp::getExplicitlyReturnedAttrName()),
413 builder.getUnitAttr());
414 convertedAttrs.push_back(newAttrs.getDictionary(
context));
416 return ArrayAttr::get(
context, convertedAttrs);
420 ImplicitLocOpBuilder builder(func.getLoc(), func);
421 ArrayAttr inputLocsAttr, outputLocsAttr;
424 auto moduleType = DPIFunctionTypeToHWModuleType(func.getDpiFunctionType());
426 if (func.getArgumentLocs()) {
427 SmallVector<Attribute> inputLocs, outputLocs;
428 auto hwPorts = moduleType.getPorts();
429 for (
auto [port, loc] : llvm::zip(
430 hwPorts, func.getArgumentLocsAttr().getAsRange<LocationAttr>())) {
434 inputLocsAttr = builder.getArrayAttr(inputLocs);
435 outputLocsAttr = builder.getArrayAttr(outputLocs);
438 auto svFuncDecl = sv::FuncOp::create(
439 builder, func.getSymNameAttr(), moduleType,
441 outputLocsAttr, func.getVerilogNameAttr());
443 svFuncDecl.setPrivate();
445 func.getSymNameAttr().getValue(),
"dpi_import_fragument"));
448 auto macroDecl = sv::MacroDeclOp::create(
450 func.getSymNameAttr().getValue().upper()));
451 emit::FragmentOp::create(builder, name, [&]() {
453 builder, macroDecl.getSymNameAttr(), []() {},
455 sv::FuncDPIImportOp::create(builder, func.getSymNameAttr(),
457 sv::MacroDefOp::create(builder, macroDecl.getSymNameAttr(),
"");
467 const llvm::DenseMap<StringAttr, StringAttr> &symbolToFragment,
468 const SimConversionState &state) {
469 llvm::SetVector<Attribute> fragments;
471 if (
auto exstingFragments =
472 module->getAttrOfType<ArrayAttr>(emit::getFragmentsAttrName()))
473 for (
auto fragment : exstingFragments.getAsRange<FlatSymbolRefAttr>())
474 fragments.insert(fragment);
475 for (
auto callee : state.dpiCallees) {
476 auto attr = symbolToFragment.at(callee);
477 fragments.insert(FlatSymbolRefAttr::get(attr));
479 if (state.usedFileDescriptorRuntime)
480 fragments.insert(sv::getFileDescriptorFragmentRef(module.getContext()));
481 if (!fragments.empty())
483 emit::getFragmentsAttrName(),
484 ArrayAttr::get(module.getContext(), fragments.takeVector()));
488 bool usedSynthesisMacro =
false;
490 rootOp->walk<WalkOrder::PreOrder>([&](Operation *op) {
494 if (isa<TriggeredOp>(op))
495 return WalkResult::skip();
497 auto loc = op->getLoc();
502 Block *block =
nullptr;
503 if (op->getPrevNode())
504 block = TypeSwitch<Operation *, Block *>(op->getPrevNode())
505 .Case<sv::IfDefOp, sv::IfDefProceduralOp>(
506 [&](
auto guardOp) -> Block * {
507 if (guardOp.getCond().getIdent().getAttr() ==
510 return guardOp.getElseBlock();
513 .Default([](
auto) {
return nullptr; });
517 OpBuilder builder(op);
519 block = sv::IfDefProceduralOp::create(
520 builder, loc,
"SYNTHESIS", [] {}, [] {})
523 block = sv::IfDefOp::create(
524 builder, loc,
"SYNTHESIS", [] {}, [] {})
526 usedSynthesisMacro =
true;
530 op->moveBefore(block, block->end());
539 Block *block =
nullptr;
540 if (
auto alwaysOp = dyn_cast_or_null<sv::AlwaysOp>(op->getPrevNode()))
541 if (alwaysOp.getNumConditions() == 1 &&
542 alwaysOp.getCondition(0).event == sv::EventControl::AtPosEdge)
543 if (
auto clockOp = alwaysOp.getCondition(0)
544 .value.getDefiningOp<seq::FromClockOp>())
545 if (clockOp.getInput() == clock)
546 block = alwaysOp.getBodyBlock();
550 OpBuilder builder(op);
551 clock = seq::FromClockOp::create(builder, loc, clock);
552 block = sv::AlwaysOp::create(builder, loc, sv::EventControl::AtPosEdge,
558 op->moveBefore(block, block->end());
564 Block *block =
nullptr;
565 if (
auto ifOp = dyn_cast_or_null<sv::IfOp>(op->getPrevNode()))
566 if (ifOp.getCond() == condition)
567 block = ifOp.getThenBlock();
571 OpBuilder builder(op);
572 block = sv::IfOp::create(builder, loc, condition, [] {}).getThenBlock();
576 op->moveBefore(block, block->end());
578 return WalkResult::advance();
581 return usedSynthesisMacro;
586void appendLiteralToSVFormat(SmallString<128> &formatString,
588 for (
char ch : literal) {
590 formatString +=
"%%";
592 formatString.push_back(ch);
596LogicalResult appendIntegerSpecifier(SmallString<128> &formatString,
597 bool isLeftAligned, uint8_t paddingChar,
598 std::optional<int32_t> width,
char spec) {
599 formatString.push_back(
'%');
601 formatString.push_back(
'-');
605 if (paddingChar ==
'0')
606 formatString.push_back(
'0');
607 else if (paddingChar !=
' ')
610 if (width.has_value())
611 llvm::Twine(width.value()).toVector(formatString);
613 formatString.push_back(spec);
617void appendFloatSpecifier(SmallString<128> &formatString,
bool isLeftAligned,
618 std::optional<int32_t> fieldWidth, int32_t fracDigits,
620 formatString.push_back(
'%');
622 formatString.push_back(
'-');
623 if (fieldWidth.has_value())
624 llvm::Twine(fieldWidth.value()).toVector(formatString);
625 formatString.push_back(
'.');
626 llvm::Twine(fracDigits).toVector(formatString);
627 formatString.push_back(spec);
630LogicalResult getFlattenedFormatFragments(Value input,
631 SmallVectorImpl<Value> &fragments) {
632 if (
auto concat = input.getDefiningOp<FormatStringConcatOp>()) {
633 if (failed(concat.getFlattenedInputs(fragments)))
634 return mlir::emitError(input.getLoc(),
635 "cyclic sim.fmt.concat is unsupported");
639 fragments.push_back(input);
643LogicalResult appendFormatFragmentToSVFormat(Value fragment,
644 SmallString<128> &formatString,
645 SmallVectorImpl<Value> &args,
646 OpBuilder &builder) {
647 Operation *fragmentOp = fragment.getDefiningOp();
649 return mlir::emitError(fragment.getLoc(),
650 "block argument format strings are unsupported");
652 return TypeSwitch<Operation *, LogicalResult>(fragmentOp)
653 .Case<FormatLiteralOp>([&](
auto literal) -> LogicalResult {
654 appendLiteralToSVFormat(formatString, literal.getLiteral());
657 .Case<FormatCurrentTimeOp>([&](
auto fmt) -> LogicalResult {
658 formatString +=
"%0t";
659 args.push_back(sv::TimeOp::create(builder, fmt.getLoc()));
662 .Case<FormatHierPathOp>([&](
auto hierPath) -> LogicalResult {
663 formatString += hierPath.getUseEscapes() ?
"%M" :
"%m";
666 .Case<FormatCharOp>([&](
auto fmt) -> LogicalResult {
667 formatString +=
"%c";
668 args.push_back(fmt.getValue());
671 .Case<FormatDecOp>([&](
auto fmt) -> LogicalResult {
672 if (failed(appendIntegerSpecifier(formatString, fmt.getIsLeftAligned(),
673 fmt.getPaddingChar(),
674 fmt.getSpecifierWidth(),
'd'))) {
675 return mlir::emitError(fmt.getLoc())
676 <<
"sim.fmt.dec only supports paddingChar 32 (' ') or 48 "
680 if (fmt.getIsSigned()) {
681 auto signedValue = sv::SystemFunctionOp::create(
682 builder, fmt.getLoc(), fmt.getValue().getType(),
"signed",
683 ValueRange{fmt.getValue()});
684 args.push_back(signedValue);
686 auto unsignedValue = sv::SystemFunctionOp::create(
687 builder, fmt.getLoc(), fmt.getValue().getType(),
"unsigned",
688 ValueRange{fmt.getValue()});
689 args.push_back(unsignedValue);
693 .Case<FormatHexOp>([&](
auto fmt) -> LogicalResult {
694 if (failed(appendIntegerSpecifier(
695 formatString, fmt.getIsLeftAligned(), fmt.getPaddingChar(),
696 fmt.getSpecifierWidth(),
697 fmt.getIsHexUppercase() ?
'X' :
'x'))) {
698 return mlir::emitError(fmt.getLoc())
699 <<
"sim.fmt.hex only supports paddingChar 32 (' ') or 48 "
702 args.push_back(fmt.getValue());
705 .Case<FormatOctOp>([&](
auto fmt) -> LogicalResult {
706 if (failed(appendIntegerSpecifier(formatString, fmt.getIsLeftAligned(),
707 fmt.getPaddingChar(),
708 fmt.getSpecifierWidth(),
'o'))) {
709 return mlir::emitError(fmt.getLoc())
710 <<
"sim.fmt.oct only supports paddingChar 32 (' ') or 48 "
713 args.push_back(fmt.getValue());
716 .Case<FormatBinOp>([&](
auto fmt) -> LogicalResult {
717 if (failed(appendIntegerSpecifier(formatString, fmt.getIsLeftAligned(),
718 fmt.getPaddingChar(),
719 fmt.getSpecifierWidth(),
'b'))) {
720 return mlir::emitError(fmt.getLoc())
721 <<
"sim.fmt.bin only supports paddingChar 32 (' ') or 48 "
724 args.push_back(fmt.getValue());
727 .Case<FormatScientificOp>([&](
auto fmt) -> LogicalResult {
728 appendFloatSpecifier(formatString, fmt.getIsLeftAligned(),
729 fmt.getFieldWidth(), fmt.getFracDigits(),
'e');
730 args.push_back(fmt.getValue());
733 .Case<FormatFloatOp>([&](
auto fmt) -> LogicalResult {
734 appendFloatSpecifier(formatString, fmt.getIsLeftAligned(),
735 fmt.getFieldWidth(), fmt.getFracDigits(),
'f');
736 args.push_back(fmt.getValue());
739 .Case<FormatGeneralOp>([&](
auto fmt) -> LogicalResult {
740 appendFloatSpecifier(formatString, fmt.getIsLeftAligned(),
741 fmt.getFieldWidth(), fmt.getFracDigits(),
'g');
742 args.push_back(fmt.getValue());
745 .Default([&](
auto unsupportedOp) {
746 return mlir::emitError(unsupportedOp->getLoc())
747 <<
"unsupported format fragment '"
748 << unsupportedOp->getName().getStringRef() <<
"'";
752LogicalResult lowerFormatStringToSVFormat(Value input,
753 SmallString<128> &formatString,
754 SmallVectorImpl<Value> &args,
755 OpBuilder &builder) {
756 SmallVector<Value, 8> fragments;
757 if (failed(getFlattenedFormatFragments(input, fragments)))
759 for (
auto fragment : fragments)
760 if (failed(appendFormatFragmentToSVFormat(fragment, formatString, args,
766FailureOr<Value> createFileDescriptorGetterForGetFile(GetFileOp getFileOp,
767 OpBuilder &builder) {
768 SmallString<128> formatString;
769 SmallVector<Value> args;
770 if (failed(lowerFormatStringToSVFormat(getFileOp.getFileName(), formatString,
772 getFileOp.emitError(
"cannot lower 'sim.get_file' to SystemVerilog")
773 .attachNote(getFileOp.getFileName().getLoc())
774 <<
"while lowering file name";
780 ? sv::ConstantStrOp::create(builder, getFileOp.getLoc(),
781 builder.getStringAttr(formatString))
783 : sv::SFormatFOp::create(builder, getFileOp.getLoc(),
784 builder.getStringAttr(formatString), args)
787 return sv::createProceduralFileDescriptorGetterCall(
788 builder, getFileOp.getLoc(), fileName);
791static void cleanupDeadSimFmtOps(ArrayRef<Operation *> seedOps) {
792 auto filter = [](Operation *op, OpOperand &operand) {
793 return isa<FormatStringType>(operand.get().getType()) &&
794 isa_and_present<SimDialect>(op->getDialect());
799 assert(sccs.getNumCyclicSCCs() == 0 &&
800 "Cyclic graph should have been rejected");
802 for (
OpSCC entry : sccs.reverseTopological()) {
803 auto *op = cast<Operation *>(entry);
807 op->emitWarning(
"sim format/stream op still has users after lowering; "
808 "dialect conversion will fail");
813 const TypeConverter &typeConverter,
814 SimConversionState &state) {
815 SmallVector<GetFileOp> getFileOps;
816 SmallVector<PrintFormattedProcOp> printOps;
817 SmallVector<Operation *, 8> cleanupSeeds;
818 module.walk([&](Operation *op) {
819 if (auto getFileOp = dyn_cast<GetFileOp>(op))
820 getFileOps.push_back(getFileOp);
821 if (
auto printOp = dyn_cast<PrintFormattedProcOp>(op))
822 printOps.push_back(printOp);
825 for (
auto getFileOp : getFileOps) {
826 OpBuilder builder(getFileOp);
827 auto fdOrFailure = createFileDescriptorGetterForGetFile(getFileOp, builder);
828 if (failed(fdOrFailure))
831 auto stream = mlir::UnrealizedConversionCastOp::create(
832 builder, getFileOp.getLoc(), getFileOp.getResult().getType(),
834 getFileOp.replaceAllUsesWith(stream.getResult(0));
835 state.usedFileDescriptorRuntime =
true;
836 state.usedSynthesisMacro =
true;
837 cleanupSeeds.push_back(getFileOp);
840 for (
auto printOp : printOps) {
841 OpBuilder builder(printOp);
842 SmallString<128> formatString;
843 SmallVector<Value> args;
844 if (failed(lowerFormatStringToSVFormat(printOp.getInput(), formatString,
846 printOp.emitError(
"cannot lower 'sim.proc.print' to SystemVerilog")
847 .attachNote(printOp.getInput().getLoc())
848 <<
"while lowering format string";
851 auto stream = printOp.getStream();
854 sv::WriteOp::create(builder, printOp.getLoc(), formatString, args);
856 auto fdType = typeConverter.convertType(stream.getType());
857 assert(fdType &&
"expected output stream type conversion");
858 Value fd = mlir::UnrealizedConversionCastOp::create(
859 builder, printOp.getLoc(), fdType, stream)
861 sv::FWriteOp::create(builder, printOp.getLoc(), fd, formatString, args);
863 cleanupSeeds.push_back(printOp);
866 cleanupDeadSimFmtOps(cleanupSeeds);
871struct SimToSVPass :
public circt::impl::LowerSimToSVBase<SimToSVPass> {
872 void runOnOperation()
override {
873 auto circuit = getOperation();
874 MLIRContext *
context = &getContext();
879 llvm::make_early_inc_range(circuit.getOps<
sim::DPIFuncOp>()))
880 lowerDPIFunc.lower(func);
882 std::atomic<bool> usedSynthesisMacro =
false;
883 std::atomic<bool> usedFileDescriptorRuntime =
false;
885 SimTypeConverter typeConverter(
context);
886 SimConversionState state;
888 if (failed(lowerPrintFormattedProcToSV(module, typeConverter, state)))
892 usedSynthesisMacro =
true;
894 ConversionTarget target(*
context);
895 target.addIllegalDialect<SimDialect>();
896 target.addLegalDialect<sv::SVDialect>();
897 target.addLegalDialect<hw::HWDialect>();
898 target.addLegalDialect<seq::SeqDialect>();
899 target.addLegalDialect<comb::CombDialect>();
900 target.addDynamicallyLegalOp<mlir::UnrealizedConversionCastOp>(
901 [&](mlir::UnrealizedConversionCastOp op) {
902 return typeConverter.isLegal(op);
918 auto result = applyPartialConversion(module, target, std::move(
patterns));
924 addFragments(module, lowerDPIFunc.symbolToFragment, state);
926 if (state.usedSynthesisMacro)
927 usedSynthesisMacro =
true;
928 if (state.usedFileDescriptorRuntime)
929 usedFileDescriptorRuntime =
true;
933 if (failed(mlir::failableParallelForEach(
935 return signalPassFailure();
937 if (usedSynthesisMacro) {
938 Operation *op = circuit.lookupSymbol(
"SYNTHESIS");
940 if (!isa<sv::MacroDeclOp>(op)) {
941 op->emitOpError(
"should be a macro declaration");
942 return signalPassFailure();
945 auto builder = ImplicitLocOpBuilder::atBlockBegin(
946 UnknownLoc::get(
context), circuit.getBody());
947 sv::MacroDeclOp::create(builder,
"SYNTHESIS");
951 if (usedFileDescriptorRuntime) {
952 auto builder = ImplicitLocOpBuilder::atBlockBegin(
953 UnknownLoc::get(
context), circuit.getBody());
954 sv::emitFileDescriptorRuntime(circuit, builder);
961 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(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)