21#include "mlir/IR/ImplicitLocOpBuilder.h"
22#include "mlir/Pass/Pass.h"
23#include "llvm/ADT/BitVector.h"
24#include "llvm/ADT/DenseMap.h"
25#include "llvm/ADT/EquivalenceClasses.h"
26#include "llvm/ADT/PostOrderIterator.h"
27#include "llvm/Support/Debug.h"
29#define DEBUG_TYPE "firrtl-lower-xmr"
33#define GEN_PASS_DEF_LOWERXMR
34#include "circt/Dialect/FIRRTL/Passes.h.inc"
39using namespace firrtl;
40using hw::InnerRefAttr;
62 using NextNodeOnPath = std::optional<size_t>;
63 using SymOrIndexOp = PointerUnion<Attribute, Operation *>;
67[[maybe_unused]] llvm::raw_ostream &
operator<<(llvm::raw_ostream &os,
68 const XMRNode &node) {
70 if (
auto attr = dyn_cast<Attribute>(node.info))
71 os <<
"path=" << attr;
73 auto subOp = cast<RefSubOp>(cast<Operation *>(node.info));
74 os <<
"index=" << subOp.getIndex() <<
" (-> " << subOp.getType() <<
")";
76 os <<
", next=" << node.next <<
")";
85 ModuleState(FModuleOp &moduleOp) : body(moduleOp.
getBodyBlock()) {}
91 Value getOrCreateXMRRefOp(Type type, FlatSymbolRefAttr symbol,
92 StringAttr suffix, ImplicitLocOpBuilder &builder) {
94 auto it = xmrRefCache.find({type, symbol, suffix});
95 if (it != xmrRefCache.end())
96 return it->getSecond();
99 OpBuilder::InsertionGuard guard(builder);
100 if (xmrRefPoint.isSet())
101 builder.restoreInsertionPoint(xmrRefPoint);
103 builder.setInsertionPointToStart(body);
105 Value xmr = builder.create<XMRRefOp>(type, symbol, suffix);
106 xmrRefCache.insert({{type, symbol, suffix}, xmr});
108 xmrRefPoint = builder.saveInsertionPoint();
118 DenseMap<std::tuple<Type, SymbolRefAttr, StringAttr>, Value> xmrRefCache;
121 OpBuilder::InsertPoint xmrRefPoint;
133 llvm::EquivalenceClasses<Value> eq;
137 SmallVector<RefResolveOp> resolveOps;
138 SmallVector<RefSubOp> indexingOps;
139 SmallVector<Operation *> forceAndReleaseOps;
142 auto transferFunc = [&](Operation *op) -> LogicalResult {
143 return TypeSwitch<Operation *, LogicalResult>(op)
144 .Case<RefSendOp>([&](RefSendOp send) {
147 Value xmrDef = send.getBase();
153 if (
auto verbExpr = xmrDef.getDefiningOp<VerbatimExprOp>())
154 if (verbExpr.getSymbolsAttr().empty() && verbExpr->hasOneUse()) {
159 auto inRef = InnerRefAttr();
170 ImplicitLocOpBuilder b(xmrDef.getLoc(), &getContext());
171 b.setInsertionPointAfterValue(xmrDef);
172 SmallString<32> opName;
173 auto nameKind = NameKindEnum::DroppableName;
179 opName = name +
"_probe";
180 nameKind = NameKindEnum::InterestingName;
181 }
else if (
auto *xmrDefOp = xmrDef.getDefiningOp()) {
184 if (
auto name = xmrDefOp->getAttrOfType<StringAttr>(
"name")) {
185 (Twine(name.strref()) +
"_probe").
toVector(opName);
186 nameKind = NameKindEnum::InterestingName;
189 xmrDef = b.create<NodeOp>(xmrDef, opName, nameKind).getResult();
197 .Case<RWProbeOp>([&](RWProbeOp rwprobe) {
203 .Case<MemOp>([&](MemOp mem) {
209 for (
const auto &res : llvm::enumerate(mem.getResults()))
210 if (isa<RefType>(mem.getResult(res.index()).getType())) {
222 .Case<FConnectLike>([&](FConnectLike connect) {
224 if (!isa<RefType>(connect.getSrc().getType()))
228 type_cast<RefType>(connect.getSrc().getType()).getType()))
245 .Case<RefSubOp>([&](RefSubOp op) -> LogicalResult {
251 indexingOps.push_back(op);
254 .Case<RefResolveOp>([&](RefResolveOp resolve) {
268 resolveOps.push_back(resolve);
271 .Case<RefCastOp>([&](RefCastOp op) {
277 .Case<Forceable>([&](Forceable op) {
279 if (type_isa<RefType>(op.getDataRaw().getType())) {
285 if (!op.isForceable() || op.getDataRef().use_empty() ||
292 .Case<RefForceOp, RefForceInitialOp, RefReleaseOp,
293 RefReleaseInitialOp>([&](
auto op) {
294 forceAndReleaseOps.push_back(op);
297 .Default([&](
auto) {
return success(); });
300 SmallVector<FModuleOp> publicModules;
304 DenseSet<InstanceGraphNode *> visited;
305 for (
auto *root : instanceGraph) {
306 for (
auto *node : llvm::post_order_ext(root, visited)) {
307 auto module = dyn_cast<FModuleOp>(*node->getModule());
310 LLVM_DEBUG(llvm::dbgs() <<
"Traversing module:"
311 << module.getModuleNameAttr() <<
"\n");
315 if (module.isPublic())
316 publicModules.push_back(module);
318 auto result =
module.walk([&](Operation *op) {
319 if (transferFunc(op).failed())
320 return WalkResult::interrupt();
321 return WalkResult::advance();
324 if (result.wasInterrupted())
325 return signalPassFailure();
328 module.setLayersAttr(ArrayAttr::get(module.getContext(), {}));
336 while (!indexingOps.empty()) {
338 decltype(indexingOps) worklist;
339 worklist.swap(indexingOps);
341 for (
auto op : worklist) {
346 indexingOps.push_back(op);
352 if (worklist.size() == indexingOps.size()) {
353 auto op = worklist.front();
356 "indexing through probe of unknown origin (input probe?)")
357 .attachNote(op.getInput().getLoc())
358 .append(
"indexing through this reference");
359 return signalPassFailure();
364 size_t numPorts =
module.getNumPorts();
365 for (
size_t portNum = 0; portNum < numPorts; ++portNum)
366 if (isa<RefType>(module.getPortType(portNum))) {
379 llvm::dbgs() <<
"\n dataflow at leader::" << I->getData() <<
"\n =>";
384 llvm::dbgs() <<
"\n " << init;
386 llvm::dbgs() <<
"\n Done\n";
389 for (
auto refResolve : resolveOps)
391 return signalPassFailure();
392 for (
auto *op : forceAndReleaseOps)
394 return signalPassFailure();
395 for (
auto module : publicModules) {
397 return signalPassFailure();
417 auto modName = mod.getModuleName();
418 if (
auto ext = dyn_cast<FExtModuleOp>(*mod)) {
420 if (
auto defname = ext.getDefname(); defname && !defname->empty())
423 (Twine(
"ref_") + modName).
toVector(prefix);
429 const Twine &prefix,
bool backTick =
false) {
430 return StringAttr::get(&getContext(), Twine(backTick ?
"`" :
"") + prefix +
431 "_" + mod.getPortName(portIndex));
435 ImplicitLocOpBuilder builder,
436 mlir::FlatSymbolRefAttr &ref,
437 SmallString<128> &stringLeaf) {
438 assert(stringLeaf.empty());
440 auto remoteOpPath = getRemoteRefSend(refVal);
443 SmallVector<Attribute> refSendPath;
444 SmallVector<RefSubOp> indexing;
446 while (remoteOpPath) {
447 lastIndex = *remoteOpPath;
448 auto entr = refSendPathList[*remoteOpPath];
450 TypeSwitch<XMRNode::SymOrIndexOp>(entr.info)
451 .Case<Attribute>([&](
auto attr) {
455 refSendPath.push_back(attr);
458 [&](
auto *op) { indexing.push_back(cast<RefSubOp>(op)); });
459 remoteOpPath = entr.next;
461 auto iter = xmrPathSuffix.find(lastIndex);
465 if (iter != xmrPathSuffix.end()) {
466 if (!refSendPath.empty())
467 stringLeaf.append(
".");
468 stringLeaf.append(iter->getSecond());
471 assert(!(refSendPath.empty() && stringLeaf.empty()) &&
472 "nothing to index through");
485 for (
auto subOp : llvm::reverse(indexing)) {
486 TypeSwitch<FIRRTLBaseType>(subOp.getInput().getType().getType())
487 .Case<FVectorType, OpenVectorType>([&](
auto vecType) {
488 (Twine(
"[") + Twine(subOp.getIndex()) +
"]").
toVector(stringLeaf);
490 .Case<BundleType, OpenBundleType>([&](
auto bundleType) {
491 auto fieldName = bundleType.getElementName(subOp.getIndex());
492 stringLeaf.append({
".", fieldName});
496 if (!refSendPath.empty())
498 ref = FlatSymbolRefAttr::get(
499 getOrCreatePath(builder.getArrayAttr(refSendPath), builder)
506 ImplicitLocOpBuilder &builder,
507 FlatSymbolRefAttr &ref, StringAttr &xmrAttr) {
508 auto remoteOpPath = getRemoteRefSend(refVal);
512 SmallString<128> xmrString;
513 if (failed(resolveReferencePath(refVal, builder, ref, xmrString)))
516 xmrString.empty() ? StringAttr{} : builder.getStringAttr(xmrString);
523 return TypeSwitch<Operation *, LogicalResult>(op)
524 .Case<RefForceOp, RefForceInitialOp, RefReleaseOp, RefReleaseInitialOp>(
527 auto destType = op.getDest().getType();
528 if (isZeroWidth(destType.getType())) {
533 ImplicitLocOpBuilder builder(op.getLoc(), op);
534 FlatSymbolRefAttr ref;
536 if (failed(resolveReference(op.getDest(), builder, ref, str)))
540 moduleStates.find(op->template getParentOfType<FModuleOp>())
542 .getOrCreateXMRRefOp(destType, ref, str, builder);
543 op.getDestMutable().assign(xmr);
546 .Default([](
auto *op) {
547 return op->emitError(
"unexpected operation kind");
554 if (resWidth.has_value() && *resWidth == 0) {
556 ImplicitLocOpBuilder builder(resolve.getLoc(), resolve);
557 auto zeroUintType = UIntType::get(builder.getContext(), 0);
558 auto zeroC = builder.createOrFold<BitCastOp>(
559 resolve.getType(), builder.create<ConstantOp>(
561 resolve.getResult().replaceAllUsesWith(zeroC);
565 FlatSymbolRefAttr ref;
567 ImplicitLocOpBuilder builder(resolve.getLoc(), resolve);
568 if (failed(resolveReference(resolve.getRef(), builder, ref, str)))
571 Value result = builder.create<XMRDerefOp>(resolve.getType(), ref, str);
572 resolve.getResult().replaceAllUsesWith(result);
577 if (refPortsToRemoveMap[op].size() < numPorts)
578 refPortsToRemoveMap[op].resize(numPorts);
579 refPortsToRemoveMap[op].set(index);
585 Operation *mod = inst.getReferencedModule(instanceGraph);
586 if (
auto extRefMod = dyn_cast<FExtModuleOp>(mod)) {
590 auto internalPaths = extRefMod.getInternalPaths();
591 auto numPorts = inst.getNumResults();
592 SmallString<128> circuitRefPrefix;
595 auto getPath = [&](
size_t portNo) {
599 cast<InternalPathAttr>(internalPaths->getValue()[portNo])
605 if (circuitRefPrefix.empty())
606 getRefABIPrefix(extRefMod, circuitRefPrefix);
608 return getRefABIMacroForPort(extRefMod, portNo, circuitRefPrefix,
true);
611 for (
const auto &res : llvm::enumerate(inst.getResults())) {
612 if (!isa<RefType>(inst.getResult(res.index()).getType()))
616 auto ind = addReachingSendsEntry(res.value(), inRef);
618 xmrPathSuffix[ind] = getPath(res.index());
620 setPortToRemove(inst, res.index(), numPorts);
621 setPortToRemove(extRefMod, res.index(), numPorts);
625 auto refMod = dyn_cast<FModuleOp>(mod);
626 bool multiplyInstantiated = !visitedModules.insert(refMod).second;
627 for (
size_t portNum = 0, numPorts = inst.getNumResults();
628 portNum < numPorts; ++portNum) {
629 auto instanceResult = inst.getResult(portNum);
630 if (!isa<RefType>(instanceResult.getType()))
633 return inst.emitOpError(
"cannot lower ext modules with RefType ports");
635 setPortToRemove(inst, portNum, numPorts);
637 if (instanceResult.use_empty() ||
638 isZeroWidth(type_cast<RefType>(instanceResult.getType()).getType()))
640 auto refModuleArg = refMod.getArgument(portNum);
641 if (inst.getPortDirection(portNum) == Direction::Out) {
645 auto remoteOpPath = getRemoteRefSend(refModuleArg);
657 if (multiplyInstantiated)
658 return refMod.emitOpError(
659 "multiply instantiated module with input RefType port '")
660 << refMod.getPortName(portNum) <<
"'";
661 dataFlowClasses->unionSets(
662 dataFlowClasses->getOrInsertLeaderValue(refModuleArg),
663 dataFlowClasses->getOrInsertLeaderValue(instanceResult));
670 auto *body = getOperation().getBodyBlock();
673 SmallString<128> circuitRefPrefix;
674 SmallVector<std::tuple<StringAttr, StringAttr, ArrayAttr>> ports;
676 ImplicitLocOpBuilder::atBlockBegin(module.getLoc(), body);
677 for (
size_t portIndex = 0, numPorts = module.getNumPorts();
678 portIndex != numPorts; ++portIndex) {
679 auto refType = type_dyn_cast<RefType>(module.getPortType(portIndex));
680 if (!refType || isZeroWidth(refType.getType()) ||
681 module.getPortDirection(portIndex) != Direction::Out)
684 cast<mlir::TypedValue<RefType>>(
module.getArgument(portIndex));
685 mlir::FlatSymbolRefAttr ref;
686 SmallString<128> stringLeaf;
687 if (failed(resolveReferencePath(portValue, declBuilder, ref, stringLeaf)))
690 SmallString<128> formatString;
692 formatString +=
"{{0}}";
693 formatString += stringLeaf;
697 if (circuitRefPrefix.empty())
698 getRefABIPrefix(module, circuitRefPrefix);
700 getRefABIMacroForPort(module, portIndex, circuitRefPrefix);
701 declBuilder.create<sv::MacroDeclOp>(macroName, ArrayAttr(), StringAttr());
702 ports.emplace_back(macroName, declBuilder.getStringAttr(formatString),
703 ref ? declBuilder.getArrayAttr({ref}) : ArrayAttr{});
712 auto fileBuilder = ImplicitLocOpBuilder(module.getLoc(), module);
713 fileBuilder.create<emit::FileOp>(circuitRefPrefix +
".sv", [&] {
714 for (
auto [macroName, formatString, symbols] : ports) {
715 fileBuilder.create<sv::MacroDefOp>(FlatSymbolRefAttr::get(macroName),
716 formatString, symbols);
725 return moduleNamespaces.try_emplace(module, module).first->second;
729 if (
auto arg = dyn_cast<BlockArgument>(val))
730 return ::getInnerRefTo(
731 cast<FModuleLike>(arg.getParentBlock()->getParentOp()),
734 return getModuleNamespace(mod);
740 return ::getInnerRefTo(op,
742 return getModuleNamespace(mod);
749 bool errorIfNotFound =
true) {
750 auto iter = dataflowAt.find(dataFlowClasses->getOrInsertLeaderValue(val));
751 if (iter != dataflowAt.end())
752 return iter->getSecond();
753 if (!errorIfNotFound)
757 if (BlockArgument arg = dyn_cast<BlockArgument>(val))
758 arg.getOwner()->getParentOp()->emitError(
759 "reference dataflow cannot be traced back to the remote read op "
761 << dyn_cast<FModuleOp>(arg.getOwner()->getParentOp())
762 .getPortName(arg.getArgNumber())
765 val.getDefiningOp()->emitOpError(
766 "reference dataflow cannot be traced back to the remote read op");
773 std::optional<size_t> continueFrom = std::nullopt) {
774 auto leader = dataFlowClasses->getOrInsertLeaderValue(atRefVal);
775 auto indx = refSendPathList.size();
776 dataflowAt[leader] = indx;
777 refSendPathList.push_back({info, continueFrom});
785 for (Operation *op : llvm::reverse(opsToRemove))
787 for (
auto iter : refPortsToRemoveMap)
788 if (
auto mod = dyn_cast<FModuleOp>(iter.getFirst()))
789 mod.erasePorts(iter.getSecond());
790 else if (
auto mod = dyn_cast<FExtModuleOp>(iter.getFirst()))
791 mod.erasePorts(iter.getSecond());
792 else if (
auto inst = dyn_cast<InstanceOp>(iter.getFirst())) {
793 ImplicitLocOpBuilder b(inst.getLoc(), inst);
794 inst.erasePorts(b, iter.getSecond());
796 }
else if (
auto mem = dyn_cast<MemOp>(iter.getFirst())) {
798 ImplicitLocOpBuilder builder(mem.getLoc(), mem);
799 SmallVector<Attribute, 4> resultNames;
800 SmallVector<Type, 4> resultTypes;
801 SmallVector<Attribute, 4> portAnnotations;
802 SmallVector<Value, 4> oldResults;
803 for (
const auto &res : llvm::enumerate(mem.getResults())) {
804 if (isa<RefType>(mem.getResult(res.index()).getType()))
806 resultNames.push_back(mem.getPortName(res.index()));
807 resultTypes.push_back(res.value().getType());
808 portAnnotations.push_back(mem.getPortAnnotation(res.index()));
809 oldResults.push_back(res.value());
811 auto newMem = builder.create<MemOp>(
812 resultTypes, mem.getReadLatency(), mem.getWriteLatency(),
813 mem.getDepth(), RUWAttr::Undefined,
814 builder.getArrayAttr(resultNames), mem.getNameAttr(),
815 mem.getNameKind(), mem.getAnnotations(),
816 builder.getArrayAttr(portAnnotations), mem.getInnerSymAttr(),
817 mem.getInitAttr(), mem.getPrefixAttr());
818 for (
const auto &res : llvm::enumerate(oldResults))
819 res.value().replaceAllUsesWith(newMem.getResult(res.index()));
823 refPortsToRemoveMap.clear();
825 refSendPathList.clear();
826 moduleStates.clear();
834 ImplicitLocOpBuilder &builder) {
835 assert(pathArray && !pathArray.empty());
837 auto pathIter = pathCache.find(pathArray);
838 if (pathIter != pathCache.end())
839 return pathIter->second;
842 OpBuilder::InsertionGuard guard(builder);
846 if (pathInsertPoint.isSet())
847 builder.restoreInsertionPoint(pathInsertPoint);
849 builder.setInsertionPointToStart(getOperation().
getBodyBlock());
852 hw::HierPathOp path =
855 builder.create<hw::HierPathOp>(
856 circuitNamespace->newName(
"xmrPath"), pathArray)})
858 path.setVisibility(SymbolTable::Visibility::Private);
862 pathInsertPoint = builder.saveInsertionPoint();
905 OpBuilder::InsertPoint pathInsertPoint = {};
912 return std::make_unique<LowerXMRPass>();
assert(baseType &&"element must be base type")
static std::vector< mlir::Value > toVector(mlir::ValueRange range)
static Block * getBodyBlock(FModuleLike mod)
LogicalResult resolveReference(mlir::TypedValue< RefType > refVal, ImplicitLocOpBuilder &builder, FlatSymbolRefAttr &ref, StringAttr &xmrAttr)
DenseMap< Operation *, hw::InnerSymbolNamespace > moduleNamespaces
Cached module namespaces.
llvm::EquivalenceClasses< Value > * dataFlowClasses
DenseMap< size_t, SmallString< 128 > > xmrPathSuffix
Record the internal path to an external module or a memory.
InnerRefAttr getInnerRefTo(Value val)
size_t addReachingSendsEntry(Value atRefVal, XMRNode::SymOrIndexOp info, std::optional< size_t > continueFrom=std::nullopt)
DenseMap< FModuleOp, ModuleState > moduleStates
Per-module helpers for creating operations within modules.
hw::HierPathOp getOrCreatePath(ArrayAttr pathArray, ImplicitLocOpBuilder &builder)
Return a HierPathOp for the provided pathArray.
LogicalResult resolveReferencePath(mlir::TypedValue< RefType > refVal, ImplicitLocOpBuilder builder, mlir::FlatSymbolRefAttr &ref, SmallString< 128 > &stringLeaf)
DenseMap< Value, size_t > dataflowAt
Map of a reference value to an entry into refSendPathList.
void setPortToRemove(Operation *op, size_t index, size_t numPorts)
hw::InnerSymbolNamespace & getModuleNamespace(FModuleLike module)
Get the cached namespace for a module.
void markForRemoval(Operation *op)
LogicalResult handlePublicModuleRefPorts(FModuleOp module)
void getRefABIPrefix(FModuleLike mod, SmallVectorImpl< char > &prefix)
Generate the ABI ref_<module> prefix string into prefix.
void runOnOperation() override
DenseMap< Attribute, hw::HierPathOp > pathCache
A cache of already created HierPathOps.
LogicalResult handleRefResolve(RefResolveOp resolve)
DenseMap< Operation *, llvm::BitVector > refPortsToRemoveMap
SmallVector< XMRNode > refSendPathList
refSendPathList is used to construct a path to the RefSendOp.
LogicalResult handleInstanceOp(InstanceOp inst, InstanceGraph &instanceGraph)
LogicalResult handleForceReleaseOp(Operation *op)
std::optional< size_t > getRemoteRefSend(Value val, bool errorIfNotFound=true)
DenseSet< Operation * > visitedModules
InnerRefAttr getInnerRefTo(Operation *op)
OpBuilder::InsertPoint pathInsertPoint
The insertion point where the pass inserts HierPathOps.
StringAttr getRefABIMacroForPort(FModuleLike mod, size_t portIndex, const Twine &prefix, bool backTick=false)
Get full macro name as StringAttr for the specified ref port.
CircuitNamespace * circuitNamespace
bool isZeroWidth(FIRRTLBaseType t)
SmallVector< Operation * > opsToRemove
RefResolve, RefSend, and Connects involving them that will be removed.
void clear()
Empty the namespace.
int32_t getBitWidthOrSentinel()
If this is an IntType, AnalogType, or sugar type for a single bit (Clock, Reset, etc) then return the...
This graph tracks modules and where they are instantiated.
FieldRef getFieldRefFromValue(Value value, bool lookThroughCasts=false)
Get the FieldRef from a value.
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.
llvm::raw_ostream & operator<<(llvm::raw_ostream &os, const InstanceInfo::LatticeValue &value)
std::pair< std::string, bool > getFieldName(const FieldRef &fieldRef, bool nameSafe=false)
Get a string identifier representing the FieldRef.
std::unique_ptr< mlir::Pass > createLowerXMRPass()
std::optional< int64_t > getBitWidth(FIRRTLBaseType type, bool ignoreFlip=false)
IntegerAttr getIntZerosAttr(Type type)
Utility for generating a constant zero attribute.
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
The namespace of a CircuitOp, generally inhabited by modules.