410 auto getOrCreateNodeOp = [&](Value operand,
411 ImplicitLocOpBuilder &builder) -> NodeOp {
413 OpBuilder::InsertionGuard guard(builder);
414 builder.setInsertionPointAfterValue(operand);
415 SmallString<16> nameHint;
417 if (
auto *definingOp = operand.getDefiningOp()) {
418 if (
auto instanceOp = dyn_cast<InstanceOp>(definingOp)) {
419 nameHint.append(instanceOp.getName());
420 nameHint.push_back(
'_');
422 instanceOp.getPortName(cast<OpResult>(operand).getResultNumber()));
423 }
else if (
auto opName = definingOp->getAttrOfType<StringAttr>(
"name")) {
424 nameHint.append(opName);
426 nameHint.append(
"_layerCapture");
429 return NodeOp::create(builder, operand.getLoc(), operand,
430 StringRef(nameHint));
436 DenseMap<Value, Value> replacements;
437 std::function<Value(Operation *, Value)> getReplacement =
438 [&](Operation *user, Value value) -> Value {
439 auto it = replacements.find(value);
440 if (it != replacements.end())
441 return it->getSecond();
443 ImplicitLocOpBuilder localBuilder(value.getLoc(), &getContext());
446 auto layerBlockOp = user->getParentOfType<LayerBlockOp>();
447 localBuilder.setInsertionPointToStart(layerBlockOp.getBody());
452 isa<debug::ScopeType>(value.getType())) {
454 auto *definingOp = value.getDefiningOp();
455 for (
auto operand : definingOp->getOperands())
456 mapping.map(operand, getReplacement(user, operand));
458 localBuilder.setInsertionPoint(user);
459 replacement = localBuilder.clone(*definingOp, mapping)
460 ->getResult(cast<OpResult>(value).getResultNumber());
462 replacements.insert({value, replacement});
467 auto *definingOp = value.getDefiningOp();
468 if (isa_and_present<XMRRefOp>(definingOp)) {
469 replacement = localBuilder.clone(*definingOp)->getResult(0);
470 replacements.insert({value, replacement});
481 if (isa_and_present<InstanceOp, InstanceChoiceOp>(definingOp)) {
482 bool isInstanceInputPort =
483 TypeSwitch<Operation *, bool>(definingOp)
484 .Case<InstanceOp, InstanceChoiceOp>([&](
auto instOp) {
485 for (
auto [idx, result] : llvm::enumerate(instOp.getResults()))
492 if (isInstanceInputPort) {
496 replacement = getReplacement(user, driver);
497 replacements.insert({value, replacement});
515 if (baseType && baseType.getBitWidthOrSentinel() == 0) {
516 OpBuilder::InsertionGuard guard(localBuilder);
517 auto zeroUIntType = UIntType::get(localBuilder.getContext(), 0);
518 replacement = localBuilder.createOrFold<BitCastOp>(
519 value.getType(), ConstantOp::create(localBuilder, zeroUIntType,
522 hw::InnerRefAttr innerRef;
523 if (
auto *definingOp = value.getDefiningOp()) {
526 auto innerSymOp = dyn_cast<hw::InnerSymbolOpInterface>(definingOp);
527 if (innerSymOp && innerSymOp.getTargetResultIndex()) {
536 auto node = getOrCreateNodeOp(value, localBuilder);
539 auto newValue = node.getResult();
540 value.replaceAllUsesExcept(newValue, node);
544 auto portIdx = cast<BlockArgument>(value).getArgNumber();
546 cast<FModuleLike>(*moduleOp), portIdx,
550 hw::HierPathOp hierPathOp;
553 auto insertPoint = OpBuilder::InsertPoint(moduleOp->getBlock(),
554 Block::iterator(moduleOp));
555 llvm::sys::SmartScopedLock<true> circuitLock(*
circuitMutex);
557 localBuilder.getArrayAttr({innerRef}), localBuilder.getLoc(),
559 hierPathOp.setVisibility(SymbolTable::Visibility::Private);
562 replacement = XMRDerefOp::create(localBuilder, value.getType(),
563 hierPathOp.getSymNameAttr());
566 replacements.insert({value, replacement});
574 DenseMap<Operation *, FModuleOp> createdInstances;
578 auto opPreconditionCheck = [](Operation *op) -> LogicalResult {
580 if (isa<RefCastOp, RefDefineOp, RefResolveOp, RefSendOp, RefSubOp,
582 return op->emitOpError()
583 <<
"cannot be handled by the lower-layers pass. This should have "
584 "already been removed by the lower-xmr pass.";
603 DenseMap<Operation *, Attribute> domainMap;
604 auto getDomain = [&domainMap](Value value,
605 Attribute &domain) -> LogicalResult {
606 SmallVector<Operation *> wires;
611 if (
auto arg = dyn_cast<BlockArgument>(value)) {
612 domain = cast<FModuleLike>(arg.getOwner()->getParentOp())
613 .getDomainInfoAttrForPort(arg.getArgNumber());
618 TypeSwitch<Operation *, LogicalResult>(value.getDefiningOp())
619 .Case<WireOp>([&](WireOp op) {
620 auto it = domainMap.find(op);
621 if (it != domainMap.end()) {
622 domain = it->getSecond();
625 for (
auto *user : op->getUsers()) {
626 auto connect = dyn_cast<FConnectLike>(user);
627 if (!connect || connect.getDest() != value)
629 value = connect.getSrc();
633 emitError(value.getLoc())
634 <<
"unable to determine domain kind for source likely "
636 "violation of static-single-connect";
639 .Case<InstanceOp>([&](
auto op) {
641 op.getPortDomain(cast<OpResult>(value).getResultNumber());
644 .Case<DomainCreateAnonOp, DomainCreateOp>([&](
auto op) {
645 domain = op.getDomainAttr();
648 .Default([&](
auto op) {
649 op->emitOpError() <<
"unhandled domain source in 'LowerLayers";
657 for (
auto *wire : wires)
658 domainMap[wire] = domain;
685 auto result = moduleOp.walk<mlir::WalkOrder::PostOrder>([&](Operation *op) {
686 if (failed(opPreconditionCheck(op)))
687 return WalkResult::interrupt();
690 for (
auto result : op->getResults())
694 if (
auto instance = dyn_cast<InstanceOp>(op))
695 instance.setLayers({});
697 auto layerBlock = dyn_cast<LayerBlockOp>(op);
699 return WalkResult::advance();
702 auto layer =
symbolToLayer.lookup(layerBlock.getLayerName());
704 if (layer.getConvention() == LayerConvention::Inline) {
706 return WalkResult::advance();
710 assert(layer.getConvention() == LayerConvention::Bind);
715 SmallVector<PortInfo> ports;
716 SmallVector<Value> connectValues;
723 DenseMap<Value, BlockArgument> domainInputPorts;
724 auto getOrCreateDomainInputPort =
725 [&](Value src, Location loc) -> FailureOr<BlockArgument> {
726 if (
auto it = domainInputPorts.find(src); it != domainInputPorts.end())
727 return it->getSecond();
736 name = StringAttr::get(src.getContext(), portNs.
newName(nameHint));
738 name = StringAttr::get(src.getContext(), portNs.
newName(
"anonDomain"));
740 auto domainInfo = ArrayAttr::get(src.getContext(), {});
749 ports.push_back(port);
750 connectValues.push_back(src);
751 BlockArgument replacement =
752 layerBlock.getBody()->addArgument(port.
type, port.
loc);
753 domainInputPorts[src] = replacement;
760 auto createInputPort = [&](Value src, Location loc) -> LogicalResult {
761 auto replacement = getOrCreateDomainInputPort(src, loc);
762 if (failed(replacement))
764 src.replaceUsesWithIf(*replacement, [&](OpOperand &use) {
765 auto *user = use.getOwner();
766 if (!layerBlock->isAncestor(user))
772 if (
auto connectLike = dyn_cast<FConnectLike>(user)) {
773 auto *destDefiningOp = connectLike.getDest().getDefiningOp();
774 return connectLike.getSrc() == src &&
775 !createdInstances.contains(destDefiningOp);
785 auto getPortLoc = [&](Value port) -> Location {
786 Location loc = UnknownLoc::get(port.getContext());
787 if (
auto *destOp = port.getDefiningOp())
788 if (
auto instOp = dyn_cast<InstanceOp>(destOp)) {
789 auto modOpIt = createdInstances.find(instOp);
790 if (modOpIt != createdInstances.end()) {
791 auto portNum = cast<OpResult>(port).getResultNumber();
792 loc = modOpIt->getSecond().getPortLocation(portNum);
800 auto createOutputPort = [&](Value src, Value dest) -> LogicalResult {
808 name = StringAttr::get(src.getContext(), portNs.
newName(nameHint));
810 name = StringAttr::get(src.getContext(), portNs.
newName(
"anonDomain"));
812 auto domainInfo = ArrayAttr::get(src.getContext(), {});
821 ports.push_back(port);
822 connectValues.push_back(dest);
823 BlockArgument replacement =
824 layerBlock.getBody()->addArgument(port.type, port.loc);
825 dest.replaceUsesWithIf(replacement, [&](OpOperand &use) {
826 auto *user = use.getOwner();
827 if (!layerBlock->isAncestor(user))
830 if (
auto connectLike = dyn_cast<FConnectLike>(user))
831 return connectLike.getDest() == dest;
838 replacements.
clear();
839 OpBuilder builder(moduleOp);
840 SmallVector<hw::InnerSymAttr> innerSyms;
841 SmallVector<sv::VerbatimOp> verbatims;
842 DenseSet<Operation *> spilledSubOps;
843 auto layerBlockWalkResult = layerBlock.walk([&](Operation *op) {
845 if (failed(opPreconditionCheck(op)))
846 return WalkResult::interrupt();
859 auto fixSubOp = [&](
auto subOp) {
860 auto input = subOp.getInput();
864 return WalkResult::advance();
868 subOp.getInputMutable().assign(getReplacement(subOp, input));
869 return WalkResult::advance();
873 op->moveBefore(layerBlock);
874 spilledSubOps.insert(op);
875 return WalkResult::advance();
878 if (
auto subOp = dyn_cast<SubfieldOp>(op))
879 return fixSubOp(subOp);
881 if (
auto subOp = dyn_cast<SubindexOp>(op))
882 return fixSubOp(subOp);
884 if (
auto subOp = dyn_cast<SubaccessOp>(op)) {
885 auto input = subOp.getInput();
886 auto index = subOp.getIndex();
892 subOp.getIndexMutable().assign(getReplacement(subOp, index));
894 return WalkResult::advance();
899 subOp.getInputMutable().assign(getReplacement(subOp, input));
901 subOp.getIndexMutable().assign(getReplacement(subOp, index));
902 return WalkResult::advance();
907 subOp->moveBefore(layerBlock);
908 spilledSubOps.insert(op);
909 return WalkResult::advance();
914 auto diag = op->emitOpError()
915 <<
"has a non-passive operand and captures a value defined "
916 "outside its enclosing bind-convention layerblock. The "
917 "'LowerLayers' pass cannot lower this as it would "
918 "create an output port on the resulting module.";
919 diag.attachNote(layerBlock.getLoc())
920 <<
"the layerblock is defined here";
921 return WalkResult::interrupt();
924 if (
auto nodeOp = dyn_cast<NodeOp>(op)) {
925 auto *definingOp = nodeOp.getInput().getDefiningOp();
927 spilledSubOps.contains(nodeOp.getInput().getDefiningOp())) {
928 op->moveBefore(layerBlock);
929 return WalkResult::advance();
937 if (
auto symOp = dyn_cast<hw::InnerSymbolOpInterface>(op))
938 if (
auto innerSym = symOp.getInnerSymAttr())
939 innerSyms.push_back(innerSym);
951 if (
auto instOp = dyn_cast<InstanceOp>(op)) {
953 if (!createdInstances.contains(instOp))
954 return WalkResult::advance();
958 <<
" Found instance created from nested layer block:\n"
959 <<
" module: " << instOp.getModuleName() <<
"\n"
960 <<
" instance: " << instOp.getName() <<
"\n";
962 instOp->moveBefore(layerBlock);
963 return WalkResult::advance();
976 if (
auto domainDefineOp = dyn_cast<DomainDefineOp>(op)) {
977 auto src = domainDefineOp.getSrc();
978 auto dest = domainDefineOp.getDest();
982 if (srcInLayerBlock) {
984 if (destInLayerBlock)
985 return WalkResult::advance();
991 return WalkResult(createOutputPort(src, dest));
997 if (destInLayerBlock)
998 return WalkResult(createInputPort(src, domainDefineOp.getLoc()));
1004 domainDefineOp->moveBefore(layerBlock);
1005 return WalkResult::advance();
1011 for (
size_t i = 0, e = op->getNumOperands(); i != e; ++i) {
1012 auto operand = op->getOperand(i);
1023 auto replacement = getOrCreateDomainInputPort(operand, op->getLoc());
1024 if (failed(replacement))
1025 return WalkResult::interrupt();
1026 op->setOperand(i, *replacement);
1030 op->setOperand(i, getReplacement(op, operand));
1033 if (
auto verbatim = dyn_cast<sv::VerbatimOp>(op))
1034 verbatims.push_back(verbatim);
1036 return WalkResult::advance();
1039 if (layerBlockWalkResult.wasInterrupted())
1040 return WalkResult::interrupt();
1047 if (llvm::all_of(layerBlock.getRegion().getBlocks(),
1048 [](
auto &a) { return a.empty(); })) {
1049 assert(verbatims.empty());
1051 return WalkResult::advance();
1055 FModuleOp newModule =
buildNewModule(builder, layerBlock, ports);
1056 newModule.getBody().takeBody(layerBlock.getRegion());
1057 SymbolTable::setSymbolVisibility(newModule,
1058 SymbolTable::Visibility::Private);
1061 llvm::dbgs() <<
" New Module: "
1063 llvm::dbgs() <<
" ports:\n";
1064 for (
size_t i = 0, e = ports.size(); i != e; ++i) {
1065 auto port = ports[i];
1066 auto value = connectValues[i];
1067 llvm::dbgs() <<
" - name: " << port.getName() <<
"\n"
1068 <<
" type: " << port.type <<
"\n"
1069 <<
" direction: " << port.direction <<
"\n"
1070 <<
" value: " << value <<
"\n";
1080 builder.setInsertionPointAfter(layerBlock);
1083 hw::InnerSymAttr::get(builder.getStringAttr(ns.
newName(instanceName)));
1085 auto instanceOp = InstanceOp::create(
1086 builder, layerBlock.getLoc(), newModule,
1088 instanceName, NameKindEnum::DroppableName,
1089 ArrayRef<Attribute>{},
1090 ArrayRef<Attribute>{},
false,
1092 for (
auto [lhs, rhs] : llvm::zip(instanceOp.getResults(), connectValues))
1093 if (instanceOp.getPortDirection(lhs.getResultNumber()) ==
Direction::In)
1094 DomainDefineOp::create(builder, builder.getUnknownLoc(), lhs, rhs);
1096 DomainDefineOp::create(builder, builder.getUnknownLoc(), rhs, lhs);
1100 layerBlock.getLayerName());
1101 instanceOp->setAttr(
"output_file", outputFile);
1103 createdInstances.try_emplace(instanceOp, newModule);
1107 auto builder = OpBuilder::atBlockEnd(
bindFiles[moduleOp][layer].body);
1108 BindOp::create(builder, layerBlock.getLoc(), moduleOp.getModuleNameAttr(),
1109 instanceOp.getInnerSymAttr().getSymName());
1112 LLVM_DEBUG(llvm::dbgs() <<
" moved inner refs:\n");
1113 for (hw::InnerSymAttr innerSym : innerSyms) {
1114 auto oldInnerRef = hw::InnerRefAttr::get(moduleOp.getModuleNameAttr(),
1115 innerSym.getSymName());
1116 auto splice = std::make_pair(instanceOp.getInnerSymAttr(),
1117 newModule.getModuleNameAttr());
1118 innerRefMap.insert({oldInnerRef, splice});
1119 LLVM_DEBUG(llvm::dbgs() <<
" - ref: " << oldInnerRef <<
"\n"
1120 <<
" splice: " << splice.first <<
", "
1121 << splice.second <<
"\n";);
1125 if (!verbatims.empty()) {
1126 mlir::AttrTypeReplacer replacer;
1127 replacer.addReplacement(
1128 [&innerRefMap](hw::InnerRefAttr ref) -> std::optional<Attribute> {
1129 auto it = innerRefMap.find(ref);
1130 if (it != innerRefMap.end())
1131 return hw::InnerRefAttr::get(it->second.second, ref.getName());
1132 return std::nullopt;
1134 for (
auto verbatim : verbatims)
1135 replacer.replaceElementsIn(verbatim);
1140 return WalkResult::advance();
1142 return success(!result.wasInterrupted());
1184 SymbolRefAttr layerName, LayerOp layer,
1186 assert(layer.getConvention() == LayerConvention::Bind);
1187 auto module = node->getModule<FModuleOp>();
1188 auto loc =
module.getLoc();
1192 auto macroSymbol = ns.
newName(macroName);
1193 auto macroNameAttr = StringAttr::get(&getContext(), macroName);
1194 auto macroSymbolAttr = StringAttr::get(&getContext(), macroSymbol);
1195 auto macroSymbolRefAttr = FlatSymbolRefAttr::get(macroSymbolAttr);
1202 auto dir = layer->getAttrOfType<hw::OutputFileAttr>(
"output_file");
1203 StringAttr filename = StringAttr::get(&getContext(), bindFileName);
1206 path = StringAttr::get(&getContext(),
1207 Twine(dir.getDirectory()) + bindFileName);
1212 sv::MacroDeclOp::create(b, loc, macroSymbolAttr, {},
1213 ArrayAttr{}, macroNameAttr);
1216 auto bindFile = emit::FileOp::create(b, loc, path);
1217 OpBuilder::InsertionGuard _(b);
1218 b.setInsertionPointToEnd(bindFile.getBody());
1221 auto includeGuard = sv::IfDefOp::create(b, loc, macroSymbolRefAttr);
1222 b.createBlock(&includeGuard.getElseRegion());
1225 sv::MacroDefOp::create(b, loc, macroSymbolRefAttr);
1228 auto parent = layer->getParentOfType<LayerOp>();
1232 if (parent.getConvention() == LayerConvention::Bind) {
1233 auto target =
bindFiles[module][parent].filename;
1234 sv::IncludeOp::create(b, loc, IncludeStyle::Local, target);
1240 if (parent.getConvention() == LayerConvention::Inline) {
1241 auto parentMacroSymbolRefAttr =
macroNames[parent];
1242 auto parentGuard = sv::IfDefOp::create(b, loc, parentMacroSymbolRefAttr);
1243 OpBuilder::InsertionGuard guard(b);
1244 b.createBlock(&parentGuard.getElseRegion());
1245 auto message = StringAttr::get(&getContext(),
1246 Twine(parent.getName()) +
" not enabled");
1247 sv::MacroErrorOp::create(b, loc, message);
1248 parent = parent->getParentOfType<LayerOp>();
1253 llvm_unreachable(
"unknown layer convention");
1258 SmallPtrSet<Operation *, 8> seen;
1259 for (
auto *record : *node) {
1260 auto *child = record->getTarget()->getModule().getOperation();
1261 if (!std::get<bool>(seen.insert(child)))
1264 auto lookup = files.find(layer);
1265 if (lookup == files.end() || !lookup->second.effectful)
1267 sv::IncludeOp::create(b, loc, IncludeStyle::Local, lookup->second.filename);
1272 info.filename = filename;
1273 info.body = includeGuard.getElseBlock();
1274 info.effectful = effectful;