15#include "mlir/Transforms/DialectConversion.h"
16#include "llvm/Support/JSON.h"
19using namespace firrtl;
31 auto numOps =
op.getNumOperands();
33 if (numOps < n || numOps > m) {
34 auto err =
emitError() <<
" has " << numOps <<
" inputs instead of ";
38 err <<
" between " << n <<
" and " << m;
50 return emitError() <<
" missing output bundle";
51 if (b.getType().getNumElements() != n)
52 return emitError() <<
" has " << b.getType().getNumElements()
53 <<
" output elements instead of " << n;
59 if (
op.getParameters())
60 num =
op.getParameters().size();
61 if (num < n || num > n + c) {
62 auto d =
emitError() <<
" has " << num <<
" parameters instead of ";
66 d <<
" between " << n <<
" and " << (n + c);
73 for (
auto a :
op.getParameters()) {
74 auto param = cast<ParamDeclAttr>(a);
75 if (param.getName().getValue() == paramName) {
76 if (isa<StringAttr>(param.getValue()))
79 return emitError() <<
" has parameter '" << param.getName()
80 <<
"' which should be a string but is not";
85 return emitError() <<
" is missing parameter " << paramName;
90 for (
auto a :
op.getParameters()) {
91 auto param = cast<ParamDeclAttr>(a);
92 if (param.getName().getValue() == paramName) {
93 if (isa<IntegerAttr>(param.getValue()))
96 return emitError() <<
" has parameter '" << param.getName()
97 <<
"' which should be an integer but is not";
102 return emitError() <<
" is missing parameter " << paramName;
111class IntrinsicOpConversion final
116 IntrinsicOpConversion(TypeConverter &typeConverter, MLIRContext *
context,
117 const ConversionMapTy &conversions,
118 size_t &numConversions,
119 bool allowUnknownIntrinsics =
false)
121 numConversions(numConversions),
122 allowUnknownIntrinsics(allowUnknownIntrinsics) {}
125 matchAndRewrite(GenericIntrinsicOp op, OpAdaptor adaptor,
126 ConversionPatternRewriter &rewriter)
const override {
128 auto it = conversions.find(op.getIntrinsicAttr());
129 if (it == conversions.end()) {
130 if (!allowUnknownIntrinsics)
131 return op.emitError(
"unknown intrinsic ") << op.getIntrinsicAttr();
135 auto &conv = *it->second;
136 auto result = conv.checkAndConvert(
GenericIntrinsic(op), adaptor, rewriter);
137 if (succeeded(result))
143 const ConversionMapTy &conversions;
144 size_t &numConversions;
145 const bool allowUnknownIntrinsics;
154 bool allowUnknownIntrinsics) {
156 ConversionTarget target(*
context);
158 target.markUnknownOpDynamicallyLegal([](Operation *op) {
return true; });
159 if (allowUnknownIntrinsics)
160 target.addDynamicallyLegalOp<GenericIntrinsicOp>(
161 [
this](GenericIntrinsicOp op) {
162 return !
conversions.contains(op.getIntrinsicAttr());
165 target.addIllegalOp<GenericIntrinsicOp>();
169 TypeConverter typeConverter;
170 typeConverter.addConversion([](Type type) {
return type; });
171 auto firrtlBaseTypeMaterialization =
172 [](OpBuilder &builder,
FIRRTLBaseType resultType, ValueRange inputs,
173 Location loc) -> Value {
174 if (inputs.size() != 1)
176 auto inputType = type_dyn_cast<FIRRTLBaseType>(inputs.front().getType());
184 auto w = WireOp::create(builder, loc, resultType).getResult();
189 typeConverter.addSourceMaterialization(firrtlBaseTypeMaterialization);
191 typeConverter.addTargetMaterialization(firrtlBaseTypeMaterialization);
196 count, allowUnknownIntrinsics);
198 if (failed(mlir::applyPartialConversion(mod, target, std::move(
patterns))))
211 interface.populateIntrinsicLowerings(lowering);
222 using IntrinsicOpConverter::IntrinsicOpConverter;
231 using IntrinsicOpConverter::IntrinsicOpConverter;
240 using IntrinsicConverter::IntrinsicConverter;
248 PatternRewriter &rewriter)
override {
249 rewriter.replaceOpWithNewOp<PlusArgsTestIntrinsicOp>(
256 using IntrinsicConverter::IntrinsicConverter;
266 PatternRewriter &rewriter)
override {
268 auto newop = PlusArgsValueIntrinsicOp::create(
269 rewriter, gi.
op.getLoc(), bty.getElementTypePreservingConst(0),
270 bty.getElementTypePreservingConst(1),
272 rewriter.replaceOpWithNewOp<BundleCreateOp>(
273 gi.
op, bty, ValueRange({newop.getFound(), newop.getResult()}));
277class CirctClockGateConverter
280 using IntrinsicOpConverter::IntrinsicOpConverter;
283 if (gi.
op.getNumOperands() == 3) {
288 if (gi.
op.getNumOperands() == 2) {
292 gi.
emitError() <<
" has " << gi.
op.getNumOperands()
293 <<
" ports instead of 3 or 4";
298class CirctClockInverterConverter
301 using IntrinsicOpConverter::IntrinsicOpConverter;
311 using IntrinsicConverter::IntrinsicConverter;
320 PatternRewriter &rewriter)
override {
322 gi.
getParamValue<IntegerAttr>(
"POW_2").getValue().getZExtValue();
324 auto pow2Attr = rewriter.getI64IntegerAttr(pow2);
326 rewriter.replaceOpWithNewOp<ClockDividerIntrinsicOp>(
327 gi.
op, adaptor.getOperands()[0], pow2Attr);
331template <
typename OpTy>
343template <
typename OpTy>
356 using IntrinsicConverter::IntrinsicConverter;
365 PatternRewriter &rewriter)
override {
366 auto getI64Attr = [&](IntegerAttr val) {
368 return IntegerAttr();
369 return rewriter.getI64IntegerAttr(val.getValue().getZExtValue());
371 auto delay = getI64Attr(gi.
getParamValue<IntegerAttr>(
"delay"));
372 auto length = getI64Attr(gi.
getParamValue<IntegerAttr>(
"length"));
373 rewriter.replaceOpWithNewOp<LTLDelayIntrinsicOp>(
374 gi.
op, gi.
op.getResultTypes(), adaptor.getOperands()[0], delay, length);
380 using IntrinsicConverter::IntrinsicConverter;
387 if (gi.
op.getNumOperands() > 1 && gi.
typedInput<ClockType>(1))
393 PatternRewriter &rewriter)
override {
394 auto delay = rewriter.getI64IntegerAttr(
395 gi.
getParamValue<IntegerAttr>(
"delay").getValue().getZExtValue());
396 auto operands = adaptor.getOperands();
398 if (operands.size() > 1)
400 rewriter.replaceOpWithNewOp<LTLPastIntrinsicOp>(
401 gi.
op, gi.
op.getResultTypes(), operands[0], delay, clock);
405class CirctLTLClockConverter
408 using IntrinsicOpConverter::IntrinsicOpConverter;
419 using IntrinsicConverter::IntrinsicConverter;
428 PatternRewriter &rewriter)
override {
429 auto getI64Attr = [&](IntegerAttr val) {
431 return IntegerAttr();
432 return rewriter.getI64IntegerAttr(val.getValue().getZExtValue());
434 auto base = getI64Attr(gi.
getParamValue<IntegerAttr>(
"base"));
435 auto more = getI64Attr(gi.
getParamValue<IntegerAttr>(
"more"));
436 rewriter.replaceOpWithNewOp<LTLRepeatIntrinsicOp>(
437 gi.
op, gi.
op.getResultTypes(), adaptor.getOperands()[0], base, more);
443 using IntrinsicConverter::IntrinsicConverter;
452 PatternRewriter &rewriter)
override {
453 auto getI64Attr = [&](IntegerAttr val) {
455 return IntegerAttr();
456 return rewriter.getI64IntegerAttr(val.getValue().getZExtValue());
458 auto base = getI64Attr(gi.
getParamValue<IntegerAttr>(
"base"));
459 auto more = getI64Attr(gi.
getParamValue<IntegerAttr>(
"more"));
460 rewriter.replaceOpWithNewOp<LTLGoToRepeatIntrinsicOp>(
461 gi.
op, gi.
op.getResultTypes(), adaptor.getOperands()[0], base, more);
467 using IntrinsicConverter::IntrinsicConverter;
476 PatternRewriter &rewriter)
override {
477 auto getI64Attr = [&](IntegerAttr val) {
479 return IntegerAttr();
480 return rewriter.getI64IntegerAttr(val.getValue().getZExtValue());
482 auto base = getI64Attr(gi.
getParamValue<IntegerAttr>(
"base"));
483 auto more = getI64Attr(gi.
getParamValue<IntegerAttr>(
"more"));
484 rewriter.replaceOpWithNewOp<LTLNonConsecutiveRepeatIntrinsicOp>(
485 gi.
op, gi.
op.getResultTypes(), adaptor.getOperands()[0], base, more);
492 using IntrinsicConverter::IntrinsicConverter;
501 PatternRewriter &rewriter)
override {
503 auto operands = adaptor.getOperands();
508 enable = operands[1];
510 rewriter.replaceOpWithNewOp<Op>(gi.
op, operands[0], enable, label);
515 using IntrinsicConverter::IntrinsicConverter;
523 PatternRewriter &rewriter)
override {
524 auto operands = adaptor.getOperands();
525 rewriter.replaceOpWithNewOp<Mux2CellIntrinsicOp>(gi.
op, operands[0],
526 operands[1], operands[2]);
531 using IntrinsicConverter::IntrinsicConverter;
539 PatternRewriter &rewriter)
override {
540 auto operands = adaptor.getOperands();
541 rewriter.replaceOpWithNewOp<Mux4CellIntrinsicOp>(
542 gi.
op, operands[0], operands[1], operands[2], operands[3], operands[4]);
546class CirctHasBeenResetConverter
549 using IntrinsicOpConverter::IntrinsicOpConverter;
560 using IntrinsicOpConverter::IntrinsicOpConverter;
568template <
class OpTy,
bool ifElseFatal = false>
571 using IntrinsicConverter::IntrinsicConverter;
574 GenericIntrinsicOpAdaptor adaptor,
575 PatternRewriter &rewriter)
override {
589 auto clock = adaptor.getOperands()[0];
590 auto predicate = adaptor.getOperands()[1];
591 auto enable = adaptor.getOperands()[2];
593 auto substitutions = adaptor.getOperands().drop_front(3);
594 auto name = label ? label.strref() :
"";
599 SmallVector<Value> allOperands;
601 SmallVector<Value> substitutionVec(substitutions.begin(),
602 substitutions.end());
604 substitutionVec, message, allOperands)))
608 message = rewriter.getStringAttr(
"");
609 allOperands.append(substitutions.begin(), substitutions.end());
612 auto op = rewriter.template replaceOpWithNewOp<OpTy>(
613 gi.
op, clock, predicate, enable, message, allOperands, name,
616 SmallVector<StringRef> guardStrings;
617 guards.strref().split(guardStrings,
';', -1,
619 rewriter.startOpModification(op);
620 op->setAttr(
"guards", rewriter.getStrArrayAttr(guardStrings));
621 rewriter.finalizeOpModification(op);
624 if constexpr (ifElseFatal) {
625 rewriter.startOpModification(op);
626 op->setAttr(
"format", rewriter.getStringAttr(
"ifElseFatal"));
627 rewriter.finalizeOpModification(op);
636 using IntrinsicConverter::IntrinsicConverter;
647 PatternRewriter &rewriter)
override {
651 auto clock = adaptor.getOperands()[0];
652 auto predicate = adaptor.getOperands()[1];
653 auto enable = adaptor.getOperands()[2];
655 auto name = label ? label.strref() :
"";
657 auto message = rewriter.getStringAttr(
"");
658 auto op = rewriter.replaceOpWithNewOp<CoverOp>(
659 gi.
op, clock, predicate, enable, message, ValueRange{}, name,
662 SmallVector<StringRef> guardStrings;
663 guards.strref().split(guardStrings,
';', -1,
665 rewriter.startOpModification(op);
666 op->setAttr(
"guards", rewriter.getStrArrayAttr(guardStrings));
667 rewriter.finalizeOpModification(op);
674 using IntrinsicConverter::IntrinsicConverter;
685 PatternRewriter &rewriter)
override {
690 auto predicate = adaptor.getOperands()[0];
691 auto enable = adaptor.getOperands()[1];
693 auto substitutions = adaptor.getOperands().drop_front(2);
694 auto name = label ? label.strref() :
"";
696 auto message = format ? format : rewriter.getStringAttr(
"");
697 auto op = rewriter.template replaceOpWithNewOp<UnclockedAssumeIntrinsicOp>(
698 gi.
op, predicate, enable, message, substitutions, name);
700 SmallVector<StringRef> guardStrings;
701 guards.strref().split(guardStrings,
';', -1,
703 rewriter.startOpModification(op);
704 op->setAttr(
"guards", rewriter.getStrArrayAttr(guardStrings));
705 rewriter.finalizeOpModification(op);
712 return !gi.
getParamValue<IntegerAttr>(
"isClocked").getValue().isZero();
716 using IntrinsicConverter::IntrinsicConverter;
724 auto isClocked = getIsClocked(gi);
736 PatternRewriter &rewriter)
override {
737 auto isClocked = getIsClocked(gi);
738 auto functionName = gi.
getParamValue<StringAttr>(
"functionName");
739 ArrayAttr inputNamesStrArray;
740 StringAttr outputStr = gi.
getParamValue<StringAttr>(
"outputName");
741 if (
auto inputNames = gi.
getParamValue<StringAttr>(
"inputNames")) {
742 SmallVector<StringRef> inputNamesTemporary;
743 inputNames.strref().split(inputNamesTemporary,
';', -1,
745 inputNamesStrArray = rewriter.getStrArrayAttr(inputNamesTemporary);
748 Value clock = isClocked ? adaptor.getOperands()[0] : Value();
749 Value enable = adaptor.getOperands()[
static_cast<size_t>(isClocked)];
752 adaptor.getOperands().drop_front(
static_cast<size_t>(isClocked) + 1);
754 rewriter.replaceOpWithNewOp<DPICallIntrinsicOp>(
755 gi.
op, gi.
op.getResultTypes(), functionName, inputNamesStrArray,
756 outputStr, clock, enable, inputs);
765A
tryGetAs(DictionaryAttr dict, Attribute root, StringRef key, Location loc,
766 Twine path = Twine()) {
767 return tryGetAsBase<A>(dict, root, key, loc,
"View 'info'",
768 "'info' attribute", path);
773std::optional<DictionaryAttr>
775 DictionaryAttr augmentedType, DictionaryAttr root,
776 StringAttr name, StringAttr defName,
777 std::optional<StringAttr> description, Twine path = {}) {
779 tryGetAs<StringAttr>(augmentedType, root,
"class", loc, path);
782 StringRef classBase = classAttr.getValue();
783 if (!classBase.consume_front(
"sifive.enterprise.grandcentral.Augmented")) {
785 "the 'class' was expected to start with "
786 "'sifive.enterprise.grandCentral.Augmented*', but was '" +
787 classAttr.getValue() +
"' (Did you misspell it?)")
789 <<
"see attribute: " << augmentedType;
796 if (classBase ==
"BundleType") {
797 defName = tryGetAs<StringAttr>(augmentedType, root,
"defName", loc, path);
805 SmallVector<Attribute> elements;
807 tryGetAs<ArrayAttr>(augmentedType, root,
"elements", loc, path);
810 for (
size_t i = 0, e = elementsAttr.size(); i != e; ++i) {
811 auto field = dyn_cast_or_null<DictionaryAttr>(elementsAttr[i]);
815 "View 'info' attribute with path '.elements[" + Twine(i) +
816 "]' contained an unexpected type (expected a DictionaryAttr).")
818 <<
"The received element was: " << elementsAttr[i];
821 auto ePath = (path +
".elements[" + Twine(i) +
"]").str();
822 auto name = tryGetAs<StringAttr>(field, root,
"name", loc, ePath);
825 auto tpe = tryGetAs<DictionaryAttr>(field, root,
"tpe", loc, ePath);
828 std::optional<StringAttr> description;
829 if (
auto maybeDescription = field.get(
"description"))
830 description = cast<StringAttr>(maybeDescription);
833 description, path +
"_" + name.getValue());
840 if (
auto maybeDescription = field.get(
"description"))
841 attrs.append(
"description", cast<StringAttr>(maybeDescription));
842 attrs.append(
"name", name);
843 auto tpeClass = tpe.getAs<StringAttr>(
"class");
845 mlir::emitError(loc,
"missing 'class' key in") << tpe;
848 attrs.append(
"tpe", tpeClass);
849 elements.push_back(*eltAttr);
855 attrs.append(
"class", classAttr);
856 attrs.append(
"defName", defName);
858 attrs.append(
"description", *description);
859 attrs.append(
"elements", ArrayAttr::get(
context, elements));
860 attrs.append(
"name", name);
861 return DictionaryAttr::getWithSorted(
context, attrs);
865 if (classBase ==
"GroundType") {
866 NamedAttrList elementIface;
869 elementIface.append(
"class", classAttr);
871 elementIface.append(
"description", *description);
872 elementIface.append(
"name", name);
874 return DictionaryAttr::getWithSorted(
context, elementIface);
879 if (classBase ==
"VectorType") {
881 tryGetAs<ArrayAttr>(augmentedType, root,
"elements", loc, path);
884 SmallVector<Attribute> elements;
885 for (
auto [i, elt] :
llvm::enumerate(elementsAttr)) {
887 context, loc, cast<DictionaryAttr>(elt), root, name,
888 StringAttr::get(
context,
""), std::nullopt, path +
"_" + Twine(i));
891 elements.push_back(*eltAttr);
894 attrs.append(
"class", classAttr);
896 attrs.append(
"description", *description);
897 attrs.append(
"elements", ArrayAttr::get(
context, elements));
898 attrs.append(
"name", name);
899 return DictionaryAttr::getWithSorted(
context, attrs);
904 mlir::emitError(loc,
"found unknown AugmentedType '" + classAttr.getValue() +
905 "' (Did you misspell it?)")
907 <<
"see attribute: " << augmentedType;
914 GenericIntrinsicOpAdaptor adaptor,
915 PatternRewriter &rewriter)
override {
922 for (
auto idx :
llvm::
seq(gi.getNumInputs()))
923 if (gi.checkInputType(idx,
"must be ground type", [](auto ty) {
924 auto base = type_dyn_cast<FIRRTLBaseType>(ty);
925 return base && base.isGround();
931 llvm::json::parse(gi.
getParamValue<StringAttr>(
"info").getValue());
932 if (
auto err = view.takeError()) {
933 handleAllErrors(std::move(err), [&](
const llvm::json::ParseError &a) {
934 gi.
emitError() <<
": error parsing view JSON: " <<
a.message();
940 llvm::json::Path::Root root;
942 assert(value &&
"JSON to attribute failed but should not ever fail");
946 auto dict = dyn_cast<DictionaryAttr>(value);
948 return gi.
emitError() <<
": 'info' parameter must be a dictionary";
952 gi.
op.getContext(), gi.
op.getLoc(), dict, dict, nameAttr,
960 AugmentedBundleTypeAttr::get(gi.
op.getContext(), *result);
961 if (augmentedType.getClass() != augmentedBundleTypeAnnoClass)
962 return gi.
emitError() <<
": 'info' must be augmented bundle";
965 SmallVector<DictionaryAttr> worklist;
966 worklist.push_back(augmentedType.getUnderlying());
967 size_t numLeaves = 0;
969 StringAttr::get(gi.
op.getContext(), augmentedGroundTypeAnnoClass);
970 [[maybe_unused]]
auto augBundleAttr =
971 StringAttr::get(gi.
op.getContext(), augmentedBundleTypeAnnoClass);
972 [[maybe_unused]]
auto augVectorAttr =
973 StringAttr::get(gi.
op.getContext(), augmentedVectorTypeAnnoClass);
974 while (!worklist.empty()) {
975 auto dict = worklist.pop_back_val();
976 auto clazz = dict.getAs<StringAttr>(
"class");
977 if (clazz == augGroundAttr) {
981 assert(clazz == augBundleAttr || clazz == augVectorAttr);
984 dict.getAs<ArrayAttr>(
"elements").getAsRange<DictionaryAttr>());
989 <<
" has " << gi.
getNumInputs() <<
" operands but view 'info' has "
990 << numLeaves <<
" leaf elements";
994 rewriter.replaceOpWithNewOp<ViewIntrinsicOp>(
995 gi.
op, nameAttr.getValue(),
yaml, augmentedType, adaptor.getOperands());
1006#include "FIRRTLIntrinsics.cpp.inc"
1010 populateLowerings(lowering);
assert(baseType &&"element must be base type")
static std::unique_ptr< Context > context
static std::optional< DictionaryAttr > parseAugmentedType(ApplyState &state, DictionaryAttr augmentedType, DictionaryAttr root, StringAttr name, StringAttr defName, std::optional< IntegerAttr > id, std::optional< StringAttr > description, Twine clazz, StringAttr companionAttr, Twine path={})
Recursively walk a sifive.enterprise.grandcentral.AugmentedType to extract any annotations it may con...
static LogicalResult convert(arc::ExecuteOp op, arc::ExecuteOp::Adaptor adaptor, ConversionPatternRewriter &rewriter, const TypeConverter &converter)
Base class for Intrinsic Converters.
Lowering helper which collects all intrinsic converters.
FailureOr< size_t > lower(FModuleOp mod, bool allowUnknownIntrinsics=false)
Lowers all intrinsics in a module. Returns number converted or failure.
llvm::DenseMap< StringAttr, std::unique_ptr< IntrinsicConverter > > ConversionMapTy
MLIRContext * context
Reference to the MLIR context.
ConversionMapTy conversions
Mapping from intrinsic names to converters.
A tryGetAs(DictionaryAttr dict, Attribute root, StringRef key, Location loc, Twine clazz, Twine path=Twine())
Implements the same behavior as DictionaryAttr::getAs<A> to return the value of a specific type assoc...
bool areTypesEquivalent(FIRRTLType destType, FIRRTLType srcType, bool destOuterTypeIsConst=false, bool srcOuterTypeIsConst=false, bool requireSameWidths=false)
Returns whether the two types are equivalent.
bool isTypeLarger(FIRRTLBaseType dstType, FIRRTLBaseType srcType)
Returns true if the destination is at least as wide as a source.
mlir::ParseResult parseFormatString(mlir::OpBuilder &builder, mlir::Location loc, llvm::StringRef formatString, llvm::ArrayRef< mlir::Value > specOperands, mlir::StringAttr &formatStringResult, llvm::SmallVectorImpl< mlir::Value > &operands)
void emitConnect(OpBuilder &builder, Location loc, Value lhs, Value rhs)
Emit a connect between two values.
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
Attribute convertJSONToAttribute(MLIRContext *context, llvm::json::Value &value, llvm::json::Path p)
Convert arbitrary JSON to an MLIR Attribute.
void populateIntrinsicLowerings(IntrinsicLowerings &lowerings) const override
Helper class for checking and extracting information from the generic instrinsic op.
ParseResult sizedInput(unsigned n, int32_t size)
mlir::TypedValue< BundleType > getOutputBundle()
T getParamValue(StringRef name)
Get parameter value by name, if present, as requested type.
ParseResult typedOutput()
ParseResult hasResetInput(unsigned n)
ParseResult typedInput(unsigned n)
ParseResult hasNOutputElements(unsigned n)
InFlightDiagnostic emitError()
ParseResult namedIntParam(StringRef paramName, bool optional=false)
ParseResult namedParam(StringRef paramName, bool optional=false)
ParseResult sizedOutput(int32_t size)
ParseResult sizedOutputElement(unsigned n, StringRef name, int32_t size)
ParseResult hasNParam(unsigned n, unsigned c=0)
ParseResult hasOutputElement(unsigned n, StringRef name)
ParseResult hasNInputs(unsigned n, unsigned c=0)
ParseResult hasNoOutput()
A dialect interface to provide lowering conversions.
void populateIntrinsicLowerings(IntrinsicLowerings &lowerings) const