CIRCT 21.0.0git
Loading...
Searching...
No Matches
LowerXMR.cpp
Go to the documentation of this file.
1//===- LowerXMR.cpp - FIRRTL Lower to XMR -----------------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements FIRRTL XMR Lowering.
10//
11//===----------------------------------------------------------------------===//
12
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"
28
29#define DEBUG_TYPE "firrtl-lower-xmr"
30
31namespace circt {
32namespace firrtl {
33#define GEN_PASS_DEF_LOWERXMR
34#include "circt/Dialect/FIRRTL/Passes.h.inc"
35} // namespace firrtl
36} // namespace circt
37
38using namespace circt;
39using namespace firrtl;
40using hw::InnerRefAttr;
41
42/// The LowerXMRPass will replace every RefResolveOp with an XMR encoded within
43/// a verbatim expr op. This also removes every RefType port from the modules
44/// and corresponding instances. This is a dataflow analysis over a very
45/// constrained RefType. Domain of the dataflow analysis is the set of all
46/// RefSendOps. It computes an interprocedural reaching definitions (of
47/// RefSendOp) analysis. Essentially every RefType value must be mapped to one
48/// and only one RefSendOp. The analysis propagates the dataflow from every
49/// RefSendOp to every value of RefType across modules. The RefResolveOp is the
50/// final leaf into which the dataflow must reach.
51///
52/// Since there can be multiple readers, multiple RefResolveOps can be reachable
53/// from a single RefSendOp. To support multiply instantiated modules and
54/// multiple readers, it is essential to track the path to the RefSendOp, other
55/// than just the RefSendOp. For example, if there exists a wire `xmr_wire` in
56/// module `Foo`, the algorithm needs to support generating Top.Bar.Foo.xmr_wire
57/// and Top.Foo.xmr_wire and Top.Zoo.Foo.xmr_wire for different instance paths
58/// that exist in the circuit.
59
60namespace {
61struct XMRNode {
62 using NextNodeOnPath = std::optional<size_t>;
63 using SymOrIndexOp = PointerUnion<Attribute, Operation *>;
64 SymOrIndexOp info;
65 NextNodeOnPath next;
66};
67[[maybe_unused]] llvm::raw_ostream &operator<<(llvm::raw_ostream &os,
68 const XMRNode &node) {
69 os << "node(";
70 if (auto attr = dyn_cast<Attribute>(node.info))
71 os << "path=" << attr;
72 else {
73 auto subOp = cast<RefSubOp>(cast<Operation *>(node.info));
74 os << "index=" << subOp.getIndex() << " (-> " << subOp.getType() << ")";
75 }
76 os << ", next=" << node.next << ")";
77 return os;
78}
79
80/// Track information about operations being created in a module. This is used
81/// to generate more compact code and reuse operations where possible.
82class ModuleState {
83
84public:
85 ModuleState(FModuleOp &moduleOp) : body(moduleOp.getBodyBlock()) {}
86
87 /// Return the existing XMRRefOp for this type, symbol, and suffix for this
88 /// module. Otherwise, create a new one. The first XMRRefOp will be created
89 /// at the beginning of the module. Subsequent XMRRefOps will be created
90 /// immediately following the first one.
91 Value getOrCreateXMRRefOp(Type type, FlatSymbolRefAttr symbol,
92 StringAttr suffix, ImplicitLocOpBuilder &builder) {
93 // Return the saved XMRRefOp.
94 auto it = xmrRefCache.find({type, symbol, suffix});
95 if (it != xmrRefCache.end())
96 return it->getSecond();
97
98 // Create a new XMRRefOp.
99 OpBuilder::InsertionGuard guard(builder);
100 if (xmrRefPoint.isSet())
101 builder.restoreInsertionPoint(xmrRefPoint);
102 else
103 builder.setInsertionPointToStart(body);
104
105 Value xmr = builder.create<XMRRefOp>(type, symbol, suffix);
106 xmrRefCache.insert({{type, symbol, suffix}, xmr});
107
108 xmrRefPoint = builder.saveInsertionPoint();
109 return xmr;
110 };
111
112private:
113 /// The module's body. This is used to set the insertion point for the first
114 /// created operation.
115 Block *body;
116
117 /// Map used to know if we created this XMRRefOp before.
118 DenseMap<std::tuple<Type, SymbolRefAttr, StringAttr>, Value> xmrRefCache;
119
120 /// The saved insertion point for XMRRefOps.
121 OpBuilder::InsertPoint xmrRefPoint;
122};
123} // end anonymous namespace
124
126
127 void runOnOperation() override {
128 // Populate a CircuitNamespace that can be used to generate unique
129 // circuit-level symbols.
130 CircuitNamespace ns(getOperation());
131 circuitNamespace = &ns;
132
133 llvm::EquivalenceClasses<Value, ValueComparator> eq;
134 dataFlowClasses = &eq;
135
136 InstanceGraph &instanceGraph = getAnalysis<InstanceGraph>();
137 SmallVector<RefResolveOp> resolveOps;
138 SmallVector<RefSubOp> indexingOps;
139 SmallVector<Operation *> forceAndReleaseOps;
140 // The dataflow function, that propagates the reachable RefSendOp across
141 // RefType Ops.
142 auto transferFunc = [&](Operation *op) -> LogicalResult {
143 return TypeSwitch<Operation *, LogicalResult>(op)
144 .Case<RefSendOp>([&](RefSendOp send) {
145 // Get a reference to the actual signal to which the XMR will be
146 // generated.
147 Value xmrDef = send.getBase();
148 if (isZeroWidth(send.getType().getType())) {
149 markForRemoval(send);
150 return success();
151 }
152
153 if (auto verbExpr = xmrDef.getDefiningOp<VerbatimExprOp>())
154 if (verbExpr.getSymbolsAttr().empty() && verbExpr->hasOneUse()) {
155 // This represents the internal path into a module. For
156 // generating the correct XMR, no node can be created in this
157 // module. Create a null InnerRef and ensure the hierarchical
158 // path ends at the parent that instantiates this module.
159 auto inRef = InnerRefAttr();
160 auto ind = addReachingSendsEntry(send.getResult(), inRef);
161 xmrPathSuffix[ind] = verbExpr.getText();
162 markForRemoval(verbExpr);
163 markForRemoval(send);
164 return success();
165 }
166 // Get an InnerRefAttr to the value being sent.
167
168 // Add a node, don't need to have symbol on defining operation,
169 // just a way to send out the value.
170 ImplicitLocOpBuilder b(xmrDef.getLoc(), &getContext());
171 b.setInsertionPointAfterValue(xmrDef);
172 SmallString<32> opName;
173 auto nameKind = NameKindEnum::DroppableName;
174
175 if (auto [name, rootKnown] = getFieldName(
176 getFieldRefFromValue(xmrDef, /*lookThroughCasts=*/true),
177 /*nameSafe=*/true);
178 rootKnown) {
179 opName = name + "_probe";
180 nameKind = NameKindEnum::InterestingName;
181 } else if (auto *xmrDefOp = xmrDef.getDefiningOp()) {
182 // Inspect "name" directly for ops that aren't named by above.
183 // (e.g., firrtl.constant)
184 if (auto name = xmrDefOp->getAttrOfType<StringAttr>("name")) {
185 (Twine(name.strref()) + "_probe").toVector(opName);
186 nameKind = NameKindEnum::InterestingName;
187 }
188 }
189 xmrDef = b.create<NodeOp>(xmrDef, opName, nameKind).getResult();
190
191 // Create a new entry for this RefSendOp. The path is currently
192 // local.
193 addReachingSendsEntry(send.getResult(), getInnerRefTo(xmrDef));
194 markForRemoval(send);
195 return success();
196 })
197 .Case<RWProbeOp>([&](RWProbeOp rwprobe) {
198 if (!isZeroWidth(rwprobe.getType().getType()))
199 addReachingSendsEntry(rwprobe.getResult(), rwprobe.getTarget());
200 markForRemoval(rwprobe);
201 return success();
202 })
203 .Case<MemOp>([&](MemOp mem) {
204 // MemOp can produce debug ports of RefType. Each debug port
205 // represents the RefType for the corresponding register of the
206 // memory. Since the memory is not yet generated the register name
207 // is assumed to be "Memory". Note that MemOp creates RefType
208 // without a RefSend.
209 for (const auto &res : llvm::enumerate(mem.getResults()))
210 if (isa<RefType>(mem.getResult(res.index()).getType())) {
211 auto inRef = getInnerRefTo(mem);
212 auto ind = addReachingSendsEntry(res.value(), inRef);
213 xmrPathSuffix[ind] = "Memory";
214 // Just node that all the debug ports of memory must be removed.
215 // So this does not record the port index.
216 refPortsToRemoveMap[mem].resize(1);
217 }
218 return success();
219 })
220 .Case<InstanceOp>(
221 [&](auto inst) { return handleInstanceOp(inst, instanceGraph); })
222 .Case<FConnectLike>([&](FConnectLike connect) {
223 // Ignore BaseType.
224 if (!isa<RefType>(connect.getSrc().getType()))
225 return success();
226 markForRemoval(connect);
227 if (isZeroWidth(
228 type_cast<RefType>(connect.getSrc().getType()).getType()))
229 return success();
230 // Merge the dataflow classes of destination into the source of the
231 // Connect. This handles two cases:
232 // 1. If the dataflow at the source is known, then the
233 // destination is also inferred. By merging the dataflow class of
234 // destination with source, every value reachable from the
235 // destination automatically infers a reaching RefSend.
236 // 2. If dataflow at source is unkown, then just record that both
237 // source and destination will have the same dataflow information.
238 // Later in the pass when the reaching RefSend is inferred at the
239 // leader of the dataflowClass, then we automatically infer the
240 // dataflow at this connect and every value reachable from the
241 // destination.
242 dataFlowClasses->unionSets(connect.getSrc(), connect.getDest());
243 return success();
244 })
245 .Case<RefSubOp>([&](RefSubOp op) -> LogicalResult {
246 markForRemoval(op);
247 if (isZeroWidth(op.getType().getType()))
248 return success();
249
250 // Enqueue for processing after visiting other operations.
251 indexingOps.push_back(op);
252 return success();
253 })
254 .Case<RefResolveOp>([&](RefResolveOp resolve) {
255 // Merge dataflow, under the same conditions as above for Connect.
256 // 1. If dataflow at the resolve.getRef is known, propagate that to
257 // the result. This is true for downward scoped XMRs, that is,
258 // RefSendOp must be visited before the corresponding RefResolveOp
259 // is visited.
260 // 2. Else, just record that both result and ref should have the
261 // same reaching RefSend. This condition is true for upward scoped
262 // XMRs. That is, RefResolveOp can be visited before the
263 // corresponding RefSendOp is recorded.
264
265 markForRemoval(resolve);
266 if (!isZeroWidth(resolve.getType()))
267 dataFlowClasses->unionSets(resolve.getRef(), resolve.getResult());
268 resolveOps.push_back(resolve);
269 return success();
270 })
271 .Case<RefCastOp>([&](RefCastOp op) {
272 markForRemoval(op);
273 if (!isZeroWidth(op.getType().getType()))
274 dataFlowClasses->unionSets(op.getInput(), op.getResult());
275 return success();
276 })
277 .Case<Forceable>([&](Forceable op) {
278 // Handle declarations containing refs as "data".
279 if (type_isa<RefType>(op.getDataRaw().getType())) {
280 markForRemoval(op);
281 return success();
282 }
283
284 // Otherwise, if forceable track the rwprobe result.
285 if (!op.isForceable() || op.getDataRef().use_empty() ||
286 isZeroWidth(op.getDataType()))
287 return success();
288
289 addReachingSendsEntry(op.getDataRef(), getInnerRefTo(op));
290 return success();
291 })
292 .Case<RefForceOp, RefForceInitialOp, RefReleaseOp,
293 RefReleaseInitialOp>([&](auto op) {
294 forceAndReleaseOps.push_back(op);
295 return success();
296 })
297 .Default([&](auto) { return success(); });
298 };
299
300 SmallVector<FModuleOp> publicModules;
301
302 // Traverse the modules in post order.
303
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());
308 if (!module)
309 continue;
310 LLVM_DEBUG(llvm::dbgs() << "Traversing module:"
311 << module.getModuleNameAttr() << "\n");
312
313 moduleStates.insert({module, ModuleState(module)});
314
315 if (module.isPublic())
316 publicModules.push_back(module);
317
318 auto result = module.walk([&](Operation *op) {
319 if (transferFunc(op).failed())
320 return WalkResult::interrupt();
321 return WalkResult::advance();
322 });
323
324 if (result.wasInterrupted())
325 return signalPassFailure();
326
327 // Clear any enabled layers.
328 module.setLayersAttr(ArrayAttr::get(module.getContext(), {}));
329
330 // Since we walk operations pre-order and not along dataflow edges,
331 // ref.sub may not be resolvable when we encounter them (they're not
332 // just unification). This can happen when refs go through an output
333 // port or input instance result and back into the design. Handle these
334 // by walking them, resolving what we can, until all are handled or
335 // nothing can be resolved.
336 while (!indexingOps.empty()) {
337 // Grab the set of unresolved ref.sub's.
338 decltype(indexingOps) worklist;
339 worklist.swap(indexingOps);
340
341 for (auto op : worklist) {
342 auto inputEntry =
343 getRemoteRefSend(op.getInput(), /*errorIfNotFound=*/false);
344 // If we can't resolve, add back and move on.
345 if (!inputEntry)
346 indexingOps.push_back(op);
347 else
348 addReachingSendsEntry(op.getResult(), op.getOperation(),
349 inputEntry);
350 }
351 // If nothing was resolved, give up.
352 if (worklist.size() == indexingOps.size()) {
353 auto op = worklist.front();
354 getRemoteRefSend(op.getInput());
355 op.emitError(
356 "indexing through probe of unknown origin (input probe?)")
357 .attachNote(op.getInput().getLoc())
358 .append("indexing through this reference");
359 return signalPassFailure();
360 }
361 }
362
363 // Record all the RefType ports to be removed later.
364 size_t numPorts = module.getNumPorts();
365 for (size_t portNum = 0; portNum < numPorts; ++portNum)
366 if (isa<RefType>(module.getPortType(portNum))) {
367 setPortToRemove(module, portNum, numPorts);
368 }
369 }
370 }
371
372 LLVM_DEBUG({
373 for (auto I = dataFlowClasses->begin(), E = dataFlowClasses->end();
374 I != E; ++I) { // Iterate over all of the equivalence sets.
375 if (!I->isLeader())
376 continue; // Ignore non-leader sets.
377 // Print members in this set.
378 llvm::interleave(llvm::make_range(dataFlowClasses->member_begin(I),
379 dataFlowClasses->member_end()),
380 llvm::dbgs(), "\n");
381 llvm::dbgs() << "\n dataflow at leader::" << I->getData() << "\n =>";
382 auto iter = dataflowAt.find(I->getData());
383 if (iter != dataflowAt.end()) {
384 for (auto init = refSendPathList[iter->getSecond()]; init.next;
385 init = refSendPathList[*init.next])
386 llvm::dbgs() << "\n " << init;
387 }
388 llvm::dbgs() << "\n Done\n"; // Finish set.
389 }
390 });
391 for (auto refResolve : resolveOps)
392 if (handleRefResolve(refResolve).failed())
393 return signalPassFailure();
394 for (auto *op : forceAndReleaseOps)
395 if (failed(handleForceReleaseOp(op)))
396 return signalPassFailure();
397 for (auto module : publicModules) {
398 if (failed(handlePublicModuleRefPorts(module)))
399 return signalPassFailure();
400 }
402
403 // Clean up
404 moduleNamespaces.clear();
405 visitedModules.clear();
406 dataflowAt.clear();
407 refSendPathList.clear();
408 dataFlowClasses = nullptr;
409 refPortsToRemoveMap.clear();
410 opsToRemove.clear();
411 xmrPathSuffix.clear();
412 circuitNamespace = nullptr;
414 pathInsertPoint = {};
415 }
416
417 /// Generate the ABI ref_<module> prefix string into `prefix`.
418 void getRefABIPrefix(FModuleLike mod, SmallVectorImpl<char> &prefix) {
419 auto modName = mod.getModuleName();
420 if (auto ext = dyn_cast<FExtModuleOp>(*mod)) {
421 // Use defName for module portion, if set.
422 if (auto defname = ext.getDefname(); defname && !defname->empty())
423 modName = *defname;
424 }
425 (Twine("ref_") + modName).toVector(prefix);
426 }
427
428 /// Get full macro name as StringAttr for the specified ref port.
429 /// Uses existing 'prefix', optionally preprends the backtick character.
430 StringAttr getRefABIMacroForPort(FModuleLike mod, size_t portIndex,
431 const Twine &prefix, bool backTick = false) {
432 return StringAttr::get(&getContext(), Twine(backTick ? "`" : "") + prefix +
433 "_" + mod.getPortName(portIndex));
434 }
435
436 LogicalResult resolveReferencePath(mlir::TypedValue<RefType> refVal,
437 ImplicitLocOpBuilder builder,
438 mlir::FlatSymbolRefAttr &ref,
439 SmallString<128> &stringLeaf) {
440 assert(stringLeaf.empty());
441
442 auto remoteOpPath = getRemoteRefSend(refVal);
443 if (!remoteOpPath)
444 return failure();
445 SmallVector<Attribute> refSendPath;
446 SmallVector<RefSubOp> indexing;
447 size_t lastIndex;
448 while (remoteOpPath) {
449 lastIndex = *remoteOpPath;
450 auto entr = refSendPathList[*remoteOpPath];
451 if (entr.info)
452 TypeSwitch<XMRNode::SymOrIndexOp>(entr.info)
453 .Case<Attribute>([&](auto attr) {
454 // If the path is a singular verbatim expression, the attribute of
455 // the send path list entry will be null.
456 if (attr)
457 refSendPath.push_back(attr);
458 })
459 .Case<Operation *>(
460 [&](auto *op) { indexing.push_back(cast<RefSubOp>(op)); });
461 remoteOpPath = entr.next;
462 }
463 auto iter = xmrPathSuffix.find(lastIndex);
464
465 // If this xmr has a suffix string (internal path into a module, that is not
466 // yet generated).
467 if (iter != xmrPathSuffix.end()) {
468 if (!refSendPath.empty())
469 stringLeaf.append(".");
470 stringLeaf.append(iter->getSecond());
471 }
472
473 assert(!(refSendPath.empty() && stringLeaf.empty()) &&
474 "nothing to index through");
475
476 // All indexing done as the ref is plumbed around indexes through
477 // the target/referent, not the current point of the path which
478 // describes how to access the referent we're indexing through.
479 // Above we gathered all indexing operations, so now append them
480 // to the path (after any relevant `xmrPathSuffix`) to reach
481 // the target element.
482 // Generating these strings here (especially if ref is sent
483 // out from a different design) is fragile but should get this
484 // working well enough while sorting out how to do this better.
485 // Some discussion of this can be found here:
486 // https://github.com/llvm/circt/pull/5551#discussion_r1258908834
487 for (auto subOp : llvm::reverse(indexing)) {
488 TypeSwitch<FIRRTLBaseType>(subOp.getInput().getType().getType())
489 .Case<FVectorType, OpenVectorType>([&](auto vecType) {
490 (Twine("[") + Twine(subOp.getIndex()) + "]").toVector(stringLeaf);
491 })
492 .Case<BundleType, OpenBundleType>([&](auto bundleType) {
493 auto fieldName = bundleType.getElementName(subOp.getIndex());
494 stringLeaf.append({".", fieldName});
495 });
496 }
497
498 if (!refSendPath.empty())
499 // Compute the HierPathOp that stores the path.
500 ref = FlatSymbolRefAttr::get(
501 getOrCreatePath(builder.getArrayAttr(refSendPath), builder)
502 .getSymNameAttr());
503
504 return success();
505 }
506
507 LogicalResult resolveReference(mlir::TypedValue<RefType> refVal,
508 ImplicitLocOpBuilder &builder,
509 FlatSymbolRefAttr &ref, StringAttr &xmrAttr) {
510 auto remoteOpPath = getRemoteRefSend(refVal);
511 if (!remoteOpPath)
512 return failure();
513
514 SmallString<128> xmrString;
515 if (failed(resolveReferencePath(refVal, builder, ref, xmrString)))
516 return failure();
517 xmrAttr =
518 xmrString.empty() ? StringAttr{} : builder.getStringAttr(xmrString);
519
520 return success();
521 }
522
523 // Replace the Force/Release's ref argument with a resolved XMRRef.
524 LogicalResult handleForceReleaseOp(Operation *op) {
525 return TypeSwitch<Operation *, LogicalResult>(op)
526 .Case<RefForceOp, RefForceInitialOp, RefReleaseOp, RefReleaseInitialOp>(
527 [&](auto op) {
528 // Drop if zero-width target.
529 auto destType = op.getDest().getType();
530 if (isZeroWidth(destType.getType())) {
531 op.erase();
532 return success();
533 }
534
535 ImplicitLocOpBuilder builder(op.getLoc(), op);
536 FlatSymbolRefAttr ref;
537 StringAttr str;
538 if (failed(resolveReference(op.getDest(), builder, ref, str)))
539 return failure();
540
541 Value xmr =
542 moduleStates.find(op->template getParentOfType<FModuleOp>())
543 ->getSecond()
544 .getOrCreateXMRRefOp(destType, ref, str, builder);
545 op.getDestMutable().assign(xmr);
546 return success();
547 })
548 .Default([](auto *op) {
549 return op->emitError("unexpected operation kind");
550 });
551 }
552
553 // Replace the RefResolveOp with verbatim op representing the XMR.
554 LogicalResult handleRefResolve(RefResolveOp resolve) {
555 auto resWidth = getBitWidth(resolve.getType());
556 if (resWidth.has_value() && *resWidth == 0) {
557 // Donot emit 0 width XMRs, replace it with constant 0.
558 ImplicitLocOpBuilder builder(resolve.getLoc(), resolve);
559 auto zeroUintType = UIntType::get(builder.getContext(), 0);
560 auto zeroC = builder.createOrFold<BitCastOp>(
561 resolve.getType(), builder.create<ConstantOp>(
562 zeroUintType, getIntZerosAttr(zeroUintType)));
563 resolve.getResult().replaceAllUsesWith(zeroC);
564 return success();
565 }
566
567 FlatSymbolRefAttr ref;
568 StringAttr str;
569 ImplicitLocOpBuilder builder(resolve.getLoc(), resolve);
570 if (failed(resolveReference(resolve.getRef(), builder, ref, str)))
571 return failure();
572
573 Value result = builder.create<XMRDerefOp>(resolve.getType(), ref, str);
574 resolve.getResult().replaceAllUsesWith(result);
575 return success();
576 }
577
578 void setPortToRemove(Operation *op, size_t index, size_t numPorts) {
579 if (refPortsToRemoveMap[op].size() < numPorts)
580 refPortsToRemoveMap[op].resize(numPorts);
581 refPortsToRemoveMap[op].set(index);
582 }
583
584 // Propagate the reachable RefSendOp across modules.
585 LogicalResult handleInstanceOp(InstanceOp inst,
586 InstanceGraph &instanceGraph) {
587 Operation *mod = inst.getReferencedModule(instanceGraph);
588 if (auto extRefMod = dyn_cast<FExtModuleOp>(mod)) {
589 // Extern modules can generate RefType ports, they have an attached
590 // attribute which specifies the internal path into the extern module.
591 // This string attribute will be used to generate the final xmr.
592 auto internalPaths = extRefMod.getInternalPaths();
593 auto numPorts = inst.getNumResults();
594 SmallString<128> circuitRefPrefix;
595
596 /// Get the resolution string for this ref-type port.
597 auto getPath = [&](size_t portNo) {
598 // If there's an internal path specified (with path), use that.
599 if (internalPaths)
600 if (auto path =
601 cast<InternalPathAttr>(internalPaths->getValue()[portNo])
602 .getPath())
603 return path;
604
605 // Otherwise, we're using the ref ABI. Generate the prefix string
606 // and return the macro for the specified port.
607 if (circuitRefPrefix.empty())
608 getRefABIPrefix(extRefMod, circuitRefPrefix);
609
610 return getRefABIMacroForPort(extRefMod, portNo, circuitRefPrefix, true);
611 };
612
613 for (const auto &res : llvm::enumerate(inst.getResults())) {
614 if (!isa<RefType>(inst.getResult(res.index()).getType()))
615 continue;
616
617 auto inRef = getInnerRefTo(inst);
618 auto ind = addReachingSendsEntry(res.value(), inRef);
619
620 xmrPathSuffix[ind] = getPath(res.index());
621 // The instance result and module port must be marked for removal.
622 setPortToRemove(inst, res.index(), numPorts);
623 setPortToRemove(extRefMod, res.index(), numPorts);
624 }
625 return success();
626 }
627 auto refMod = dyn_cast<FModuleOp>(mod);
628 bool multiplyInstantiated = !visitedModules.insert(refMod).second;
629 for (size_t portNum = 0, numPorts = inst.getNumResults();
630 portNum < numPorts; ++portNum) {
631 auto instanceResult = inst.getResult(portNum);
632 if (!isa<RefType>(instanceResult.getType()))
633 continue;
634 if (!refMod)
635 return inst.emitOpError("cannot lower ext modules with RefType ports");
636 // Reference ports must be removed.
637 setPortToRemove(inst, portNum, numPorts);
638 // Drop the dead-instance-ports.
639 if (instanceResult.use_empty() ||
640 isZeroWidth(type_cast<RefType>(instanceResult.getType()).getType()))
641 continue;
642 auto refModuleArg = refMod.getArgument(portNum);
643 if (inst.getPortDirection(portNum) == Direction::Out) {
644 // For output instance ports, the dataflow is into this module.
645 // Get the remote RefSendOp, that flows through the module ports.
646 // If dataflow at remote module argument does not exist, error out.
647 auto remoteOpPath = getRemoteRefSend(refModuleArg);
648 if (!remoteOpPath)
649 return failure();
650 // Get the path to reaching refSend at the referenced module argument.
651 // Now append this instance to the path to the reaching refSend.
652 addReachingSendsEntry(instanceResult, getInnerRefTo(inst),
653 remoteOpPath);
654 } else {
655 // For input instance ports, the dataflow is into the referenced module.
656 // Input RefType port implies, generating an upward scoped XMR.
657 // No need to add the instance context, since downward reference must be
658 // through single instantiated modules.
659 if (multiplyInstantiated)
660 return refMod.emitOpError(
661 "multiply instantiated module with input RefType port '")
662 << refMod.getPortName(portNum) << "'";
663 dataFlowClasses->unionSets(
664 dataFlowClasses->getOrInsertLeaderValue(refModuleArg),
665 dataFlowClasses->getOrInsertLeaderValue(instanceResult));
666 }
667 }
668 return success();
669 }
670
671 LogicalResult handlePublicModuleRefPorts(FModuleOp module) {
672 auto *body = getOperation().getBodyBlock();
673
674 // Find all the output reference ports.
675 SmallString<128> circuitRefPrefix;
676 SmallVector<std::tuple<StringAttr, StringAttr, ArrayAttr>> ports;
677 auto declBuilder =
678 ImplicitLocOpBuilder::atBlockBegin(module.getLoc(), body);
679 for (size_t portIndex = 0, numPorts = module.getNumPorts();
680 portIndex != numPorts; ++portIndex) {
681 auto refType = type_dyn_cast<RefType>(module.getPortType(portIndex));
682 if (!refType || isZeroWidth(refType.getType()) ||
683 module.getPortDirection(portIndex) != Direction::Out)
684 continue;
685 auto portValue =
686 cast<mlir::TypedValue<RefType>>(module.getArgument(portIndex));
687 mlir::FlatSymbolRefAttr ref;
688 SmallString<128> stringLeaf;
689 if (failed(resolveReferencePath(portValue, declBuilder, ref, stringLeaf)))
690 return failure();
691
692 SmallString<128> formatString;
693 if (ref)
694 formatString += "{{0}}";
695 formatString += stringLeaf;
696
697 // Insert a macro with the format:
698 // ref_<module-name>_<ref-name> <path>
699 if (circuitRefPrefix.empty())
700 getRefABIPrefix(module, circuitRefPrefix);
701 auto macroName =
702 getRefABIMacroForPort(module, portIndex, circuitRefPrefix);
703 declBuilder.create<sv::MacroDeclOp>(macroName, ArrayAttr(), StringAttr());
704 ports.emplace_back(macroName, declBuilder.getStringAttr(formatString),
705 ref ? declBuilder.getArrayAttr({ref}) : ArrayAttr{});
706 }
707
708 // Create a file only if the module has at least one ref port.
709 if (ports.empty())
710 return success();
711
712 // The macros will be exported to a `ref_<module-name>.sv` file.
713 // In the IR, the file is inserted before the module.
714 auto fileBuilder = ImplicitLocOpBuilder(module.getLoc(), module);
715 fileBuilder.create<emit::FileOp>(circuitRefPrefix + ".sv", [&] {
716 for (auto [macroName, formatString, symbols] : ports) {
717 fileBuilder.create<sv::MacroDefOp>(FlatSymbolRefAttr::get(macroName),
718 formatString, symbols);
719 }
720 });
721
722 return success();
723 }
724
725 /// Get the cached namespace for a module.
727 return moduleNamespaces.try_emplace(module, module).first->second;
728 }
729
730 InnerRefAttr getInnerRefTo(Value val) {
731 if (auto arg = dyn_cast<BlockArgument>(val))
732 return ::getInnerRefTo(
733 cast<FModuleLike>(arg.getParentBlock()->getParentOp()),
734 arg.getArgNumber(),
735 [&](FModuleLike mod) -> hw::InnerSymbolNamespace & {
736 return getModuleNamespace(mod);
737 });
738 return getInnerRefTo(val.getDefiningOp());
739 }
740
741 InnerRefAttr getInnerRefTo(Operation *op) {
742 return ::getInnerRefTo(op,
743 [&](FModuleLike mod) -> hw::InnerSymbolNamespace & {
744 return getModuleNamespace(mod);
745 });
746 }
747
748 void markForRemoval(Operation *op) { opsToRemove.push_back(op); }
749
750 std::optional<size_t> getRemoteRefSend(Value val,
751 bool errorIfNotFound = true) {
752 auto iter = dataflowAt.find(dataFlowClasses->getOrInsertLeaderValue(val));
753 if (iter != dataflowAt.end())
754 return iter->getSecond();
755 if (!errorIfNotFound)
756 return std::nullopt;
757 // The referenced module must have already been analyzed, error out if the
758 // dataflow at the child module is not resolved.
759 if (BlockArgument arg = dyn_cast<BlockArgument>(val))
760 arg.getOwner()->getParentOp()->emitError(
761 "reference dataflow cannot be traced back to the remote read op "
762 "for module port '")
763 << dyn_cast<FModuleOp>(arg.getOwner()->getParentOp())
764 .getPortName(arg.getArgNumber())
765 << "'";
766 else
767 val.getDefiningOp()->emitOpError(
768 "reference dataflow cannot be traced back to the remote read op");
769 signalPassFailure();
770 return std::nullopt;
771 }
772
773 size_t
774 addReachingSendsEntry(Value atRefVal, XMRNode::SymOrIndexOp info,
775 std::optional<size_t> continueFrom = std::nullopt) {
776 auto leader = dataFlowClasses->getOrInsertLeaderValue(atRefVal);
777 auto indx = refSendPathList.size();
778 dataflowAt[leader] = indx;
779 refSendPathList.push_back({info, continueFrom});
780 return indx;
781 }
782
784 // Now erase all the Ops and ports of RefType.
785 // This needs to be done as the last step to ensure uses are erased before
786 // the def is erased.
787 for (Operation *op : llvm::reverse(opsToRemove))
788 op->erase();
789 for (auto iter : refPortsToRemoveMap)
790 if (auto mod = dyn_cast<FModuleOp>(iter.getFirst()))
791 mod.erasePorts(iter.getSecond());
792 else if (auto mod = dyn_cast<FExtModuleOp>(iter.getFirst()))
793 mod.erasePorts(iter.getSecond());
794 else if (auto inst = dyn_cast<InstanceOp>(iter.getFirst())) {
795 ImplicitLocOpBuilder b(inst.getLoc(), inst);
796 inst.erasePorts(b, iter.getSecond());
797 inst.erase();
798 } else if (auto mem = dyn_cast<MemOp>(iter.getFirst())) {
799 // Remove all debug ports of the memory.
800 ImplicitLocOpBuilder builder(mem.getLoc(), mem);
801 SmallVector<Attribute, 4> resultNames;
802 SmallVector<Type, 4> resultTypes;
803 SmallVector<Attribute, 4> portAnnotations;
804 SmallVector<Value, 4> oldResults;
805 for (const auto &res : llvm::enumerate(mem.getResults())) {
806 if (isa<RefType>(mem.getResult(res.index()).getType()))
807 continue;
808 resultNames.push_back(mem.getPortName(res.index()));
809 resultTypes.push_back(res.value().getType());
810 portAnnotations.push_back(mem.getPortAnnotation(res.index()));
811 oldResults.push_back(res.value());
812 }
813 auto newMem = builder.create<MemOp>(
814 resultTypes, mem.getReadLatency(), mem.getWriteLatency(),
815 mem.getDepth(), RUWAttr::Undefined,
816 builder.getArrayAttr(resultNames), mem.getNameAttr(),
817 mem.getNameKind(), mem.getAnnotations(),
818 builder.getArrayAttr(portAnnotations), mem.getInnerSymAttr(),
819 mem.getInitAttr(), mem.getPrefixAttr());
820 for (const auto &res : llvm::enumerate(oldResults))
821 res.value().replaceAllUsesWith(newMem.getResult(res.index()));
822 mem.erase();
823 }
824 opsToRemove.clear();
825 refPortsToRemoveMap.clear();
826 dataflowAt.clear();
827 refSendPathList.clear();
828 moduleStates.clear();
829 }
830
832
833 /// Return a HierPathOp for the provided pathArray. This will either return
834 /// an existing HierPathOp or it will create and return a new one.
835 hw::HierPathOp getOrCreatePath(ArrayAttr pathArray,
836 ImplicitLocOpBuilder &builder) {
837 assert(pathArray && !pathArray.empty());
838 // Return an existing HierPathOp if one exists with the same path.
839 auto pathIter = pathCache.find(pathArray);
840 if (pathIter != pathCache.end())
841 return pathIter->second;
842
843 // Reset the insertion point after this function returns.
844 OpBuilder::InsertionGuard guard(builder);
845
846 // Set the insertion point to either the known location where the pass
847 // inserts HierPathOps or to the start of the circuit.
848 if (pathInsertPoint.isSet())
849 builder.restoreInsertionPoint(pathInsertPoint);
850 else
851 builder.setInsertionPointToStart(getOperation().getBodyBlock());
852
853 // Create the new HierPathOp and insert it into the pathCache.
854 hw::HierPathOp path =
855 pathCache
856 .insert({pathArray,
857 builder.create<hw::HierPathOp>(
858 circuitNamespace->newName("xmrPath"), pathArray)})
859 .first->second;
860 path.setVisibility(SymbolTable::Visibility::Private);
861
862 // Save the insertion point so other unique HierPathOps will be created
863 // after this one.
864 pathInsertPoint = builder.saveInsertionPoint();
865
866 // Return the new path.
867 return path;
868 }
869
870private:
871 /// Cached module namespaces.
872 DenseMap<Operation *, hw::InnerSymbolNamespace> moduleNamespaces;
873
874 DenseSet<Operation *> visitedModules;
875 /// Map of a reference value to an entry into refSendPathList. Each entry in
876 /// refSendPathList represents the path to RefSend.
877 /// The path is required since there can be multiple paths to the RefSend and
878 /// we need to identify a unique path.
879 DenseMap<Value, size_t> dataflowAt;
880
881 /// refSendPathList is used to construct a path to the RefSendOp. Each entry
882 /// is an XMRNode, with an InnerRefAttr or indexing op, and a pointer to the
883 /// next node in the path. The InnerRefAttr can be to an InstanceOp or to the
884 /// XMR defining op, the index op records narrowing along path. All the nodes
885 /// representing an InstanceOp or indexing operation must have a valid
886 /// NextNodeOnPath. Only the node representing the final XMR defining op has
887 /// no NextNodeOnPath, which denotes a leaf node on the path.
888 SmallVector<XMRNode> refSendPathList;
889
890 /// llvm::EquivalenceClasses wants comparable elements. This comparator uses
891 /// uses pointer comparison on the Impl.
893 bool operator()(const Value &lhs, const Value &rhs) const {
894 return lhs.getImpl() < rhs.getImpl();
895 }
896 };
897
898 llvm::EquivalenceClasses<Value, ValueComparator> *dataFlowClasses;
899 // Instance and module ref ports that needs to be removed.
900 DenseMap<Operation *, llvm::BitVector> refPortsToRemoveMap;
901
902 /// RefResolve, RefSend, and Connects involving them that will be removed.
903 SmallVector<Operation *> opsToRemove;
904
905 /// Record the internal path to an external module or a memory.
906 DenseMap<size_t, SmallString<128>> xmrPathSuffix;
907
909
910 /// A cache of already created HierPathOps. This is used to avoid repeatedly
911 /// creating the same HierPathOp.
912 DenseMap<Attribute, hw::HierPathOp> pathCache;
913
914 /// The insertion point where the pass inserts HierPathOps.
915 OpBuilder::InsertPoint pathInsertPoint = {};
916
917 /// Per-module helpers for creating operations within modules.
918 DenseMap<FModuleOp, ModuleState> moduleStates;
919};
920
921std::unique_ptr<mlir::Pass> circt::firrtl::createLowerXMRPass() {
922 return std::make_unique<LowerXMRPass>();
923}
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)
Definition LowerXMR.cpp:507
DenseMap< Operation *, hw::InnerSymbolNamespace > moduleNamespaces
Cached module namespaces.
Definition LowerXMR.cpp:872
DenseMap< size_t, SmallString< 128 > > xmrPathSuffix
Record the internal path to an external module or a memory.
Definition LowerXMR.cpp:906
InnerRefAttr getInnerRefTo(Value val)
Definition LowerXMR.cpp:730
size_t addReachingSendsEntry(Value atRefVal, XMRNode::SymOrIndexOp info, std::optional< size_t > continueFrom=std::nullopt)
Definition LowerXMR.cpp:774
DenseMap< FModuleOp, ModuleState > moduleStates
Per-module helpers for creating operations within modules.
Definition LowerXMR.cpp:918
hw::HierPathOp getOrCreatePath(ArrayAttr pathArray, ImplicitLocOpBuilder &builder)
Return a HierPathOp for the provided pathArray.
Definition LowerXMR.cpp:835
LogicalResult resolveReferencePath(mlir::TypedValue< RefType > refVal, ImplicitLocOpBuilder builder, mlir::FlatSymbolRefAttr &ref, SmallString< 128 > &stringLeaf)
Definition LowerXMR.cpp:436
DenseMap< Value, size_t > dataflowAt
Map of a reference value to an entry into refSendPathList.
Definition LowerXMR.cpp:879
void setPortToRemove(Operation *op, size_t index, size_t numPorts)
Definition LowerXMR.cpp:578
hw::InnerSymbolNamespace & getModuleNamespace(FModuleLike module)
Get the cached namespace for a module.
Definition LowerXMR.cpp:726
llvm::EquivalenceClasses< Value, ValueComparator > * dataFlowClasses
Definition LowerXMR.cpp:898
void markForRemoval(Operation *op)
Definition LowerXMR.cpp:748
void garbageCollect()
Definition LowerXMR.cpp:783
LogicalResult handlePublicModuleRefPorts(FModuleOp module)
Definition LowerXMR.cpp:671
void getRefABIPrefix(FModuleLike mod, SmallVectorImpl< char > &prefix)
Generate the ABI ref_<module> prefix string into prefix.
Definition LowerXMR.cpp:418
void runOnOperation() override
Definition LowerXMR.cpp:127
DenseMap< Attribute, hw::HierPathOp > pathCache
A cache of already created HierPathOps.
Definition LowerXMR.cpp:912
LogicalResult handleRefResolve(RefResolveOp resolve)
Definition LowerXMR.cpp:554
DenseMap< Operation *, llvm::BitVector > refPortsToRemoveMap
Definition LowerXMR.cpp:900
SmallVector< XMRNode > refSendPathList
refSendPathList is used to construct a path to the RefSendOp.
Definition LowerXMR.cpp:888
LogicalResult handleInstanceOp(InstanceOp inst, InstanceGraph &instanceGraph)
Definition LowerXMR.cpp:585
LogicalResult handleForceReleaseOp(Operation *op)
Definition LowerXMR.cpp:524
std::optional< size_t > getRemoteRefSend(Value val, bool errorIfNotFound=true)
Definition LowerXMR.cpp:750
DenseSet< Operation * > visitedModules
Definition LowerXMR.cpp:874
InnerRefAttr getInnerRefTo(Operation *op)
Definition LowerXMR.cpp:741
OpBuilder::InsertPoint pathInsertPoint
The insertion point where the pass inserts HierPathOps.
Definition LowerXMR.cpp:915
StringAttr getRefABIMacroForPort(FModuleLike mod, size_t portIndex, const Twine &prefix, bool backTick=false)
Get full macro name as StringAttr for the specified ref port.
Definition LowerXMR.cpp:430
CircuitNamespace * circuitNamespace
Definition LowerXMR.cpp:908
bool isZeroWidth(FIRRTLBaseType t)
Definition LowerXMR.cpp:831
SmallVector< Operation * > opsToRemove
RefResolve, RefSend, and Connects involving them that will be removed.
Definition LowerXMR.cpp:903
void clear()
Empty the namespace.
Definition Namespace.h:75
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()
Definition LowerXMR.cpp:921
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.
Definition LowerXMR.cpp:892
bool operator()(const Value &lhs, const Value &rhs) const
Definition LowerXMR.cpp:893
The namespace of a CircuitOp, generally inhabited by modules.
Definition Namespace.h:24