23#include "mlir/IR/Builders.h"
24#include "mlir/IR/Matchers.h"
25#include "mlir/IR/PatternMatch.h"
26#include "mlir/Interfaces/FunctionImplementation.h"
27#include "llvm/ADT/BitVector.h"
28#include "llvm/ADT/SmallPtrSet.h"
29#include "llvm/ADT/StringSet.h"
38 case ModulePort::Direction::Input:
39 return ModulePort::Direction::Output;
40 case ModulePort::Direction::Output:
41 return ModulePort::Direction::Input;
42 case ModulePort::Direction::InOut:
43 return ModulePort::Direction::InOut;
45 llvm_unreachable(
"unknown PortDirection");
48bool hw::isValidIndexBitWidth(Value index, Value array) {
49 hw::ArrayType arrayType =
50 dyn_cast<hw::ArrayType>(hw::getCanonicalType(array.getType()));
51 assert(arrayType &&
"expected array type");
52 unsigned indexWidth = index.getType().getIntOrFloatBitWidth();
53 auto requiredWidth = llvm::Log2_64_Ceil(arrayType.getNumElements());
54 return requiredWidth == 0 ? (indexWidth == 0 || indexWidth == 1)
55 : indexWidth == requiredWidth;
59bool hw::isCombinational(Operation *op) {
60 struct IsCombClassifier :
public TypeOpVisitor<IsCombClassifier, bool> {
65 return (op->getDialect() && op->getDialect()->getNamespace() ==
"comb") ||
71 if (
auto structCreate = dyn_cast_or_null<StructCreateOp>(inputOp)) {
72 return structCreate.getOperand(fieldIndex);
76 if (
auto structInject = dyn_cast_or_null<StructInjectOp>(inputOp)) {
77 if (structInject.getFieldIndex() != fieldIndex)
79 return structInject.getNewValue();
85 ArrayRef<Attribute> attrs) {
87 return ArrayAttr::get(
context, {});
90 if (a && !cast<DictionaryAttr>(a).empty()) {
95 return ArrayAttr::get(
context, {});
96 return ArrayAttr::get(
context, attrs);
102 OpAsmSetValueNameFn setNameFn) {
106 auto module = cast<HWModuleOp>(region.getParentOp());
108 auto *block = ®ion.front();
109 for (
size_t i = 0, e = block->getNumArguments(); i != e; ++i) {
110 auto name =
module.getInputName(i);
112 setNameFn(block->getArgument(i), name);
128LogicalResult hw::checkParameterInContext(
129 Attribute value, ArrayAttr moduleParameters,
131 bool disallowParamRefs) {
134 if (isa<IntegerAttr>(value) || isa<FloatAttr>(value) ||
135 isa<StringAttr>(value) || isa<ParamVerbatimAttr>(value))
139 if (
auto expr = dyn_cast<ParamExprAttr>(value)) {
140 for (
auto op : expr.getOperands())
149 if (
auto parameterRef = dyn_cast<ParamDeclRefAttr>(value)) {
150 auto nameAttr = parameterRef.getName();
154 if (disallowParamRefs) {
155 instanceError([&](
auto &diag) {
156 diag <<
"parameter " << nameAttr
157 <<
" cannot be used as a default value for a parameter";
164 for (
auto param : moduleParameters) {
165 auto paramAttr = cast<ParamDeclAttr>(param);
166 if (paramAttr.getName() != nameAttr)
170 if (paramAttr.getType() == parameterRef.getType())
173 instanceError([&](
auto &diag) {
174 diag <<
"parameter " << nameAttr <<
" used with type "
175 << parameterRef.getType() <<
"; should have type "
176 << paramAttr.getType();
182 instanceError([&](
auto &diag) {
183 diag <<
"use of unknown parameter " << nameAttr;
189 instanceError([&](
auto &diag) {
190 diag <<
"invalid parameter value " << value;
202LogicalResult hw::checkParameterInContext(Attribute value, Operation *module,
204 bool disallowParamRefs) {
206 [&](
const std::function<bool(InFlightDiagnostic &)> &fn) {
208 auto diag = usingOp->emitOpError();
210 diag.attachNote(module->getLoc()) <<
"module declared here";
215 module->getAttrOfType<ArrayAttr>(
"parameters"),
216 emitError, disallowParamRefs);
221bool hw::isValidParameterExpression(Attribute attr, Operation *module) {
230 for (
auto [i, barg] : llvm::enumerate(bodyRegion.getArguments())) {
263#include "circt/Dialect/HW/HWCanonicalization.cpp.inc"
270void ConstantOp::print(OpAsmPrinter &p) {
272 if (getType() == getValueAttr().getType()) {
273 p.printAttribute(getValueAttr());
276 p.printAttributeWithoutType(getValueAttr());
277 p <<
" : " << getType();
279 p.printOptionalAttrDict((*this)->getAttrs(), {
"value"});
282ParseResult ConstantOp::parse(OpAsmParser &parser, OperationState &result) {
283 auto loc = parser.getCurrentLocation();
287 bool isTrue = succeeded(parser.parseOptionalKeyword(
"true"));
288 if (isTrue || succeeded(parser.parseOptionalKeyword(
"false"))) {
289 value = APInt(1, isTrue);
290 if (failed(parser.parseOptionalColon()))
291 type = parser.getBuilder().getI1Type();
292 }
else if (parser.parseInteger(value) || parser.parseColon()) {
295 if (!type && parser.parseType(type))
297 if (parser.parseOptionalAttrDict(result.attributes))
302 auto intType = type_dyn_cast<IntegerType>(type);
304 return parser.emitError(loc,
"expected an integer type, but got ") << type;
305 unsigned width = intType.getWidth();
306 if (value.isNegative() ? value.getSignificantBits() > width
307 : value.getActiveBits() > width)
308 return parser.emitError(loc,
"constant out of range for type ") << type;
310 result.addAttribute(
"value",
311 IntegerAttr::get(intType, value.sextOrTrunc(width)));
312 result.addTypes(type);
316LogicalResult ConstantOp::verify() {
318 auto intType = type_dyn_cast<IntegerType>(getType());
320 return emitError(
"hw.constant must have an integer result type");
323 if (getValueAttr().getType() != intType)
324 return emitError(
"hw.constant attribute type ")
325 << getValueAttr().getType() <<
" doesn't match the result type "
333void ConstantOp::build(OpBuilder &builder, OperationState &result,
334 const APInt &value) {
336 auto type = IntegerType::get(builder.getContext(), value.getBitWidth());
337 auto attr = builder.getIntegerAttr(type, value);
338 return build(builder, result, type, attr);
343void ConstantOp::build(OpBuilder &builder, OperationState &result,
345 return build(builder, result, value.getType(), value);
352void ConstantOp::build(OpBuilder &builder, OperationState &result, Type type,
354 auto intType = type_cast<IntegerType>(type);
356 builder, result, type,
357 builder.getIntegerAttr(intType, APInt(intType.getWidth(), (uint64_t)value,
362void ConstantOp::getAsmResultNames(
363 function_ref<
void(Value, StringRef)> setNameFn) {
364 Type intTy = getType();
365 auto intCst = getValue();
368 if (type_cast<IntegerType>(intTy).
getWidth() == 1)
369 return setNameFn(getResult(), intCst.isZero() ?
"false" :
"true");
373 SmallVector<char, 32> specialNameBuffer;
374 llvm::raw_svector_ostream specialName(specialNameBuffer);
375 specialName <<
'c' << intCst <<
'_';
376 if (
auto alias = dyn_cast<TypeAliasType>(intTy))
377 specialName << alias.getRef().getLeafReference().getValue();
379 specialName << intTy;
380 setNameFn(getResult(), specialName.str());
383OpFoldResult ConstantOp::fold(FoldAdaptor adaptor) {
384 assert(adaptor.getOperands().empty() &&
"constant has no operands");
385 return getValueAttr();
396 ArrayRef<StringRef> ignoredAttrs = {}) {
397 auto names = op.getAttributeNames();
398 llvm::SmallDenseSet<StringRef> nameSet;
399 nameSet.reserve(names.size() + ignoredAttrs.size());
400 nameSet.insert(names.begin(), names.end());
401 nameSet.insert(ignoredAttrs.begin(), ignoredAttrs.end());
402 return llvm::any_of(op->getAttrs(), [&](
auto namedAttr) {
403 return !nameSet.contains(namedAttr.getName());
407void WireOp::getAsmResultNames(OpAsmSetValueNameFn setNameFn) {
409 auto nameAttr = (*this)->getAttrOfType<StringAttr>(
"name");
410 if (nameAttr && !nameAttr.getValue().empty())
411 setNameFn(getResult(), nameAttr.getValue());
414std::optional<size_t> WireOp::getTargetResultIndex() {
return 0; }
416OpFoldResult WireOp::fold(FoldAdaptor adaptor) {
425LogicalResult WireOp::canonicalize(WireOp wire, PatternRewriter &rewriter) {
431 if (wire.getInnerSymAttr())
435 if (wire.getInput() == wire.getResult())
440 if (
auto *inputOp = wire.getInput().getDefiningOp())
442 rewriter.modifyOpInPlace(inputOp,
443 [&] { inputOp->setAttr(
"sv.namehint", name); });
445 rewriter.replaceOp(wire, wire.getInput());
455 if (
auto typeAlias = dyn_cast<TypeAliasType>(type))
456 type = typeAlias.getCanonicalType();
458 if (
auto structType = dyn_cast<StructType>(type)) {
459 auto arrayAttr = dyn_cast<ArrayAttr>(attr);
461 return op->emitOpError(
"expected array attribute for constant of type ")
463 if (structType.getElements().size() != arrayAttr.size())
464 return op->emitOpError(
"array attribute (")
465 << arrayAttr.size() <<
") has wrong size for struct constant ("
466 << structType.getElements().size() <<
")";
468 for (
auto [attr, fieldInfo] :
469 llvm::zip(arrayAttr.getValue(), structType.getElements())) {
473 }
else if (
auto arrayType = dyn_cast<ArrayType>(type)) {
474 auto arrayAttr = dyn_cast<ArrayAttr>(attr);
476 return op->emitOpError(
"expected array attribute for constant of type ")
478 if (arrayType.getNumElements() != arrayAttr.size())
479 return op->emitOpError(
"array attribute (")
480 << arrayAttr.size() <<
") has wrong size for array constant ("
481 << arrayType.getNumElements() <<
")";
484 for (
auto attr : arrayAttr.getValue()) {
488 }
else if (
auto arrayType = dyn_cast<UnpackedArrayType>(type)) {
489 auto arrayAttr = dyn_cast<ArrayAttr>(attr);
491 return op->emitOpError(
"expected array attribute for constant of type ")
494 if (arrayType.getNumElements() != arrayAttr.size())
495 return op->emitOpError(
"array attribute (")
497 <<
") has wrong size for unpacked array constant ("
498 << arrayType.getNumElements() <<
")";
500 for (
auto attr : arrayAttr.getValue()) {
504 }
else if (
auto enumType = dyn_cast<EnumType>(type)) {
505 auto stringAttr = dyn_cast<StringAttr>(attr);
507 return op->emitOpError(
"expected string attribute for constant of type ")
509 }
else if (
auto intType = dyn_cast<IntegerType>(type)) {
511 auto intAttr = dyn_cast<IntegerAttr>(attr);
513 return op->emitOpError(
"expected integer attribute for constant of type ")
516 if (intAttr.getValue().getBitWidth() != intType.getWidth())
517 return op->emitOpError(
"hw.constant attribute bitwidth "
518 "doesn't match return type");
519 }
else if (
auto typedAttr = dyn_cast<TypedAttr>(attr)) {
520 if (typedAttr.getType() != type)
521 return op->emitOpError(
"typed attr doesn't match the return type ")
524 return op->emitOpError(
"unknown element type ") << type;
529LogicalResult AggregateConstantOp::verify() {
533OpFoldResult AggregateConstantOp::fold(FoldAdaptor) {
return getFieldsAttr(); }
541 if (p.parseType(resultType) || p.parseEqual() ||
542 p.parseAttribute(value, resultType))
549 p << resultType <<
" = ";
550 p.printAttributeWithoutType(value);
553LogicalResult ParamValueOp::verify() {
559OpFoldResult ParamValueOp::fold(FoldAdaptor adaptor) {
560 assert(adaptor.getOperands().empty() &&
"hw.param.value has no operands");
561 return getValueAttr();
570 return isa<HWModuleLike, InstanceOp>(moduleOrInstance);
576 return TypeSwitch<Operation *, FunctionType>(moduleOrInstance)
577 .Case<InstanceOp>([](
auto instance) {
578 SmallVector<Type> inputs(instance->getOperandTypes());
579 SmallVector<Type> results(instance->getResultTypes());
580 return FunctionType::get(instance->getContext(), inputs, results);
583 [](
auto mod) {
return mod.getHWModuleType().getFuncType(); })
584 .Default([](Operation *op) {
585 return cast<FunctionType>(
586 cast<mlir::FunctionOpInterface>(op).getFunctionType());
594 auto nameAttr =
module->getAttrOfType<StringAttr>("verilogName");
598 if (
auto symbol = dyn_cast<mlir::SymbolOpInterface>(module))
599 return symbol.getNameAttr();
603template <
typename ModuleTy>
605buildModule(OpBuilder &builder, OperationState &result, StringAttr name,
607 ArrayRef<NamedAttribute> attributes, StringAttr comment) {
608 using namespace mlir::function_interface_impl;
611 result.addAttribute(ModuleTy::getSymNameAttrName(result.name), name);
613 SmallVector<Attribute> perPortAttrs;
614 SmallVector<ModulePort> portTypes;
616 for (
auto elt : ports) {
617 portTypes.push_back(elt);
618 llvm::SmallVector<NamedAttribute> portAttrs;
620 llvm::copy(elt.attrs, std::back_inserter(portAttrs));
621 perPortAttrs.push_back(builder.getDictionaryAttr(portAttrs));
626 parameters = builder.getArrayAttr({});
629 auto type = ModuleType::get(builder.getContext(), portTypes);
630 result.addAttribute(ModuleTy::getModuleTypeAttrName(result.name),
631 TypeAttr::get(type));
632 result.addAttribute(
"per_port_attrs",
634 result.addAttribute(
"parameters", parameters);
636 comment = builder.getStringAttr(
"");
637 result.addAttribute(
"comment", comment);
638 result.addAttributes(attributes);
644 MLIRContext *
context, ArrayRef<std::pair<unsigned, PortInfo>> insertArgs,
645 ArrayRef<unsigned> removeArgs, ArrayRef<Attribute> oldArgNames,
646 ArrayRef<Type> oldArgTypes, ArrayRef<Attribute> oldArgAttrs,
647 ArrayRef<Location> oldArgLocs, SmallVector<Attribute> &newArgNames,
648 SmallVector<Type> &newArgTypes, SmallVector<Attribute> &newArgAttrs,
649 SmallVector<Location> &newArgLocs, Block *body =
nullptr) {
654 assert(llvm::is_sorted(insertArgs,
655 [](
auto &a,
auto &b) {
return a.first < b.first; }) &&
656 "insertArgs must be in ascending order");
657 assert(llvm::is_sorted(removeArgs, [](
auto &a,
auto &b) {
return a < b; }) &&
658 "removeArgs must be in ascending order");
661 auto oldArgCount = oldArgTypes.size();
662 auto newArgCount = oldArgCount + insertArgs.size() - removeArgs.size();
663 assert((
int)newArgCount >= 0);
665 newArgNames.reserve(newArgCount);
666 newArgTypes.reserve(newArgCount);
667 newArgAttrs.reserve(newArgCount);
668 newArgLocs.reserve(newArgCount);
670 auto emptyDictAttr = DictionaryAttr::get(
context, {});
671 auto unknownLoc = UnknownLoc::get(
context);
673 BitVector erasedIndices;
675 erasedIndices.resize(oldArgCount + insertArgs.size());
677 for (
unsigned argIdx = 0, idx = 0; argIdx <= oldArgCount; ++argIdx, ++idx) {
679 while (!insertArgs.empty() && insertArgs[0].first == argIdx) {
680 auto port = insertArgs[0].second;
682 !isa<InOutType>(port.type))
683 port.type = InOutType::get(port.type);
684 newArgNames.push_back(port.name);
685 newArgTypes.push_back(port.type);
686 newArgAttrs.push_back(port.attrs ? port.attrs : emptyDictAttr);
687 insertArgs = insertArgs.drop_front();
688 LocationAttr loc = port.loc ? port.loc : unknownLoc;
689 newArgLocs.push_back(loc);
691 body->insertArgument(idx++, port.type, loc);
693 if (argIdx == oldArgCount)
697 bool removed =
false;
698 while (!removeArgs.empty() && removeArgs[0] == argIdx) {
699 removeArgs = removeArgs.drop_front();
705 erasedIndices.set(idx);
707 newArgNames.push_back(oldArgNames[argIdx]);
708 newArgTypes.push_back(oldArgTypes[argIdx]);
709 newArgAttrs.push_back(oldArgAttrs.empty() ? emptyDictAttr
710 : oldArgAttrs[argIdx]);
711 newArgLocs.push_back(oldArgLocs[argIdx]);
716 body->eraseArguments(erasedIndices);
718 assert(newArgNames.size() == newArgCount);
719 assert(newArgTypes.size() == newArgCount);
720 assert(newArgAttrs.size() == newArgCount);
721 assert(newArgLocs.size() == newArgCount);
735[[deprecated]]
static void
737 ArrayRef<std::pair<unsigned, PortInfo>> insertInputs,
738 ArrayRef<std::pair<unsigned, PortInfo>> insertOutputs,
739 ArrayRef<unsigned> removeInputs,
740 ArrayRef<unsigned> removeOutputs, Block *body =
nullptr) {
741 auto moduleOp = cast<HWModuleLike>(op);
742 auto *
context = moduleOp.getContext();
745 auto oldArgNames = moduleOp.getInputNames();
746 auto oldArgTypes = moduleOp.getInputTypes();
747 auto oldArgAttrs = moduleOp.getAllInputAttrs();
748 auto oldArgLocs = moduleOp.getInputLocs();
750 auto oldResultNames = moduleOp.getOutputNames();
751 auto oldResultTypes = moduleOp.getOutputTypes();
752 auto oldResultAttrs = moduleOp.getAllOutputAttrs();
753 auto oldResultLocs = moduleOp.getOutputLocs();
756 SmallVector<Attribute> newArgNames, newResultNames;
757 SmallVector<Type> newArgTypes, newResultTypes;
758 SmallVector<Attribute> newArgAttrs, newResultAttrs;
759 SmallVector<Location> newArgLocs, newResultLocs;
762 oldArgTypes, oldArgAttrs, oldArgLocs, newArgNames,
763 newArgTypes, newArgAttrs, newArgLocs, body);
766 oldResultTypes, oldResultAttrs, oldResultLocs,
767 newResultNames, newResultTypes, newResultAttrs,
771 auto fnty = FunctionType::get(
context, newArgTypes, newResultTypes);
773 moduleOp.setHWModuleType(modty);
774 moduleOp.setAllInputAttrs(newArgAttrs);
775 moduleOp.setAllOutputAttrs(newResultAttrs);
777 newArgLocs.append(newResultLocs.begin(), newResultLocs.end());
778 moduleOp.setAllPortLocs(newArgLocs);
781void HWModuleOp::build(OpBuilder &builder, OperationState &result,
783 ArrayAttr parameters,
784 ArrayRef<NamedAttribute> attributes, StringAttr comment,
785 bool shouldEnsureTerminator) {
786 buildModule<HWModuleOp>(builder, result, name, ports, parameters, attributes,
790 auto *bodyRegion = result.regions[0].get();
792 bodyRegion->push_back(body);
795 auto unknownLoc = builder.getUnknownLoc();
796 for (
auto port : ports.getInputs()) {
797 auto loc = port.loc ? Location(port.loc) : unknownLoc;
798 auto type = port.type;
799 if (port.isInOut() && !isa<InOutType>(type))
800 type = InOutType::get(type);
801 body->addArgument(type, loc);
805 auto unknownLocAttr = cast<LocationAttr>(unknownLoc);
806 SmallVector<Attribute> resultLocs;
807 for (
auto port : ports.getOutputs())
808 resultLocs.push_back(port.loc ? port.loc : unknownLocAttr);
809 result.addAttribute(
"result_locs", builder.getArrayAttr(resultLocs));
811 if (shouldEnsureTerminator)
812 HWModuleOp::ensureTerminator(*bodyRegion, builder, result.location);
815void HWModuleOp::build(OpBuilder &builder, OperationState &result,
816 StringAttr name, ArrayRef<PortInfo> ports,
817 ArrayAttr parameters,
818 ArrayRef<NamedAttribute> attributes,
819 StringAttr comment) {
820 build(builder, result, name,
ModulePortInfo(ports), parameters, attributes,
824void HWModuleOp::build(OpBuilder &builder, OperationState &odsState,
827 ArrayRef<NamedAttribute> attributes,
828 StringAttr comment) {
829 build(builder, odsState, name, ports, parameters, attributes, comment,
831 auto *bodyRegion = odsState.regions[0].get();
832 OpBuilder::InsertionGuard guard(builder);
834 builder.setInsertionPointToEnd(&bodyRegion->front());
835 modBuilder(builder, accessor);
837 llvm::SmallVector<Value> outputOperands = accessor.getOutputOperands();
838 hw::OutputOp::create(builder, odsState.location, outputOperands);
841void HWModuleOp::modifyPorts(
842 ArrayRef<std::pair<unsigned, PortInfo>> insertInputs,
843 ArrayRef<std::pair<unsigned, PortInfo>> insertOutputs,
844 ArrayRef<unsigned> eraseInputs, ArrayRef<unsigned> eraseOutputs) {
852StringAttr HWModuleExternOp::getVerilogModuleNameAttr() {
853 if (
auto vName = getVerilogNameAttr())
856 return getSymNameAttr();
859StringAttr HWModuleGeneratedOp::getVerilogModuleNameAttr() {
860 if (
auto vName = getVerilogNameAttr()) {
863 return getSymNameAttr();
866void HWModuleExternOp::build(OpBuilder &builder, OperationState &result,
868 StringRef verilogName, ArrayAttr parameters,
869 ArrayRef<NamedAttribute> attributes) {
870 buildModule<HWModuleExternOp>(builder, result, name, ports, parameters,
874 LocationAttr unknownLoc = builder.getUnknownLoc();
875 SmallVector<Attribute> portLocs;
876 for (
auto elt : ports)
877 portLocs.push_back(elt.loc ? elt.loc : unknownLoc);
878 result.addAttribute(
"port_locs", builder.getArrayAttr(portLocs));
880 if (!verilogName.empty())
881 result.addAttribute(
"verilogName", builder.getStringAttr(verilogName));
884void HWModuleExternOp::build(OpBuilder &builder, OperationState &result,
885 StringAttr name, ArrayRef<PortInfo> ports,
886 StringRef verilogName, ArrayAttr parameters,
887 ArrayRef<NamedAttribute> attributes) {
888 build(builder, result, name,
ModulePortInfo(ports), verilogName, parameters,
892void HWModuleExternOp::modifyPorts(
893 ArrayRef<std::pair<unsigned, PortInfo>> insertInputs,
894 ArrayRef<std::pair<unsigned, PortInfo>> insertOutputs,
895 ArrayRef<unsigned> eraseInputs, ArrayRef<unsigned> eraseOutputs) {
900void HWModuleExternOp::appendOutputs(
901 ArrayRef<std::pair<StringAttr, Value>> outputs) {}
903void HWModuleGeneratedOp::build(OpBuilder &builder, OperationState &result,
904 FlatSymbolRefAttr genKind, StringAttr name,
906 StringRef verilogName, ArrayAttr parameters,
907 ArrayRef<NamedAttribute> attributes) {
908 buildModule<HWModuleGeneratedOp>(builder, result, name, ports, parameters,
911 LocationAttr unknownLoc = builder.getUnknownLoc();
912 SmallVector<Attribute> portLocs;
913 for (
auto elt : ports)
914 portLocs.push_back(elt.loc ? elt.loc : unknownLoc);
915 result.addAttribute(
"port_locs", builder.getArrayAttr(portLocs));
917 result.addAttribute(
"generatorKind", genKind);
918 if (!verilogName.empty())
919 result.addAttribute(
"verilogName", builder.getStringAttr(verilogName));
922void HWModuleGeneratedOp::build(OpBuilder &builder, OperationState &result,
923 FlatSymbolRefAttr genKind, StringAttr name,
924 ArrayRef<PortInfo> ports, StringRef verilogName,
925 ArrayAttr parameters,
926 ArrayRef<NamedAttribute> attributes) {
927 build(builder, result, genKind, name,
ModulePortInfo(ports), verilogName,
928 parameters, attributes);
931void HWModuleGeneratedOp::modifyPorts(
932 ArrayRef<std::pair<unsigned, PortInfo>> insertInputs,
933 ArrayRef<std::pair<unsigned, PortInfo>> insertOutputs,
934 ArrayRef<unsigned> eraseInputs, ArrayRef<unsigned> eraseOutputs) {
939void HWModuleGeneratedOp::appendOutputs(
940 ArrayRef<std::pair<StringAttr, Value>> outputs) {}
942static bool hasAttribute(StringRef name, ArrayRef<NamedAttribute> attrs) {
943 for (
auto &argAttr : attrs)
944 if (argAttr.getName() == name)
949template <
typename ModuleTy>
951 OperationState &result) {
953 using namespace mlir::function_interface_impl;
954 auto builder = parser.getBuilder();
955 auto loc = parser.getCurrentLocation();
958 (void)mlir::impl::parseOptionalVisibilityKeyword(parser, result.attributes);
962 if (parser.parseSymbolName(nameAttr,
963 ModuleTy::getSymNameAttrName(result.name),
968 FlatSymbolRefAttr kindAttr;
969 if constexpr (std::is_same_v<ModuleTy, HWModuleGeneratedOp>) {
970 if (parser.parseComma() ||
971 parser.parseAttribute(kindAttr,
"generatorKind", result.attributes)) {
977 ArrayAttr parameters;
981 SmallVector<module_like_impl::PortParse> ports;
987 if (failed(parser.parseOptionalAttrDictWithKeyword(result.attributes)))
991 parser.emitError(loc,
"explicit `parameters` attributes not allowed");
995 result.addAttribute(
"parameters", parameters);
996 result.addAttribute(ModuleTy::getModuleTypeAttrName(result.name), modType);
1000 SmallVector<Attribute> attrs;
1001 for (
auto &port : ports)
1002 attrs.push_back(port.attrs ? port.attrs : builder.getDictionaryAttr({}));
1004 auto nonEmptyAttrsFn = [](Attribute attr) {
1005 return attr && !cast<DictionaryAttr>(attr).empty();
1007 if (llvm::any_of(attrs, nonEmptyAttrsFn))
1008 result.addAttribute(ModuleTy::getPerPortAttrsAttrName(result.name),
1009 builder.getArrayAttr(attrs));
1012 auto unknownLoc = builder.getUnknownLoc();
1013 auto nonEmptyLocsFn = [unknownLoc](Attribute attr) {
1014 return attr && cast<Location>(attr) != unknownLoc;
1016 SmallVector<Attribute> locs;
1017 StringAttr portLocsAttrName;
1018 if constexpr (std::is_same_v<ModuleTy, HWModuleOp>) {
1021 portLocsAttrName = ModuleTy::getResultLocsAttrName(result.name);
1022 for (
auto &port : ports)
1024 locs.push_back(port.sourceLoc ? Location(*port.sourceLoc) : unknownLoc);
1027 portLocsAttrName = ModuleTy::getPortLocsAttrName(result.name);
1028 for (
auto &port : ports)
1029 locs.push_back(port.sourceLoc ? Location(*port.sourceLoc) : unknownLoc);
1031 if (llvm::any_of(locs, nonEmptyLocsFn))
1032 result.addAttribute(portLocsAttrName, builder.getArrayAttr(locs));
1035 SmallVector<OpAsmParser::Argument, 4> entryArgs;
1036 for (
auto &port : ports)
1038 entryArgs.push_back(port);
1041 auto *body = result.addRegion();
1042 if (std::is_same_v<ModuleTy, HWModuleOp>) {
1043 if (parser.parseRegion(*body, entryArgs))
1046 HWModuleOp::ensureTerminator(*body, parser.getBuilder(), result.location);
1051ParseResult HWModuleOp::parse(OpAsmParser &parser, OperationState &result) {
1052 return parseHWModuleOp<HWModuleOp>(parser, result);
1055ParseResult HWModuleExternOp::parse(OpAsmParser &parser,
1056 OperationState &result) {
1057 return parseHWModuleOp<HWModuleExternOp>(parser, result);
1060ParseResult HWModuleGeneratedOp::parse(OpAsmParser &parser,
1061 OperationState &result) {
1062 return parseHWModuleOp<HWModuleGeneratedOp>(parser, result);
1066 if (
auto mod = dyn_cast<HWModuleLike>(op))
1067 return mod.getHWModuleType().getFuncType();
1068 return cast<FunctionType>(
1069 cast<mlir::FunctionOpInterface>(op).getFunctionType());
1072template <
typename ModuleTy>
1076 StringRef visibilityAttrName =
1077 mlir::SymbolOpInterface::getDefaultVisibilityAttrName();
1078 if (
auto visibility = mod.getOperation()->template getAttrOfType<StringAttr>(
1079 visibilityAttrName))
1080 p << visibility.getValue() <<
' ';
1083 p.printSymbolName(mod.getName());
1084 if (
auto gen = dyn_cast<HWModuleGeneratedOp>(mod.getOperation())) {
1086 p.printSymbolName(gen.getGeneratorKind());
1094 SmallVector<StringRef, 3> omittedAttrs;
1095 omittedAttrs.push_back(mod.getSymNameAttrName());
1096 if (isa<HWModuleGeneratedOp>(mod.getOperation()))
1097 omittedAttrs.push_back(
"generatorKind");
1098 if constexpr (std::is_same_v<ModuleTy, HWModuleOp>)
1099 omittedAttrs.push_back(mod.getResultLocsAttrName());
1101 omittedAttrs.push_back(mod.getPortLocsAttrName());
1102 omittedAttrs.push_back(mod.getModuleTypeAttrName());
1103 omittedAttrs.push_back(mod.getPerPortAttrsAttrName());
1104 omittedAttrs.push_back(mod.getParametersAttrName());
1105 omittedAttrs.push_back(visibilityAttrName);
1107 mod.getOperation()->template getAttrOfType<StringAttr>(
"comment"))
1108 if (cmt.getValue().empty())
1109 omittedAttrs.push_back(
"comment");
1111 mlir::function_interface_impl::printFunctionAttributes(p, mod.getOperation(),
1115void HWModuleExternOp::print(OpAsmPrinter &p) {
printModuleOp(p, *
this); }
1116void HWModuleGeneratedOp::print(OpAsmPrinter &p) {
printModuleOp(p, *
this); }
1118void HWModuleOp::print(OpAsmPrinter &p) {
1122 Region &body = getBody();
1123 if (!body.empty()) {
1125 p.printRegion(body,
false,
1131 assert(isa<HWModuleLike>(module) &&
1132 "verifier hook should only be called on modules");
1134 if (
auto portLocs = module->getAttrOfType<ArrayAttr>(
"port_locs"))
1135 if (!portLocs.empty() && portLocs.size() != module.getNumPorts())
1136 return module->emitOpError("requires ")
1137 << module.getNumPorts() << " port locations but got "
1140 for (
auto port :
module.getPortList()) {
1141 auto result = success();
1142 port.type.walk([&](Type type) {
1145 auto &dialect = type.getDialect();
1150 result = interface->verifyHWModulePortType(
1151 [&] { return module->emitOpError(); }, port.dir, type);
1157 SmallPtrSet<Attribute, 4> paramNames;
1160 for (auto param : module->getAttrOfType<ArrayAttr>("parameters")) {
1161 auto paramAttr = cast<ParamDeclAttr>(param);
1165 if (!paramNames.insert(paramAttr.getName()).second)
1166 return module->emitOpError("parameter ")
1167 << paramAttr << " has the same name as a previous parameter";
1170 auto value = paramAttr.getValue();
1174 auto typedValue = dyn_cast<TypedAttr>(value);
1176 return module->emitOpError("parameter ")
1177 << paramAttr << " should have a typed value; has value
" << value;
1179 if (typedValue.getType() != paramAttr.getType())
1180 return module->emitOpError("parameter
")
1181 << paramAttr << " should have type
" << paramAttr.getType()
1182 << "; has type
" << typedValue.getType();
1184 // Verify that this is a valid parameter value, disallowing parameter
1185 // references. We could allow parameters to refer to each other in the
1186 // future with lexical ordering if there is a need.
1187 if (failed(checkParameterInContext(value, module, module,
1188 /*disallowParamRefs=*/true)))
1194LogicalResult HWModuleOp::verify() {
1195 if (failed(verifyModuleCommon(*this)))
1198 auto type = getModuleType();
1199 auto *body = getBodyBlock();
1201 // Verify the number of block arguments.
1202 auto numInputs = type.getNumInputs();
1203 if (body->getNumArguments() != numInputs)
1204 return emitOpError("entry block must have
")
1205 << numInputs << " arguments to match
module signature";
1212std::pair<StringAttr, BlockArgument>
1213HWModuleOp::insertInput(
unsigned index, StringAttr name, Type ty) {
1217 for (
auto port : ports)
1218 ns.
newName(port.name.getValue());
1219 auto nameAttr = StringAttr::get(getContext(), ns.
newName(name.getValue()));
1225 port.
name = nameAttr;
1232 return {nameAttr, body->getArgument(index)};
1235void HWModuleOp::insertOutputs(
unsigned index,
1236 ArrayRef<std::pair<StringAttr, Value>> outputs) {
1238 auto output = cast<OutputOp>(
getBodyBlock()->getTerminator());
1239 assert(index <= output->getNumOperands() &&
"invalid output index");
1242 SmallVector<std::pair<unsigned, PortInfo>> indexedNewPorts;
1243 for (
auto &[name, value] : outputs) {
1247 port.
type = value.getType();
1248 indexedNewPorts.emplace_back(index, port);
1254 for (
auto &[name, value] : outputs)
1255 output->insertOperands(index++, value);
1258void HWModuleOp::appendOutputs(ArrayRef<std::pair<StringAttr, Value>> outputs) {
1259 return insertOutputs(getNumOutputPorts(), outputs);
1262void HWModuleOp::getAsmBlockArgumentNames(mlir::Region ®ion,
1267void HWModuleExternOp::getAsmBlockArgumentNames(
1272template <
typename ModTy>
1274 auto locs =
module.getPortLocs();
1276 SmallVector<Location> retval;
1277 retval.reserve(locs->size());
1278 for (
auto l : *locs)
1279 retval.push_back(cast<Location>(l));
1281 assert(!locs->size() || locs->size() == module.getNumPorts());
1284 return SmallVector<Location>(module.getNumPorts(),
1285 UnknownLoc::get(module.getContext()));
1288SmallVector<Location> HWModuleOp::getAllPortLocs() {
1289 SmallVector<Location> portLocs;
1291 auto resultLocs = getResultLocsAttr();
1292 unsigned inputCount = 0;
1294 auto unknownLoc = UnknownLoc::get(getContext());
1296 for (
unsigned i = 0, e =
getNumPorts(); i < e; ++i) {
1297 if (modType.isOutput(i)) {
1298 auto loc = resultLocs
1300 resultLocs.getValue()[portLocs.size() - inputCount])
1302 portLocs.push_back(loc);
1304 auto loc = body ? body->getArgument(inputCount).getLoc() : unknownLoc;
1305 portLocs.push_back(loc);
1312SmallVector<Location> HWModuleExternOp::getAllPortLocs() {
1313 return ::getAllPortLocs(*
this);
1316SmallVector<Location> HWModuleGeneratedOp::getAllPortLocs() {
1317 return ::getAllPortLocs(*
this);
1320void HWModuleOp::setAllPortLocsAttrs(ArrayRef<Attribute> locs) {
1321 SmallVector<Attribute> resultLocs;
1322 unsigned inputCount = 0;
1325 for (
unsigned i = 0, e =
getNumPorts(); i < e; ++i) {
1326 if (modType.isOutput(i))
1327 resultLocs.push_back(locs[i]);
1329 body->getArgument(inputCount++).setLoc(cast<Location>(locs[i]));
1331 setResultLocsAttr(ArrayAttr::get(getContext(), resultLocs));
1334void HWModuleExternOp::setAllPortLocsAttrs(ArrayRef<Attribute> locs) {
1335 setPortLocsAttr(ArrayAttr::get(getContext(), locs));
1338void HWModuleGeneratedOp::setAllPortLocsAttrs(ArrayRef<Attribute> locs) {
1339 setPortLocsAttr(ArrayAttr::get(getContext(), locs));
1342template <
typename ModTy>
1344 auto numInputs =
module.getNumInputPorts();
1345 SmallVector<Attribute> argNames(names.begin(), names.begin() + numInputs);
1346 SmallVector<Attribute> resNames(names.begin() + numInputs, names.end());
1347 auto oldType =
module.getModuleType();
1348 SmallVector<ModulePort> newPorts(oldType.getPorts().begin(),
1349 oldType.getPorts().end());
1350 for (
size_t i = 0UL, e = newPorts.size(); i != e; ++i)
1351 newPorts[i].name = cast<StringAttr>(names[i]);
1352 auto newType = ModuleType::get(module.getContext(), newPorts);
1353 module.setModuleType(newType);
1356void HWModuleOp::setAllPortNames(ArrayRef<Attribute> names) {
1360void HWModuleExternOp::setAllPortNames(ArrayRef<Attribute> names) {
1364void HWModuleGeneratedOp::setAllPortNames(ArrayRef<Attribute> names) {
1368ArrayRef<Attribute> HWModuleOp::getAllPortAttrs() {
1369 auto attrs = getPerPortAttrs();
1370 if (attrs && !attrs->empty())
1371 return attrs->getValue();
1375ArrayRef<Attribute> HWModuleExternOp::getAllPortAttrs() {
1376 auto attrs = getPerPortAttrs();
1377 if (attrs && !attrs->empty())
1378 return attrs->getValue();
1382ArrayRef<Attribute> HWModuleGeneratedOp::getAllPortAttrs() {
1383 auto attrs = getPerPortAttrs();
1384 if (attrs && !attrs->empty())
1385 return attrs->getValue();
1389void HWModuleOp::setAllPortAttrs(ArrayRef<Attribute> attrs) {
1390 setPerPortAttrsAttr(
arrayOrEmpty(getContext(), attrs));
1393void HWModuleExternOp::setAllPortAttrs(ArrayRef<Attribute> attrs) {
1394 setPerPortAttrsAttr(
arrayOrEmpty(getContext(), attrs));
1397void HWModuleGeneratedOp::setAllPortAttrs(ArrayRef<Attribute> attrs) {
1398 setPerPortAttrsAttr(
arrayOrEmpty(getContext(), attrs));
1401void HWModuleOp::removeAllPortAttrs() {
1402 setPerPortAttrsAttr(ArrayAttr::get(getContext(), {}));
1405void HWModuleExternOp::removeAllPortAttrs() {
1406 setPerPortAttrsAttr(ArrayAttr::get(getContext(), {}));
1409void HWModuleGeneratedOp::removeAllPortAttrs() {
1410 setPerPortAttrsAttr(ArrayAttr::get(getContext(), {}));
1415template <
typename ModTy>
1417 auto argAttrs = mod.getAllInputAttrs();
1418 auto resAttrs = mod.getAllOutputAttrs();
1419 mod.setModuleTypeAttr(TypeAttr::get(type));
1420 unsigned newNumArgs = type.getNumInputs();
1421 unsigned newNumResults = type.getNumOutputs();
1423 auto emptyDict = DictionaryAttr::get(mod.getContext());
1424 argAttrs.resize(newNumArgs, emptyDict);
1425 resAttrs.resize(newNumResults, emptyDict);
1427 SmallVector<Attribute> attrs;
1428 attrs.append(argAttrs.begin(), argAttrs.end());
1429 attrs.append(resAttrs.begin(), resAttrs.end());
1432 return mod.removeAllPortAttrs();
1433 mod.setAllPortAttrs(attrs);
1436void HWModuleOp::setHWModuleType(ModuleType type) {
1437 return ::setHWModuleType(*
this, type);
1440void HWModuleExternOp::setHWModuleType(ModuleType type) {
1441 return ::setHWModuleType(*
this, type);
1444void HWModuleGeneratedOp::setHWModuleType(ModuleType type) {
1445 return ::setHWModuleType(*
this, type);
1450Operation *HWModuleGeneratedOp::getGeneratorKindOp() {
1451 auto topLevelModuleOp = (*this)->getParentOfType<ModuleOp>();
1452 return topLevelModuleOp.lookupSymbol(getGeneratorKind());
1456HWModuleGeneratedOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1457 auto *referencedKind =
1458 symbolTable.lookupNearestSymbolFrom(*
this, getGeneratorKindAttr());
1460 if (referencedKind ==
nullptr)
1461 return emitError(
"Cannot find generator definition '")
1462 << getGeneratorKind() <<
"'";
1464 if (!isa<HWGeneratorSchemaOp>(referencedKind))
1465 return emitError(
"Symbol resolved to '")
1466 << referencedKind->getName()
1467 <<
"' which is not a HWGeneratorSchemaOp";
1469 auto referencedKindOp = dyn_cast<HWGeneratorSchemaOp>(referencedKind);
1470 auto paramRef = referencedKindOp.getRequiredAttrs();
1471 auto dict = (*this)->getAttrDictionary();
1472 for (
auto str : paramRef) {
1473 auto strAttr = dyn_cast<StringAttr>(str);
1475 return emitError(
"Unknown attribute type, expected a string");
1476 if (!dict.get(strAttr.getValue()))
1477 return emitError(
"Missing attribute '") << strAttr.getValue() <<
"'";
1483LogicalResult HWModuleGeneratedOp::verify() {
1487void HWModuleGeneratedOp::getAsmBlockArgumentNames(
1492LogicalResult HWModuleOp::verifyBody() {
return success(); }
1494template <
typename ModuleTy>
1496 auto modTy = mod.getHWModuleType();
1497 auto emptyDict = DictionaryAttr::get(mod.getContext());
1498 SmallVector<PortInfo> retval;
1499 auto locs = mod.getAllPortLocs();
1500 for (
unsigned i = 0, e = modTy.getNumPorts(); i < e; ++i) {
1501 LocationAttr loc = locs[i];
1502 DictionaryAttr attrs =
1503 dyn_cast_or_null<DictionaryAttr>(mod.getPortAttrs(i));
1506 retval.push_back({modTy.getPorts()[i],
1507 modTy.isOutput(i) ? modTy.getOutputIdForPortId(i)
1508 : modTy.getInputIdForPortId(i),
1514template <
typename ModuleTy>
1516 auto modTy = mod.getHWModuleType();
1517 auto emptyDict = DictionaryAttr::get(mod.getContext());
1518 LocationAttr loc = mod.getPortLoc(idx);
1519 DictionaryAttr attrs =
1520 dyn_cast_or_null<DictionaryAttr>(mod.getPortAttrs(idx));
1523 return {modTy.getPorts()[idx],
1524 modTy.isOutput(idx) ? modTy.getOutputIdForPortId(idx)
1525 : modTy.getInputIdForPortId(idx),
1534void InstanceOp::build(OpBuilder &builder, OperationState &result,
1535 Operation *module, StringAttr name,
1536 ArrayRef<Value> inputs, ArrayAttr parameters,
1537 InnerSymAttr innerSym) {
1539 parameters = builder.getArrayAttr({});
1541 auto mod = cast<hw::HWModuleLike>(module);
1542 auto argNames = builder.getArrayAttr(mod.getInputNames());
1543 auto resultNames = builder.getArrayAttr(mod.getOutputNames());
1548 ModuleType modType = mod.getHWModuleType();
1549 FailureOr<ModuleType> resolvedModType = modType.resolveParametricTypes(
1550 parameters, result.location,
false);
1551 if (succeeded(resolvedModType))
1552 modType = *resolvedModType;
1553 FunctionType funcType = resolvedModType->getFuncType();
1554 build(builder, result, funcType.getResults(), name,
1555 FlatSymbolRefAttr::get(SymbolTable::getSymbolName(module)), inputs,
1556 argNames, resultNames, parameters, innerSym, {});
1559std::optional<size_t> InstanceOp::getTargetResultIndex() {
1561 return std::nullopt;
1564LogicalResult InstanceOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1566 *
this, getModuleNameAttr(), getInputs(), getResultTypes(), getArgNames(),
1567 getResultNames(), getParameters(), symbolTable);
1570LogicalResult InstanceOp::verify() {
1571 auto module = (*this)->getParentOfType<HWModuleOp>();
1575 auto moduleParameters =
module->getAttrOfType<ArrayAttr>("parameters");
1577 [&](
const std::function<bool(InFlightDiagnostic &)> &fn) {
1578 auto diag = emitOpError();
1580 diag.attachNote(module->getLoc()) <<
"module declared here";
1583 getParameters(), moduleParameters, emitError);
1586ParseResult InstanceOp::parse(OpAsmParser &parser, OperationState &result) {
1587 StringAttr instanceNameAttr;
1588 InnerSymAttr innerSym;
1589 FlatSymbolRefAttr moduleNameAttr;
1590 SmallVector<OpAsmParser::UnresolvedOperand, 4> inputsOperands;
1591 SmallVector<Type, 1> inputsTypes, allResultTypes;
1592 ArrayAttr argNames, resultNames, parameters;
1593 auto noneType = parser.getBuilder().getType<NoneType>();
1595 if (parser.parseAttribute(instanceNameAttr, noneType,
"instanceName",
1599 if (succeeded(parser.parseOptionalKeyword(
"sym"))) {
1602 if (parser.parseCustomAttributeWithFallback(innerSym))
1607 llvm::SMLoc parametersLoc, inputsOperandsLoc;
1608 if (parser.parseAttribute(moduleNameAttr, noneType,
"moduleName",
1609 result.attributes) ||
1610 parser.getCurrentLocation(¶metersLoc) ||
1613 parser.resolveOperands(inputsOperands, inputsTypes, inputsOperandsLoc,
1615 parser.parseArrow() ||
1617 parser.parseOptionalAttrDict(result.attributes)) {
1621 result.addAttribute(
"argNames", argNames);
1622 result.addAttribute(
"resultNames", resultNames);
1623 result.addAttribute(
"parameters", parameters);
1624 result.addTypes(allResultTypes);
1628void InstanceOp::print(OpAsmPrinter &p) {
1630 p.printAttributeWithoutType(getInstanceNameAttr());
1631 if (
auto attr = getInnerSymAttr()) {
1636 p.printAttributeWithoutType(getModuleNameAttr());
1643 p.printOptionalAttrDict(
1644 (*this)->getAttrs(),
1646 InnerSymbolTable::getInnerSymbolAttrName(),
"moduleName",
1647 "argNames",
"resultNames",
"parameters"});
1655LogicalResult OutputOp::verify() {
1659 if (
auto mod = dyn_cast<HWModuleOp>((*this)->getParentOp()))
1660 modType = mod.getHWModuleType();
1662 emitOpError(
"must have a module parent");
1665 auto modResults = modType.getOutputTypes();
1666 OperandRange outputValues = getOperands();
1667 if (modResults.size() != outputValues.size()) {
1668 emitOpError(
"must have same number of operands as region results.");
1673 for (
size_t i = 0, e = modResults.size(); i < e; ++i) {
1674 if (modResults[i] != outputValues[i].getType()) {
1675 emitOpError(
"output types must match module. In "
1677 << i <<
", expected " << modResults[i] <<
", but got "
1678 << outputValues[i].getType() <<
".";
1693 if (p.parseType(type))
1694 return p.emitError(p.getCurrentLocation(),
"Expected type");
1695 auto arrType = type_dyn_cast<ArrayType>(type);
1697 return p.emitError(p.getCurrentLocation(),
"Expected !hw.array type");
1699 unsigned idxWidth = llvm::Log2_64_Ceil(arrType.getNumElements());
1700 idxType = IntegerType::get(p.getBuilder().getContext(), idxWidth);
1706 p.printType(srcType);
1709ParseResult ArrayCreateOp::parse(OpAsmParser &parser, OperationState &result) {
1710 llvm::SMLoc inputOperandsLoc = parser.getCurrentLocation();
1711 llvm::SmallVector<OpAsmParser::UnresolvedOperand, 16> operands;
1714 if (parser.parseOperandList(operands) ||
1715 parser.parseOptionalAttrDict(result.attributes) || parser.parseColon() ||
1716 parser.parseType(elemType))
1719 if (operands.size() == 0)
1720 return parser.emitError(inputOperandsLoc,
1721 "Cannot construct an array of length 0");
1725 if (parser.parseOptionalArrow().succeeded()) {
1726 if (parser.parseType(resultType))
1728 result.addTypes(resultType);
1730 result.addTypes({ArrayType::get(elemType, operands.size())});
1733 for (
auto operand : operands)
1734 if (parser.resolveOperand(operand, elemType, result.operands))
1739void ArrayCreateOp::print(OpAsmPrinter &p) {
1741 p.printOperands(getInputs());
1742 p.printOptionalAttrDict((*this)->getAttrs());
1743 p <<
" : " << getInputs()[0].getType();
1747 ArrayType::get(getInputs()[0].getType(), getInputs().size());
1748 if (getType() != expectedType)
1749 p <<
" -> " << getType();
1752void ArrayCreateOp::build(OpBuilder &b, OperationState &state,
1753 ValueRange values) {
1754 assert(values.size() > 0 &&
"Cannot build array of zero elements");
1755 Type elemType = values[0].getType();
1758 [elemType](Value v) ->
bool {
return v.getType() == elemType; }) &&
1759 "All values must have same type.");
1760 build(b, state, ArrayType::get(elemType, values.size()), values);
1763LogicalResult ArrayCreateOp::verify() {
1764 unsigned returnSize = hw::type_cast<ArrayType>(getType()).getNumElements();
1765 if (getInputs().size() != returnSize)
1770OpFoldResult ArrayCreateOp::fold(FoldAdaptor adaptor) {
1771 if (llvm::any_of(adaptor.getInputs(), [](Attribute attr) {
1772 return !isa_and_nonnull<IntegerAttr>(attr);
1775 return ArrayAttr::get(getContext(), adaptor.getInputs());
1785 auto baseValue = constBase.getValue();
1786 auto indexValue = constIndex.getValue();
1788 unsigned bits = baseValue.getBitWidth();
1789 assert(bits == indexValue.getBitWidth() &&
"mismatched widths");
1791 if (bits < 64 && offset >= (1ull << bits))
1794 APInt baseExt = baseValue.zextOrTrunc(bits + 1);
1795 APInt indexExt = indexValue.zextOrTrunc(bits + 1);
1796 return baseExt + offset == indexExt;
1804 PatternRewriter &rewriter) {
1806 auto arrayTy = hw::type_cast<ArrayType>(op.getType());
1807 if (arrayTy.getNumElements() <= 1)
1809 auto elemTy = arrayTy.getElementType();
1818 SmallVector<Chunk> chunks;
1819 for (Value value : llvm::reverse(op.getInputs())) {
1820 auto get = value.getDefiningOp<
ArrayGetOp>();
1824 Value input = get.getInput();
1825 Value index = get.getIndex();
1826 if (!chunks.empty()) {
1827 auto &c = *chunks.rbegin();
1828 if (c.input == get.getInput() &&
isOffset(c.index, index, c.size)) {
1834 chunks.push_back(Chunk{input, index, 1});
1838 if (chunks.size() == 1) {
1839 auto &chunk = chunks[0];
1840 rewriter.replaceOp(op, rewriter.createOrFold<
ArraySliceOp>(
1841 op.getLoc(), arrayTy, chunk.input, chunk.index));
1847 if (chunks.size() * 2 < arrayTy.getNumElements()) {
1848 SmallVector<Value> slices;
1849 for (
auto &chunk : llvm::reverse(chunks)) {
1850 auto sliceTy = ArrayType::get(elemTy, chunk.size);
1852 op.getLoc(), sliceTy, chunk.input, chunk.index));
1854 rewriter.replaceOpWithNewOp<
ArrayConcatOp>(op, arrayTy, slices);
1862 PatternRewriter &rewriter) {
1868Value ArrayCreateOp::getUniformElement() {
1869 if (!getInputs().
empty() && llvm::all_equal(getInputs()))
1870 return getInputs()[0];
1875 auto idxOp = dyn_cast_or_null<ConstantOp>(value.getDefiningOp());
1877 return std::nullopt;
1878 APInt idxAttr = idxOp.getValue();
1879 if (idxAttr.getBitWidth() > 64)
1880 return std::nullopt;
1881 return idxAttr.getLimitedValue();
1884LogicalResult ArraySliceOp::verify() {
1885 unsigned inputSize =
1886 type_cast<ArrayType>(getInput().getType()).getNumElements();
1887 if (llvm::Log2_64_Ceil(inputSize) !=
1888 getLowIndex().getType().getIntOrFloatBitWidth())
1890 "ArraySlice: index width must match clog2 of array size");
1894OpFoldResult ArraySliceOp::fold(FoldAdaptor adaptor) {
1896 if (getType() == getInput().getType())
1901LogicalResult ArraySliceOp::canonicalize(
ArraySliceOp op,
1902 PatternRewriter &rewriter) {
1903 auto sliceTy = hw::type_cast<ArrayType>(op.getType());
1904 auto elemTy = sliceTy.getElementType();
1905 uint64_t sliceSize = sliceTy.getNumElements();
1909 if (sliceSize == 1) {
1913 rewriter.replaceOpWithNewOp<
ArrayCreateOp>(op, op.getType(),
1922 auto *inputOp = op.getInput().getDefiningOp();
1923 if (
auto inputSlice = dyn_cast_or_null<ArraySliceOp>(inputOp)) {
1925 if (inputSlice == op)
1928 auto inputIndex = inputSlice.getLowIndex();
1930 if (!inputOffsetOpt)
1933 uint64_t offset = *offsetOpt + *inputOffsetOpt;
1936 rewriter.replaceOpWithNewOp<
ArraySliceOp>(op, op.getType(),
1937 inputSlice.getInput(), lowIndex);
1941 if (
auto inputCreate = dyn_cast_or_null<ArrayCreateOp>(inputOp)) {
1943 auto inputs = inputCreate.getInputs();
1945 uint64_t begin = inputs.size() - *offsetOpt - sliceSize;
1946 rewriter.replaceOpWithNewOp<
ArrayCreateOp>(op, op.getType(),
1947 inputs.slice(begin, sliceSize));
1951 if (
auto inputConcat = dyn_cast_or_null<ArrayConcatOp>(inputOp)) {
1953 SmallVector<Value> chunks;
1954 uint64_t sliceStart = *offsetOpt;
1955 for (
auto input :
llvm::reverse(inputConcat.getInputs())) {
1957 uint64_t inputSize =
1958 hw::type_cast<ArrayType>(input.getType()).getNumElements();
1959 if (inputSize == 0 || inputSize <= sliceStart) {
1960 sliceStart -= inputSize;
1965 uint64_t cutEnd = std::min(inputSize, sliceStart + sliceSize);
1966 uint64_t cutSize = cutEnd - sliceStart;
1967 assert(cutSize != 0 &&
"slice cannot be empty");
1969 if (cutSize == inputSize) {
1971 assert(sliceStart == 0 &&
"invalid cut size");
1972 chunks.push_back(input);
1975 unsigned width = inputSize == 1 ? 1 : llvm::Log2_64_Ceil(inputSize);
1977 rewriter, op.getLoc(), rewriter.getIntegerType(width), sliceStart);
1979 rewriter, op.getLoc(), hw::ArrayType::get(elemTy, cutSize), input,
1984 sliceSize -= cutSize;
1989 assert(chunks.size() > 0 &&
"missing sliced items");
1990 if (chunks.size() == 1)
1991 rewriter.replaceOp(op, chunks[0]);
1994 op, llvm::to_vector(llvm::reverse(chunks)));
2005 SmallVectorImpl<Type> &inputTypes,
2008 uint64_t resultSize = 0;
2010 auto parseElement = [&]() -> ParseResult {
2012 if (p.parseType(ty))
2014 auto arrTy = type_dyn_cast<ArrayType>(ty);
2016 return p.emitError(p.getCurrentLocation(),
"Expected !hw.array type");
2017 if (elemType && elemType != arrTy.getElementType())
2018 return p.emitError(p.getCurrentLocation(),
"Expected array element type ")
2021 elemType = arrTy.getElementType();
2022 inputTypes.push_back(ty);
2023 resultSize += arrTy.getNumElements();
2027 if (p.parseCommaSeparatedList(parseElement))
2030 resultType = ArrayType::get(elemType, resultSize);
2035 TypeRange inputTypes, Type resultType) {
2036 llvm::interleaveComma(inputTypes, p, [&p](Type t) { p << t; });
2039void ArrayConcatOp::build(OpBuilder &b, OperationState &state,
2040 ValueRange values) {
2041 assert(!values.empty() &&
"Cannot build array of zero elements");
2042 ArrayType arrayTy = cast<ArrayType>(values[0].getType());
2043 Type elemTy = arrayTy.getElementType();
2044 assert(llvm::all_of(values,
2045 [elemTy](Value v) ->
bool {
2046 return isa<ArrayType>(v.getType()) &&
2047 cast<ArrayType>(v.getType()).getElementType() ==
2050 "All values must be of ArrayType with the same element type.");
2052 uint64_t resultSize = 0;
2053 for (Value val : values)
2054 resultSize += cast<ArrayType>(val.getType()).getNumElements();
2055 build(b, state, ArrayType::get(elemTy, resultSize), values);
2058OpFoldResult ArrayConcatOp::fold(FoldAdaptor adaptor) {
2059 if (getInputs().size() == 1)
2060 return getInputs()[0];
2062 auto inputs = adaptor.getInputs();
2063 SmallVector<Attribute> array;
2064 for (
size_t i = 0, e = getNumOperands(); i < e; ++i) {
2067 llvm::copy(cast<ArrayAttr>(inputs[i]), std::back_inserter(array));
2069 return ArrayAttr::get(getContext(), array);
2074 for (
auto input : op.getInputs())
2078 SmallVector<Value> items;
2079 for (
auto input : op.getInputs()) {
2080 auto create = cast<ArrayCreateOp>(input.getDefiningOp());
2081 for (
auto item : create.getInputs())
2082 items.push_back(item);
2096 SmallVector<Location> locs;
2099 SmallVector<Value> items;
2100 std::optional<Slice> last;
2101 bool changed =
false;
2103 auto concatenate = [&] {
2108 items.push_back(last->op);
2116 auto loc = FusedLoc::get(op.getContext(), last->locs);
2117 auto origTy = hw::type_cast<ArrayType>(last->input.getType());
2118 auto arrayTy = ArrayType::get(origTy.getElementType(), last->size);
2120 loc, arrayTy, last->input, last->index));
2125 auto append = [&](Value op, Value input, Value index,
size_t size) {
2130 if (last->input == input &&
isOffset(last->index, index, last->size)) {
2133 last->locs.push_back(op.getLoc());
2138 last.emplace(Slice{input, index, size, op, {op.getLoc()}});
2141 for (
auto item : llvm::reverse(op.getInputs())) {
2143 auto size = hw::type_cast<ArrayType>(slice.getType()).getNumElements();
2144 append(item, slice.getInput(), slice.getLowIndex(), size);
2149 if (create.getInputs().size() == 1) {
2150 if (
auto get = create.getInputs()[0].getDefiningOp<
ArrayGetOp>()) {
2151 append(item, get.getInput(), get.getIndex(), 1);
2158 items.push_back(item);
2165 if (items.size() == 1) {
2166 rewriter.replaceOp(op, items[0]);
2168 std::reverse(items.begin(), items.end());
2175 PatternRewriter &rewriter) {
2191ParseResult EnumConstantOp::parse(OpAsmParser &parser, OperationState &result) {
2198 auto loc = parser.getEncodedSourceLoc(parser.getCurrentLocation());
2199 if (parser.parseKeyword(&field) || parser.parseColonType(type))
2202 auto fieldAttr = EnumFieldAttr::get(
2203 loc, StringAttr::get(parser.getContext(), field), type);
2208 result.addAttribute(
"field", fieldAttr);
2209 result.addTypes(type);
2214void EnumConstantOp::print(OpAsmPrinter &p) {
2215 p <<
" " << getField().getField().getValue() <<
" : "
2216 << getField().getType().getValue();
2219void EnumConstantOp::getAsmResultNames(
2220 function_ref<
void(Value, StringRef)> setNameFn) {
2221 setNameFn(getResult(), getField().getField().str());
2224void EnumConstantOp::build(OpBuilder &builder, OperationState &odsState,
2225 EnumFieldAttr field) {
2226 return build(builder, odsState, field.getType().getValue(), field);
2229OpFoldResult EnumConstantOp::fold(FoldAdaptor adaptor) {
2230 assert(adaptor.getOperands().empty() &&
"constant has no operands");
2231 return getFieldAttr();
2234LogicalResult EnumConstantOp::verify() {
2235 auto fieldAttr = getFieldAttr();
2236 auto fieldType = fieldAttr.getType().getValue();
2239 if (fieldType != getType())
2240 emitOpError(
"return type ")
2241 << getType() <<
" does not match attribute type " << fieldAttr;
2249LogicalResult EnumCmpOp::verify() {
2251 auto lhsType = type_cast<EnumType>(getLhs().getType());
2252 auto rhsType = type_cast<EnumType>(getRhs().getType());
2253 if (rhsType != lhsType)
2254 emitOpError(
"types do not match");
2262ParseResult StructCreateOp::parse(OpAsmParser &parser, OperationState &result) {
2263 llvm::SMLoc inputOperandsLoc = parser.getCurrentLocation();
2264 llvm::SmallVector<OpAsmParser::UnresolvedOperand, 4> operands;
2265 Type declOrAliasType;
2267 if (parser.parseLParen() || parser.parseOperandList(operands) ||
2268 parser.parseRParen() || parser.parseOptionalAttrDict(result.attributes) ||
2269 parser.parseColonType(declOrAliasType))
2272 auto declType = type_dyn_cast<StructType>(declOrAliasType);
2274 return parser.emitError(parser.getNameLoc(),
2275 "expected !hw.struct type or alias");
2277 llvm::SmallVector<Type, 4> structInnerTypes;
2278 declType.getInnerTypes(structInnerTypes);
2279 result.addTypes(declOrAliasType);
2281 if (parser.resolveOperands(operands, structInnerTypes, inputOperandsLoc,
2287void StructCreateOp::print(OpAsmPrinter &printer) {
2289 printer.printOperands(getInput());
2291 printer.printOptionalAttrDict((*this)->getAttrs());
2292 printer <<
" : " << getType();
2295LogicalResult StructCreateOp::verify() {
2296 auto elements = hw::type_cast<StructType>(getType()).getElements();
2298 if (elements.size() != getInput().size())
2299 return emitOpError(
"structure field count mismatch");
2301 for (
const auto &[field, value] :
llvm::zip(elements, getInput()))
2302 if (field.type != value.getType())
2303 return emitOpError(
"structure field `")
2304 << field.name <<
"` type does not match";
2309OpFoldResult StructCreateOp::fold(FoldAdaptor adaptor) {
2311 if (!getInput().
empty())
2312 if (
auto explodeOp = getInput()[0].getDefiningOp<StructExplodeOp>();
2313 explodeOp && getInput() == explodeOp.getResults() &&
2314 getResult().getType() == explodeOp.getInput().getType())
2315 return explodeOp.getInput();
2317 auto inputs = adaptor.getInput();
2318 if (llvm::any_of(inputs, [](Attribute attr) {
2319 return !isa_and_nonnull<IntegerAttr>(attr);
2322 return ArrayAttr::get(getContext(), inputs);
2326 PatternRewriter &rewriter) {
2330 for (
auto [i, operand] :
llvm::enumerate(op.getInput())) {
2332 if (!extractOp || extractOp.getFieldIndex() != i ||
2333 extractOp.getInput().getType() != op.getType()) {
2338 foldVal = extractOp.getInput();
2339 }
else if (extractOp.getInput() != foldVal) {
2344 if (foldVal && foldVal != op.getResult()) {
2345 rewriter.replaceOp(op, foldVal);
2355ParseResult StructExplodeOp::parse(OpAsmParser &parser,
2356 OperationState &result) {
2357 OpAsmParser::UnresolvedOperand operand;
2360 if (parser.parseOperand(operand) ||
2361 parser.parseOptionalAttrDict(result.attributes) ||
2362 parser.parseColonType(declType))
2364 auto structType = type_dyn_cast<StructType>(declType);
2366 return parser.emitError(parser.getNameLoc(),
2367 "invalid kind of type specified");
2369 llvm::SmallVector<Type, 4> structInnerTypes;
2370 structType.getInnerTypes(structInnerTypes);
2371 result.addTypes(structInnerTypes);
2373 if (parser.resolveOperand(operand, declType, result.operands))
2378void StructExplodeOp::print(OpAsmPrinter &printer) {
2380 printer.printOperand(getInput());
2381 printer.printOptionalAttrDict((*this)->getAttrs());
2382 printer <<
" : " << getInput().getType();
2385LogicalResult StructExplodeOp::fold(FoldAdaptor adaptor,
2386 SmallVectorImpl<OpFoldResult> &results) {
2387 auto input = adaptor.getInput();
2390 llvm::copy(cast<ArrayAttr>(input), std::back_inserter(results));
2394LogicalResult StructExplodeOp::canonicalize(StructExplodeOp op,
2395 PatternRewriter &rewriter) {
2396 auto *inputOp = op.getInput().getDefiningOp();
2397 auto elements = type_cast<StructType>(op.getInput().getType()).getElements();
2398 auto result = failure();
2399 auto opResults = op.getResults();
2400 for (uint32_t index = 0; index < elements.size(); index++) {
2402 rewriter.replaceAllUsesWith(opResults[index], foldResult);
2409void StructExplodeOp::getAsmResultNames(
2410 function_ref<
void(Value, StringRef)> setNameFn) {
2411 auto structType = type_cast<StructType>(getInput().getType());
2412 for (
auto [res, field] :
llvm::zip(getResults(), structType.getElements()))
2413 setNameFn(res, field.name.str());
2416void StructExplodeOp::build(OpBuilder &odsBuilder, OperationState &odsState,
2418 StructType inputType = dyn_cast<StructType>(input.getType());
2420 SmallVector<Type, 16> fieldTypes;
2421 for (
auto field : inputType.getElements())
2422 fieldTypes.push_back(field.type);
2423 build(odsBuilder, odsState, fieldTypes, input);
2432template <
typename AggregateOp,
typename AggregateType>
2434 AggregateType aggType,
2436 auto index = op.getFieldIndex();
2437 if (index >= aggType.getElements().size())
2438 return op.emitOpError() <<
"field index " << index
2439 <<
" exceeds element count of aggregate type";
2443 return op.emitOpError()
2444 <<
"type " << aggType.getElements()[index].type
2445 <<
" of accessed field in aggregate at index " << index
2446 <<
" does not match expected type " <<
elementType;
2451LogicalResult StructExtractOp::verify() {
2452 return verifyAggregateFieldIndexAndType<StructExtractOp, StructType>(
2453 *
this, getInput().getType(), getType());
2458template <
typename AggregateType>
2460 OpAsmParser::UnresolvedOperand operand;
2461 StringAttr fieldName;
2464 if (parser.parseOperand(operand) || parser.parseLSquare() ||
2465 parser.parseAttribute(fieldName) || parser.parseRSquare() ||
2466 parser.parseOptionalAttrDict(result.attributes) ||
2467 parser.parseColonType(declType))
2469 auto aggType = type_dyn_cast<AggregateType>(declType);
2471 return parser.emitError(parser.getNameLoc(),
2472 "invalid kind of type specified");
2474 auto fieldIndex = aggType.getFieldIndex(fieldName);
2476 parser.emitError(parser.getNameLoc(),
"field name '" +
2477 fieldName.getValue() +
2478 "' not found in aggregate type");
2483 IntegerAttr::get(IntegerType::get(parser.getContext(), 32), *fieldIndex);
2484 result.addAttribute(
"fieldIndex", indexAttr);
2485 Type resultType = aggType.getElements()[*fieldIndex].type;
2486 result.addTypes(resultType);
2488 if (parser.resolveOperand(operand, declType, result.operands))
2495template <
typename AggType>
2498 printer.printOperand(op.getInput());
2499 printer <<
"[\"" << op.getFieldName() <<
"\"]";
2500 printer.printOptionalAttrDict(op->getAttrs(), {
"fieldIndex"});
2501 printer <<
" : " << op.getInput().getType();
2504ParseResult StructExtractOp::parse(OpAsmParser &parser,
2505 OperationState &result) {
2506 return parseExtractOp<StructType>(parser, result);
2509void StructExtractOp::print(OpAsmPrinter &printer) {
2513void StructExtractOp::build(OpBuilder &builder, OperationState &odsState,
2514 Value input, StructType::FieldInfo field) {
2516 type_cast<StructType>(input.getType()).getFieldIndex(field.name);
2517 assert(fieldIndex.has_value() &&
"field name not found in aggregate type");
2518 build(builder, odsState, field.type, input, *fieldIndex);
2521void StructExtractOp::build(OpBuilder &builder, OperationState &odsState,
2522 Value input, StringAttr fieldName) {
2523 auto structType = type_cast<StructType>(input.getType());
2524 auto fieldIndex = structType.getFieldIndex(fieldName);
2525 assert(fieldIndex.has_value() &&
"field name not found in aggregate type");
2526 auto resultType = structType.getElements()[*fieldIndex].type;
2527 build(builder, odsState, resultType, input, *fieldIndex);
2530OpFoldResult StructExtractOp::fold(FoldAdaptor adaptor) {
2531 if (
auto constOperand = adaptor.getInput()) {
2533 auto operandAttr = llvm::cast<ArrayAttr>(constOperand);
2534 return operandAttr.getValue()[getFieldIndex()];
2537 if (
auto foldResult =
2544 PatternRewriter &rewriter) {
2545 auto *inputOp = op.getInput().getDefiningOp();
2548 if (
auto structInject = dyn_cast_or_null<StructInjectOp>(inputOp)) {
2549 if (structInject.getFieldIndex() != op.getFieldIndex()) {
2551 op, op.getType(), structInject.getInput(), op.getFieldIndexAttr());
2559void StructExtractOp::getAsmResultNames(
2560 function_ref<
void(Value, StringRef)> setNameFn) {
2568void StructInjectOp::build(OpBuilder &builder, OperationState &odsState,
2569 Value input, StringAttr fieldName, Value newValue) {
2570 auto structType = type_cast<StructType>(input.getType());
2571 auto fieldIndex = structType.getFieldIndex(fieldName);
2572 assert(fieldIndex.has_value() &&
"field name not found in aggregate type");
2573 build(builder, odsState, input, *fieldIndex, newValue);
2576LogicalResult StructInjectOp::verify() {
2577 return verifyAggregateFieldIndexAndType<StructInjectOp, StructType>(
2578 *
this, getInput().getType(), getNewValue().getType());
2581ParseResult StructInjectOp::parse(OpAsmParser &parser, OperationState &result) {
2582 llvm::SMLoc inputOperandsLoc = parser.getCurrentLocation();
2583 OpAsmParser::UnresolvedOperand operand, val;
2584 StringAttr fieldName;
2587 if (parser.parseOperand(operand) || parser.parseLSquare() ||
2588 parser.parseAttribute(fieldName) || parser.parseRSquare() ||
2589 parser.parseComma() || parser.parseOperand(val) ||
2590 parser.parseOptionalAttrDict(result.attributes) ||
2591 parser.parseColonType(declType))
2593 auto structType = type_dyn_cast<StructType>(declType);
2595 return parser.emitError(inputOperandsLoc,
"invalid kind of type specified");
2597 auto fieldIndex = structType.getFieldIndex(fieldName);
2599 parser.emitError(parser.getNameLoc(),
"field name '" +
2600 fieldName.getValue() +
2601 "' not found in aggregate type");
2606 IntegerAttr::get(IntegerType::get(parser.getContext(), 32), *fieldIndex);
2607 result.addAttribute(
"fieldIndex", indexAttr);
2608 result.addTypes(declType);
2610 Type resultType = structType.getElements()[*fieldIndex].type;
2611 if (parser.resolveOperands({operand, val}, {declType, resultType},
2612 inputOperandsLoc, result.operands))
2617void StructInjectOp::print(OpAsmPrinter &printer) {
2619 printer.printOperand(getInput());
2621 printer.printOperand(getNewValue());
2622 printer.printOptionalAttrDict((*this)->getAttrs(), {
"fieldIndex"});
2623 printer <<
" : " << getInput().getType();
2626OpFoldResult StructInjectOp::fold(FoldAdaptor adaptor) {
2627 auto input = adaptor.getInput();
2628 auto newValue = adaptor.getNewValue();
2629 if (!input || !newValue)
2631 SmallVector<Attribute> array;
2632 llvm::copy(cast<ArrayAttr>(input), std::back_inserter(array));
2633 array[getFieldIndex()] = newValue;
2634 return ArrayAttr::get(getContext(), array);
2637LogicalResult StructInjectOp::canonicalize(StructInjectOp op,
2638 PatternRewriter &rewriter) {
2642 if (op->hasOneUse()) {
2643 auto &use = *op->use_begin();
2644 if (isa<StructInjectOp>(use.getOwner()) && use.getOperandNumber() == 0)
2649 SmallPtrSet<Operation *, 4> injects;
2650 DenseMap<StringAttr, Value> fields;
2653 StructInjectOp inject = op;
2656 if (!injects.insert(inject).second)
2659 fields.try_emplace(inject.getFieldNameAttr(), inject.getNewValue());
2660 input = inject.getInput();
2661 inject = dyn_cast_or_null<StructInjectOp>(input.getDefiningOp());
2663 assert(input &&
"missing input to inject chain");
2665 auto ty = hw::type_cast<StructType>(op.getType());
2666 auto elements = ty.getElements();
2669 if (fields.size() == elements.size()) {
2670 SmallVector<Value> createFields;
2671 for (
const auto &field : elements) {
2672 auto it = fields.find(field.name);
2673 assert(it != fields.end() &&
"missing field");
2674 createFields.push_back(it->second);
2676 rewriter.replaceOpWithNewOp<
StructCreateOp>(op, ty, createFields);
2681 if (injects.size() == fields.size())
2685 for (uint32_t fieldIndex = 0; fieldIndex < elements.size(); fieldIndex++) {
2686 auto it = fields.find(elements[fieldIndex].name);
2687 if (it == fields.end())
2689 input = StructInjectOp::create(rewriter, op.getLoc(), ty, input, fieldIndex,
2693 rewriter.replaceOp(op, input);
2701LogicalResult UnionCreateOp::verify() {
2702 return verifyAggregateFieldIndexAndType<UnionCreateOp, UnionType>(
2703 *
this, getType(), getInput().getType());
2706void UnionCreateOp::build(OpBuilder &builder, OperationState &odsState,
2707 Type unionType, StringAttr fieldName, Value input) {
2708 auto fieldIndex = type_cast<UnionType>(unionType).getFieldIndex(fieldName);
2709 assert(fieldIndex.has_value() &&
"field name not found in aggregate type");
2710 build(builder, odsState, unionType, *fieldIndex, input);
2713ParseResult UnionCreateOp::parse(OpAsmParser &parser, OperationState &result) {
2714 Type declOrAliasType;
2715 StringAttr fieldName;
2716 OpAsmParser::UnresolvedOperand input;
2717 llvm::SMLoc fieldLoc = parser.getCurrentLocation();
2719 if (parser.parseAttribute(fieldName) || parser.parseComma() ||
2720 parser.parseOperand(input) ||
2721 parser.parseOptionalAttrDict(result.attributes) ||
2722 parser.parseColonType(declOrAliasType))
2725 auto declType = type_dyn_cast<UnionType>(declOrAliasType);
2727 return parser.emitError(parser.getNameLoc(),
2728 "expected !hw.union type or alias");
2730 auto fieldIndex = declType.getFieldIndex(fieldName);
2732 parser.emitError(fieldLoc,
"cannot find union field '")
2733 << fieldName.getValue() <<
'\'';
2738 IntegerAttr::get(IntegerType::get(parser.getContext(), 32), *fieldIndex);
2739 result.addAttribute(
"fieldIndex", indexAttr);
2740 Type inputType = declType.getElements()[*fieldIndex].type;
2742 if (parser.resolveOperand(input, inputType, result.operands))
2744 result.addTypes({declOrAliasType});
2748void UnionCreateOp::print(OpAsmPrinter &printer) {
2750 printer.printOperand(getInput());
2751 printer.printOptionalAttrDict((*this)->getAttrs(), {
"fieldIndex"});
2752 printer <<
" : " << getType();
2759ParseResult UnionExtractOp::parse(OpAsmParser &parser, OperationState &result) {
2760 return parseExtractOp<UnionType>(parser, result);
2763void UnionExtractOp::print(OpAsmPrinter &printer) {
2767LogicalResult UnionExtractOp::inferReturnTypes(
2768 MLIRContext *
context, std::optional<Location> loc, ValueRange operands,
2769 DictionaryAttr attrs, mlir::PropertyRef properties,
2770 mlir::RegionRange regions, SmallVectorImpl<Type> &results) {
2771 Adaptor adaptor(operands, attrs, properties, regions);
2772 auto unionElements =
2773 hw::type_cast<UnionType>((adaptor.getInput().getType())).getElements();
2774 unsigned fieldIndex = adaptor.getFieldIndexAttr().getValue().getZExtValue();
2775 if (fieldIndex >= unionElements.size()) {
2777 mlir::emitError(*loc,
"field index " + Twine(fieldIndex) +
2778 " exceeds element count of aggregate type");
2781 results.push_back(unionElements[fieldIndex].type);
2785void UnionExtractOp::build(OpBuilder &odsBuilder, OperationState &odsState,
2786 Value input, StringAttr fieldName) {
2787 auto unionType = type_cast<UnionType>(input.getType());
2788 auto fieldIndex = unionType.getFieldIndex(fieldName);
2789 assert(fieldIndex.has_value() &&
"field name not found in aggregate type");
2790 auto resultType = unionType.getElements()[*fieldIndex].type;
2791 build(odsBuilder, odsState, resultType, input, *fieldIndex);
2794LogicalResult UnionExtractOp::canonicalize(UnionExtractOp extractOp,
2795 PatternRewriter &rewriter) {
2798 if (
auto createOp = extractOp.getInput().getDefiningOp<UnionCreateOp>()) {
2799 if (createOp.getInput().getType() == extractOp.getType() &&
2800 createOp.getInput() != extractOp.getResult()) {
2801 auto unionTypeElts =
2802 cast<UnionType>(extractOp.getInput().getType()).getElements();
2803 if (unionTypeElts[createOp.getFieldIndex()].offset ==
2804 unionTypeElts[extractOp.getFieldIndex()].offset) {
2805 rewriter.replaceOp(extractOp, createOp.getInput());
2811 if (
auto bitcastOp = extractOp.getInput().getDefiningOp<
BitcastOp>()) {
2812 auto inputWidth =
getBitWidth(bitcastOp.getInput().getType());
2813 assert(inputWidth >= 0 &&
2814 inputWidth ==
getBitWidth(extractOp.getInput().getType()) &&
2815 "bitcast does not cover entire union");
2816 if (inputWidth ==
getBitWidth(extractOp.getType())) {
2817 auto loc = FusedLoc::get(rewriter.getContext(),
2818 {bitcastOp.getLoc(), extractOp.getLoc()});
2819 auto newBitcast = rewriter.createOrFold<
BitcastOp>(
2820 loc, extractOp.getType(), bitcastOp.getInput());
2821 rewriter.replaceOp(extractOp, newBitcast);
2838OpFoldResult ArrayGetOp::fold(FoldAdaptor adaptor) {
2839 auto inputCst = dyn_cast_or_null<ArrayAttr>(adaptor.getInput());
2840 auto indexCst = dyn_cast_or_null<IntegerAttr>(adaptor.getIndex());
2845 auto indexVal = indexCst.getValue();
2846 if (indexVal.getBitWidth() < 64) {
2847 auto index = indexVal.getZExtValue();
2848 return inputCst[inputCst.size() - 1 - index];
2853 if (!inputCst.empty() && llvm::all_equal(inputCst))
2858 if (
auto bitcast = getInput().getDefiningOp<hw::BitcastOp>()) {
2859 auto intTy = dyn_cast<IntegerType>(getType());
2862 auto bitcastInputOp = bitcast.getInput().getDefiningOp<
hw::ConstantOp>();
2863 if (!bitcastInputOp)
2867 auto bitcastInputCst = bitcastInputOp.getValue();
2870 auto startIdx = indexCst.getValue().zext(bitcastInputCst.getBitWidth()) *
2871 getType().getIntOrFloatBitWidth();
2873 return IntegerAttr::get(intTy, bitcastInputCst.lshr(startIdx).trunc(
2874 intTy.getIntOrFloatBitWidth()));
2878 if (
auto inject = getInput().getDefiningOp<ArrayInjectOp>())
2879 if (getIndex() == inject.getIndex())
2880 return inject.getElement();
2882 auto inputCreate = getInput().getDefiningOp<
ArrayCreateOp>();
2886 if (
auto uniformValue = inputCreate.getUniformElement())
2887 return uniformValue;
2889 if (!indexCst || indexCst.getValue().getBitWidth() > 64)
2892 uint64_t index = indexCst.getValue().getLimitedValue();
2893 auto createInputs = inputCreate.getInputs();
2894 if (index >= createInputs.size())
2896 return createInputs[createInputs.size() - index - 1];
2899LogicalResult ArrayGetOp::canonicalize(
ArrayGetOp op,
2900 PatternRewriter &rewriter) {
2905 auto *inputOp = op.getInput().getDefiningOp();
2906 if (
auto inputSlice = dyn_cast_or_null<ArraySliceOp>(inputOp)) {
2908 auto offsetOp = inputSlice.getLowIndex();
2913 uint64_t offset = *offsetOpt + *idxOpt;
2916 rewriter.replaceOpWithNewOp<
ArrayGetOp>(op, inputSlice.getInput(),
2921 if (
auto inputConcat = dyn_cast_or_null<ArrayConcatOp>(inputOp)) {
2923 uint64_t elemIndex = *idxOpt;
2924 for (
auto input :
llvm::reverse(inputConcat.getInputs())) {
2925 size_t size = hw::type_cast<ArrayType>(input.getType()).getNumElements();
2926 if (elemIndex >= size) {
2931 unsigned indexWidth = size == 1 ? 1 : llvm::Log2_64_Ceil(size);
2934 rewriter.getIntegerType(indexWidth), elemIndex);
2936 rewriter.replaceOpWithNewOp<
ArrayGetOp>(op, input, newIdxOp);
2945 if (
auto innerGet = dyn_cast_or_null<hw::ArrayGetOp>(inputOp)) {
2950 SmallVector<Value> newValues;
2951 for (
auto operand : create.getOperands())
2952 newValues.push_back(rewriter.createOrFold<
hw::
ArrayGetOp>(
2953 op.
getLoc(), operand, op.getIndex()));
2958 innerGet.getIndex());
2971OpFoldResult ArrayInjectOp::fold(FoldAdaptor adaptor) {
2972 auto inputAttr = dyn_cast_or_null<ArrayAttr>(adaptor.getInput());
2973 auto indexAttr = dyn_cast_or_null<IntegerAttr>(adaptor.getIndex());
2974 auto elementAttr = adaptor.getElement();
2977 if (inputAttr && indexAttr && elementAttr) {
2978 if (
auto index = indexAttr.getValue().tryZExtValue()) {
2979 if (*index < inputAttr.size()) {
2980 SmallVector<Attribute> elements(inputAttr.getValue());
2981 elements[inputAttr.size() - 1 - *index] = elementAttr;
2982 return ArrayAttr::get(getContext(), elements);
2991 PatternRewriter &rewriter) {
2995 if (op->hasOneUse()) {
2996 auto &use = *op->use_begin();
2997 if (isa<ArrayInjectOp>(use.getOwner()) && use.getOperandNumber() == 0)
3002 auto arrayLength = type_cast<ArrayType>(op.getType()).getNumElements();
3005 while (
auto inject = input.getDefiningOp<ArrayInjectOp>()) {
3008 if (!matchPattern(inject.getIndex(), mlir::m_ConstantInt(&indexAPInt)))
3010 if (indexAPInt.getActiveBits() > 32)
3012 uint32_t index = indexAPInt.getZExtValue();
3017 if (index < arrayLength)
3018 elements.insert({index, inject.getElement()});
3021 input = inject.getInput();
3028 if (elements.size() == arrayLength) {
3029 SmallVector<Value, 4> operands;
3030 operands.reserve(arrayLength);
3031 for (uint32_t idx = 0; idx < arrayLength; ++idx)
3032 operands.push_back(elements.at(arrayLength - idx - 1));
3033 rewriter.replaceOpWithNewOp<
ArrayCreateOp>(op, op.getType(), operands);
3042 auto createOp = op.getInput().getDefiningOp<
ArrayCreateOp>();
3048 if (!matchPattern(op.getIndex(), mlir::m_ConstantInt(&indexAPInt)) ||
3049 !indexAPInt.ult(createOp.getInputs().size()))
3053 SmallVector<Value> elements = createOp.getInputs();
3054 elements[elements.size() - indexAPInt.getZExtValue() - 1] = op.getElement();
3059void ArrayInjectOp::getCanonicalizationPatterns(RewritePatternSet &
patterns,
3070LogicalResult TypedeclOp::verify() {
3071 if (!isa_and_nonnull<hw::TypeScopeLike>(getOperation()->getParentOp()))
3072 return emitOpError(
"expects parent op to be a type scope, such as "
3073 "'hw.type_scope' or 'sv.package'");
3077StringRef TypedeclOp::getPreferredName() {
3078 return getVerilogName().value_or(
getName());
3081Type TypedeclOp::getAliasType() {
3082 auto parentScope = cast<hw::TypeScopeLike>(getOperation()->getParentOp());
3083 return hw::TypeAliasType::get(
3084 SymbolRefAttr::get(parentScope.getNameAttr(),
3085 {FlatSymbolRefAttr::get(*this)}),
3093OpFoldResult BitcastOp::fold(FoldAdaptor adaptor) {
3096 if (getOperand().getType() == getType())
3097 return getOperand();
3100 if (
auto intAttr = dyn_cast_or_null<IntegerAttr>(adaptor.getInput())) {
3107 if (
auto arrayAttr = dyn_cast_or_null<ArrayAttr>(adaptor.getInput())) {
3111 if (
auto intType = dyn_cast<IntegerType>(getType()))
3112 return IntegerAttr::get(intType, intVal);
3122LogicalResult BitcastOp::canonicalize(
BitcastOp op, PatternRewriter &rewriter) {
3128 dyn_cast_or_null<BitcastOp>(op.getInput().getDefiningOp());
3131 auto bitcast = rewriter.createOrFold<
BitcastOp>(op.getLoc(), op.getType(),
3132 inputBitcast.getInput());
3133 rewriter.replaceOp(op, bitcast);
3137LogicalResult BitcastOp::verify() {
3139 return this->emitOpError(
"Bitwidth of input must match result");
3147bool HierPathOp::dropModule(StringAttr moduleToDrop) {
3148 SmallVector<Attribute, 4> newPath;
3149 bool updateMade =
false;
3150 for (
auto nameRef : getNamepath()) {
3152 if (
auto ref = dyn_cast<hw::InnerRefAttr>(nameRef)) {
3153 if (ref.getModule() == moduleToDrop)
3156 newPath.push_back(ref);
3158 if (cast<FlatSymbolRefAttr>(nameRef).getAttr() == moduleToDrop)
3161 newPath.push_back(nameRef);
3165 setNamepathAttr(ArrayAttr::get(getContext(), newPath));
3169bool HierPathOp::inlineModule(StringAttr moduleToDrop) {
3170 SmallVector<Attribute, 4> newPath;
3171 bool updateMade =
false;
3172 StringRef inlinedInstanceName =
"";
3173 for (
auto nameRef : getNamepath()) {
3175 if (
auto ref = dyn_cast<hw::InnerRefAttr>(nameRef)) {
3176 if (ref.getModule() == moduleToDrop) {
3177 inlinedInstanceName = ref.getName().getValue();
3179 }
else if (!inlinedInstanceName.empty()) {
3180 newPath.push_back(hw::InnerRefAttr::get(
3182 StringAttr::get(getContext(), inlinedInstanceName +
"_" +
3183 ref.getName().getValue())));
3184 inlinedInstanceName =
"";
3186 newPath.push_back(ref);
3188 if (cast<FlatSymbolRefAttr>(nameRef).getAttr() == moduleToDrop)
3191 newPath.push_back(nameRef);
3195 setNamepathAttr(ArrayAttr::get(getContext(), newPath));
3199bool HierPathOp::updateModule(StringAttr oldMod, StringAttr newMod) {
3200 SmallVector<Attribute, 4> newPath;
3201 bool updateMade =
false;
3202 for (
auto nameRef : getNamepath()) {
3204 if (
auto ref = dyn_cast<hw::InnerRefAttr>(nameRef)) {
3205 if (ref.getModule() == oldMod) {
3206 newPath.push_back(hw::InnerRefAttr::get(newMod, ref.getName()));
3209 newPath.push_back(ref);
3211 if (cast<FlatSymbolRefAttr>(nameRef).getAttr() == oldMod) {
3212 newPath.push_back(FlatSymbolRefAttr::get(newMod));
3215 newPath.push_back(nameRef);
3219 setNamepathAttr(ArrayAttr::get(getContext(), newPath));
3223bool HierPathOp::updateModuleAndInnerRef(
3224 StringAttr oldMod, StringAttr newMod,
3225 const llvm::DenseMap<StringAttr, StringAttr> &innerSymRenameMap) {
3226 auto fromRef = FlatSymbolRefAttr::get(oldMod);
3227 if (oldMod == newMod)
3230 auto namepathNew = getNamepath().getValue().vec();
3231 bool updateMade =
false;
3233 for (
auto &element : namepathNew) {
3234 if (
auto innerRef = dyn_cast<hw::InnerRefAttr>(element)) {
3235 if (innerRef.getModule() != oldMod)
3237 auto symName = innerRef.getName();
3240 auto to = innerSymRenameMap.find(symName);
3241 if (to != innerSymRenameMap.end())
3242 symName = to->second;
3244 element = hw::InnerRefAttr::get(newMod, symName);
3247 if (element != fromRef)
3251 element = FlatSymbolRefAttr::get(newMod);
3255 setNamepathAttr(ArrayAttr::get(getContext(), namepathNew));
3259bool HierPathOp::truncateAtModule(StringAttr atMod,
bool includeMod) {
3260 SmallVector<Attribute, 4> newPath;
3261 bool updateMade =
false;
3262 for (
auto nameRef : getNamepath()) {
3264 if (
auto ref = dyn_cast<hw::InnerRefAttr>(nameRef)) {
3265 if (ref.getModule() == atMod) {
3268 newPath.push_back(ref);
3270 newPath.push_back(ref);
3272 if (cast<FlatSymbolRefAttr>(nameRef).getAttr() == atMod && !includeMod)
3275 newPath.push_back(nameRef);
3281 setNamepathAttr(ArrayAttr::get(getContext(), newPath));
3286StringAttr HierPathOp::modPart(
unsigned i) {
3287 return TypeSwitch<Attribute, StringAttr>(getNamepath()[i])
3288 .Case<FlatSymbolRefAttr>([](
auto a) {
return a.getAttr(); })
3289 .Case<hw::InnerRefAttr>([](
auto a) {
return a.getModule(); });
3293StringAttr HierPathOp::root() {
3299bool HierPathOp::hasModule(StringAttr modName) {
3300 for (
auto nameRef : getNamepath()) {
3302 if (
auto ref = dyn_cast<hw::InnerRefAttr>(nameRef)) {
3303 if (ref.getModule() == modName)
3306 if (cast<FlatSymbolRefAttr>(nameRef).getAttr() == modName)
3314bool HierPathOp::hasInnerSym(StringAttr modName, StringAttr symName)
const {
3315 for (
auto nameRef : const_cast<HierPathOp *>(this)->getNamepath())
3316 if (auto ref = dyn_cast<
hw::InnerRefAttr>(nameRef))
3317 if (ref.
getName() == symName && ref.getModule() == modName)
3325StringAttr HierPathOp::refPart(
unsigned i) {
3326 return TypeSwitch<Attribute, StringAttr>(getNamepath()[i])
3327 .Case<FlatSymbolRefAttr>([](
auto a) {
return StringAttr({}); })
3328 .Case<hw::InnerRefAttr>([](
auto a) {
return a.getName(); });
3333StringAttr HierPathOp::ref() {
3335 return refPart(getNamepath().size() - 1);
3339StringAttr HierPathOp::leafMod() {
3341 return modPart(getNamepath().size() - 1);
3346bool HierPathOp::isModule() {
return !ref(); }
3350bool HierPathOp::isComponent() {
return (
bool)ref(); }
3366 ArrayAttr expectedModuleNames = {};
3367 auto checkExpectedModule = [&](Attribute name) -> LogicalResult {
3368 if (!expectedModuleNames)
3370 if (llvm::any_of(expectedModuleNames,
3371 [name](Attribute attr) {
return attr == name; }))
3373 auto diag = emitOpError() <<
"instance path is incorrect. Expected ";
3374 size_t n = expectedModuleNames.size();
3378 for (
size_t i = 0; i < n; ++i) {
3380 diag << ((i + 1 == n) ?
" or " :
", ");
3381 diag << cast<StringAttr>(expectedModuleNames[i]);
3383 diag <<
". Instead found: " << name;
3387 if (!getNamepath() || getNamepath().
empty())
3388 return emitOpError() <<
"the instance path cannot be empty";
3389 for (
unsigned i = 0, s = getNamepath().size() - 1; i <
s; ++i) {
3390 hw::InnerRefAttr innerRef = dyn_cast<hw::InnerRefAttr>(getNamepath()[i]);
3392 return emitOpError()
3393 <<
"the instance path can only contain inner sym reference"
3394 <<
", only the leaf can refer to a module symbol";
3396 if (failed(checkExpectedModule(innerRef.getModule())))
3399 auto instOp = ns.
lookupOp<igraph::InstanceOpInterface>(innerRef);
3401 return emitOpError() <<
" module: " << innerRef.getModule()
3402 <<
" does not contain any instance with symbol: "
3403 << innerRef.getName();
3404 expectedModuleNames = instOp.getReferencedModuleNamesAttr();
3408 auto leafRef = getNamepath()[getNamepath().size() - 1];
3409 if (
auto innerRef = dyn_cast<hw::InnerRefAttr>(leafRef)) {
3410 if (!ns.
lookup(innerRef)) {
3411 return emitOpError() <<
" operation with symbol: " << innerRef
3412 <<
" was not found ";
3414 if (failed(checkExpectedModule(innerRef.getModule())))
3416 }
else if (failed(checkExpectedModule(
3417 cast<FlatSymbolRefAttr>(leafRef).getAttr()))) {
3423void HierPathOp::print(OpAsmPrinter &p) {
3427 StringRef visibilityAttrName =
3428 mlir::SymbolOpInterface::getDefaultVisibilityAttrName();
3429 if (
auto visibility =
3430 getOperation()->getAttrOfType<StringAttr>(visibilityAttrName))
3431 p << visibility.getValue() <<
' ';
3433 p.printSymbolName(getSymName());
3435 llvm::interleaveComma(getNamepath().getValue(), p, [&](Attribute attr) {
3436 if (
auto ref = dyn_cast<hw::InnerRefAttr>(attr)) {
3437 p.printSymbolName(ref.getModule().getValue());
3439 p.printSymbolName(ref.getName().getValue());
3441 p.printSymbolName(cast<FlatSymbolRefAttr>(attr).getValue());
3445 p.printOptionalAttrDict(
3446 (*this)->getAttrs(),
3447 {getSymNameAttrName(),
"namepath", visibilityAttrName});
3450ParseResult HierPathOp::parse(OpAsmParser &parser, OperationState &result) {
3452 (void)mlir::impl::parseOptionalVisibilityKeyword(parser, result.attributes);
3456 if (parser.parseSymbolName(symName, getSymNameAttrName(result.name),
3461 SmallVector<Attribute> namepath;
3462 if (parser.parseCommaSeparatedList(
3463 OpAsmParser::Delimiter::Square, [&]() -> ParseResult {
3464 auto loc = parser.getCurrentLocation();
3466 if (parser.parseAttribute(ref))
3470 auto pathLength = ref.getNestedReferences().size();
3471 if (pathLength == 0)
3473 FlatSymbolRefAttr::get(ref.getRootReference()));
3474 else if (pathLength == 1)
3475 namepath.push_back(hw::InnerRefAttr::get(ref.getRootReference(),
3476 ref.getLeafReference()));
3478 return parser.emitError(loc,
3479 "only one nested reference is allowed");
3483 result.addAttribute(
"namepath",
3484 ArrayAttr::get(parser.getContext(), namepath));
3486 if (parser.parseOptionalAttrDict(result.attributes))
3496void TriggeredOp::build(OpBuilder &builder, OperationState &odsState,
3497 EventControlAttr event, Value trigger,
3498 ValueRange inputs) {
3499 odsState.addOperands(trigger);
3500 odsState.addOperands(inputs);
3501 odsState.addAttribute(getEventAttrName(odsState.name), event);
3502 auto *r = odsState.addRegion();
3506 llvm::SmallVector<Location> argLocs;
3507 llvm::transform(inputs, std::back_inserter(argLocs),
3508 [&](Value v) {
return v.getLoc(); });
3509 b->addArguments(inputs.getTypes(), argLocs);
3517#define GET_OP_CLASSES
3518#include "circt/Dialect/HW/HW.cpp.inc"
assert(baseType &&"element must be base type")
static std::unique_ptr< Context > context
static void buildModule(OpBuilder &builder, OperationState &result, StringAttr name, ArrayRef< PortInfo > ports, ArrayAttr annotations, ArrayAttr layers)
void getAsmBlockArgumentNamesImpl(Operation *op, mlir::Region ®ion, OpAsmSetValueNameFn setNameFn)
Get a special name to use when printing the entry block arguments of the region contained by an opera...
static LogicalResult verifyModuleCommon(HWModuleLike module)
static void printParamValue(OpAsmPrinter &p, Operation *, Attribute value, Type resultType)
static LogicalResult canonicalizeArrayInjectChain(ArrayInjectOp op, PatternRewriter &rewriter)
static void printModuleOp(OpAsmPrinter &p, ModuleTy mod)
static bool flattenConcatOp(ArrayConcatOp op, PatternRewriter &rewriter)
static LogicalResult foldCreateToSlice(ArrayCreateOp op, PatternRewriter &rewriter)
static SmallVector< PortInfo > getPortList(ModuleTy &mod)
static ArrayAttr arrayOrEmpty(mlir::MLIRContext *context, ArrayRef< Attribute > attrs)
FunctionType getHWModuleOpType(Operation *op)
static void printExtractOp(OpAsmPrinter &printer, AggType op)
Use the same printer for both struct_extract and union_extract since the syntax is identical.
static void printArrayConcatTypes(OpAsmPrinter &p, Operation *, TypeRange inputTypes, Type resultType)
static ParseResult parseSliceTypes(OpAsmParser &p, Type &srcType, Type &idxType)
static void modifyModulePorts(Operation *op, ArrayRef< std::pair< unsigned, PortInfo > > insertInputs, ArrayRef< std::pair< unsigned, PortInfo > > insertOutputs, ArrayRef< unsigned > removeInputs, ArrayRef< unsigned > removeOutputs, Block *body=nullptr)
Insert and remove ports of a module.
static Value foldStructExtract(Operation *inputOp, uint32_t fieldIndex)
static bool hasAttribute(StringRef name, ArrayRef< NamedAttribute > attrs)
static void modifyModuleArgs(MLIRContext *context, ArrayRef< std::pair< unsigned, PortInfo > > insertArgs, ArrayRef< unsigned > removeArgs, ArrayRef< Attribute > oldArgNames, ArrayRef< Type > oldArgTypes, ArrayRef< Attribute > oldArgAttrs, ArrayRef< Location > oldArgLocs, SmallVector< Attribute > &newArgNames, SmallVector< Type > &newArgTypes, SmallVector< Attribute > &newArgAttrs, SmallVector< Location > &newArgLocs, Block *body=nullptr)
Internal implementation of argument/result insertion and removal on modules.
static bool mergeConcatSlices(ArrayConcatOp op, PatternRewriter &rewriter)
static SmallVector< Location > getAllPortLocs(ModTy module)
static ParseResult parseExtractOp(OpAsmParser &parser, OperationState &result)
Use the same parser for both struct_extract and union_extract since the syntax is identical.
static void setAllPortNames(ArrayRef< Attribute > names, ModTy module)
static void getAsmBlockArgumentNamesImpl(mlir::Region ®ion, OpAsmSetValueNameFn setNameFn)
Get a special name to use when printing the entry block arguments of the region contained by an opera...
static void setHWModuleType(ModTy &mod, ModuleType type)
static ParseResult parseParamValue(OpAsmParser &p, Attribute &value, Type &resultType)
static LogicalResult checkAttributes(Operation *op, Attribute attr, Type type)
static LogicalResult canonicalizeArrayInjectIntoCreate(ArrayInjectOp op, PatternRewriter &rewriter)
static std::optional< uint64_t > getUIntFromValue(Value value)
static ParseResult parseHWModuleOp(OpAsmParser &parser, OperationState &result)
static LogicalResult verifyAggregateFieldIndexAndType(AggregateOp &op, AggregateType aggType, Type elementType)
Ensure an aggregate op's field index is within the bounds of the aggregate type and the accessed fiel...
static PortInfo getPort(ModuleTy &mod, size_t idx)
static void printSliceTypes(OpAsmPrinter &p, Operation *, Type srcType, Type idxType)
static bool hasAdditionalAttributes(Op op, ArrayRef< StringRef > ignoredAttrs={})
Check whether an operation has any additional attributes set beyond its standard list of attributes r...
static ParseResult parseArrayConcatTypes(OpAsmParser &p, SmallVectorImpl< Type > &inputTypes, Type &resultType)
static bool getFieldName(const FieldRef &fieldRef, SmallString< 32 > &string)
static Location getLoc(DefSlot slot)
static StringAttr append(StringAttr base, const Twine &suffix)
Return a attribute with the specified suffix appended.
static Block * getBodyBlock(FModuleLike mod)
static InstancePath empty
A namespace that is used to store existing names and generate new names in some scope within the IR.
StringRef newName(const Twine &name)
Return a unique name, derived from the input name, and add the new name to the internal namespace.
void setOutput(unsigned i, Value v)
Value getInput(unsigned i)
llvm::SmallVector< Value > outputOperands
llvm::SmallVector< Value > inputArgs
llvm::StringMap< unsigned > outputIdx
llvm::StringMap< unsigned > inputIdx
HWModulePortAccessor(Location loc, const ModulePortInfo &info, Region &bodyRegion)
static StringRef getInnerSymbolAttrName()
Return the name of the attribute used for inner symbol names.
This helps visit TypeOp nodes.
ResultType dispatchTypeOpVisitor(Operation *op, ExtraArgs... args)
ResultType visitUnhandledTypeOp(Operation *op, ExtraArgs... args)
This callback is invoked on any combinational operations that are not handled by the concrete visitor...
ResultType visitInvalidTypeOp(Operation *op, ExtraArgs... args)
This callback is invoked on any non-expression operations.
create(array_value, low_index, ret_type)
Direction get(bool isOutput)
Returns an output direction if isOutput is true, otherwise returns an input direction.
uint64_t getWidth(Type t)
size_t getNumPorts(Operation *op)
Return the number of ports in a module-like thing (modules, memories, etc)
ModuleType fnToMod(Operation *op, ArrayRef< Attribute > inputNames, ArrayRef< Attribute > outputNames)
LogicalResult verifyParameterStructure(ArrayAttr parameters, ArrayAttr moduleParameters, const EmitErrorFn &emitError)
Check that all the parameter values specified to the instance are structurally valid.
std::function< void(std::function< bool(InFlightDiagnostic &)>)> EmitErrorFn
Whenever the nested function returns true, a note referring to the referenced module is attached to t...
LogicalResult verifyInstanceOfHWModule(Operation *instance, FlatSymbolRefAttr moduleRef, OperandRange inputs, TypeRange results, ArrayAttr argNames, ArrayAttr resultNames, ArrayAttr parameters, SymbolTableCollection &symbolTable)
Combines verifyReferencedModule, verifyInputs, verifyOutputs, and verifyParameters.
StringAttr getName(ArrayAttr names, size_t idx)
Return the name at the specified index of the ArrayAttr or null if it cannot be determined.
ParseResult parseModuleSignature(OpAsmParser &parser, SmallVectorImpl< PortParse > &args, TypeAttr &modType)
New Style parsing.
void printModuleSignatureNew(OpAsmPrinter &p, Region &body, hw::ModuleType modType, ArrayRef< Attribute > portAttrs, ArrayRef< Location > locAttrs)
bool isOffset(Value base, Value index, uint64_t offset)
llvm::function_ref< void(OpBuilder &, HWModulePortAccessor &)> HWModuleBuilder
FunctionType getModuleType(Operation *module)
Return the signature for the specified module as a function type.
LogicalResult checkParameterInContext(Attribute value, Operation *module, Operation *usingOp, bool disallowParamRefs=false)
Check parameter specified by value to see if it is valid within the scope of the specified module mod...
LogicalResult aggregateAttrToAPInt(mlir::Type type, ArrayAttr attr, APInt &result)
Convert an ArrayAttr into an APInt value matching the given type.
int64_t getBitWidth(mlir::Type type)
Return the hardware bit width of a type.
bool isAnyModuleOrInstance(Operation *module)
TODO: Move all these functions to a hw::ModuleLike interface.
LogicalResult apIntToAggregateAttr(mlir::Type aggregateType, const APInt &intVal, ArrayAttr &result)
Convert an APInt value into a nested aggregate attribute matching the given HWAggregateType.
StringAttr getVerilogModuleNameAttr(Operation *module)
Returns the verilog module name attribute or symbol name of any module-like operations.
mlir::Type getCanonicalType(mlir::Type type)
Recursively remove HW type aliases from a type and its subelements.
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
ParseResult parseInputPortList(OpAsmParser &parser, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &inputs, SmallVectorImpl< Type > &inputTypes, ArrayAttr &inputNames)
Parse a list of instance input ports.
void printOutputPortList(OpAsmPrinter &p, Operation *op, TypeRange resultTypes, ArrayAttr resultNames)
Print a list of instance output ports.
ParseResult parseOptionalParameterList(OpAsmParser &parser, ArrayAttr ¶meters)
Parse an parameter list if present.
void printOptionalParameterList(OpAsmPrinter &p, Operation *op, ArrayAttr parameters)
Print a parameter list for a module or instance.
StringRef chooseName(StringRef a, StringRef b)
Choose a good name for an item from two options.
void printInputPortList(OpAsmPrinter &p, Operation *op, OperandRange inputs, TypeRange inputTypes, ArrayAttr inputNames)
Print a list of instance input ports.
ParseResult parseOutputPortList(OpAsmParser &parser, SmallVectorImpl< Type > &resultTypes, ArrayAttr &resultNames)
Parse a list of instance output ports.
function_ref< void(Value, StringRef)> OpAsmSetValueNameFn
This class represents the namespace in which InnerRef's can be resolved.
InnerSymTarget lookup(hw::InnerRefAttr inner) const
Resolve the InnerRef to its target within this namespace, returning empty target if no such name exis...
Operation * lookupOp(hw::InnerRefAttr inner) const
Resolve the InnerRef to its target within this namespace, returning empty target if no such name exis...
This holds a decoded list of input/inout and output ports for a module or instance.
PortInfo & at(size_t idx)
size_t sizeOutputs() const
size_t sizeInputs() const
PortDirectionRange getOutputs()
This holds the name, type, direction of a module's ports.