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
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 modName = ext.getExtModuleName();
421 (Twine("ref_") + modName).toVector(prefix);
422 }
423
424 /// Get full macro name as StringAttr for the specified ref port.
425 /// Uses existing 'prefix', optionally preprends the backtick character.
426 StringAttr getRefABIMacroForPort(FModuleLike mod, size_t portIndex,
427 const Twine &prefix, bool backTick = false) {
428 return StringAttr::get(&getContext(), Twine(backTick ? "`" : "") + prefix +
429 "_" + mod.getPortName(portIndex));
430 }
431
432 LogicalResult resolveReferencePath(mlir::TypedValue<RefType> refVal,
433 ImplicitLocOpBuilder builder,
434 mlir::FlatSymbolRefAttr &ref,
435 SmallString<128> &stringLeaf) {
436 assert(stringLeaf.empty());
437
438 auto remoteOpPath = getRemoteRefSend(refVal);
439 if (!remoteOpPath)
440 return failure();
441 SmallVector<Attribute> refSendPath;
442 SmallVector<RefSubOp> indexing;
443 size_t lastIndex;
444 while (remoteOpPath) {
445 lastIndex = *remoteOpPath;
446 auto entr = refSendPathList[*remoteOpPath];
447 if (entr.info)
448 TypeSwitch<XMRNode::SymOrIndexOp>(entr.info)
449 .Case<Attribute>([&](auto attr) {
450 // If the path is a singular verbatim expression, the attribute of
451 // the send path list entry will be null.
452 if (attr)
453 refSendPath.push_back(attr);
454 })
455 .Case<Operation *>(
456 [&](auto *op) { indexing.push_back(cast<RefSubOp>(op)); });
457 remoteOpPath = entr.next;
458 }
459 auto iter = xmrPathSuffix.find(lastIndex);
460
461 // If this xmr has a suffix string (internal path into a module, that is not
462 // yet generated).
463 if (iter != xmrPathSuffix.end()) {
464 if (!refSendPath.empty())
465 stringLeaf.append(".");
466 stringLeaf.append(iter->getSecond());
467 }
468
469 assert(!(refSendPath.empty() && stringLeaf.empty()) &&
470 "nothing to index through");
471
472 // All indexing done as the ref is plumbed around indexes through
473 // the target/referent, not the current point of the path which
474 // describes how to access the referent we're indexing through.
475 // Above we gathered all indexing operations, so now append them
476 // to the path (after any relevant `xmrPathSuffix`) to reach
477 // the target element.
478 // Generating these strings here (especially if ref is sent
479 // out from a different design) is fragile but should get this
480 // working well enough while sorting out how to do this better.
481 // Some discussion of this can be found here:
482 // https://github.com/llvm/circt/pull/5551#discussion_r1258908834
483 for (auto subOp : llvm::reverse(indexing)) {
484 TypeSwitch<FIRRTLBaseType>(subOp.getInput().getType().getType())
485 .Case<FVectorType, OpenVectorType>([&](auto vecType) {
486 (Twine("[") + Twine(subOp.getIndex()) + "]").toVector(stringLeaf);
487 })
488 .Case<BundleType, OpenBundleType>([&](auto bundleType) {
489 auto fieldName = bundleType.getElementName(subOp.getIndex());
490 stringLeaf.append({".", fieldName});
491 });
492 }
493
494 if (!refSendPath.empty())
495 // Compute the HierPathOp that stores the path.
496 ref = FlatSymbolRefAttr::get(
497 hierPathCache
498 ->getOrCreatePath(builder.getArrayAttr(refSendPath),
499 builder.getLoc())
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(), ConstantOp::create(builder, zeroUintType,
560 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 = XMRDerefOp::create(builder, 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 auto numPorts = inst.getNumResults();
588 SmallString<128> circuitRefPrefix;
589
590 /// Get the resolution string for this ref-type port.
591 auto getPath = [&](size_t portNo) {
592 // Otherwise, we're using the ref ABI. Generate the prefix string
593 // and return the macro for the specified port.
594 if (circuitRefPrefix.empty())
595 getRefABIPrefix(extRefMod, circuitRefPrefix);
596
597 return getRefABIMacroForPort(extRefMod, portNo, circuitRefPrefix, true);
598 };
599
600 for (const auto &res : llvm::enumerate(inst.getResults())) {
601 if (!isa<RefType>(inst.getResult(res.index()).getType()))
602 continue;
603
604 auto inRef = getInnerRefTo(inst);
605 auto ind = addReachingSendsEntry(res.value(), inRef);
606
607 xmrPathSuffix[ind] = getPath(res.index());
608 // The instance result and module port must be marked for removal.
609 setPortToRemove(inst, res.index(), numPorts);
610 setPortToRemove(extRefMod, res.index(), numPorts);
611 }
612 return success();
613 }
614 auto refMod = dyn_cast<FModuleOp>(mod);
615 bool multiplyInstantiated = !visitedModules.insert(refMod).second;
616 for (size_t portNum = 0, numPorts = inst.getNumResults();
617 portNum < numPorts; ++portNum) {
618 auto instanceResult = inst.getResult(portNum);
619 if (!isa<RefType>(instanceResult.getType()))
620 continue;
621 if (!refMod)
622 return inst.emitOpError("cannot lower ext modules with RefType ports");
623 // Reference ports must be removed.
624 setPortToRemove(inst, portNum, numPorts);
625 // Drop the dead-instance-ports.
626 if (instanceResult.use_empty() ||
627 isZeroWidth(type_cast<RefType>(instanceResult.getType()).getType()))
628 continue;
629 auto refModuleArg = refMod.getArgument(portNum);
630 if (inst.getPortDirection(portNum) == Direction::Out) {
631 // For output instance ports, the dataflow is into this module.
632 // Get the remote RefSendOp, that flows through the module ports.
633 // If dataflow at remote module argument does not exist, error out.
634 auto remoteOpPath = getRemoteRefSend(refModuleArg);
635 if (!remoteOpPath)
636 return failure();
637 // Get the path to reaching refSend at the referenced module argument.
638 // Now append this instance to the path to the reaching refSend.
639 addReachingSendsEntry(instanceResult, getInnerRefTo(inst),
640 remoteOpPath);
641 } else {
642 // For input instance ports, the dataflow is into the referenced module.
643 // Input RefType port implies, generating an upward scoped XMR.
644 // No need to add the instance context, since downward reference must be
645 // through single instantiated modules.
646 if (multiplyInstantiated)
647 return refMod.emitOpError(
648 "multiply instantiated module with input RefType port '")
649 << refMod.getPortName(portNum) << "'";
650 dataFlowClasses->unionSets(
651 dataFlowClasses->getOrInsertLeaderValue(refModuleArg),
652 dataFlowClasses->getOrInsertLeaderValue(instanceResult));
653 }
654 }
655 return success();
656 }
657
658 LogicalResult handlePublicModuleRefPorts(FModuleOp module) {
659 auto *body = getOperation().getBodyBlock();
660
661 // Find all the output reference ports.
662 SmallString<128> circuitRefPrefix;
663 SmallVector<std::tuple<StringAttr, StringAttr, ArrayAttr>> ports;
664 auto declBuilder =
665 ImplicitLocOpBuilder::atBlockBegin(module.getLoc(), body);
666 for (size_t portIndex = 0, numPorts = module.getNumPorts();
667 portIndex != numPorts; ++portIndex) {
668 auto refType = type_dyn_cast<RefType>(module.getPortType(portIndex));
669 if (!refType || isZeroWidth(refType.getType()) ||
670 module.getPortDirection(portIndex) != Direction::Out)
671 continue;
672 auto portValue =
673 cast<mlir::TypedValue<RefType>>(module.getArgument(portIndex));
674 mlir::FlatSymbolRefAttr ref;
675 SmallString<128> stringLeaf;
676 if (failed(resolveReferencePath(portValue, declBuilder, ref, stringLeaf)))
677 return failure();
678
679 SmallString<128> formatString;
680 if (ref)
681 formatString += "{{0}}";
682 formatString += stringLeaf;
683
684 // Insert a macro with the format:
685 // ref_<module-name>_<ref-name> <path>
686 if (circuitRefPrefix.empty())
687 getRefABIPrefix(module, circuitRefPrefix);
688 auto macroName =
689 getRefABIMacroForPort(module, portIndex, circuitRefPrefix);
690 sv::MacroDeclOp::create(declBuilder, macroName, ArrayAttr(),
691 StringAttr());
692 ports.emplace_back(macroName, declBuilder.getStringAttr(formatString),
693 ref ? declBuilder.getArrayAttr({ref}) : ArrayAttr{});
694 }
695
696 // Create a file only if the module has at least one ref port.
697 if (ports.empty())
698 return success();
699
700 // The macros will be exported to a `ref_<module-name>.sv` file.
701 // In the IR, the file is inserted before the module.
702 auto fileBuilder = ImplicitLocOpBuilder(module.getLoc(), module);
703 emit::FileOp::create(fileBuilder, circuitRefPrefix + ".sv", [&] {
704 for (auto [macroName, formatString, symbols] : ports) {
705 sv::MacroDefOp::create(fileBuilder, FlatSymbolRefAttr::get(macroName),
706 formatString, symbols);
707 }
708 });
709
710 return success();
711 }
712
713 /// Get the cached namespace for a module.
715 return moduleNamespaces.try_emplace(module, module).first->second;
716 }
717
718 InnerRefAttr getInnerRefTo(Value val) {
719 if (auto arg = dyn_cast<BlockArgument>(val))
720 return ::getInnerRefTo(
721 cast<FModuleLike>(arg.getParentBlock()->getParentOp()),
722 arg.getArgNumber(),
723 [&](FModuleLike mod) -> hw::InnerSymbolNamespace & {
724 return getModuleNamespace(mod);
725 });
726 return getInnerRefTo(val.getDefiningOp());
727 }
728
729 InnerRefAttr getInnerRefTo(Operation *op) {
730 return ::getInnerRefTo(op,
731 [&](FModuleLike mod) -> hw::InnerSymbolNamespace & {
732 return getModuleNamespace(mod);
733 });
734 }
735
736 void markForRemoval(Operation *op) { opsToRemove.push_back(op); }
737
738 std::optional<size_t> getRemoteRefSend(Value val,
739 bool errorIfNotFound = true) {
740 auto iter = dataflowAt.find(dataFlowClasses->getOrInsertLeaderValue(val));
741 if (iter != dataflowAt.end())
742 return iter->getSecond();
743 if (!errorIfNotFound)
744 return std::nullopt;
745 // The referenced module must have already been analyzed, error out if the
746 // dataflow at the child module is not resolved.
747 if (BlockArgument arg = dyn_cast<BlockArgument>(val))
748 arg.getOwner()->getParentOp()->emitError(
749 "reference dataflow cannot be traced back to the remote read op "
750 "for module port '")
751 << dyn_cast<FModuleOp>(arg.getOwner()->getParentOp())
752 .getPortName(arg.getArgNumber())
753 << "'";
754 else
755 val.getDefiningOp()->emitOpError(
756 "reference dataflow cannot be traced back to the remote read op");
757 signalPassFailure();
758 return std::nullopt;
759 }
760
761 size_t
762 addReachingSendsEntry(Value atRefVal, XMRNode::SymOrIndexOp info,
763 std::optional<size_t> continueFrom = std::nullopt) {
764 auto leader = dataFlowClasses->getOrInsertLeaderValue(atRefVal);
765 auto indx = refSendPathList.size();
766 dataflowAt[leader] = indx;
767 refSendPathList.push_back({info, continueFrom});
768 return indx;
769 }
770
772 // Now erase all the Ops and ports of RefType.
773 // This needs to be done as the last step to ensure uses are erased before
774 // the def is erased.
775 for (Operation *op : llvm::reverse(opsToRemove))
776 op->erase();
777 for (auto iter : refPortsToRemoveMap)
778 if (auto mod = dyn_cast<FModuleOp>(iter.getFirst()))
779 mod.erasePorts(iter.getSecond());
780 else if (auto mod = dyn_cast<FExtModuleOp>(iter.getFirst()))
781 mod.erasePorts(iter.getSecond());
782 else if (auto inst = dyn_cast<InstanceOp>(iter.getFirst())) {
783 inst.cloneWithErasedPortsAndReplaceUses(iter.getSecond());
784 inst.erase();
785 } else if (auto mem = dyn_cast<MemOp>(iter.getFirst())) {
786 // Remove all debug ports of the memory.
787 ImplicitLocOpBuilder builder(mem.getLoc(), mem);
788 SmallVector<Attribute, 4> resultNames;
789 SmallVector<Type, 4> resultTypes;
790 SmallVector<Attribute, 4> portAnnotations;
791 SmallVector<Value, 4> oldResults;
792 for (const auto &res : llvm::enumerate(mem.getResults())) {
793 if (isa<RefType>(mem.getResult(res.index()).getType()))
794 continue;
795 resultNames.push_back(mem.getPortNameAttr(res.index()));
796 resultTypes.push_back(res.value().getType());
797 portAnnotations.push_back(mem.getPortAnnotation(res.index()));
798 oldResults.push_back(res.value());
799 }
800 auto newMem = MemOp::create(
801 builder, resultTypes, mem.getReadLatency(), mem.getWriteLatency(),
802 mem.getDepth(), RUWBehavior::Undefined,
803 builder.getArrayAttr(resultNames), mem.getNameAttr(),
804 mem.getNameKind(), mem.getAnnotations(),
805 builder.getArrayAttr(portAnnotations), mem.getInnerSymAttr(),
806 mem.getInitAttr(), mem.getPrefixAttr());
807 for (const auto &res : llvm::enumerate(oldResults))
808 res.value().replaceAllUsesWith(newMem.getResult(res.index()));
809 mem.erase();
810 }
811 opsToRemove.clear();
812 refPortsToRemoveMap.clear();
813 dataflowAt.clear();
814 refSendPathList.clear();
815 moduleStates.clear();
816 }
817
819
820private:
821 /// Cached module namespaces.
822 DenseMap<Operation *, hw::InnerSymbolNamespace> moduleNamespaces;
823
824 DenseSet<Operation *> visitedModules;
825 /// Map of a reference value to an entry into refSendPathList. Each entry in
826 /// refSendPathList represents the path to RefSend.
827 /// The path is required since there can be multiple paths to the RefSend and
828 /// we need to identify a unique path.
829 DenseMap<Value, size_t> dataflowAt;
830
831 /// refSendPathList is used to construct a path to the RefSendOp. Each entry
832 /// is an XMRNode, with an InnerRefAttr or indexing op, and a pointer to the
833 /// next node in the path. The InnerRefAttr can be to an InstanceOp or to the
834 /// XMR defining op, the index op records narrowing along path. All the nodes
835 /// representing an InstanceOp or indexing operation must have a valid
836 /// NextNodeOnPath. Only the node representing the final XMR defining op has
837 /// no NextNodeOnPath, which denotes a leaf node on the path.
838 SmallVector<XMRNode> refSendPathList;
839
840 llvm::EquivalenceClasses<Value> *dataFlowClasses;
841 // Instance and module ref ports that needs to be removed.
842 DenseMap<Operation *, llvm::BitVector> refPortsToRemoveMap;
843
844 /// RefResolve, RefSend, and Connects involving them that will be removed.
845 SmallVector<Operation *> opsToRemove;
846
847 /// Record the internal path to an external module or a memory.
848 DenseMap<size_t, SmallString<128>> xmrPathSuffix;
849
851
852 /// Utility to create HerPathOps at a predefined location in the circuit.
853 /// This handles caching and keeps the order consistent.
855
856 /// Per-module helpers for creating operations within modules.
857 DenseMap<FModuleOp, ModuleState> moduleStates;
858};
assert(baseType &&"element must be base type")
static mlir::Operation * resolve(Context &context, mlir::SymbolRefAttr sym)
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:822
llvm::EquivalenceClasses< Value > * dataFlowClasses
Definition LowerXMR.cpp:840
DenseMap< size_t, SmallString< 128 > > xmrPathSuffix
Record the internal path to an external module or a memory.
Definition LowerXMR.cpp:848
InnerRefAttr getInnerRefTo(Value val)
Definition LowerXMR.cpp:718
size_t addReachingSendsEntry(Value atRefVal, XMRNode::SymOrIndexOp info, std::optional< size_t > continueFrom=std::nullopt)
Definition LowerXMR.cpp:762
DenseMap< FModuleOp, ModuleState > moduleStates
Per-module helpers for creating operations within modules.
Definition LowerXMR.cpp:857
LogicalResult resolveReferencePath(mlir::TypedValue< RefType > refVal, ImplicitLocOpBuilder builder, mlir::FlatSymbolRefAttr &ref, SmallString< 128 > &stringLeaf)
Definition LowerXMR.cpp:432
DenseMap< Value, size_t > dataflowAt
Map of a reference value to an entry into refSendPathList.
Definition LowerXMR.cpp:829
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:714
void markForRemoval(Operation *op)
Definition LowerXMR.cpp:736
hw::HierPathCache * hierPathCache
Utility to create HerPathOps at a predefined location in the circuit.
Definition LowerXMR.cpp:854
void garbageCollect()
Definition LowerXMR.cpp:771
LogicalResult handlePublicModuleRefPorts(FModuleOp module)
Definition LowerXMR.cpp:658
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:552
DenseMap< Operation *, llvm::BitVector > refPortsToRemoveMap
Definition LowerXMR.cpp:842
SmallVector< XMRNode > refSendPathList
refSendPathList is used to construct a path to the RefSendOp.
Definition LowerXMR.cpp:838
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:738
DenseSet< Operation * > visitedModules
Definition LowerXMR.cpp:824
InnerRefAttr getInnerRefTo(Operation *op)
Definition LowerXMR.cpp:729
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:426
CircuitNamespace * circuitNamespace
Definition LowerXMR.cpp:850
bool isZeroWidth(FIRRTLBaseType t)
Definition LowerXMR.cpp:818
SmallVector< Operation * > opsToRemove
RefResolve, RefSend, and Connects involving them that will be removed.
Definition LowerXMR.cpp:845
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