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, ValueComparator> 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;
303 for (
auto node : llvm::post_order(&instanceGraph)) {
304 auto module = dyn_cast<FModuleOp>(*node->getModule());
307 LLVM_DEBUG(llvm::dbgs()
308 <<
"Traversing module:" << module.getModuleNameAttr() <<
"\n");
312 if (module.isPublic())
313 publicModules.push_back(module);
315 auto result =
module.walk([&](Operation *op) {
316 if (transferFunc(op).failed())
317 return WalkResult::interrupt();
318 return WalkResult::advance();
321 if (result.wasInterrupted())
322 return signalPassFailure();
325 module.setLayersAttr(ArrayAttr::get(module.getContext(), {}));
333 while (!indexingOps.empty()) {
335 decltype(indexingOps) worklist;
336 worklist.swap(indexingOps);
338 for (
auto op : worklist) {
343 indexingOps.push_back(op);
349 if (worklist.size() == indexingOps.size()) {
350 auto op = worklist.front();
353 "indexing through probe of unknown origin (input probe?)")
354 .attachNote(op.getInput().getLoc())
355 .append(
"indexing through this reference");
356 return signalPassFailure();
361 size_t numPorts =
module.getNumPorts();
362 for (
size_t portNum = 0; portNum < numPorts; ++portNum)
363 if (isa<RefType>(module.getPortType(portNum))) {
377 llvm::dbgs() <<
"\n dataflow at leader::" << I->getData() <<
"\n =>";
382 llvm::dbgs() <<
"\n " << init;
384 llvm::dbgs() <<
"\n Done\n";
387 for (
auto refResolve : resolveOps)
389 return signalPassFailure();
390 for (
auto *op : forceAndReleaseOps)
392 return signalPassFailure();
393 for (
auto module : publicModules) {
395 return signalPassFailure();
415 auto modName = mod.getModuleName();
416 if (
auto ext = dyn_cast<FExtModuleOp>(*mod)) {
418 if (
auto defname = ext.getDefname(); defname && !defname->empty())
421 (Twine(
"ref_") + modName).
toVector(prefix);
427 const Twine &prefix,
bool backTick =
false) {
428 return StringAttr::get(&getContext(), Twine(backTick ?
"`" :
"") + prefix +
429 "_" + mod.getPortName(portIndex));
433 ImplicitLocOpBuilder builder,
434 mlir::FlatSymbolRefAttr &ref,
435 SmallString<128> &stringLeaf) {
436 assert(stringLeaf.empty());
438 auto remoteOpPath = getRemoteRefSend(refVal);
441 SmallVector<Attribute> refSendPath;
442 SmallVector<RefSubOp> indexing;
444 while (remoteOpPath) {
445 lastIndex = *remoteOpPath;
446 auto entr = refSendPathList[*remoteOpPath];
448 TypeSwitch<XMRNode::SymOrIndexOp>(entr.info)
449 .Case<Attribute>([&](
auto attr) {
453 refSendPath.push_back(attr);
456 [&](
auto *op) { indexing.push_back(cast<RefSubOp>(op)); });
457 remoteOpPath = entr.next;
459 auto iter = xmrPathSuffix.find(lastIndex);
463 if (iter != xmrPathSuffix.end()) {
464 if (!refSendPath.empty())
465 stringLeaf.append(
".");
466 stringLeaf.append(iter->getSecond());
469 assert(!(refSendPath.empty() && stringLeaf.empty()) &&
470 "nothing to index through");
483 for (
auto subOp : llvm::reverse(indexing)) {
484 TypeSwitch<FIRRTLBaseType>(subOp.getInput().getType().getType())
485 .Case<FVectorType, OpenVectorType>([&](
auto vecType) {
486 (Twine(
"[") + Twine(subOp.getIndex()) +
"]").
toVector(stringLeaf);
488 .Case<BundleType, OpenBundleType>([&](
auto bundleType) {
489 auto fieldName = bundleType.getElementName(subOp.getIndex());
490 stringLeaf.append({
".", fieldName});
494 if (!refSendPath.empty())
496 ref = FlatSymbolRefAttr::get(
497 getOrCreatePath(builder.getArrayAttr(refSendPath), builder)
504 ImplicitLocOpBuilder &builder,
505 FlatSymbolRefAttr &ref, StringAttr &xmrAttr) {
506 auto remoteOpPath = getRemoteRefSend(refVal);
510 SmallString<128> xmrString;
511 if (failed(resolveReferencePath(refVal, builder, ref, xmrString)))
514 xmrString.empty() ? StringAttr{} : builder.getStringAttr(xmrString);
521 return TypeSwitch<Operation *, LogicalResult>(op)
522 .Case<RefForceOp, RefForceInitialOp, RefReleaseOp, RefReleaseInitialOp>(
525 auto destType = op.getDest().getType();
526 if (isZeroWidth(destType.getType())) {
531 ImplicitLocOpBuilder builder(op.getLoc(), op);
532 FlatSymbolRefAttr ref;
534 if (failed(resolveReference(op.getDest(), builder, ref, str)))
538 moduleStates.find(op->template getParentOfType<FModuleOp>())
540 .getOrCreateXMRRefOp(destType, ref, str, builder);
541 op.getDestMutable().assign(xmr);
544 .Default([](
auto *op) {
545 return op->emitError(
"unexpected operation kind");
552 if (resWidth.has_value() && *resWidth == 0) {
554 ImplicitLocOpBuilder builder(resolve.getLoc(), resolve);
555 auto zeroUintType = UIntType::get(builder.getContext(), 0);
556 auto zeroC = builder.createOrFold<BitCastOp>(
557 resolve.getType(), builder.create<ConstantOp>(
559 resolve.getResult().replaceAllUsesWith(zeroC);
563 FlatSymbolRefAttr ref;
565 ImplicitLocOpBuilder builder(resolve.getLoc(), resolve);
566 if (failed(resolveReference(resolve.getRef(), builder, ref, str)))
569 Value result = builder.create<XMRDerefOp>(resolve.getType(), ref, str);
570 resolve.getResult().replaceAllUsesWith(result);
575 if (refPortsToRemoveMap[op].size() < numPorts)
576 refPortsToRemoveMap[op].resize(numPorts);
577 refPortsToRemoveMap[op].set(index);
583 Operation *mod = inst.getReferencedModule(instanceGraph);
584 if (
auto extRefMod = dyn_cast<FExtModuleOp>(mod)) {
588 auto internalPaths = extRefMod.getInternalPaths();
589 auto numPorts = inst.getNumResults();
590 SmallString<128> circuitRefPrefix;
593 auto getPath = [&](
size_t portNo) {
597 cast<InternalPathAttr>(internalPaths->getValue()[portNo])
603 if (circuitRefPrefix.empty())
604 getRefABIPrefix(extRefMod, circuitRefPrefix);
606 return getRefABIMacroForPort(extRefMod, portNo, circuitRefPrefix,
true);
609 for (
const auto &res : llvm::enumerate(inst.getResults())) {
610 if (!isa<RefType>(inst.getResult(res.index()).getType()))
614 auto ind = addReachingSendsEntry(res.value(), inRef);
616 xmrPathSuffix[ind] = getPath(res.index());
618 setPortToRemove(inst, res.index(), numPorts);
619 setPortToRemove(extRefMod, res.index(), numPorts);
623 auto refMod = dyn_cast<FModuleOp>(mod);
624 bool multiplyInstantiated = !visitedModules.insert(refMod).second;
625 for (
size_t portNum = 0, numPorts = inst.getNumResults();
626 portNum < numPorts; ++portNum) {
627 auto instanceResult = inst.getResult(portNum);
628 if (!isa<RefType>(instanceResult.getType()))
631 return inst.emitOpError(
"cannot lower ext modules with RefType ports");
633 setPortToRemove(inst, portNum, numPorts);
635 if (instanceResult.use_empty() ||
636 isZeroWidth(type_cast<RefType>(instanceResult.getType()).getType()))
638 auto refModuleArg = refMod.getArgument(portNum);
639 if (inst.getPortDirection(portNum) == Direction::Out) {
643 auto remoteOpPath = getRemoteRefSend(refModuleArg);
655 if (multiplyInstantiated)
656 return refMod.emitOpError(
657 "multiply instantiated module with input RefType port '")
658 << refMod.getPortName(portNum) <<
"'";
659 dataFlowClasses->unionSets(
660 dataFlowClasses->getOrInsertLeaderValue(refModuleArg),
661 dataFlowClasses->getOrInsertLeaderValue(instanceResult));
668 auto *body = getOperation().getBodyBlock();
671 SmallString<128> circuitRefPrefix;
672 SmallVector<std::tuple<StringAttr, StringAttr, ArrayAttr>> ports;
674 ImplicitLocOpBuilder::atBlockBegin(module.getLoc(), body);
675 for (
size_t portIndex = 0, numPorts = module.getNumPorts();
676 portIndex != numPorts; ++portIndex) {
677 auto refType = type_dyn_cast<RefType>(module.getPortType(portIndex));
678 if (!refType || isZeroWidth(refType.getType()) ||
679 module.getPortDirection(portIndex) != Direction::Out)
682 cast<mlir::TypedValue<RefType>>(
module.getArgument(portIndex));
683 mlir::FlatSymbolRefAttr ref;
684 SmallString<128> stringLeaf;
685 if (failed(resolveReferencePath(portValue, declBuilder, ref, stringLeaf)))
688 SmallString<128> formatString;
690 formatString +=
"{{0}}";
691 formatString += stringLeaf;
695 if (circuitRefPrefix.empty())
696 getRefABIPrefix(module, circuitRefPrefix);
698 getRefABIMacroForPort(module, portIndex, circuitRefPrefix);
699 declBuilder.create<sv::MacroDeclOp>(macroName, ArrayAttr(), StringAttr());
700 ports.emplace_back(macroName, declBuilder.getStringAttr(formatString),
701 ref ? declBuilder.getArrayAttr({ref}) : ArrayAttr{});
710 auto fileBuilder = ImplicitLocOpBuilder(module.getLoc(), module);
711 fileBuilder.create<emit::FileOp>(circuitRefPrefix +
".sv", [&] {
712 for (
auto [macroName, formatString, symbols] : ports) {
713 fileBuilder.create<sv::MacroDefOp>(FlatSymbolRefAttr::get(macroName),
714 formatString, symbols);
723 return moduleNamespaces.try_emplace(module, module).first->second;
727 if (
auto arg = dyn_cast<BlockArgument>(val))
728 return ::getInnerRefTo(
729 cast<FModuleLike>(arg.getParentBlock()->getParentOp()),
732 return getModuleNamespace(mod);
738 return ::getInnerRefTo(op,
740 return getModuleNamespace(mod);
747 bool errorIfNotFound =
true) {
748 auto iter = dataflowAt.find(dataFlowClasses->getOrInsertLeaderValue(val));
749 if (iter != dataflowAt.end())
750 return iter->getSecond();
751 if (!errorIfNotFound)
755 if (BlockArgument arg = dyn_cast<BlockArgument>(val))
756 arg.getOwner()->getParentOp()->emitError(
757 "reference dataflow cannot be traced back to the remote read op "
759 << dyn_cast<FModuleOp>(arg.getOwner()->getParentOp())
760 .getPortName(arg.getArgNumber())
763 val.getDefiningOp()->emitOpError(
764 "reference dataflow cannot be traced back to the remote read op");
771 std::optional<size_t> continueFrom = std::nullopt) {
772 auto leader = dataFlowClasses->getOrInsertLeaderValue(atRefVal);
773 auto indx = refSendPathList.size();
774 dataflowAt[leader] = indx;
775 refSendPathList.push_back({info, continueFrom});
783 for (Operation *op : llvm::reverse(opsToRemove))
785 for (
auto iter : refPortsToRemoveMap)
786 if (
auto mod = dyn_cast<FModuleOp>(iter.getFirst()))
787 mod.erasePorts(iter.getSecond());
788 else if (
auto mod = dyn_cast<FExtModuleOp>(iter.getFirst()))
789 mod.erasePorts(iter.getSecond());
790 else if (
auto inst = dyn_cast<InstanceOp>(iter.getFirst())) {
791 ImplicitLocOpBuilder b(inst.getLoc(), inst);
792 inst.erasePorts(b, iter.getSecond());
794 }
else if (
auto mem = dyn_cast<MemOp>(iter.getFirst())) {
796 ImplicitLocOpBuilder builder(mem.getLoc(), mem);
797 SmallVector<Attribute, 4> resultNames;
798 SmallVector<Type, 4> resultTypes;
799 SmallVector<Attribute, 4> portAnnotations;
800 SmallVector<Value, 4> oldResults;
801 for (
const auto &res : llvm::enumerate(mem.getResults())) {
802 if (isa<RefType>(mem.getResult(res.index()).getType()))
804 resultNames.push_back(mem.getPortName(res.index()));
805 resultTypes.push_back(res.value().getType());
806 portAnnotations.push_back(mem.getPortAnnotation(res.index()));
807 oldResults.push_back(res.value());
809 auto newMem = builder.create<MemOp>(
810 resultTypes, mem.getReadLatency(), mem.getWriteLatency(),
811 mem.getDepth(), RUWAttr::Undefined,
812 builder.getArrayAttr(resultNames), mem.getNameAttr(),
813 mem.getNameKind(), mem.getAnnotations(),
814 builder.getArrayAttr(portAnnotations), mem.getInnerSymAttr(),
815 mem.getInitAttr(), mem.getPrefixAttr());
816 for (
const auto &res : llvm::enumerate(oldResults))
817 res.value().replaceAllUsesWith(newMem.getResult(res.index()));
821 refPortsToRemoveMap.clear();
823 refSendPathList.clear();
824 moduleStates.clear();
832 ImplicitLocOpBuilder &builder) {
833 assert(pathArray && !pathArray.empty());
835 auto pathIter = pathCache.find(pathArray);
836 if (pathIter != pathCache.end())
837 return pathIter->second;
840 OpBuilder::InsertionGuard guard(builder);
844 if (pathInsertPoint.isSet())
845 builder.restoreInsertionPoint(pathInsertPoint);
847 builder.setInsertionPointToStart(getOperation().
getBodyBlock());
850 hw::HierPathOp path =
853 builder.create<hw::HierPathOp>(
854 circuitNamespace->newName(
"xmrPath"), pathArray)})
856 path.setVisibility(SymbolTable::Visibility::Private);
860 pathInsertPoint = builder.saveInsertionPoint();
890 return lhs.getImpl() < rhs.getImpl();
911 OpBuilder::InsertPoint pathInsertPoint = {};
918 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.
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.
llvm::EquivalenceClasses< Value, ValueComparator > * dataFlowClasses
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.
llvm::EquivalenceClasses wants comparable elements.
bool operator()(const Value &lhs, const Value &rhs) const
The namespace of a CircuitOp, generally inhabited by modules.