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