CIRCT 22.0.0git
Loading...
Searching...
No Matches
LowerLayers.cpp
Go to the documentation of this file.
1//===- LowerLayers.cpp - Lower Layers by Convention -------------*- 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// This pass lowers FIRRTL layers based on their specified convention.
9//
10//===----------------------------------------------------------------------===//
11
21#include "circt/Support/Utils.h"
22#include "mlir/Pass/Pass.h"
23#include "llvm/ADT/PostOrderIterator.h"
24#include "llvm/ADT/SmallPtrSet.h"
25#include "llvm/Support/Debug.h"
26#include "llvm/Support/Mutex.h"
27
28#define DEBUG_TYPE "firrtl-lower-layers"
29
30namespace circt {
31namespace firrtl {
32#define GEN_PASS_DEF_LOWERLAYERS
33#include "circt/Dialect/FIRRTL/Passes.h.inc"
34} // namespace firrtl
35} // namespace circt
36
37using namespace circt;
38using namespace firrtl;
39
40namespace {
41
42/// Indicates the kind of reference that was captured.
43enum class ConnectKind {
44 /// A normal captured value. This is a read of a value outside the
45 /// layerblock.
46 NonRef,
47 /// A reference. This is a destination of a ref define.
48 Ref
49};
50
51struct ConnectInfo {
52 Value value;
53 ConnectKind kind;
54};
55
56/// The delimiters that should be used for a given generated name. These vary
57/// for modules and files, as well as by convention.
58enum class Delimiter { BindModule = '_', BindFile = '-', InlineMacro = '$' };
59
60/// This struct contains pre-allocated "safe" names that parallel regions can
61/// use to create names in the global namespace. This is allocated per-layer
62/// block.
63struct LayerBlockGlobals {
64 /// If the layer needs to create a module, use this name.
65 StringRef moduleName;
66
67 /// If the layer needs to create a hw::HierPathOp, use this name.
68 StringRef hierPathName;
69};
70
71} // namespace
72
73// A mapping of an old InnerRefAttr to the new inner symbol and module name that
74// need to be spliced into the old InnerRefAttr. This is used to fix
75// hierarchical path operations after layers are converted to modules.
77 DenseMap<hw::InnerRefAttr, std::pair<hw::InnerSymAttr, StringAttr>>;
78
79//===----------------------------------------------------------------------===//
80// Naming Helpers
81//===----------------------------------------------------------------------===//
82
83static void appendName(StringRef name, SmallString<32> &output,
84 bool toLower = false,
85 Delimiter delimiter = Delimiter::BindFile) {
86 if (name.empty())
87 return;
88 if (!output.empty())
89 output.push_back(static_cast<char>(delimiter));
90 output.append(name);
91 if (!toLower)
92 return;
93 auto i = output.size() - name.size();
94 output[i] = llvm::toLower(output[i]);
95}
96
97static void appendName(const ArrayRef<FlatSymbolRefAttr> &names,
98 SmallString<32> &output, bool toLower = false,
99 Delimiter delimiter = Delimiter::BindFile) {
100 for (auto name : names)
101 appendName(name.getValue(), output, toLower, delimiter);
102}
103
104static void appendName(SymbolRefAttr name, SmallString<32> &output,
105 bool toLower = false,
106 Delimiter delimiter = Delimiter::BindFile) {
107 appendName(name.getRootReference(), output, toLower, delimiter);
108 appendName(name.getNestedReferences(), output, toLower, delimiter);
109}
110
111/// For a layer `@A::@B::@C` in module Module,
112/// the generated module is called `Module_A_B_C`.
113static SmallString<32> moduleNameForLayer(StringRef moduleName,
114 SymbolRefAttr layerName) {
115 SmallString<32> result;
116 appendName(moduleName, result, /*toLower=*/false,
117 /*delimiter=*/Delimiter::BindModule);
118 appendName(layerName, result, /*toLower=*/false,
119 /*delimiter=*/Delimiter::BindModule);
120 return result;
121}
122
123static SmallString<32> hierPathNameForLayer(StringRef moduleName,
124 SymbolRefAttr layerName) {
125 SmallString<32> result("__lowerLayers_path");
126 appendName(moduleName, result, /*toLower=*/false,
127 /*delimiter=*/Delimiter::BindModule);
128 appendName(layerName, result, /*toLower=*/false,
129 /*delimiter=*/Delimiter::BindModule);
130 return result;
131}
132
133/// For a layerblock `@A::@B::@C`,
134/// the generated instance is called `a_b_c`.
135static SmallString<32> instanceNameForLayer(SymbolRefAttr layerName) {
136 SmallString<32> result;
137 appendName(layerName, result, /*toLower=*/true,
138 /*delimiter=*/Delimiter::BindModule);
139 return result;
140}
141
142static SmallString<32> fileNameForLayer(StringRef moduleName, StringAttr root,
143 ArrayRef<FlatSymbolRefAttr> nested) {
144 SmallString<32> result;
145 result.append("layers");
146 appendName(moduleName, result);
147 appendName(root, result);
148 appendName(nested, result);
149 result.append(".sv");
150 return result;
151}
152
153/// For all layerblocks `@A::@B::@C` in a module called Module,
154/// the output filename is `layers-Module-A-B-C.sv`.
155static SmallString<32> fileNameForLayer(StringRef moduleName,
156 SymbolRefAttr layerName) {
157 return fileNameForLayer(moduleName, layerName.getRootReference(),
158 layerName.getNestedReferences());
159}
160
161/// For all layerblocks `@A::@B::@C` in a module called Module,
162/// the include-guard macro is `layers_Module_A_B_C`.
163static SmallString<32> guardMacroNameForLayer(StringRef moduleName,
164 SymbolRefAttr layerName) {
165 SmallString<32> result;
166 result.append("layers");
167 appendName(moduleName, result, false, Delimiter::BindModule);
168 appendName(layerName, result, false, Delimiter::BindModule);
169 return result;
170}
171
172/// For a layerblock `@A::@B::@C`, the verilog macro is `A_B_C`.
173static SmallString<32>
174macroNameForLayer(StringRef circuitName,
175 ArrayRef<FlatSymbolRefAttr> layerName) {
176 SmallString<32> result("layer");
177 for (auto part : layerName)
178 appendName(part, result, /*toLower=*/false,
179 /*delimiter=*/Delimiter::InlineMacro);
180 return result;
181}
182
183//===----------------------------------------------------------------------===//
184// LowerLayersPass
185//===----------------------------------------------------------------------===//
186
187namespace {
188/// Information about each bind file we are emitting. During a prepass, we walk
189/// the modules to find layerblocks, creating an emit::FileOp for each bound
190/// layer used under each module. As we do this, we build a table of these info
191/// objects for quick lookup later.
192struct BindFileInfo {
193 /// The filename of the bind file _without_ a directory.
194 StringAttr filename;
195 /// Where to insert bind statements into the bind file.
196 Block *body;
197};
198} // namespace
199
201 : public circt::firrtl::impl::LowerLayersBase<LowerLayersPass> {
202 using Base::Base;
203
204 hw::OutputFileAttr getOutputFile(SymbolRefAttr layerName) {
205 auto layer = symbolToLayer.lookup(layerName);
206 if (!layer)
207 return nullptr;
208 return layer->getAttrOfType<hw::OutputFileAttr>("output_file");
209 }
210
211 hw::OutputFileAttr outputFileForLayer(StringRef moduleName,
212 SymbolRefAttr layerName) {
213 if (auto file = getOutputFile(layerName))
214 return hw::OutputFileAttr::getFromDirectoryAndFilename(
215 &getContext(), file.getDirectory(),
216 fileNameForLayer(moduleName, layerName),
217 /*excludeFromFileList=*/true);
218 return hw::OutputFileAttr::getFromFilename(
219 &getContext(), fileNameForLayer(moduleName, layerName),
220 /*excludeFromFileList=*/true);
221 }
222
223 /// Safely build a new module with a given namehint. This handles geting a
224 /// lock to modify the top-level circuit.
225 FModuleOp buildNewModule(OpBuilder &builder, LayerBlockOp layerBlock,
226 ArrayRef<PortInfo> ports);
227
228 /// Strip layer colors from the module's interface.
229 FailureOr<InnerRefMap> runOnModuleLike(FModuleLike moduleLike);
230
231 /// Extract layerblocks and strip probe colors from all ops under the module.
232 LogicalResult runOnModuleBody(FModuleOp moduleOp, InnerRefMap &innerRefMap);
233
234 /// Update the module's port types to remove any explicit layer requirements
235 /// from any probe types.
236 void removeLayersFromPorts(FModuleLike moduleLike);
237
238 /// Update the value's type to remove any layers from any probe types.
239 void removeLayersFromValue(Value value);
240
241 /// Lower an inline layerblock to an ifdef block.
242 void lowerInlineLayerBlock(LayerOp layer, LayerBlockOp layerBlock);
243
244 /// Build macro declarations and cache information about the layers.
245 void preprocessLayers(CircuitNamespace &ns, OpBuilder &b, LayerOp layer,
246 StringRef circuitName,
247 SmallVector<FlatSymbolRefAttr> &stack);
249
250 /// For each module, build a bindfile for each bound-layer, if needed.
252
253 /// Build the bindfile skeletons for each module. Set up a table which tells
254 /// us for each module/layer pair, where to insert the bind operations.
256
257 /// Build the bindfile skeleton for a module.
259 FModuleOp module);
260
261 /// Record the supposed bindfiles for any known layers of the ext module.
263 FExtModuleOp extModule);
264
265 /// Build a bindfile skeleton for a particular module and layer.
267 OpBuilder &b, SymbolRefAttr layerName, LayerOp layer);
268
269 /// Entry point for the function.
270 void runOnOperation() override;
271
272 /// Indicates exclusive access to modify the circuitNamespace and the circuit.
273 llvm::sys::SmartMutex<true> *circuitMutex;
274
275 /// A map of layer blocks to "safe" global names which are fine to create in
276 /// the circuit namespace.
277 DenseMap<LayerBlockOp, LayerBlockGlobals> layerBlockGlobals;
278
279 /// A map from inline layers to their macro names.
280 DenseMap<LayerOp, FlatSymbolRefAttr> macroNames;
281
282 /// A mapping of symbol name to layer operation. This also serves as an
283 /// iterable list of all layers declared in a circuit. We use a map vector so
284 /// that the iteration order matches the order of declaration in the circuit.
285 /// This order is not required for correctness, it helps with legibility.
286 llvm::MapVector<SymbolRefAttr, LayerOp> symbolToLayer;
287
288 /// Utility for creating hw::HierPathOp.
290
291 /// A mapping from module*layer to bindfile name.
292 DenseMap<Operation *, DenseMap<LayerOp, BindFileInfo>> bindFiles;
293};
294
295/// Multi-process safe function to build a module in the circuit and return it.
296/// The name provided is only a namehint for the module---a unique name will be
297/// generated if there are conflicts with the namehint in the circuit-level
298/// namespace.
299FModuleOp LowerLayersPass::buildNewModule(OpBuilder &builder,
300 LayerBlockOp layerBlock,
301 ArrayRef<PortInfo> ports) {
302 auto location = layerBlock.getLoc();
303 auto namehint = layerBlockGlobals.lookup(layerBlock).moduleName;
304 llvm::sys::SmartScopedLock<true> instrumentationLock(*circuitMutex);
305 FModuleOp newModule = FModuleOp::create(
306 builder, location, builder.getStringAttr(namehint),
307 ConventionAttr::get(builder.getContext(), Convention::Internal), ports,
308 ArrayAttr{});
309 if (auto dir = getOutputFile(layerBlock.getLayerNameAttr())) {
310 assert(dir.isDirectory());
311 newModule->setAttr("output_file", dir);
312 }
313 SymbolTable::setSymbolVisibility(newModule, SymbolTable::Visibility::Private);
314 return newModule;
315}
316
318 auto type = dyn_cast<RefType>(value.getType());
319 if (!type || !type.getLayer())
320 return;
321 value.setType(type.removeLayer());
322}
323
324void LowerLayersPass::removeLayersFromPorts(FModuleLike moduleLike) {
325 auto oldTypeAttrs = moduleLike.getPortTypesAttr();
326 SmallVector<Attribute> newTypeAttrs;
327 newTypeAttrs.reserve(oldTypeAttrs.size());
328 bool changed = false;
329
330 for (auto typeAttr : oldTypeAttrs.getAsRange<TypeAttr>()) {
331 if (auto refType = dyn_cast<RefType>(typeAttr.getValue())) {
332 if (refType.getLayer()) {
333 typeAttr = TypeAttr::get(refType.removeLayer());
334 changed = true;
335 }
336 }
337 newTypeAttrs.push_back(typeAttr);
338 }
339
340 if (!changed)
341 return;
342
343 moduleLike.setPortTypesAttr(
344 ArrayAttr::get(moduleLike.getContext(), newTypeAttrs));
345
346 if (auto moduleOp = dyn_cast<FModuleOp>(moduleLike.getOperation())) {
347 for (auto arg : moduleOp.getBodyBlock()->getArguments())
349 }
350}
351
352FailureOr<InnerRefMap>
353LowerLayersPass::runOnModuleLike(FModuleLike moduleLike) {
354 LLVM_DEBUG({
355 llvm::dbgs() << "Module: " << moduleLike.getModuleName() << "\n";
356 llvm::dbgs() << " Examining Layer Blocks:\n";
357 });
358
359 // Strip away layers from the interface of the module-like op.
360 InnerRefMap innerRefMap;
361 auto result =
362 TypeSwitch<Operation *, LogicalResult>(moduleLike.getOperation())
363 .Case<FModuleOp>([&](auto op) {
364 op.setLayers({});
366 return runOnModuleBody(op, innerRefMap);
367 })
368 .Case<FExtModuleOp>([&](auto op) {
369 op.setKnownLayers({});
370 op.setLayers({});
372 return success();
373 })
374 .Case<FIntModuleOp, FMemModuleOp>([&](auto op) {
375 op.setLayers({});
377 return success();
378 })
379 .Case<ClassOp, ExtClassOp>([](auto) { return success(); })
380 .Default(
381 [](auto *op) { return op->emitError("unknown module-like op"); });
382
383 if (failed(result))
384 return failure();
385
386 return innerRefMap;
387}
388
390 LayerBlockOp layerBlock) {
391 if (!layerBlock.getBody()->empty()) {
392 OpBuilder builder(layerBlock);
393 auto macroName = macroNames[layer];
394 auto ifDef = sv::IfDefOp::create(builder, layerBlock.getLoc(), macroName);
395 ifDef.getBodyRegion().takeBody(layerBlock.getBodyRegion());
396 }
397 layerBlock.erase();
398}
399
400LogicalResult LowerLayersPass::runOnModuleBody(FModuleOp moduleOp,
401 InnerRefMap &innerRefMap) {
402 hw::InnerSymbolNamespace ns(moduleOp);
403
404 // A cache of values to nameable ops that can be used
405 DenseMap<Value, Operation *> nodeCache;
406
407 // Get or create a node op for a value captured by a layer block.
408 auto getOrCreateNodeOp = [&](Value operand,
409 ImplicitLocOpBuilder &builder) -> Operation * {
410 // Use the cache hit.
411 auto *nodeOp = nodeCache.lookup(operand);
412 if (nodeOp)
413 return nodeOp;
414
415 // Create a new node. Put it in the cache and use it.
416 OpBuilder::InsertionGuard guard(builder);
417 builder.setInsertionPointAfterValue(operand);
418 SmallString<16> nameHint;
419 // Try to generate a "good" name hint to use for the node.
420 if (auto *definingOp = operand.getDefiningOp()) {
421 if (auto instanceOp = dyn_cast<InstanceOp>(definingOp)) {
422 nameHint.append(instanceOp.getName());
423 nameHint.push_back('_');
424 nameHint.append(
425 instanceOp.getPortName(cast<OpResult>(operand).getResultNumber()));
426 } else if (auto opName = definingOp->getAttrOfType<StringAttr>("name")) {
427 nameHint.append(opName);
428 }
429 }
430 return nodeOp = NodeOp::create(builder, operand.getLoc(), operand,
431 nameHint.empty() ? "_layer_probe"
432 : StringRef(nameHint));
433 };
434
435 // Determine the replacement for an operand within the current region. Keep a
436 // densemap of replacements around to avoid creating the same hardware
437 // multiple times.
438 DenseMap<Value, Value> replacements;
439 auto getReplacement = [&](Operation *user, Value value) -> Value {
440 auto it = replacements.find(value);
441 if (it != replacements.end())
442 return it->getSecond();
443
444 ImplicitLocOpBuilder localBuilder(value.getLoc(), &getContext());
445 Value replacement;
446
447 auto layerBlockOp = user->getParentOfType<LayerBlockOp>();
448 localBuilder.setInsertionPointToStart(layerBlockOp.getBody());
449
450 // If the operand is "special", e.g., it has no XMR representation, then we
451 // need to clone it.
452 //
453 // TODO: Change this to recursively clone. This will matter once FString
454 // operations have operands.
455 if (type_isa<FStringType>(value.getType())) {
456 localBuilder.setInsertionPoint(user);
457 replacement = localBuilder.clone(*value.getDefiningOp())->getResult(0);
458 replacements.insert({value, replacement});
459 return replacement;
460 }
461
462 // If the operand is an XMR ref, then we _have_ to clone it.
463 auto *definingOp = value.getDefiningOp();
464 if (isa_and_present<XMRRefOp>(definingOp)) {
465 replacement = localBuilder.clone(*definingOp)->getResult(0);
466 replacements.insert({value, replacement});
467 return replacement;
468 }
469
470 // Determine the replacement value for the captured operand. There are
471 // three cases that can occur:
472 //
473 // 1. Capturing something zero-width. Create a zero-width constant zero.
474 // 2. Capture an expression or instance port. Drop a node and XMR deref
475 // that.
476 // 3. Capture something that can handle an inner sym. XMR deref that.
477 //
478 // Note: (3) can be either an operation or a _module_ port.
479 auto baseType = type_cast<FIRRTLBaseType>(value.getType());
480 if (baseType && baseType.getBitWidthOrSentinel() == 0) {
481 OpBuilder::InsertionGuard guard(localBuilder);
482 auto zeroUIntType = UIntType::get(localBuilder.getContext(), 0);
483 replacement = localBuilder.createOrFold<BitCastOp>(
484 value.getType(), ConstantOp::create(localBuilder, zeroUIntType,
485 getIntZerosAttr(zeroUIntType)));
486 } else {
487 auto *definingOp = value.getDefiningOp();
488 hw::InnerRefAttr innerRef;
489 if (definingOp) {
490 // Always create a node. This is a trade-off between optimizations and
491 // dead code. By adding the node, this allows the original path to be
492 // better optimized, but will leave dead code in the design. If the
493 // node is not created, then the output is less optimized. Err on the
494 // side of dead code. This dead node _may_ be eventually inlined by
495 // `ExportVerilog`. However, this is not guaranteed.
496 definingOp = getOrCreateNodeOp(value, localBuilder);
497 innerRef = getInnerRefTo(
498 definingOp, [&](auto) -> hw::InnerSymbolNamespace & { return ns; });
499 } else {
500 auto portIdx = cast<BlockArgument>(value).getArgNumber();
501 innerRef = getInnerRefTo(
502 cast<FModuleLike>(*moduleOp), portIdx,
503 [&](auto) -> hw::InnerSymbolNamespace & { return ns; });
504 }
505
506 hw::HierPathOp hierPathOp;
507 {
508 // TODO: Move to before parallel region to avoid the lock.
509 auto insertPoint = OpBuilder::InsertPoint(moduleOp->getBlock(),
510 Block::iterator(moduleOp));
511 llvm::sys::SmartScopedLock<true> circuitLock(*circuitMutex);
512 hierPathOp = hierPathCache->getOrCreatePath(
513 localBuilder.getArrayAttr({innerRef}), localBuilder.getLoc(),
514 insertPoint, layerBlockGlobals.lookup(layerBlockOp).hierPathName);
515 hierPathOp.setVisibility(SymbolTable::Visibility::Private);
516 }
517
518 replacement = XMRDerefOp::create(localBuilder, value.getType(),
519 hierPathOp.getSymNameAttr());
520 }
521
522 replacements.insert({value, replacement});
523
524 return replacement;
525 };
526
527 // A map of instance ops to modules that this pass creates. This is used to
528 // check if this was an instance that we created and to do fast module
529 // dereferencing (avoiding a symbol table).
530 DenseMap<Operation *, FModuleOp> createdInstances;
531
532 // Check that the preconditions for this pass are met. Reject any ops which
533 // must have been removed before this runs.
534 auto opPreconditionCheck = [](Operation *op) -> LogicalResult {
535 // LowerXMR op removal postconditions.
536 if (isa<RefCastOp, RefDefineOp, RefResolveOp, RefSendOp, RefSubOp,
537 RWProbeOp>(op))
538 return op->emitOpError()
539 << "cannot be handled by the lower-layers pass. This should have "
540 "already been removed by the lower-xmr pass.";
541
542 return success();
543 };
544
545 // Utility to determine the domain type of some value. This looks backwards
546 // through connections to find the source driver in the module and gets the
547 // domain type of that. This is necessary as intermediary wires do not track
548 // domain information.
549 //
550 // This cannot use `getModuleScopedDriver` because this can be called while
551 // `LayerBlockOp`s have temporarily gained block arguments while they are
552 // being migrated to modules. This is worked around by caching the known
553 // domain kinds of earlier-visited `WireOp`s to avoid needing to look through
554 // these non-`ModuleOp` block arguments.
555 //
556 // TODO: Simplify this once wires have domain kind information [1].
557 //
558 // [1]: https://github.com/llvm/circt/issues/9398
559 DenseMap<Operation *, Attribute> domainMap;
560 auto getDomain = [&domainMap](Value value,
561 Attribute &domain) -> LogicalResult {
562 SmallVector<Operation *> wires;
563
564 // Use iteration as this is recursive over the IR. `value` is changed for
565 // each iteration.
566 while (!domain) {
567 if (auto arg = dyn_cast<BlockArgument>(value)) {
568 domain = cast<FModuleLike>(arg.getOwner()->getParentOp())
569 .getDomainInfoAttrForPort(arg.getArgNumber());
570 continue;
571 }
572
573 auto result =
574 TypeSwitch<Operation *, LogicalResult>(value.getDefiningOp())
575 .Case<WireOp>([&](WireOp op) {
576 auto it = domainMap.find(op);
577 if (it != domainMap.end()) {
578 domain = it->getSecond();
579 return success();
580 }
581 for (auto *user : op->getUsers()) {
582 auto connect = dyn_cast<FConnectLike>(user);
583 if (!connect || connect.getDest() != value)
584 continue;
585 value = connect.getSrc();
586 wires.push_back(op);
587 return success();
588 }
589 emitError(value.getLoc())
590 << "unable to determine domain kind for source likely "
591 "indicating a "
592 "violation of static-single-connect";
593 return failure();
594 })
595 .Case<InstanceOp>([&](auto op) {
596 domain =
597 op.getPortDomain(cast<OpResult>(value).getResultNumber());
598 return success();
599 })
600 .Case<DomainCreateAnonOp>([&](auto op) {
601 domain = op.getDomainAttr();
602 return success();
603 })
604 .Default([&](auto op) {
605 op->emitOpError() << "unhandled domain source in 'LowerLayers";
606 return failure();
607 });
608 if (failed(result))
609 return failure();
610 }
611
612 // Update the `domainMap` with wire/domain information.
613 for (auto *wire : wires)
614 domainMap[wire] = domain;
615
616 return success();
617 };
618
619 // Post-order traversal that expands a layer block into its parent. Because of
620 // the pass precondition that this runs _after_ `LowerXMR`, not much has to
621 // happen here, other than for domain information. All of the following do
622 // happen, though:
623 //
624 // 1. Any layer coloring is stripped.
625 // 2. Layers with Inline convention are converted to SV ifdefs.
626 // 3. Layers with Bind convention are converted to new modules and then
627 // instantiated at their original location. Any captured values are either
628 // moved, cloned, or converted to XMR deref ops.
629 // 4. Move instances created from earlier (3) conversions out of later (3)
630 // conversions. This is necessary to avoid a SystemVerilog-illegal
631 // bind-under-bind. (See Section 23.11 of 1800-2023.)
632 // 5. Keep track of special ops (ops with inner symbols or verbatims) which
633 // need to have something updated because of the new instance hierarchy
634 // being created.
635 // 6. Any captured domain information result in input/output ports being
636 // created and these being hooked up when new modules are instantiated.
637 //
638 // Remember, this is post-order, in-order. Child layer blocks are visited
639 // before parents. Any nested regions _within_ the layer block are also
640 // visited before the outer layer block.
641 auto result = moduleOp.walk<mlir::WalkOrder::PostOrder>([&](Operation *op) {
642 if (failed(opPreconditionCheck(op)))
643 return WalkResult::interrupt();
644
645 // Strip layer requirements from any op that might represent a probe.
646 for (auto result : op->getResults())
647 removeLayersFromValue(result);
648
649 // If the op is an instance, clear the enablelayers attribute.
650 if (auto instance = dyn_cast<InstanceOp>(op))
651 instance.setLayers({});
652
653 auto layerBlock = dyn_cast<LayerBlockOp>(op);
654 if (!layerBlock)
655 return WalkResult::advance();
656
657 // After this point, we are dealing with a layer block.
658 auto layer = symbolToLayer.lookup(layerBlock.getLayerName());
659
660 if (layer.getConvention() == LayerConvention::Inline) {
661 lowerInlineLayerBlock(layer, layerBlock);
662 return WalkResult::advance();
663 }
664
665 // After this point, we are dealing with a bind convention layer block.
666 assert(layer.getConvention() == LayerConvention::Bind);
667
668 // Utilities and mutable state that results from creating ports. Due to the
669 // way in which this pass works and its phase ordering, the only types of
670 // ports that can be created are domain type ports.
671 SmallVector<PortInfo> ports;
672 SmallVector<Value> connectValues;
673 Namespace portNs;
674
675 // Create an input port for a domain-type operand. The source is not in the
676 // current layer block.
677 auto createInputPort = [&](Value src, Location loc) -> LogicalResult {
678 Attribute domain;
679 if (failed(getDomain(src, domain)))
680 return failure();
681
682 StringAttr name;
683 auto [nameHint, rootKnown] = getFieldName(FieldRef(src, 0), true);
684 if (rootKnown)
685 name = StringAttr::get(src.getContext(), portNs.newName(nameHint));
686 else
687 name = StringAttr::get(src.getContext(), portNs.newName("anonDomain"));
688 PortInfo port(
689 /*name=*/name,
690 /*type=*/src.getType(),
691 /*dir=*/Direction::In,
692 /*symName=*/{},
693 /*location=*/loc,
694 /*annos=*/{},
695 /*domains=*/domain);
696 ports.push_back(port);
697 connectValues.push_back(src);
698 BlockArgument replacement =
699 layerBlock.getBody()->addArgument(port.type, port.loc);
700 src.replaceUsesWithIf(replacement, [&](OpOperand &use) {
701 auto *user = use.getOwner();
702 if (!layerBlock->isAncestor(user))
703 return false;
704 // Replace if the connection source is the src and if the destination is
705 // _not_ in this layer block. If the destination is a spilled or
706 // to-be-spilled instance, then do not replace this connection as it
707 // will _later_ be spilled.
708 if (auto connectLike = dyn_cast<FConnectLike>(user)) {
709 auto *destDefiningOp = connectLike.getDest().getDefiningOp();
710 return connectLike.getSrc() == src &&
711 !createdInstances.contains(destDefiningOp);
712 }
713 return false;
714 });
715 return success();
716 };
717
718 // Set the location intelligently. Use the location of the capture if this
719 // is a port created for forwarding from a parent layer block to a nested
720 // layer block. Otherwise, use unknown.
721 auto getPortLoc = [&](Value port) -> Location {
722 Location loc = UnknownLoc::get(port.getContext());
723 if (auto *destOp = port.getDefiningOp())
724 if (auto instOp = dyn_cast<InstanceOp>(destOp)) {
725 auto modOpIt = createdInstances.find(instOp);
726 if (modOpIt != createdInstances.end()) {
727 auto portNum = cast<OpResult>(port).getResultNumber();
728 loc = modOpIt->getSecond().getPortLocation(portNum);
729 }
730 }
731 return loc;
732 };
733
734 // Source is in the current layer block. The destination is not in the
735 // current layer block.
736 auto createOutputPort = [&](Value src, Value dest) -> LogicalResult {
737 Attribute domain;
738 if (failed(getDomain(src, domain)))
739 return failure();
740
741 StringAttr name;
742 auto [nameHint, rootKnown] = getFieldName(FieldRef(src, 0), true);
743 if (rootKnown)
744 name = StringAttr::get(src.getContext(), portNs.newName(nameHint));
745 else
746 name = StringAttr::get(src.getContext(), portNs.newName("anonDomain"));
747 PortInfo port(
748 /*name=*/name,
749 /*type=*/src.getType(),
750 /*dir=*/Direction::Out,
751 /*symName=*/{},
752 /*location=*/getPortLoc(dest),
753 /*annos=*/{},
754 /*domains=*/domain);
755 ports.push_back(port);
756 connectValues.push_back(dest);
757 BlockArgument replacement =
758 layerBlock.getBody()->addArgument(port.type, port.loc);
759 dest.replaceUsesWithIf(replacement, [&](OpOperand &use) {
760 auto *user = use.getOwner();
761 if (!layerBlock->isAncestor(user))
762 return false;
763 // Replace connection destinations.
764 if (auto connectLike = dyn_cast<FConnectLike>(user))
765 return connectLike.getDest() == dest;
766 return false;
767 });
768 return success();
769 };
770
771 // Clear the replacements so that none are re-used across layer blocks.
772 replacements.clear();
773 OpBuilder builder(moduleOp);
774 SmallVector<hw::InnerSymAttr> innerSyms;
775 SmallVector<sv::VerbatimOp> verbatims;
776 DenseSet<Operation *> spilledSubOps;
777 auto layerBlockWalkResult = layerBlock.walk([&](Operation *op) {
778 // Error if pass preconditions are not met.
779 if (failed(opPreconditionCheck(op)))
780 return WalkResult::interrupt();
781
782 // Specialized handling of subfields, subindexes, and subaccesses which
783 // need to be spilled and nodes that referred to spilled nodes. If these
784 // are kept in the module, then the XMR is going to be bidirectional. Fix
785 // this for subfield and subindex by moving these ops outside the
786 // layerblock. Try to fix this for subaccess and error if the move can't
787 // be made because the index is defined inside the layerblock. (This case
788 // is exceedingly rare given that subaccesses are almost always unexepcted
789 // when this pass runs.) Additionally, if any nodes are seen that are
790 // transparently referencing a spilled op, spill the node, too. The node
791 // provides an anchor for an inner symbol (which subfield, subindex, and
792 // subaccess do not).
793 auto fixSubOp = [&](auto subOp) {
794 auto input = subOp.getInput();
795
796 // If the input is defined in this layerblock, we are done.
797 if (isAncestorOfValueOwner(layerBlock, input))
798 return WalkResult::advance();
799
800 // Otherwise, capture the input operand, if possible.
801 if (firrtl::type_cast<FIRRTLBaseType>(input.getType()).isPassive()) {
802 subOp.getInputMutable().assign(getReplacement(subOp, input));
803 return WalkResult::advance();
804 }
805
806 // Otherwise, move the subfield op out of the layerblock.
807 op->moveBefore(layerBlock);
808 spilledSubOps.insert(op);
809 return WalkResult::advance();
810 };
811
812 if (auto subOp = dyn_cast<SubfieldOp>(op))
813 return fixSubOp(subOp);
814
815 if (auto subOp = dyn_cast<SubindexOp>(op))
816 return fixSubOp(subOp);
817
818 if (auto subOp = dyn_cast<SubaccessOp>(op)) {
819 auto input = subOp.getInput();
820 auto index = subOp.getIndex();
821
822 // If the input is defined in this layerblock, capture the index if
823 // needed, and we are done.
824 if (isAncestorOfValueOwner(layerBlock, input)) {
825 if (!isAncestorOfValueOwner(layerBlock, index)) {
826 subOp.getIndexMutable().assign(getReplacement(subOp, index));
827 }
828 return WalkResult::advance();
829 }
830
831 // Otherwise, capture the input operand, if possible.
832 if (firrtl::type_cast<FIRRTLBaseType>(input.getType()).isPassive()) {
833 subOp.getInputMutable().assign(getReplacement(subOp, input));
834 if (!isAncestorOfValueOwner(layerBlock, index))
835 subOp.getIndexMutable().assign(getReplacement(subOp, index));
836 return WalkResult::advance();
837 }
838
839 // Otherwise, move the subaccess op out of the layerblock, if possible.
840 if (!isAncestorOfValueOwner(layerBlock, index)) {
841 subOp->moveBefore(layerBlock);
842 spilledSubOps.insert(op);
843 return WalkResult::advance();
844 }
845
846 // When the input is not passive, but the index is defined inside this
847 // layerblock, we are out of options.
848 auto diag = op->emitOpError()
849 << "has a non-passive operand and captures a value defined "
850 "outside its enclosing bind-convention layerblock. The "
851 "'LowerLayers' pass cannot lower this as it would "
852 "create an output port on the resulting module.";
853 diag.attachNote(layerBlock.getLoc())
854 << "the layerblock is defined here";
855 return WalkResult::interrupt();
856 }
857
858 if (auto nodeOp = dyn_cast<NodeOp>(op)) {
859 auto *definingOp = nodeOp.getInput().getDefiningOp();
860 if (definingOp &&
861 spilledSubOps.contains(nodeOp.getInput().getDefiningOp())) {
862 op->moveBefore(layerBlock);
863 return WalkResult::advance();
864 }
865 }
866
867 // Record any operations inside the layer block which have inner symbols.
868 // Theses may have symbol users which need to be updated.
869 //
870 // Note: this needs to _not_ index spilled NodeOps above.
871 if (auto symOp = dyn_cast<hw::InnerSymbolOpInterface>(op))
872 if (auto innerSym = symOp.getInnerSymAttr())
873 innerSyms.push_back(innerSym);
874
875 // Handle instance ops that were created from nested layer blocks. These
876 // ops need to be moved outside the layer block to avoid nested binds.
877 // Nested binds are illegal in the SystemVerilog specification (and
878 // checked by FIRRTL verification).
879 //
880 // For each value defined in this layer block which drives a port of one
881 // of these instances, create an output reference type port on the
882 // to-be-created module and drive it with the value. Move the instance
883 // outside the layer block. We will hook it up later once we replace the
884 // layer block with an instance.
885 if (auto instOp = dyn_cast<InstanceOp>(op)) {
886 // Ignore instances which this pass did not create.
887 if (!createdInstances.contains(instOp))
888 return WalkResult::advance();
889
890 LLVM_DEBUG({
891 llvm::dbgs()
892 << " Found instance created from nested layer block:\n"
893 << " module: " << instOp.getModuleName() << "\n"
894 << " instance: " << instOp.getName() << "\n";
895 });
896 instOp->moveBefore(layerBlock);
897 return WalkResult::advance();
898 }
899
900 // Handle domain define ops. The destination must be within the current
901 // layer block. The source may be outside it. These, unlike other XMR
902 // captures, need to create ports as there is no XMR representation for
903 // domains. When creating these, look through any intermediate wires as
904 // these need to know the domain kind when creating the port and wires do
905 // not presently have this.
906 //
907 // TODO: Stop looking through wires when wires support domain info [1].
908 //
909 // [1]: https://github.com/llvm/circt/issues/9398
910 if (auto domainDefineOp = dyn_cast<DomainDefineOp>(op)) {
911 auto src = domainDefineOp.getSrc();
912 auto dest = domainDefineOp.getDest();
913 auto srcInLayerBlock = isAncestorOfValueOwner(layerBlock, src);
914 auto destInLayerBlock = isAncestorOfValueOwner(layerBlock, dest);
915
916 if (srcInLayerBlock) {
917 // The source and destination are in the current block. Do nothing.
918 if (destInLayerBlock)
919 return WalkResult::advance();
920 // The source is in the current layer block, but the destination is
921 // outside it. This is not possible except in situations where we
922 // have moved an instance out of the layer block. I.e., this is due
923 // to a child layer (which has already been processed) capturing
924 // something from the current layer block.
925 return WalkResult(createOutputPort(src, dest));
926 }
927
928 // The source is _not_ in the current block. Create an input domain
929 // type port with the right kind. To find the right kind, we need to
930 // look through wires to the original source.
931 if (destInLayerBlock)
932 return WalkResult(createInputPort(src, domainDefineOp.getLoc()));
933
934 // The source and destination are outside the layer block. Bubble this
935 // up. Note: this code is only reachable for situations where a prior
936 // instance, created from a bind layer has been bubbled up. This flavor
937 // of construction is otherwise illegal.
938 domainDefineOp->moveBefore(layerBlock);
939 return WalkResult::advance();
940 }
941
942 // Handle captures. For any captured operands, convert them to a suitable
943 // replacement value. The `getReplacement` function will automatically
944 // reuse values whenever possible.
945 for (size_t i = 0, e = op->getNumOperands(); i != e; ++i) {
946 auto operand = op->getOperand(i);
947
948 // If the operand is in this layer block, do nothing.
949 //
950 // Note: This check is what avoids handling ConnectOp destinations.
951 if (isAncestorOfValueOwner(layerBlock, operand))
952 continue;
953
954 op->setOperand(i, getReplacement(op, operand));
955 }
956
957 if (auto verbatim = dyn_cast<sv::VerbatimOp>(op))
958 verbatims.push_back(verbatim);
959
960 return WalkResult::advance();
961 });
962
963 if (layerBlockWalkResult.wasInterrupted())
964 return WalkResult::interrupt();
965
966 // If the layer block is empty, erase it instead of creating an empty
967 // module. Note: empty leaf layer blocks will be erased by canonicalizers.
968 // We don't expect to see these here. However, this handles the case of
969 // empty intermediary layer blocks which are important in the layer block
970 // representation, but can disappear when lowered to modules.
971 if (llvm::all_of(layerBlock.getRegion().getBlocks(),
972 [](auto &a) { return a.empty(); })) {
973 assert(verbatims.empty());
974 layerBlock.erase();
975 return WalkResult::advance();
976 }
977
978 // Create the new module. This grabs a lock to modify the circuit.
979 FModuleOp newModule = buildNewModule(builder, layerBlock, ports);
980 newModule.getBody().takeBody(layerBlock.getRegion());
981 SymbolTable::setSymbolVisibility(newModule,
982 SymbolTable::Visibility::Private);
983
984 LLVM_DEBUG({
985 llvm::dbgs() << " New Module: "
986 << layerBlockGlobals.lookup(layerBlock).moduleName << "\n";
987 llvm::dbgs() << " ports:\n";
988 for (size_t i = 0, e = ports.size(); i != e; ++i) {
989 auto port = ports[i];
990 auto value = connectValues[i];
991 llvm::dbgs() << " - name: " << port.getName() << "\n"
992 << " type: " << port.type << "\n"
993 << " direction: " << port.direction << "\n"
994 << " value: " << value << "\n";
995 }
996 });
997
998 // Replace the original layer block with an instance. Hook up the
999 // instance. Intentionally create instance with probe ports which do
1000 // not have an associated layer. This is illegal IR that will be
1001 // made legal by the end of the pass. This is done to avoid having
1002 // to revisit and rewrite each instance everytime it is moved into a
1003 // parent layer.
1004 builder.setInsertionPointAfter(layerBlock);
1005 auto instanceName = instanceNameForLayer(layerBlock.getLayerName());
1006 auto innerSym =
1007 hw::InnerSymAttr::get(builder.getStringAttr(ns.newName(instanceName)));
1008
1009 auto instanceOp = InstanceOp::create(
1010 builder, layerBlock.getLoc(), /*moduleName=*/newModule,
1011 /*name=*/
1012 instanceName, NameKindEnum::DroppableName,
1013 /*annotations=*/ArrayRef<Attribute>{},
1014 /*portAnnotations=*/ArrayRef<Attribute>{}, /*lowerToBind=*/false,
1015 /*doNotPrint=*/true, innerSym);
1016 for (auto [lhs, rhs] : llvm::zip(instanceOp.getResults(), connectValues))
1017 if (instanceOp.getPortDirection(lhs.getResultNumber()) == Direction::In)
1018 DomainDefineOp::create(builder, builder.getUnknownLoc(), lhs, rhs);
1019 else {
1020 DomainDefineOp::create(builder, builder.getUnknownLoc(), rhs, lhs);
1021 }
1022
1023 auto outputFile = outputFileForLayer(moduleOp.getModuleNameAttr(),
1024 layerBlock.getLayerName());
1025 instanceOp->setAttr("output_file", outputFile);
1026
1027 createdInstances.try_emplace(instanceOp, newModule);
1028
1029 // create the bind op.
1030 {
1031 auto builder = OpBuilder::atBlockEnd(bindFiles[moduleOp][layer].body);
1032 BindOp::create(builder, layerBlock.getLoc(), moduleOp.getModuleNameAttr(),
1033 instanceOp.getInnerSymAttr().getSymName());
1034 }
1035
1036 LLVM_DEBUG(llvm::dbgs() << " moved inner refs:\n");
1037 for (hw::InnerSymAttr innerSym : innerSyms) {
1038 auto oldInnerRef = hw::InnerRefAttr::get(moduleOp.getModuleNameAttr(),
1039 innerSym.getSymName());
1040 auto splice = std::make_pair(instanceOp.getInnerSymAttr(),
1041 newModule.getModuleNameAttr());
1042 innerRefMap.insert({oldInnerRef, splice});
1043 LLVM_DEBUG(llvm::dbgs() << " - ref: " << oldInnerRef << "\n"
1044 << " splice: " << splice.first << ", "
1045 << splice.second << "\n";);
1046 }
1047
1048 // Update verbatims that target operations extracted alongside.
1049 if (!verbatims.empty()) {
1050 mlir::AttrTypeReplacer replacer;
1051 replacer.addReplacement(
1052 [&innerRefMap](hw::InnerRefAttr ref) -> std::optional<Attribute> {
1053 auto it = innerRefMap.find(ref);
1054 if (it != innerRefMap.end())
1055 return hw::InnerRefAttr::get(it->second.second, ref.getName());
1056 return std::nullopt;
1057 });
1058 for (auto verbatim : verbatims)
1059 replacer.replaceElementsIn(verbatim);
1060 }
1061
1062 layerBlock.erase();
1063
1064 return WalkResult::advance();
1065 });
1066 return success(!result.wasInterrupted());
1067}
1068
1070 LayerOp layer, StringRef circuitName,
1071 SmallVector<FlatSymbolRefAttr> &stack) {
1072 stack.emplace_back(FlatSymbolRefAttr::get(layer.getSymNameAttr()));
1073 ArrayRef stackRef(stack);
1074 symbolToLayer.insert(
1075 {SymbolRefAttr::get(stackRef.front().getAttr(), stackRef.drop_front()),
1076 layer});
1077 if (layer.getConvention() == LayerConvention::Inline) {
1078 auto *ctx = &getContext();
1079 auto macName = macroNameForLayer(circuitName, stack);
1080 auto symName = ns.newName(macName);
1081
1082 auto symNameAttr = StringAttr::get(ctx, symName);
1083 auto macNameAttr = StringAttr();
1084 if (macName != symName)
1085 macNameAttr = StringAttr::get(ctx, macName);
1086
1087 sv::MacroDeclOp::create(b, layer->getLoc(), symNameAttr, ArrayAttr(),
1088 macNameAttr);
1089 macroNames[layer] = FlatSymbolRefAttr::get(&getContext(), symNameAttr);
1090 }
1091 for (auto child : layer.getOps<LayerOp>())
1092 preprocessLayers(ns, b, child, circuitName, stack);
1093 stack.pop_back();
1094}
1095
1097 auto circuit = getOperation();
1098 auto circuitName = circuit.getName();
1099 for (auto layer : circuit.getOps<LayerOp>()) {
1100 OpBuilder b(layer);
1101 SmallVector<FlatSymbolRefAttr> stack;
1102 preprocessLayers(ns, b, layer, circuitName, stack);
1103 }
1104}
1105
1107 InstanceGraphNode *node, OpBuilder &b,
1108 SymbolRefAttr layerName, LayerOp layer) {
1109 assert(layer.getConvention() == LayerConvention::Bind);
1110 auto module = node->getModule<FModuleOp>();
1111 auto loc = module.getLoc();
1112
1113 // Compute the include guard macro name.
1114 auto macroName = guardMacroNameForLayer(module.getModuleName(), layerName);
1115 auto macroSymbol = ns.newName(macroName);
1116 auto macroNameAttr = StringAttr::get(&getContext(), macroName);
1117 auto macroSymbolAttr = StringAttr::get(&getContext(), macroSymbol);
1118 auto macroSymbolRefAttr = FlatSymbolRefAttr::get(macroSymbolAttr);
1119
1120 // Compute the base name for the bind file.
1121 auto bindFileName = fileNameForLayer(module.getName(), layerName);
1122
1123 // Build the full output path using the filename of the bindfile and the
1124 // output directory of the layer, if any.
1125 auto dir = layer->getAttrOfType<hw::OutputFileAttr>("output_file");
1126 StringAttr filename = StringAttr::get(&getContext(), bindFileName);
1127 StringAttr path;
1128 if (dir)
1129 path = StringAttr::get(&getContext(),
1130 Twine(dir.getDirectory()) + bindFileName);
1131 else
1132 path = filename;
1133
1134 // Declare the macro for the include guard.
1135 sv::MacroDeclOp::create(b, loc, macroSymbolAttr, ArrayAttr{}, macroNameAttr);
1136
1137 // Create the emit op.
1138 auto bindFile = emit::FileOp::create(b, loc, path);
1139 OpBuilder::InsertionGuard _(b);
1140 b.setInsertionPointToEnd(bindFile.getBody());
1141
1142 // Create the #ifndef for the include guard.
1143 auto includeGuard = sv::IfDefOp::create(b, loc, macroSymbolRefAttr);
1144 b.createBlock(&includeGuard.getElseRegion());
1145
1146 // Create the #define for the include guard.
1147 sv::MacroDefOp::create(b, loc, macroSymbolRefAttr);
1148
1149 // Create IR to enable any parent layers.
1150 auto parent = layer->getParentOfType<LayerOp>();
1151 while (parent) {
1152 // If the parent is bound-in, we enable it by including the bindfile.
1153 // The parent bindfile will enable all ancestors.
1154 if (parent.getConvention() == LayerConvention::Bind) {
1155 auto target = bindFiles[module][parent].filename;
1156 sv::IncludeOp::create(b, loc, IncludeStyle::Local, target);
1157 break;
1158 }
1159
1160 // If the parent layer is inline, we can only assert that the parent is
1161 // already enabled.
1162 if (parent.getConvention() == LayerConvention::Inline) {
1163 auto parentMacroSymbolRefAttr = macroNames[parent];
1164 auto parentGuard = sv::IfDefOp::create(b, loc, parentMacroSymbolRefAttr);
1165 OpBuilder::InsertionGuard guard(b);
1166 b.createBlock(&parentGuard.getElseRegion());
1167 auto message = StringAttr::get(&getContext(),
1168 Twine(parent.getName()) + " not enabled");
1169 sv::MacroErrorOp::create(b, loc, message);
1170 parent = parent->getParentOfType<LayerOp>();
1171 continue;
1172 }
1173
1174 // Unknown Layer convention.
1175 llvm_unreachable("unknown layer convention");
1176 }
1177
1178 // Create IR to include bind files for child modules. If a module is
1179 // instantiated more than once, we only need to include the bindfile once.
1180 SmallPtrSet<Operation *, 8> seen;
1181 for (auto *record : *node) {
1182 auto *child = record->getTarget()->getModule().getOperation();
1183 if (!std::get<bool>(seen.insert(child)))
1184 continue;
1185 auto files = bindFiles[child];
1186 auto lookup = files.find(layer);
1187 if (lookup != files.end())
1188 sv::IncludeOp::create(b, loc, IncludeStyle::Local,
1189 lookup->second.filename);
1190 }
1191
1192 // Save the bind file information for later.
1193 auto &info = bindFiles[module][layer];
1194 info.filename = filename;
1195 info.body = includeGuard.getElseBlock();
1196}
1197
1199 InstanceGraphNode *node,
1200 FModuleOp module) {
1201 OpBuilder b(&getContext());
1202 b.setInsertionPointAfter(module);
1203
1204 // Create a bind file only if the layer is used under the module.
1205 llvm::SmallDenseSet<LayerOp> layersRequiringBindFiles;
1206
1207 // If the module is public, create a bind file for all layers.
1208 if (module.isPublic() || emitAllBindFiles)
1209 for (auto [_, layer] : symbolToLayer)
1210 if (layer.getConvention() == LayerConvention::Bind)
1211 layersRequiringBindFiles.insert(layer);
1212
1213 // Handle layers used directly in this module.
1214 module->walk([&](LayerBlockOp layerBlock) {
1215 auto layer = symbolToLayer[layerBlock.getLayerNameAttr()];
1216 if (layer.getConvention() == LayerConvention::Inline)
1217 return;
1218
1219 // Create a bindfile for any layer directly used in the module.
1220 layersRequiringBindFiles.insert(layer);
1221
1222 // Determine names for all modules that will be created.
1223 auto moduleName = module.getModuleName();
1224 auto layerName = layerBlock.getLayerName();
1225
1226 // A name hint for the module created from this layerblock.
1227 auto layerBlockModuleName = moduleNameForLayer(moduleName, layerName);
1228
1229 // A name hint for the hier-path-op which targets the bound-in instance of
1230 // the module created from this layerblock.
1231 auto layerBlockHierPathName = hierPathNameForLayer(moduleName, layerName);
1232
1233 LayerBlockGlobals globals;
1234 globals.moduleName = ns.newName(layerBlockModuleName);
1235 globals.hierPathName = ns.newName(layerBlockHierPathName);
1236 layerBlockGlobals.insert({layerBlock, globals});
1237 });
1238
1239 // Create a bindfile for layers used indirectly under this module.
1240 for (auto *record : *node) {
1241 auto *child = record->getTarget()->getModule().getOperation();
1242 for (auto [layer, _] : bindFiles[child])
1243 layersRequiringBindFiles.insert(layer);
1244 }
1245
1246 // Build the bindfiles for any layer seen under this module. The bindfiles
1247 // are emitted in the order which they are declared, for readability.
1248 for (auto [sym, layer] : symbolToLayer)
1249 if (layersRequiringBindFiles.contains(layer))
1250 buildBindFile(ns, node, b, sym, layer);
1251}
1252
1254 InstanceGraphNode *node,
1255 FExtModuleOp extModule) {
1256 // For each known layer of the extmodule, compute and record the bindfile
1257 // name. When a layer is known, its parent layers are implicitly known,
1258 // so compute bindfiles for parent layers too. Use a set to avoid
1259 // repeated work, which can happen if, for example, both a child layer and
1260 // a parent layer are explicitly declared to be known.
1261 auto known = extModule.getKnownLayersAttr().getAsRange<SymbolRefAttr>();
1262 if (known.empty())
1263 return;
1264
1265 auto moduleName = extModule.getExtModuleName();
1266 auto &files = bindFiles[extModule];
1267 SmallPtrSet<Operation *, 8> seen;
1268
1269 for (auto name : known) {
1270 auto layer = symbolToLayer[name];
1271 auto rootLayerName = name.getRootReference();
1272 auto nestedLayerNames = name.getNestedReferences();
1273 while (layer && std::get<bool>(seen.insert(layer))) {
1274 if (layer.getConvention() == LayerConvention::Bind) {
1275 BindFileInfo info;
1276 auto filename =
1277 fileNameForLayer(moduleName, rootLayerName, nestedLayerNames);
1278 info.filename = StringAttr::get(&getContext(), filename);
1279 info.body = nullptr;
1280 files.insert({layer, info});
1281 }
1282 layer = layer->getParentOfType<LayerOp>();
1283 if (!nestedLayerNames.empty())
1284 nestedLayerNames = nestedLayerNames.drop_back();
1285 }
1286 }
1287}
1288
1290 InstanceGraphNode *node) {
1291 auto *op = node->getModule().getOperation();
1292 if (!op)
1293 return;
1294
1295 if (auto module = dyn_cast<FModuleOp>(op))
1296 return preprocessModule(ns, node, module);
1297
1298 if (auto extModule = dyn_cast<FExtModuleOp>(op))
1299 return preprocessExtModule(ns, node, extModule);
1300}
1301
1302/// Create the bind file skeleton for each layer, for each module.
1304 InstanceGraph &ig) {
1305 ig.walkPostOrder([&](auto &node) { preprocessModuleLike(ns, &node); });
1306}
1307
1308/// Process a circuit to remove all layer blocks in each module and top-level
1309/// layer definition.
1311 LLVM_DEBUG(
1312 llvm::dbgs() << "==----- Running LowerLayers "
1313 "-------------------------------------------------===\n");
1314 CircuitOp circuitOp = getOperation();
1315
1316 // Initialize members which cannot be initialized automatically.
1317 llvm::sys::SmartMutex<true> mutex;
1318 circuitMutex = &mutex;
1319
1320 auto *ig = &getAnalysis<InstanceGraph>();
1321 CircuitNamespace ns(circuitOp);
1323 &ns, OpBuilder::InsertPoint(getOperation().getBodyBlock(),
1324 getOperation().getBodyBlock()->begin()));
1325 hierPathCache = &hpc;
1326
1327 preprocessLayers(ns);
1328 preprocessModules(ns, *ig);
1329
1330 auto mergeMaps = [](auto &&a, auto &&b) {
1331 if (failed(a))
1332 return std::forward<decltype(a)>(a);
1333 if (failed(b))
1334 return std::forward<decltype(b)>(b);
1335
1336 for (auto bb : *b)
1337 a->insert(bb);
1338 return std::forward<decltype(a)>(a);
1339 };
1340
1341 // Lower the layer blocks of each module.
1342 SmallVector<FModuleLike> modules(
1343 circuitOp.getBodyBlock()->getOps<FModuleLike>());
1344 auto failureOrInnerRefMap = transformReduce(
1345 circuitOp.getContext(), modules, FailureOr<InnerRefMap>(InnerRefMap{}),
1346 mergeMaps, [this](FModuleLike mod) -> FailureOr<InnerRefMap> {
1347 return runOnModuleLike(mod);
1348 });
1349 if (failed(failureOrInnerRefMap))
1350 return signalPassFailure();
1351 auto &innerRefMap = *failureOrInnerRefMap;
1352
1353 // Rewrite any hw::HierPathOps which have namepaths that contain rewritting
1354 // inner refs.
1355 //
1356 // TODO: This unnecessarily computes a new namepath for every hw::HierPathOp
1357 // even if that namepath is not used. It would be better to only build the
1358 // new namepath when a change is needed, e.g., by recording updates to the
1359 // namepath.
1360 for (hw::HierPathOp hierPathOp : circuitOp.getOps<hw::HierPathOp>()) {
1361 SmallVector<Attribute> newNamepath;
1362 bool modified = false;
1363 for (auto attr : hierPathOp.getNamepath()) {
1364 hw::InnerRefAttr innerRef = dyn_cast<hw::InnerRefAttr>(attr);
1365 if (!innerRef) {
1366 newNamepath.push_back(attr);
1367 continue;
1368 }
1369 auto it = innerRefMap.find(innerRef);
1370 if (it == innerRefMap.end()) {
1371 newNamepath.push_back(attr);
1372 continue;
1373 }
1374
1375 auto &[inst, mod] = it->getSecond();
1376 newNamepath.push_back(
1377 hw::InnerRefAttr::get(innerRef.getModule(), inst.getSymName()));
1378 newNamepath.push_back(hw::InnerRefAttr::get(mod, innerRef.getName()));
1379 modified = true;
1380 }
1381 if (modified)
1382 hierPathOp.setNamepathAttr(
1383 ArrayAttr::get(circuitOp.getContext(), newNamepath));
1384 }
1385
1386 // All layers definitions can now be deleted.
1387 for (auto layerOp :
1388 llvm::make_early_inc_range(circuitOp.getBodyBlock()->getOps<LayerOp>()))
1389 layerOp.erase();
1390
1391 // Cleanup state.
1392 circuitMutex = nullptr;
1393 layerBlockGlobals.clear();
1394 macroNames.clear();
1395 symbolToLayer.clear();
1396 hierPathCache = nullptr;
1397 bindFiles.clear();
1398}
assert(baseType &&"element must be base type")
Delimiter
Definition HWOps.cpp:116
static SmallString< 32 > guardMacroNameForLayer(StringRef moduleName, SymbolRefAttr layerName)
For all layerblocks @A::@B::@C in a module called Module, the include-guard macro is layers_Module_A_...
static SmallString< 32 > instanceNameForLayer(SymbolRefAttr layerName)
For a layerblock @A::@B::@C, the generated instance is called a_b_c.
static void appendName(StringRef name, SmallString< 32 > &output, bool toLower=false, Delimiter delimiter=Delimiter::BindFile)
DenseMap< hw::InnerRefAttr, std::pair< hw::InnerSymAttr, StringAttr > > InnerRefMap
static SmallString< 32 > moduleNameForLayer(StringRef moduleName, SymbolRefAttr layerName)
For a layer @A::@B::@C in module Module, the generated module is called Module_A_B_C.
static SmallString< 32 > fileNameForLayer(StringRef moduleName, StringAttr root, ArrayRef< FlatSymbolRefAttr > nested)
static SmallString< 32 > macroNameForLayer(StringRef circuitName, ArrayRef< FlatSymbolRefAttr > layerName)
For a layerblock @A::@B::@C, the verilog macro is A_B_C.
static SmallString< 32 > hierPathNameForLayer(StringRef moduleName, SymbolRefAttr layerName)
static Block * getBodyBlock(FModuleLike mod)
void runOnOperation() override
Entry point for the function.
void removeLayersFromPorts(FModuleLike moduleLike)
Update the module's port types to remove any explicit layer requirements from any probe types.
FailureOr< InnerRefMap > runOnModuleLike(FModuleLike moduleLike)
Strip layer colors from the module's interface.
void preprocessModuleLike(CircuitNamespace &ns, InstanceGraphNode *node)
Build the bindfile skeletons for each module.
void preprocessModule(CircuitNamespace &ns, InstanceGraphNode *node, FModuleOp module)
Build the bindfile skeleton for a module.
DenseMap< LayerOp, FlatSymbolRefAttr > macroNames
A map from inline layers to their macro names.
hw::OutputFileAttr outputFileForLayer(StringRef moduleName, SymbolRefAttr layerName)
void preprocessExtModule(CircuitNamespace &ns, InstanceGraphNode *node, FExtModuleOp extModule)
Record the supposed bindfiles for any known layers of the ext module.
void lowerInlineLayerBlock(LayerOp layer, LayerBlockOp layerBlock)
Lower an inline layerblock to an ifdef block.
llvm::MapVector< SymbolRefAttr, LayerOp > symbolToLayer
A mapping of symbol name to layer operation.
void buildBindFile(CircuitNamespace &ns, InstanceGraphNode *node, OpBuilder &b, SymbolRefAttr layerName, LayerOp layer)
Build a bindfile skeleton for a particular module and layer.
void preprocessModules(CircuitNamespace &ns, InstanceGraph &ig)
For each module, build a bindfile for each bound-layer, if needed.
LogicalResult runOnModuleBody(FModuleOp moduleOp, InnerRefMap &innerRefMap)
Extract layerblocks and strip probe colors from all ops under the module.
FModuleOp buildNewModule(OpBuilder &builder, LayerBlockOp layerBlock, ArrayRef< PortInfo > ports)
Safely build a new module with a given namehint.
hw::OutputFileAttr getOutputFile(SymbolRefAttr layerName)
hw::HierPathCache * hierPathCache
Utility for creating hw::HierPathOp.
void removeLayersFromValue(Value value)
Update the value's type to remove any layers from any probe types.
void preprocessLayers(CircuitNamespace &ns, OpBuilder &b, LayerOp layer, StringRef circuitName, SmallVector< FlatSymbolRefAttr > &stack)
Build macro declarations and cache information about the layers.
DenseMap< Operation *, DenseMap< LayerOp, BindFileInfo > > bindFiles
A mapping from module*layer to bindfile name.
DenseMap< LayerBlockOp, LayerBlockGlobals > layerBlockGlobals
A map of layer blocks to "safe" global names which are fine to create in the circuit namespace.
llvm::sys::SmartMutex< true > * circuitMutex
Indicates exclusive access to modify the circuitNamespace and the circuit.
This class represents a reference to a specific field or element of an aggregate value.
Definition FieldRef.h:28
A namespace that is used to store existing names and generate new names in some scope within the IR.
Definition Namespace.h:30
StringRef newName(const Twine &name)
Return a unique name, derived from the input name, and add the new name to the internal namespace.
Definition Namespace.h:87
This graph tracks modules and where they are instantiated.
This is a Node in the InstanceGraph.
auto getModule()
Get the module that this node is tracking.
decltype(auto) walkPostOrder(Fn &&fn)
Perform a post-order walk across the modules.
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.
std::pair< std::string, bool > getFieldName(const FieldRef &fieldRef, bool nameSafe=false)
Get a string identifier representing the FieldRef.
IntegerAttr getIntZerosAttr(Type type)
Utility for generating a constant zero attribute.
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
static ResultTy transformReduce(MLIRContext *context, IterTy begin, IterTy end, ResultTy init, ReduceFuncTy reduce, TransformFuncTy transform)
Wrapper for llvm::parallelTransformReduce that performs the transform_reduce serially when MLIR multi...
Definition Utils.h:40
bool isAncestorOfValueOwner(Operation *op, Value value)
Return true if a Value is created "underneath" an operation.
Definition Utils.h:27
The namespace of a CircuitOp, generally inhabited by modules.
Definition Namespace.h:24
This holds the name and type that describes the module's ports.