Loading [MathJax]/extensions/tex2jax.js
CIRCT 21.0.0git
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
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> 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 (const auto &I :
374 *dataFlowClasses) { // 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(dataFlowClasses->members(*I), llvm::dbgs(), "\n");
379 llvm::dbgs() << "\n dataflow at leader::" << I->getData() << "\n =>";
380 auto iter = dataflowAt.find(I->getData());
381 if (iter != dataflowAt.end()) {
382 for (auto init = refSendPathList[iter->getSecond()]; init.next;
383 init = refSendPathList[*init.next])
384 llvm::dbgs() << "\n " << init;
385 }
386 llvm::dbgs() << "\n Done\n"; // Finish set.
387 }
388 });
389 for (auto refResolve : resolveOps)
390 if (handleRefResolve(refResolve).failed())
391 return signalPassFailure();
392 for (auto *op : forceAndReleaseOps)
393 if (failed(handleForceReleaseOp(op)))
394 return signalPassFailure();
395 for (auto module : publicModules) {
396 if (failed(handlePublicModuleRefPorts(module)))
397 return signalPassFailure();
398 }
400
401 // Clean up
402 moduleNamespaces.clear();
403 visitedModules.clear();
404 dataflowAt.clear();
405 refSendPathList.clear();
406 dataFlowClasses = nullptr;
407 refPortsToRemoveMap.clear();
408 opsToRemove.clear();
409 xmrPathSuffix.clear();
410 circuitNamespace = nullptr;
412 pathInsertPoint = {};
413 }
414
415 /// Generate the ABI ref_<module> prefix string into `prefix`.
416 void getRefABIPrefix(FModuleLike mod, SmallVectorImpl<char> &prefix) {
417 auto modName = mod.getModuleName();
418 if (auto ext = dyn_cast<FExtModuleOp>(*mod)) {
419 // Use defName for module portion, if set.
420 if (auto defname = ext.getDefname(); defname && !defname->empty())
421 modName = *defname;
422 }
423 (Twine("ref_") + modName).toVector(prefix);
424 }
425
426 /// Get full macro name as StringAttr for the specified ref port.
427 /// Uses existing 'prefix', optionally preprends the backtick character.
428 StringAttr getRefABIMacroForPort(FModuleLike mod, size_t portIndex,
429 const Twine &prefix, bool backTick = false) {
430 return StringAttr::get(&getContext(), Twine(backTick ? "`" : "") + prefix +
431 "_" + mod.getPortName(portIndex));
432 }
433
434 LogicalResult resolveReferencePath(mlir::TypedValue<RefType> refVal,
435 ImplicitLocOpBuilder builder,
436 mlir::FlatSymbolRefAttr &ref,
437 SmallString<128> &stringLeaf) {
438 assert(stringLeaf.empty());
439
440 auto remoteOpPath = getRemoteRefSend(refVal);
441 if (!remoteOpPath)
442 return failure();
443 SmallVector<Attribute> refSendPath;
444 SmallVector<RefSubOp> indexing;
445 size_t lastIndex;
446 while (remoteOpPath) {
447 lastIndex = *remoteOpPath;
448 auto entr = refSendPathList[*remoteOpPath];
449 if (entr.info)
450 TypeSwitch<XMRNode::SymOrIndexOp>(entr.info)
451 .Case<Attribute>([&](auto attr) {
452 // If the path is a singular verbatim expression, the attribute of
453 // the send path list entry will be null.
454 if (attr)
455 refSendPath.push_back(attr);
456 })
457 .Case<Operation *>(
458 [&](auto *op) { indexing.push_back(cast<RefSubOp>(op)); });
459 remoteOpPath = entr.next;
460 }
461 auto iter = xmrPathSuffix.find(lastIndex);
462
463 // If this xmr has a suffix string (internal path into a module, that is not
464 // yet generated).
465 if (iter != xmrPathSuffix.end()) {
466 if (!refSendPath.empty())
467 stringLeaf.append(".");
468 stringLeaf.append(iter->getSecond());
469 }
470
471 assert(!(refSendPath.empty() && stringLeaf.empty()) &&
472 "nothing to index through");
473
474 // All indexing done as the ref is plumbed around indexes through
475 // the target/referent, not the current point of the path which
476 // describes how to access the referent we're indexing through.
477 // Above we gathered all indexing operations, so now append them
478 // to the path (after any relevant `xmrPathSuffix`) to reach
479 // the target element.
480 // Generating these strings here (especially if ref is sent
481 // out from a different design) is fragile but should get this
482 // working well enough while sorting out how to do this better.
483 // Some discussion of this can be found here:
484 // https://github.com/llvm/circt/pull/5551#discussion_r1258908834
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);
489 })
490 .Case<BundleType, OpenBundleType>([&](auto bundleType) {
491 auto fieldName = bundleType.getElementName(subOp.getIndex());
492 stringLeaf.append({".", fieldName});
493 });
494 }
495
496 if (!refSendPath.empty())
497 // Compute the HierPathOp that stores the path.
498 ref = FlatSymbolRefAttr::get(
499 getOrCreatePath(builder.getArrayAttr(refSendPath), builder)
500 .getSymNameAttr());
501
502 return success();
503 }
504
505 LogicalResult resolveReference(mlir::TypedValue<RefType> refVal,
506 ImplicitLocOpBuilder &builder,
507 FlatSymbolRefAttr &ref, StringAttr &xmrAttr) {
508 auto remoteOpPath = getRemoteRefSend(refVal);
509 if (!remoteOpPath)
510 return failure();
511
512 SmallString<128> xmrString;
513 if (failed(resolveReferencePath(refVal, builder, ref, xmrString)))
514 return failure();
515 xmrAttr =
516 xmrString.empty() ? StringAttr{} : builder.getStringAttr(xmrString);
517
518 return success();
519 }
520
521 // Replace the Force/Release's ref argument with a resolved XMRRef.
522 LogicalResult handleForceReleaseOp(Operation *op) {
523 return TypeSwitch<Operation *, LogicalResult>(op)
524 .Case<RefForceOp, RefForceInitialOp, RefReleaseOp, RefReleaseInitialOp>(
525 [&](auto op) {
526 // Drop if zero-width target.
527 auto destType = op.getDest().getType();
528 if (isZeroWidth(destType.getType())) {
529 op.erase();
530 return success();
531 }
532
533 ImplicitLocOpBuilder builder(op.getLoc(), op);
534 FlatSymbolRefAttr ref;
535 StringAttr str;
536 if (failed(resolveReference(op.getDest(), builder, ref, str)))
537 return failure();
538
539 Value xmr =
540 moduleStates.find(op->template getParentOfType<FModuleOp>())
541 ->getSecond()
542 .getOrCreateXMRRefOp(destType, ref, str, builder);
543 op.getDestMutable().assign(xmr);
544 return success();
545 })
546 .Default([](auto *op) {
547 return op->emitError("unexpected operation kind");
548 });
549 }
550
551 // Replace the RefResolveOp with verbatim op representing the XMR.
552 LogicalResult handleRefResolve(RefResolveOp resolve) {
553 auto resWidth = getBitWidth(resolve.getType());
554 if (resWidth.has_value() && *resWidth == 0) {
555 // Donot emit 0 width XMRs, replace it with constant 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>(
560 zeroUintType, getIntZerosAttr(zeroUintType)));
561 resolve.getResult().replaceAllUsesWith(zeroC);
562 return success();
563 }
564
565 FlatSymbolRefAttr ref;
566 StringAttr str;
567 ImplicitLocOpBuilder builder(resolve.getLoc(), resolve);
568 if (failed(resolveReference(resolve.getRef(), builder, ref, str)))
569 return failure();
570
571 Value result = builder.create<XMRDerefOp>(resolve.getType(), ref, str);
572 resolve.getResult().replaceAllUsesWith(result);
573 return success();
574 }
575
576 void setPortToRemove(Operation *op, size_t index, size_t numPorts) {
577 if (refPortsToRemoveMap[op].size() < numPorts)
578 refPortsToRemoveMap[op].resize(numPorts);
579 refPortsToRemoveMap[op].set(index);
580 }
581
582 // Propagate the reachable RefSendOp across modules.
583 LogicalResult handleInstanceOp(InstanceOp inst,
584 InstanceGraph &instanceGraph) {
585 Operation *mod = inst.getReferencedModule(instanceGraph);
586 if (auto extRefMod = dyn_cast<FExtModuleOp>(mod)) {
587 // Extern modules can generate RefType ports, they have an attached
588 // attribute which specifies the internal path into the extern module.
589 // This string attribute will be used to generate the final xmr.
590 auto internalPaths = extRefMod.getInternalPaths();
591 auto numPorts = inst.getNumResults();
592 SmallString<128> circuitRefPrefix;
593
594 /// Get the resolution string for this ref-type port.
595 auto getPath = [&](size_t portNo) {
596 // If there's an internal path specified (with path), use that.
597 if (internalPaths)
598 if (auto path =
599 cast<InternalPathAttr>(internalPaths->getValue()[portNo])
600 .getPath())
601 return path;
602
603 // Otherwise, we're using the ref ABI. Generate the prefix string
604 // and return the macro for the specified port.
605 if (circuitRefPrefix.empty())
606 getRefABIPrefix(extRefMod, circuitRefPrefix);
607
608 return getRefABIMacroForPort(extRefMod, portNo, circuitRefPrefix, true);
609 };
610
611 for (const auto &res : llvm::enumerate(inst.getResults())) {
612 if (!isa<RefType>(inst.getResult(res.index()).getType()))
613 continue;
614
615 auto inRef = getInnerRefTo(inst);
616 auto ind = addReachingSendsEntry(res.value(), inRef);
617
618 xmrPathSuffix[ind] = getPath(res.index());
619 // The instance result and module port must be marked for removal.
620 setPortToRemove(inst, res.index(), numPorts);
621 setPortToRemove(extRefMod, res.index(), numPorts);
622 }
623 return success();
624 }
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()))
631 continue;
632 if (!refMod)
633 return inst.emitOpError("cannot lower ext modules with RefType ports");
634 // Reference ports must be removed.
635 setPortToRemove(inst, portNum, numPorts);
636 // Drop the dead-instance-ports.
637 if (instanceResult.use_empty() ||
638 isZeroWidth(type_cast<RefType>(instanceResult.getType()).getType()))
639 continue;
640 auto refModuleArg = refMod.getArgument(portNum);
641 if (inst.getPortDirection(portNum) == Direction::Out) {
642 // For output instance ports, the dataflow is into this module.
643 // Get the remote RefSendOp, that flows through the module ports.
644 // If dataflow at remote module argument does not exist, error out.
645 auto remoteOpPath = getRemoteRefSend(refModuleArg);
646 if (!remoteOpPath)
647 return failure();
648 // Get the path to reaching refSend at the referenced module argument.
649 // Now append this instance to the path to the reaching refSend.
650 addReachingSendsEntry(instanceResult, getInnerRefTo(inst),
651 remoteOpPath);
652 } else {
653 // For input instance ports, the dataflow is into the referenced module.
654 // Input RefType port implies, generating an upward scoped XMR.
655 // No need to add the instance context, since downward reference must be
656 // through single instantiated modules.
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));
664 }
665 }
666 return success();
667 }
668
669 LogicalResult handlePublicModuleRefPorts(FModuleOp module) {
670 auto *body = getOperation().getBodyBlock();
671
672 // Find all the output reference ports.
673 SmallString<128> circuitRefPrefix;
674 SmallVector<std::tuple<StringAttr, StringAttr, ArrayAttr>> ports;
675 auto declBuilder =
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)
682 continue;
683 auto portValue =
684 cast<mlir::TypedValue<RefType>>(module.getArgument(portIndex));
685 mlir::FlatSymbolRefAttr ref;
686 SmallString<128> stringLeaf;
687 if (failed(resolveReferencePath(portValue, declBuilder, ref, stringLeaf)))
688 return failure();
689
690 SmallString<128> formatString;
691 if (ref)
692 formatString += "{{0}}";
693 formatString += stringLeaf;
694
695 // Insert a macro with the format:
696 // ref_<module-name>_<ref-name> <path>
697 if (circuitRefPrefix.empty())
698 getRefABIPrefix(module, circuitRefPrefix);
699 auto macroName =
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{});
704 }
705
706 // Create a file only if the module has at least one ref port.
707 if (ports.empty())
708 return success();
709
710 // The macros will be exported to a `ref_<module-name>.sv` file.
711 // In the IR, the file is inserted before the module.
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);
717 }
718 });
719
720 return success();
721 }
722
723 /// Get the cached namespace for a module.
725 return moduleNamespaces.try_emplace(module, module).first->second;
726 }
727
728 InnerRefAttr getInnerRefTo(Value val) {
729 if (auto arg = dyn_cast<BlockArgument>(val))
730 return ::getInnerRefTo(
731 cast<FModuleLike>(arg.getParentBlock()->getParentOp()),
732 arg.getArgNumber(),
733 [&](FModuleLike mod) -> hw::InnerSymbolNamespace & {
734 return getModuleNamespace(mod);
735 });
736 return getInnerRefTo(val.getDefiningOp());
737 }
738
739 InnerRefAttr getInnerRefTo(Operation *op) {
740 return ::getInnerRefTo(op,
741 [&](FModuleLike mod) -> hw::InnerSymbolNamespace & {
742 return getModuleNamespace(mod);
743 });
744 }
745
746 void markForRemoval(Operation *op) { opsToRemove.push_back(op); }
747
748 std::optional<size_t> getRemoteRefSend(Value val,
749 bool errorIfNotFound = true) {
750 auto iter = dataflowAt.find(dataFlowClasses->getOrInsertLeaderValue(val));
751 if (iter != dataflowAt.end())
752 return iter->getSecond();
753 if (!errorIfNotFound)
754 return std::nullopt;
755 // The referenced module must have already been analyzed, error out if the
756 // dataflow at the child module is not resolved.
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 "
760 "for module port '")
761 << dyn_cast<FModuleOp>(arg.getOwner()->getParentOp())
762 .getPortName(arg.getArgNumber())
763 << "'";
764 else
765 val.getDefiningOp()->emitOpError(
766 "reference dataflow cannot be traced back to the remote read op");
767 signalPassFailure();
768 return std::nullopt;
769 }
770
771 size_t
772 addReachingSendsEntry(Value atRefVal, XMRNode::SymOrIndexOp info,
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});
778 return indx;
779 }
780
782 // Now erase all the Ops and ports of RefType.
783 // This needs to be done as the last step to ensure uses are erased before
784 // the def is erased.
785 for (Operation *op : llvm::reverse(opsToRemove))
786 op->erase();
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());
795 inst.erase();
796 } else if (auto mem = dyn_cast<MemOp>(iter.getFirst())) {
797 // Remove all debug ports of the memory.
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()))
805 continue;
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());
810 }
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()));
820 mem.erase();
821 }
822 opsToRemove.clear();
823 refPortsToRemoveMap.clear();
824 dataflowAt.clear();
825 refSendPathList.clear();
826 moduleStates.clear();
827 }
828
830
831 /// Return a HierPathOp for the provided pathArray. This will either return
832 /// an existing HierPathOp or it will create and return a new one.
833 hw::HierPathOp getOrCreatePath(ArrayAttr pathArray,
834 ImplicitLocOpBuilder &builder) {
835 assert(pathArray && !pathArray.empty());
836 // Return an existing HierPathOp if one exists with the same path.
837 auto pathIter = pathCache.find(pathArray);
838 if (pathIter != pathCache.end())
839 return pathIter->second;
840
841 // Reset the insertion point after this function returns.
842 OpBuilder::InsertionGuard guard(builder);
843
844 // Set the insertion point to either the known location where the pass
845 // inserts HierPathOps or to the start of the circuit.
846 if (pathInsertPoint.isSet())
847 builder.restoreInsertionPoint(pathInsertPoint);
848 else
849 builder.setInsertionPointToStart(getOperation().getBodyBlock());
850
851 // Create the new HierPathOp and insert it into the pathCache.
852 hw::HierPathOp path =
853 pathCache
854 .insert({pathArray,
855 builder.create<hw::HierPathOp>(
856 circuitNamespace->newName("xmrPath"), pathArray)})
857 .first->second;
858 path.setVisibility(SymbolTable::Visibility::Private);
859
860 // Save the insertion point so other unique HierPathOps will be created
861 // after this one.
862 pathInsertPoint = builder.saveInsertionPoint();
863
864 // Return the new path.
865 return path;
866 }
867
868private:
869 /// Cached module namespaces.
870 DenseMap<Operation *, hw::InnerSymbolNamespace> moduleNamespaces;
871
872 DenseSet<Operation *> visitedModules;
873 /// Map of a reference value to an entry into refSendPathList. Each entry in
874 /// refSendPathList represents the path to RefSend.
875 /// The path is required since there can be multiple paths to the RefSend and
876 /// we need to identify a unique path.
877 DenseMap<Value, size_t> dataflowAt;
878
879 /// refSendPathList is used to construct a path to the RefSendOp. Each entry
880 /// is an XMRNode, with an InnerRefAttr or indexing op, and a pointer to the
881 /// next node in the path. The InnerRefAttr can be to an InstanceOp or to the
882 /// XMR defining op, the index op records narrowing along path. All the nodes
883 /// representing an InstanceOp or indexing operation must have a valid
884 /// NextNodeOnPath. Only the node representing the final XMR defining op has
885 /// no NextNodeOnPath, which denotes a leaf node on the path.
886 SmallVector<XMRNode> refSendPathList;
887
888 llvm::EquivalenceClasses<Value> *dataFlowClasses;
889 // Instance and module ref ports that needs to be removed.
890 DenseMap<Operation *, llvm::BitVector> refPortsToRemoveMap;
891
892 /// RefResolve, RefSend, and Connects involving them that will be removed.
893 SmallVector<Operation *> opsToRemove;
894
895 /// Record the internal path to an external module or a memory.
896 DenseMap<size_t, SmallString<128>> xmrPathSuffix;
897
899
900 /// A cache of already created HierPathOps. This is used to avoid repeatedly
901 /// creating the same HierPathOp.
902 DenseMap<Attribute, hw::HierPathOp> pathCache;
903
904 /// The insertion point where the pass inserts HierPathOps.
905 OpBuilder::InsertPoint pathInsertPoint = {};
906
907 /// Per-module helpers for creating operations within modules.
908 DenseMap<FModuleOp, ModuleState> moduleStates;
909};
910
911std::unique_ptr<mlir::Pass> circt::firrtl::createLowerXMRPass() {
912 return std::make_unique<LowerXMRPass>();
913}
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:505
DenseMap< Operation *, hw::InnerSymbolNamespace > moduleNamespaces
Cached module namespaces.
Definition LowerXMR.cpp:870
llvm::EquivalenceClasses< Value > * dataFlowClasses
Definition LowerXMR.cpp:888
DenseMap< size_t, SmallString< 128 > > xmrPathSuffix
Record the internal path to an external module or a memory.
Definition LowerXMR.cpp:896
InnerRefAttr getInnerRefTo(Value val)
Definition LowerXMR.cpp:728
size_t addReachingSendsEntry(Value atRefVal, XMRNode::SymOrIndexOp info, std::optional< size_t > continueFrom=std::nullopt)
Definition LowerXMR.cpp:772
DenseMap< FModuleOp, ModuleState > moduleStates
Per-module helpers for creating operations within modules.
Definition LowerXMR.cpp:908
hw::HierPathOp getOrCreatePath(ArrayAttr pathArray, ImplicitLocOpBuilder &builder)
Return a HierPathOp for the provided pathArray.
Definition LowerXMR.cpp:833
LogicalResult resolveReferencePath(mlir::TypedValue< RefType > refVal, ImplicitLocOpBuilder builder, mlir::FlatSymbolRefAttr &ref, SmallString< 128 > &stringLeaf)
Definition LowerXMR.cpp:434
DenseMap< Value, size_t > dataflowAt
Map of a reference value to an entry into refSendPathList.
Definition LowerXMR.cpp:877
void setPortToRemove(Operation *op, size_t index, size_t numPorts)
Definition LowerXMR.cpp:576
hw::InnerSymbolNamespace & getModuleNamespace(FModuleLike module)
Get the cached namespace for a module.
Definition LowerXMR.cpp:724
void markForRemoval(Operation *op)
Definition LowerXMR.cpp:746
void garbageCollect()
Definition LowerXMR.cpp:781
LogicalResult handlePublicModuleRefPorts(FModuleOp module)
Definition LowerXMR.cpp:669
void getRefABIPrefix(FModuleLike mod, SmallVectorImpl< char > &prefix)
Generate the ABI ref_<module> prefix string into prefix.
Definition LowerXMR.cpp:416
void runOnOperation() override
Definition LowerXMR.cpp:127
DenseMap< Attribute, hw::HierPathOp > pathCache
A cache of already created HierPathOps.
Definition LowerXMR.cpp:902
LogicalResult handleRefResolve(RefResolveOp resolve)
Definition LowerXMR.cpp:552
DenseMap< Operation *, llvm::BitVector > refPortsToRemoveMap
Definition LowerXMR.cpp:890
SmallVector< XMRNode > refSendPathList
refSendPathList is used to construct a path to the RefSendOp.
Definition LowerXMR.cpp:886
LogicalResult handleInstanceOp(InstanceOp inst, InstanceGraph &instanceGraph)
Definition LowerXMR.cpp:583
LogicalResult handleForceReleaseOp(Operation *op)
Definition LowerXMR.cpp:522
std::optional< size_t > getRemoteRefSend(Value val, bool errorIfNotFound=true)
Definition LowerXMR.cpp:748
DenseSet< Operation * > visitedModules
Definition LowerXMR.cpp:872
InnerRefAttr getInnerRefTo(Operation *op)
Definition LowerXMR.cpp:739
OpBuilder::InsertPoint pathInsertPoint
The insertion point where the pass inserts HierPathOps.
Definition LowerXMR.cpp:905
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:428
CircuitNamespace * circuitNamespace
Definition LowerXMR.cpp:898
bool isZeroWidth(FIRRTLBaseType t)
Definition LowerXMR.cpp:829
SmallVector< Operation * > opsToRemove
RefResolve, RefSend, and Connects involving them that will be removed.
Definition LowerXMR.cpp:893
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:911
std::optional< int64_t > getBitWidth(FIRRTLBaseType type, bool ignoreFlip=false)
IntegerAttr getIntZerosAttr(Type type)
Utility for generating a constant zero attribute.
void info(Twine message)
Definition LSPUtils.cpp:20
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
The namespace of a CircuitOp, generally inhabited by modules.
Definition Namespace.h:24