19#include "mlir/IR/ImplicitLocOpBuilder.h"
20#include "llvm/ADT/SmallString.h"
21#include "llvm/ADT/TypeSwitch.h"
24using namespace firrtl;
31 Value &cached =
cache[type];
33 cached =
builder.create<UnknownValueOp>(type);
42 Value src,
bool warnOnTruncation) {
43 ImplicitLocOpBuilder locBuilder(loc, builder.getInsertionBlock(),
44 builder.getInsertionPoint());
45 emitConnect(locBuilder, dst, src, warnOnTruncation);
46 builder.restoreInsertionPoint(locBuilder.saveInsertionPoint());
50 Value src,
bool warnOnTruncation) {
52 builder, dst, src, [&] {
return builder.getLoc(); }, warnOnTruncation);
55template <
typename ATy,
typename IndexOp,
bool isBundle >
59 llvm::function_ref<Location()> getDiagLoc,
60 bool warnOnTruncation) {
61 auto dstAggTy = type_dyn_cast<ATy>(dstFType);
64 auto srcAggTy = type_dyn_cast<ATy>(srcFType);
73 ConnectOp::create(builder, dst, src);
78 auto dstField = IndexOp::create(builder, dst, i);
79 auto srcField = IndexOp::create(builder, src, i);
80 if constexpr (isBundle) {
81 if (dstAggTy.getElement(i).isFlip)
82 std::swap(dstField, srcField);
84 emitConnect(builder, dstField, srcField, getDiagLoc, warnOnTruncation);
93 llvm::function_ref<Location()> getDiagLoc,
94 bool warnOnTruncation) {
95 auto dstFType = type_cast<FIRRTLType>(dst.getType());
96 auto srcFType = type_cast<FIRRTLType>(src.getType());
97 auto dstType = type_dyn_cast<FIRRTLBaseType>(dstFType);
98 auto srcType = type_dyn_cast<FIRRTLBaseType>(srcFType);
102 if (type_isa<RefType>(dstFType)) {
103 if (dstFType != srcFType)
104 src = RefCastOp::create(builder, dstFType, src);
105 RefDefineOp::create(builder, dst, src);
106 }
else if (type_isa<PropertyType>(dstFType) &&
107 type_isa<PropertyType>(srcFType)) {
109 PropAssignOp::create(builder, dst, src);
110 }
else if (type_isa<DomainType>(dstFType) &&
111 type_isa<DomainType>(srcFType)) {
112 DomainDefineOp::create(builder, dst, src);
113 }
else if (failed(connectIfAggregates<OpenBundleType, OpenSubfieldOp, true>(
114 builder, dst, dstFType, src, srcFType, getDiagLoc,
115 warnOnTruncation)) &&
117 connectIfAggregates<OpenVectorType, OpenSubindexOp, false>(
118 builder, dst, dstFType, src, srcFType, getDiagLoc,
119 warnOnTruncation))) {
121 ConnectOp::create(builder, dst, src);
127 if (isa<AnalogType>(dstType)) {
128 AttachOp::create(builder, ArrayRef{dst, src});
133 if (dstType == srcType && dstType.isPassive() &&
134 !dstType.hasUninferredWidth() && !dstType.containsAnalog()) {
135 MatchingConnectOp::create(builder, dst, src);
139 if (succeeded(connectIfAggregates<BundleType, SubfieldOp, true>(
140 builder, dst, dstFType, src, srcFType, getDiagLoc,
141 warnOnTruncation)) ||
142 succeeded(connectIfAggregates<FVectorType, SubindexOp, false>(
143 builder, dst, dstFType, src, srcFType, getDiagLoc, warnOnTruncation)))
146 if ((dstType.hasUninferredReset() || srcType.hasUninferredReset()) &&
147 dstType != srcType) {
148 srcType = dstType.getConstType(srcType.isConst());
149 src = UninferredResetCastOp::create(builder, srcType, src);
153 auto dstWidth = dstType.getBitWidthOrSentinel();
154 auto srcWidth = srcType.getBitWidthOrSentinel();
155 if (dstWidth < 0 || srcWidth < 0) {
162 if (dstType != srcType && dstType.getWidthlessType() != srcType &&
164 src = ConstCastOp::create(builder, dstType.getWidthlessType(), src);
167 ConnectOp::create(builder, dst, src);
172 if (dstWidth < srcWidth) {
173 if (warnOnTruncation)
174 mlir::emitWarning(getDiagLoc())
175 <<
"RHS width " << srcWidth <<
" exceeds LHS width " << dstWidth
176 <<
", inserting implicit truncation";
180 type_cast<IntType>(dstType).
getConstType(srcType.isConst());
181 bool isSignedDest = tmpType.
isSigned();
184 UIntType::get(dstType.getContext(), dstWidth, srcType.isConst());
185 src = TailPrimOp::create(builder, tmpType, src, srcWidth - dstWidth);
188 src = AsSIntPrimOp::create(builder,
189 dstType.getConstType(tmpType.
isConst()), src);
190 }
else if (srcWidth < dstWidth) {
192 src = PadPrimOp::create(builder, src, dstWidth);
195 if (
auto srcType = type_cast<FIRRTLBaseType>(src.getType());
196 srcType && dstType != srcType &&
198 src = ConstCastOp::create(builder, dstType, src);
203 if (dstType == src.getType() && dstType.isPassive() &&
204 !dstType.hasUninferredWidth()) {
205 MatchingConnectOp::create(builder, dst, src);
207 ConnectOp::create(builder, dst, src);
211 auto intType = type_cast<IntType>(type);
212 assert((!intType.hasWidth() ||
213 (
unsigned)intType.getWidthOrSentinel() == value.getBitWidth()) &&
214 "value / type width mismatch");
216 intType.isSigned() ? IntegerType::Signed : IntegerType::Unsigned;
218 IntegerType::get(type.getContext(), value.getBitWidth(), intSign);
219 return IntegerAttr::get(attrType, value);
225 int32_t width = abs(type_cast<IntType>(type).getWidthOrSentinel());
232 int32_t width = abs(type_cast<IntType>(type).getWidthOrSentinel());
234 type, APInt(width, -1,
false,
true));
240 for (
auto *user : value.getUsers())
241 if (
auto propassign = dyn_cast<PropAssignOp>(user))
242 if (propassign.getDest() == value)
257 for (
auto *user : val.getUsers()) {
258 if (
auto connect = dyn_cast<FConnectLike>(user)) {
259 if (connect.getDest() != val)
261 return connect.getSrc();
268 bool lookThroughNodes,
269 bool lookThroughCasts) {
274 auto updateVal = [&](Value thisVal) {
275 for (
auto *user : thisVal.getUsers()) {
276 if (
auto connect = dyn_cast<FConnectLike>(user)) {
277 if (connect.getDest() != val)
279 val = connect.getSrc();
289 if (
auto blockArg = dyn_cast<BlockArgument>(val)) {
290 FModuleOp op = cast<FModuleOp>(val.getParentBlock()->getParentOp());
291 auto direction = op.getPortDirection(blockArg.getArgNumber());
299 auto *op = val.getDefiningOp();
302 if (
auto inst = dyn_cast<InstanceOp>(op)) {
303 auto resultNo = cast<OpResult>(val).getResultNumber();
306 return inst.getResult(resultNo);
313 updateVal(op->getResult(0));
318 if (lookThroughNodes && isa<NodeOp>(op)) {
319 val = cast<NodeOp>(op).getInput();
323 if (lookThroughCasts &&
324 isa<AsUIntPrimOp, AsSIntPrimOp, AsClockPrimOp, AsAsyncResetPrimOp>(
326 val = op->getOperand(0);
331 if (isa<PadPrimOp, TailPrimOp>(op)) {
332 val = op->getOperand(0);
347 bool lookThroughNodes,
bool lookThroughCasts,
351 assert(value.getType().isPassive() &&
"this code was not tested with flips");
362 struct StackElement {
364 : dst(dst), src(src), current(current), it(current.user_begin()),
377 Value::user_iterator it;
381 SmallVector<StackElement> workStack;
387 auto value = src.getValue();
388 workStack.emplace_back(dst, src, value, src.
getFieldID());
394 auto fieldRef = original;
402 auto val = fieldRef.getValue();
405 if (
auto blockArg = dyn_cast<BlockArgument>(val)) {
406 auto *parent = val.getParentBlock()->getParentOp();
407 auto module = cast<FModuleLike>(parent);
408 auto direction =
module.getPortDirection(blockArg.getArgNumber());
411 if (!callback(original, fieldRef))
415 addToWorklist(original, fieldRef);
419 auto *op = val.getDefiningOp();
422 if (
auto inst = dyn_cast<InstanceOp>(op)) {
423 auto resultNo = cast<OpResult>(val).getResultNumber();
426 if (!callback(original, fieldRef))
430 addToWorklist(original, fieldRef);
436 addToWorklist(original, fieldRef);
441 if (lookThroughNodes && isa<NodeOp>(op)) {
442 auto input = cast<NodeOp>(op).getInput();
444 fieldRef = next.getSubField(fieldRef.getFieldID());
449 if (lookThroughCasts &&
450 isa<AsUIntPrimOp, AsSIntPrimOp, AsClockPrimOp, AsAsyncResetPrimOp>(
452 auto input = op->getOperand(0);
454 fieldRef = next.getSubField(fieldRef.getFieldID());
459 if (isa<PadPrimOp, TailPrimOp>(op)) {
460 auto input = op->getOperand(0);
462 fieldRef = next.getSubField(fieldRef.getFieldID());
471 if (!callback(original, fieldRef))
479 if (workStack.empty())
481 auto &back = workStack.back();
482 auto current = back.current;
484 if (back.it == current.user_end()) {
485 workStack.pop_back();
491 auto *user = *back.it++;
492 auto fieldID = back.fieldID;
494 if (
auto subfield = dyn_cast<SubfieldOp>(user)) {
495 BundleType bundleType = subfield.getInput().getType();
496 auto index = subfield.getFieldIndex();
497 auto subID = bundleType.getFieldID(index);
499 if (fieldID && index != bundleType.getIndexForFieldID(fieldID))
501 auto subRef = fieldRef.getSubField(subID);
502 auto subOriginal = original.getSubField(subID);
503 auto value = subfield.getResult();
506 workStack.emplace_back(subOriginal, subRef, value, 0);
509 workStack.emplace_back(subOriginal, subRef, value, fieldID - subID);
511 }
else if (
auto subindex = dyn_cast<SubindexOp>(user)) {
512 FVectorType vectorType = subindex.getInput().getType();
513 auto index = subindex.getIndex();
514 auto subID = vectorType.getFieldID(index);
516 if (fieldID && index != vectorType.getIndexForFieldID(fieldID))
518 auto subRef = fieldRef.getSubField(subID);
519 auto subOriginal = original.getSubField(subID);
520 auto value = subindex.getResult();
523 workStack.emplace_back(subOriginal, subRef, value, 0);
526 workStack.emplace_back(subOriginal, subRef, value, fieldID - subID);
528 }
else if (
auto connect = dyn_cast<FConnectLike>(user)) {
530 if (connect.getDest() != current)
548 if (LLVM_UNLIKELY(!value))
552 auto *op = value.getDefiningOp();
559 return TypeSwitch<Operation *, FieldRef>(op)
560 .Case<RefCastOp, ConstCastOp, UninferredResetCastOp>(
561 [lookThroughCasts](
auto op) {
562 if (!lookThroughCasts)
566 .Case<SubfieldOp, OpenSubfieldOp, SubindexOp, OpenSubindexOp, RefSubOp,
568 [](
auto subOp) {
return subOp.getAccessedField(); })
573 bool lookThroughCasts) {
574 if (LLVM_UNLIKELY(!value))
580 auto deltaRef =
getDeltaRef(value, lookThroughCasts);
584 id = deltaRef.getSubField(
id).getFieldID();
586 value = deltaRef.getValue();
591static void getDeclName(Value value, SmallString<64> &
string,
bool nameSafe) {
594 if (
auto arg = dyn_cast<BlockArgument>(value)) {
596 auto *op = arg.getOwner()->getParentOp();
597 TypeSwitch<Operation *>(op).Case<FModuleOp, ClassOp>([&](
auto op) {
598 auto name = cast<StringAttr>(op.getPortNames()[arg.getArgNumber()]);
599 string += name.getValue();
604 auto *op = value.getDefiningOp();
605 TypeSwitch<Operation *>(op)
606 .Case<ObjectOp>([&](ObjectOp op) {
607 string += op.getInstanceName();
610 .Case<InstanceOp, InstanceChoiceOp, MemOp>([&](
auto op) {
611 string += op.getName();
612 string += nameSafe ?
"_" :
".";
613 string += op.getPortName(cast<OpResult>(value).getResultNumber());
616 .Case<FNamableOp>([&](
auto op) {
617 string += op.getName();
620 .Case<mlir::UnrealizedConversionCastOp>(
621 [&](mlir::UnrealizedConversionCastOp cast) {
623 if (cast.getNumResults() == 1 && cast.getNumOperands() == 1 &&
624 cast.getResult(0).getType() == cast.getOperand(0).getType()) {
625 value = cast.getInputs()[0];
640std::pair<std::string, bool>
642 SmallString<64> name;
645 bool rootKnown = !name.empty();
647 auto type = value.getType();
651 if (
auto refTy = type_dyn_cast<RefType>(type))
652 type = refTy.getType();
654 if (
auto bundleType = type_dyn_cast<BundleType>(type)) {
655 auto index = bundleType.getIndexForFieldID(localID);
657 auto &element = bundleType.getElements()[index];
659 name += nameSafe ?
"_" :
".";
660 name += element.name.getValue();
663 localID = localID - bundleType.getFieldID(index);
664 }
else if (
auto bundleType = type_dyn_cast<OpenBundleType>(type)) {
665 auto index = bundleType.getIndexForFieldID(localID);
667 auto &element = bundleType.getElements()[index];
669 name += nameSafe ?
"_" :
".";
670 name += element.name.getValue();
673 localID = localID - bundleType.getFieldID(index);
674 }
else if (
auto vecType = type_dyn_cast<FVectorType>(type)) {
675 auto index = vecType.getIndexForFieldID(localID);
676 name += nameSafe ?
"_" :
"[";
677 name += std::to_string(index);
681 type = vecType.getElementType();
682 localID = localID - vecType.getFieldID(index);
683 }
else if (
auto vecType = type_dyn_cast<OpenVectorType>(type)) {
684 auto index = vecType.getIndexForFieldID(localID);
685 name += nameSafe ?
"_" :
"[";
686 name += std::to_string(index);
690 type = vecType.getElementType();
691 localID = localID - vecType.getFieldID(index);
692 }
else if (
auto classType = type_dyn_cast<ClassType>(type)) {
693 auto index = classType.getIndexForFieldID(localID);
694 auto &element = classType.getElement(index);
695 name += nameSafe ?
"_" :
".";
696 name += element.name.getValue();
698 localID = localID - classType.getFieldID(index);
704 llvm_unreachable(
"unsupported type");
708 return {name.str().str(), rootKnown};
716 Value value,
unsigned fieldID) {
718 while (fieldID != 0) {
720 .
Case<BundleType>([&](
auto bundle) {
721 auto index = bundle.getIndexForFieldID(fieldID);
722 value = SubfieldOp::create(builder, value, index);
723 fieldID -= bundle.getFieldID(index);
725 .Case<OpenBundleType>([&](
auto bundle) {
726 auto index = bundle.getIndexForFieldID(fieldID);
727 value = OpenSubfieldOp::create(builder, value, index);
728 fieldID -= bundle.getFieldID(index);
730 .Case<FVectorType>([&](
auto vector) {
731 auto index = vector.getIndexForFieldID(fieldID);
732 value = SubindexOp::create(builder, value, index);
733 fieldID -= vector.getFieldID(index);
735 .Case<OpenVectorType>([&](
auto vector) {
736 auto index = vector.getIndexForFieldID(fieldID);
737 value = OpenSubindexOp::create(builder, value, index);
738 fieldID -= vector.getFieldID(index);
740 .Case<RefType>([&](
auto reftype) {
742 .template Case<BundleType, FVectorType>([&](
auto type) {
743 auto index = type.getIndexForFieldID(fieldID);
744 value = RefSubOp::create(builder, value, index);
745 fieldID -= type.getFieldID(index);
747 .Default([&](
auto _) {
748 llvm::report_fatal_error(
749 "unrecognized type for indexing through with fieldID");
753 .Default([&](
auto _) {
754 llvm::report_fatal_error(
755 "unrecognized type for indexing through with fieldID");
775 return fn(0, type,
false);
777 uint64_t fieldID = 0;
778 auto recurse = [&](
auto &&f,
FIRRTLBaseType type,
bool isFlip) ->
void {
780 .
Case<BundleType>([&](BundleType bundle) {
781 for (
size_t i = 0, e = bundle.getNumElements(); i < e; ++i) {
783 f(f, bundle.getElementType(i),
784 isFlip ^ bundle.getElement(i).isFlip);
787 .
template Case<FVectorType>([&](FVectorType vector) {
788 for (
size_t i = 0, e = vector.getNumElements(); i < e; ++i) {
790 f(f, vector.getElementType(), isFlip);
793 .
template Case<FEnumType>([&](FEnumType fenum) {
797 fn(fieldID, fenum, isFlip);
800 assert(groundType.isGround() &&
801 "only ground types are expected here");
802 fn(fieldID, groundType, isFlip);
805 recurse(recurse, type,
false);
812 if (
auto arg = dyn_cast<BlockArgument>(root)) {
813 auto mod = cast<FModuleLike>(arg.getOwner()->getParentOp());
824 return TypeSwitch<Operation *, FieldRef>(ist.
getOp())
825 .Case<FModuleOp>([&](
auto fmod) {
831 auto symOp = dyn_cast<hw::InnerSymbolOpInterface>(ist.
getOp());
832 assert(symOp && symOp.getTargetResultIndex() &&
833 (symOp.supportsPerFieldSymbols() || ist.
getField() == 0));
839 MLIRContext *
context, hw::InnerSymAttr attr, uint64_t fieldID,
841 SmallVector<hw::InnerSymPropertiesAttr> props;
844 if (
auto sym = attr.getSymIfExists(fieldID))
846 llvm::append_range(props, attr.getProps());
850 auto sym = StringAttr::get(
context, getNamespace().newName(
"sym"));
851 props.push_back(hw::InnerSymPropertiesAttr::get(
856 [](
auto &p,
auto &q) {
return p.getFieldID() < q.getFieldID(); });
857 return {hw::InnerSymAttr::get(
context, props), sym};
864 if (
auto mod = dyn_cast<FModuleLike>(target.
getOp())) {
865 auto portIdx = target.
getPort();
866 assert(portIdx < mod.getNumPorts());
870 mod.setPortSymbolAttr(portIdx, attr);
875 if (
auto symOp = dyn_cast<hw::InnerSymbolOpInterface>(target.
getOp())) {
879 symOp.setInnerSymbolAttr(attr);
884 assert(0 &&
"target must be port of FModuleLike or InnerSymbol");
892 module = cast<FModuleLike>(target.getOp());
894 module = target.getOp()->getParentOfType<FModuleOp>();
898 return getNamespace(module);
907 auto mod = target.
isPort() ? dyn_cast<FModuleLike>(target.
getOp())
908 : target.
getOp()->getParentOfType<FModuleOp>();
910 "must be an operation inside an FModuleOp or port of FModuleLike");
911 return hw::InnerRefAttr::get(SymbolTable::getSymbolName(mod),
916std::pair<bool, std::optional<mlir::LocationAttr>>
918 StringAttr &locatorFilenameCache,
919 FileLineColLoc &fileLineColLocCache,
922 if (!spelling.starts_with(
"@[") || !spelling.ends_with(
"]"))
923 return {
false, std::nullopt};
925 spelling = spelling.drop_front(2).drop_back(1);
929 auto decodeLocator = [&](StringRef input,
unsigned &resultLineNo,
930 unsigned &resultColNo) -> StringRef {
932 auto spaceLoc = input.find_last_of(
' ');
933 if (spaceLoc == StringRef::npos)
936 auto filename = input.take_front(spaceLoc);
937 auto lineAndColumn = input.drop_front(spaceLoc + 1);
941 StringRef lineStr, colStr;
942 std::tie(lineStr, colStr) = lineAndColumn.split(
':');
945 if (lineStr.getAsInteger(10, resultLineNo))
947 if (!colStr.empty()) {
948 if (colStr.front() !=
'{') {
949 if (colStr.getAsInteger(10, resultColNo))
953 if (colStr.drop_front().split(
',').first.getAsInteger(10, resultColNo))
961 unsigned lineNo = 0, columnNo = 0;
962 StringRef filename = decodeLocator(spelling, lineNo, columnNo);
963 if (filename.empty())
964 return {
false, std::nullopt};
969 return {
true, std::nullopt};
973 auto getFileLineColLoc = [&](StringRef filename,
unsigned lineNo,
974 unsigned columnNo) -> FileLineColLoc {
976 StringAttr filenameId = locatorFilenameCache;
977 if (filenameId.str() != filename) {
979 locatorFilenameCache = filenameId = StringAttr::get(
context, filename);
983 return fileLineColLocCache =
984 FileLineColLoc::get(filenameId, lineNo, columnNo);
988 auto result = fileLineColLocCache;
989 if (result && result.getLine() == lineNo && result.getColumn() == columnNo)
992 return fileLineColLocCache =
993 FileLineColLoc::get(filenameId, lineNo, columnNo);
1004 SmallVector<Location> extraLocs;
1005 auto spaceLoc = filename.find_last_of(
' ');
1006 while (spaceLoc != StringRef::npos) {
1009 unsigned nextLineNo = 0, nextColumnNo = 0;
1011 decodeLocator(filename.take_front(spaceLoc), nextLineNo, nextColumnNo);
1014 if (nextFilename.empty())
1020 getFileLineColLoc(filename.drop_front(spaceLoc + 1), lineNo, columnNo);
1021 extraLocs.push_back(loc);
1022 filename = nextFilename;
1023 lineNo = nextLineNo;
1024 columnNo = nextColumnNo;
1025 spaceLoc = filename.find_last_of(
' ');
1028 mlir::LocationAttr result = getFileLineColLoc(filename, lineNo, columnNo);
1029 if (!extraLocs.empty()) {
1030 extraLocs.push_back(result);
1031 std::reverse(extraLocs.begin(), extraLocs.end());
1032 result = FusedLoc::get(
context, extraLocs);
1034 return {
true, result};
1041 Type type, std::optional<Location> loc,
1042 llvm::function_ref<hw::TypeAliasType(Type, BaseTypeAliasType, Location)>
1044 auto firType = type_dyn_cast<FIRRTLBaseType>(type);
1050 if (BaseTypeAliasType aliasType = dyn_cast<BaseTypeAliasType>(firType)) {
1052 loc = UnknownLoc::get(type.getContext());
1053 type =
lowerType(aliasType.getInnerType(), loc, getTypeDeclFn);
1054 return getTypeDeclFn(type, aliasType, *loc);
1057 firType = firType.getPassiveType();
1059 if (
auto bundle = type_dyn_cast<BundleType>(firType)) {
1060 mlir::SmallVector<hw::StructType::FieldInfo, 8> hwfields;
1061 for (
auto element : bundle) {
1062 Type etype =
lowerType(element.type, loc, getTypeDeclFn);
1065 hwfields.push_back(hw::StructType::FieldInfo{element.name, etype});
1067 return hw::StructType::get(type.getContext(), hwfields);
1069 if (
auto vec = type_dyn_cast<FVectorType>(firType)) {
1070 auto elemTy =
lowerType(vec.getElementType(), loc, getTypeDeclFn);
1073 return hw::ArrayType::get(elemTy, vec.getNumElements());
1075 if (
auto fenum = type_dyn_cast<FEnumType>(firType)) {
1076 mlir::SmallVector<hw::UnionType::FieldInfo, 8> hwfields;
1078 for (
auto element : fenum) {
1079 Type etype =
lowerType(element.type, loc, getTypeDeclFn);
1082 hwfields.push_back(hw::UnionType::FieldInfo{element.name, etype, 0});
1083 if (element.type.getBitWidthOrSentinel() != 0)
1086 auto tagTy = IntegerType::get(type.getContext(), fenum.getTagWidth());
1089 auto bodyTy = hw::UnionType::get(type.getContext(), hwfields);
1090 hw::StructType::FieldInfo fields[2] = {
1091 {StringAttr::get(type.getContext(),
"tag"), tagTy},
1092 {StringAttr::get(type.getContext(),
"body"), bodyTy}};
1093 return hw::StructType::get(type.getContext(), fields);
1095 if (type_isa<ClockType>(firType))
1096 return seq::ClockType::get(firType.getContext());
1098 auto width = firType.getBitWidthOrSentinel();
1100 return IntegerType::get(type.getContext(), width);
1106 mlir::ImplicitLocOpBuilder &builderOM) {
1108 auto *
context = op->getContext();
1109 auto id = DistinctAttr::create(UnitAttr::get(
context));
1110 TargetKind kind = TargetKind::Reference;
1113 NamedAttrList fields;
1114 fields.append(
"id",
id);
1115 fields.append(
"class", StringAttr::get(
context,
"circt.tracker"));
1117 fields.append(
"circt.nonlocal", mlir::FlatSymbolRefAttr::get(nla));
1121 if (isa<InstanceOp, FModuleLike>(op))
1122 kind = TargetKind::Instance;
1126 return PathOp::create(builderOM, kind,
id);
1135 llvm::StringRef formatString,
1136 llvm::ArrayRef<mlir::Value> specOperands,
1137 mlir::StringAttr &formatStringResult,
1138 llvm::SmallVectorImpl<mlir::Value> &operands) {
1141 llvm::SmallString<64> validatedFormatString;
1143 for (
size_t i = 0, e = formatString.size(), opIdx = 0; i != e; ++i) {
1144 auto c = formatString[i];
1149 validatedFormatString.push_back(c);
1152 llvm::SmallString<6> width;
1153 c = formatString[++i];
1156 c = formatString[++i];
1163 return mlir::emitError(loc) <<
"ASCII character format specifiers "
1164 "('%c') may not specify a width";
1170 validatedFormatString.append(width);
1171 if (specOperands.size() <= opIdx)
1172 return mlir::emitError(loc) <<
"not enough operands for format "
1174 operands.push_back(specOperands[opIdx++]);
1178 return mlir::emitError(loc)
1179 <<
"literal percents ('%%') may not specify a width";
1183 return mlir::emitError(loc)
1184 <<
"unknown printf substitution '%" << width << c <<
"'";
1186 validatedFormatString.push_back(c);
1194 if (formatString[i + 1] !=
'{') {
1195 validatedFormatString.push_back(c);
1201 while (formatString[i] !=
'}')
1203 if (formatString[i] !=
'}')
1204 return mlir::emitError(loc)
1205 <<
"expected '}' to terminate special substitution";
1207 auto specialString = formatString.slice(start, i);
1208 if (specialString ==
"SimulationTime") {
1209 operands.push_back(TimeOp::create(builder, loc));
1210 }
else if (specialString ==
"HierarchicalModuleName") {
1211 operands.push_back(HierarchicalModuleNameOp::create(builder, loc));
1213 return mlir::emitError(loc)
1214 <<
"unknown printf substitution '" << specialString
1215 <<
"' (did you misspell it?)";
1218 validatedFormatString.append(
"{{}}");
1223 validatedFormatString.push_back(c);
1227 formatStringResult = builder.getStringAttr(validatedFormatString);
1228 return mlir::success();
1236 Operation *operation) {
1237 if (
auto mod = dyn_cast<mlir::ModuleOp>(operation))
1238 for (
auto &op : *mod.getBody())
1239 if ((operation = dyn_cast<CircuitOp>(&op)))
1242 for (
auto option : cast<CircuitOp>(operation).getOps<OptionOp>())
1243 for (
auto optionCase : option.getOps<OptionCaseOp>())
1244 cache[{option.getSymNameAttr(), optionCase.getSymNameAttr()}] =
1245 optionCase.getCaseMacroAttr();
1250 StringAttr caseName)
const {
1251 auto it = cache.find({optionName, caseName});
1252 if (it == cache.end())
assert(baseType &&"element must be base type")
MlirType uint64_t numElements
static std::unique_ptr< Context > context
static LogicalResult connectIfAggregates(ImplicitLocOpBuilder &builder, Value dst, FIRRTLType dstFType, Value src, FIRRTLType srcFType, llvm::function_ref< Location()> getDiagLoc, bool warnOnTruncation)
static void getDeclName(Value value, SmallString< 64 > &string, bool nameSafe)
Get the string name of a value which is a direct child of a declaration op.
static Value lookThroughWires(Value value)
Trace a value through wires to its original definition.
This class represents a reference to a specific field or element of an aggregate value.
unsigned getFieldID() const
Get the field ID of this FieldRef, which is a unique identifier mapped to a specific field in a bundl...
Value getValue() const
Get the Value which created this location.
This class provides a read-only projection over the MLIR attributes that represent a set of annotatio...
bool applyToOperation(Operation *op) const
Store the annotations in this set in an operation's annotations attribute, overwriting any existing a...
void addAnnotations(ArrayRef< Annotation > annotations)
Add more annotations to this annotation set.
bool isConst() const
Returns true if this is a 'const' type that can only hold compile-time constant values.
This class implements the same functionality as TypeSwitch except that it uses firrtl::type_dyn_cast ...
FIRRTLTypeSwitch< T, ResultT > & Case(CallableT &&caseFn)
Add a case on the given type.
FlatSymbolRefAttr getMacro(StringAttr optionName, StringAttr caseName) const
InstanceChoiceMacroTable(Operation *op)
This is the common base class between SIntType and UIntType.
IntType getConstType(bool isConst) const
Return a 'const' or non-'const' version of this type.
ImplicitLocOpBuilder & builder
SmallDenseMap< Type, Value, 8 > cache
Value getUnknown(PropertyType type)
Get or create an UnknownValueOp for the given property type.
The target of an inner symbol, the entity the symbol is a handle for.
auto getField() const
Return the target's fieldID.
auto getPort() const
Return the target's port, if valid. Check "isPort()".
bool isPort() const
Return if this targets a port.
Operation * getOp() const
Return the target's base operation. For ports, this is the module.
llvm::function_ref< hw::InnerSymbolNamespace &(FModuleLike mod)> GetNamespaceCallback
FieldRef getFieldRefForTarget(const hw::InnerSymTarget &ist)
Get FieldRef pointing to the specified inner symbol target, which must be valid.
FieldRef getDeltaRef(Value value, bool lookThroughCasts=false)
Get the delta indexing from a value, as a FieldRef.
FIRRTLBaseType getBaseType(Type type)
If it is a base type, return it as is.
FieldRef getFieldRefFromValue(Value value, bool lookThroughCasts=false)
Get the FieldRef from a value.
mlir::TypedValue< FIRRTLBaseType > FIRRTLBaseValue
void walkGroundTypes(FIRRTLType firrtlType, llvm::function_ref< void(uint64_t, FIRRTLBaseType, bool)> fn)
Walk leaf ground types in the firrtlType and apply the function fn.
PathOp createPathRef(Operation *op, hw::HierPathOp nla, mlir::ImplicitLocOpBuilder &builderOM)
Add the tracker annotation to the op and get a PathOp to the op.
IntegerAttr getIntAttr(Type type, const APInt &value)
Utiility for generating a constant attribute.
std::pair< bool, std::optional< mlir::LocationAttr > > maybeStringToLocation(llvm::StringRef spelling, bool skipParsing, mlir::StringAttr &locatorFilenameCache, FileLineColLoc &fileLineColLocCache, MLIRContext *context)
std::pair< hw::InnerSymAttr, StringAttr > getOrAddInnerSym(MLIRContext *context, hw::InnerSymAttr attr, uint64_t fieldID, llvm::function_ref< hw::InnerSymbolNamespace &()> getNamespace)
Ensure that the the InnerSymAttr has a symbol on the field specified.
hw::InnerRefAttr getInnerRefTo(const hw::InnerSymTarget &target, GetNamespaceCallback getNamespace)
Obtain an inner reference to the target (operation or port), adding an inner symbol as necessary.
void emitConnect(OpBuilder &builder, Location loc, Value lhs, Value rhs, bool warnOnTruncation=false)
Emit a connect between two values.
PropAssignOp getPropertyAssignment(FIRRTLPropertyValue value)
Return the single assignment to a Property value.
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)
Value getModuleScopedDriver(Value val, bool lookThroughWires, bool lookThroughNodes, bool lookThroughCasts)
Return the value that drives another FIRRTL value within module scope.
Value getDriverFromConnect(Value val)
Return the module-scoped driver of a value only looking through one connect.
Value getValueByFieldID(ImplicitLocOpBuilder builder, Value value, unsigned fieldID)
This gets the value targeted by a field id.
std::pair< std::string, bool > getFieldName(const FieldRef &fieldRef, bool nameSafe=false)
Get a string identifier representing the FieldRef.
llvm::function_ref< bool(const FieldRef &dst, const FieldRef &src)> WalkDriverCallback
Walk all the drivers of a value, passing in the connect operations drive the value.
mlir::TypedValue< PropertyType > FIRRTLPropertyValue
Type lowerType(Type type, std::optional< Location > loc={}, llvm::function_ref< hw::TypeAliasType(Type, BaseTypeAliasType, Location)> getTypeDeclFn={})
Given a type, return the corresponding lowered type for the HW dialect.
hw::InnerSymTarget getTargetFor(FieldRef ref)
Return the inner sym target for the specified value and fieldID.
bool areTypesConstCastable(FIRRTLType destType, FIRRTLType srcType, bool srcOuterTypeIsConst=false)
Returns whether the srcType can be const-casted to the destType.
bool walkDrivers(FIRRTLBaseValue value, bool lookThroughWires, bool lookThroughNodes, bool lookThroughCasts, WalkDriverCallback callback)
IntegerAttr getIntOnesAttr(Type type)
Utility for generating a constant all ones attribute.
IntegerAttr getIntZerosAttr(Type type)
Utility for generating a constant zero attribute.
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.