405 auto getOrCreateNodeOp = [&](Value operand,
406 ImplicitLocOpBuilder &builder) -> NodeOp {
408 OpBuilder::InsertionGuard guard(builder);
409 builder.setInsertionPointAfterValue(operand);
410 SmallString<16> nameHint;
412 if (
auto *definingOp = operand.getDefiningOp()) {
413 if (
auto instanceOp = dyn_cast<InstanceOp>(definingOp)) {
414 nameHint.append(instanceOp.getName());
415 nameHint.push_back(
'_');
417 instanceOp.getPortName(cast<OpResult>(operand).getResultNumber()));
418 }
else if (
auto opName = definingOp->getAttrOfType<StringAttr>(
"name")) {
419 nameHint.append(opName);
421 nameHint.append(
"_layer_probe");
424 return NodeOp::create(builder, operand.getLoc(), operand,
425 StringRef(nameHint));
431 DenseMap<Value, Value> replacements;
432 std::function<Value(Operation *, Value)> getReplacement =
433 [&](Operation *user, Value value) -> Value {
434 auto it = replacements.find(value);
435 if (it != replacements.end())
436 return it->getSecond();
438 ImplicitLocOpBuilder localBuilder(value.getLoc(), &getContext());
441 auto layerBlockOp = user->getParentOfType<LayerBlockOp>();
442 localBuilder.setInsertionPointToStart(layerBlockOp.getBody());
449 if (type_isa<FStringType>(value.getType())) {
450 localBuilder.setInsertionPoint(user);
451 replacement = localBuilder.clone(*value.getDefiningOp())->getResult(0);
452 replacements.insert({value, replacement});
457 auto *definingOp = value.getDefiningOp();
458 if (isa_and_present<XMRRefOp>(definingOp)) {
459 replacement = localBuilder.clone(*definingOp)->getResult(0);
460 replacements.insert({value, replacement});
471 if (isa_and_present<InstanceOp, InstanceChoiceOp>(definingOp)) {
472 bool isInstanceInputPort =
473 TypeSwitch<Operation *, bool>(definingOp)
474 .Case<InstanceOp, InstanceChoiceOp>([&](
auto instOp) {
475 for (
auto [idx, result] : llvm::enumerate(instOp.getResults()))
477 return instOp.getPortDirection(idx) == Direction::In;
482 if (isInstanceInputPort) {
486 replacement = getReplacement(user, driver);
487 replacements.insert({value, replacement});
504 auto baseType = type_cast<FIRRTLBaseType>(value.getType());
505 if (baseType && baseType.getBitWidthOrSentinel() == 0) {
506 OpBuilder::InsertionGuard guard(localBuilder);
507 auto zeroUIntType = UIntType::get(localBuilder.getContext(), 0);
508 replacement = localBuilder.createOrFold<BitCastOp>(
509 value.getType(), ConstantOp::create(localBuilder, zeroUIntType,
512 hw::InnerRefAttr innerRef;
513 if (
auto *definingOp = value.getDefiningOp()) {
516 auto innerSymOp = dyn_cast<hw::InnerSymbolOpInterface>(definingOp);
517 if (innerSymOp && innerSymOp.getTargetResultIndex()) {
526 auto node = getOrCreateNodeOp(value, localBuilder);
529 auto newValue = node.getResult();
530 value.replaceAllUsesExcept(newValue, node);
534 auto portIdx = cast<BlockArgument>(value).getArgNumber();
536 cast<FModuleLike>(*moduleOp), portIdx,
540 hw::HierPathOp hierPathOp;
543 auto insertPoint = OpBuilder::InsertPoint(moduleOp->getBlock(),
544 Block::iterator(moduleOp));
545 llvm::sys::SmartScopedLock<true> circuitLock(*
circuitMutex);
547 localBuilder.getArrayAttr({innerRef}), localBuilder.getLoc(),
549 hierPathOp.setVisibility(SymbolTable::Visibility::Private);
552 replacement = XMRDerefOp::create(localBuilder, value.getType(),
553 hierPathOp.getSymNameAttr());
556 replacements.insert({value, replacement});
564 DenseMap<Operation *, FModuleOp> createdInstances;
568 auto opPreconditionCheck = [](Operation *op) -> LogicalResult {
570 if (isa<RefCastOp, RefDefineOp, RefResolveOp, RefSendOp, RefSubOp,
572 return op->emitOpError()
573 <<
"cannot be handled by the lower-layers pass. This should have "
574 "already been removed by the lower-xmr pass.";
593 DenseMap<Operation *, Attribute> domainMap;
594 auto getDomain = [&domainMap](Value value,
595 Attribute &domain) -> LogicalResult {
596 SmallVector<Operation *> wires;
601 if (
auto arg = dyn_cast<BlockArgument>(value)) {
602 domain = cast<FModuleLike>(arg.getOwner()->getParentOp())
603 .getDomainInfoAttrForPort(arg.getArgNumber());
608 TypeSwitch<Operation *, LogicalResult>(value.getDefiningOp())
609 .Case<WireOp>([&](WireOp op) {
610 auto it = domainMap.find(op);
611 if (it != domainMap.end()) {
612 domain = it->getSecond();
615 for (
auto *user : op->getUsers()) {
616 auto connect = dyn_cast<FConnectLike>(user);
617 if (!connect || connect.getDest() != value)
619 value = connect.getSrc();
623 emitError(value.getLoc())
624 <<
"unable to determine domain kind for source likely "
626 "violation of static-single-connect";
629 .Case<InstanceOp>([&](
auto op) {
631 op.getPortDomain(cast<OpResult>(value).getResultNumber());
634 .Case<DomainCreateAnonOp>([&](
auto op) {
635 domain = op.getDomainAttr();
638 .Default([&](
auto op) {
639 op->emitOpError() <<
"unhandled domain source in 'LowerLayers";
647 for (
auto *wire : wires)
648 domainMap[wire] = domain;
675 auto result = moduleOp.walk<mlir::WalkOrder::PostOrder>([&](Operation *op) {
676 if (failed(opPreconditionCheck(op)))
677 return WalkResult::interrupt();
680 for (
auto result : op->getResults())
684 if (
auto instance = dyn_cast<InstanceOp>(op))
685 instance.setLayers({});
687 auto layerBlock = dyn_cast<LayerBlockOp>(op);
689 return WalkResult::advance();
692 auto layer =
symbolToLayer.lookup(layerBlock.getLayerName());
694 if (layer.getConvention() == LayerConvention::Inline) {
696 return WalkResult::advance();
700 assert(layer.getConvention() == LayerConvention::Bind);
705 SmallVector<PortInfo> ports;
706 SmallVector<Value> connectValues;
711 auto createInputPort = [&](Value src, Location loc) -> LogicalResult {
713 if (failed(getDomain(src, domain)))
719 name = StringAttr::get(src.getContext(), portNs.
newName(nameHint));
721 name = StringAttr::get(src.getContext(), portNs.
newName(
"anonDomain"));
730 ports.push_back(port);
731 connectValues.push_back(src);
732 BlockArgument replacement =
733 layerBlock.getBody()->addArgument(port.
type, port.
loc);
734 src.replaceUsesWithIf(replacement, [&](OpOperand &use) {
735 auto *user = use.getOwner();
736 if (!layerBlock->isAncestor(user))
742 if (
auto connectLike = dyn_cast<FConnectLike>(user)) {
743 auto *destDefiningOp = connectLike.getDest().getDefiningOp();
744 return connectLike.getSrc() == src &&
745 !createdInstances.contains(destDefiningOp);
755 auto getPortLoc = [&](Value port) -> Location {
756 Location loc = UnknownLoc::get(port.getContext());
757 if (
auto *destOp = port.getDefiningOp())
758 if (
auto instOp = dyn_cast<InstanceOp>(destOp)) {
759 auto modOpIt = createdInstances.find(instOp);
760 if (modOpIt != createdInstances.end()) {
761 auto portNum = cast<OpResult>(port).getResultNumber();
762 loc = modOpIt->getSecond().getPortLocation(portNum);
770 auto createOutputPort = [&](Value src, Value dest) -> LogicalResult {
772 if (failed(getDomain(src, domain)))
778 name = StringAttr::get(src.getContext(), portNs.
newName(nameHint));
780 name = StringAttr::get(src.getContext(), portNs.
newName(
"anonDomain"));
789 ports.push_back(port);
790 connectValues.push_back(dest);
791 BlockArgument replacement =
792 layerBlock.getBody()->addArgument(port.type, port.loc);
793 dest.replaceUsesWithIf(replacement, [&](OpOperand &use) {
794 auto *user = use.getOwner();
795 if (!layerBlock->isAncestor(user))
798 if (
auto connectLike = dyn_cast<FConnectLike>(user))
799 return connectLike.getDest() == dest;
806 replacements.clear();
807 OpBuilder builder(moduleOp);
808 SmallVector<hw::InnerSymAttr> innerSyms;
809 SmallVector<sv::VerbatimOp> verbatims;
810 DenseSet<Operation *> spilledSubOps;
811 auto layerBlockWalkResult = layerBlock.walk([&](Operation *op) {
813 if (failed(opPreconditionCheck(op)))
814 return WalkResult::interrupt();
827 auto fixSubOp = [&](
auto subOp) {
828 auto input = subOp.getInput();
832 return WalkResult::advance();
835 if (firrtl::type_cast<FIRRTLBaseType>(input.getType()).isPassive()) {
836 subOp.getInputMutable().assign(getReplacement(subOp, input));
837 return WalkResult::advance();
841 op->moveBefore(layerBlock);
842 spilledSubOps.insert(op);
843 return WalkResult::advance();
846 if (
auto subOp = dyn_cast<SubfieldOp>(op))
847 return fixSubOp(subOp);
849 if (
auto subOp = dyn_cast<SubindexOp>(op))
850 return fixSubOp(subOp);
852 if (
auto subOp = dyn_cast<SubaccessOp>(op)) {
853 auto input = subOp.getInput();
854 auto index = subOp.getIndex();
860 subOp.getIndexMutable().assign(getReplacement(subOp, index));
862 return WalkResult::advance();
866 if (firrtl::type_cast<FIRRTLBaseType>(input.getType()).isPassive()) {
867 subOp.getInputMutable().assign(getReplacement(subOp, input));
869 subOp.getIndexMutable().assign(getReplacement(subOp, index));
870 return WalkResult::advance();
875 subOp->moveBefore(layerBlock);
876 spilledSubOps.insert(op);
877 return WalkResult::advance();
882 auto diag = op->emitOpError()
883 <<
"has a non-passive operand and captures a value defined "
884 "outside its enclosing bind-convention layerblock. The "
885 "'LowerLayers' pass cannot lower this as it would "
886 "create an output port on the resulting module.";
887 diag.attachNote(layerBlock.getLoc())
888 <<
"the layerblock is defined here";
889 return WalkResult::interrupt();
892 if (
auto nodeOp = dyn_cast<NodeOp>(op)) {
893 auto *definingOp = nodeOp.getInput().getDefiningOp();
895 spilledSubOps.contains(nodeOp.getInput().getDefiningOp())) {
896 op->moveBefore(layerBlock);
897 return WalkResult::advance();
905 if (
auto symOp = dyn_cast<hw::InnerSymbolOpInterface>(op))
906 if (
auto innerSym = symOp.getInnerSymAttr())
907 innerSyms.push_back(innerSym);
919 if (
auto instOp = dyn_cast<InstanceOp>(op)) {
921 if (!createdInstances.contains(instOp))
922 return WalkResult::advance();
926 <<
" Found instance created from nested layer block:\n"
927 <<
" module: " << instOp.getModuleName() <<
"\n"
928 <<
" instance: " << instOp.getName() <<
"\n";
930 instOp->moveBefore(layerBlock);
931 return WalkResult::advance();
944 if (
auto domainDefineOp = dyn_cast<DomainDefineOp>(op)) {
945 auto src = domainDefineOp.getSrc();
946 auto dest = domainDefineOp.getDest();
950 if (srcInLayerBlock) {
952 if (destInLayerBlock)
953 return WalkResult::advance();
959 return WalkResult(createOutputPort(src, dest));
965 if (destInLayerBlock)
966 return WalkResult(createInputPort(src, domainDefineOp.getLoc()));
972 domainDefineOp->moveBefore(layerBlock);
973 return WalkResult::advance();
979 for (
size_t i = 0, e = op->getNumOperands(); i != e; ++i) {
980 auto operand = op->getOperand(i);
988 op->setOperand(i, getReplacement(op, operand));
991 if (
auto verbatim = dyn_cast<sv::VerbatimOp>(op))
992 verbatims.push_back(verbatim);
994 return WalkResult::advance();
997 if (layerBlockWalkResult.wasInterrupted())
998 return WalkResult::interrupt();
1005 if (llvm::all_of(layerBlock.getRegion().getBlocks(),
1006 [](
auto &a) { return a.empty(); })) {
1007 assert(verbatims.empty());
1009 return WalkResult::advance();
1013 FModuleOp newModule =
buildNewModule(builder, layerBlock, ports);
1014 newModule.getBody().takeBody(layerBlock.getRegion());
1015 SymbolTable::setSymbolVisibility(newModule,
1016 SymbolTable::Visibility::Private);
1019 llvm::dbgs() <<
" New Module: "
1021 llvm::dbgs() <<
" ports:\n";
1022 for (
size_t i = 0, e = ports.size(); i != e; ++i) {
1023 auto port = ports[i];
1024 auto value = connectValues[i];
1025 llvm::dbgs() <<
" - name: " << port.getName() <<
"\n"
1026 <<
" type: " << port.type <<
"\n"
1027 <<
" direction: " << port.direction <<
"\n"
1028 <<
" value: " << value <<
"\n";
1038 builder.setInsertionPointAfter(layerBlock);
1041 hw::InnerSymAttr::get(builder.getStringAttr(ns.
newName(instanceName)));
1043 auto instanceOp = InstanceOp::create(
1044 builder, layerBlock.getLoc(), newModule,
1046 instanceName, NameKindEnum::DroppableName,
1047 ArrayRef<Attribute>{},
1048 ArrayRef<Attribute>{},
false,
1050 for (
auto [lhs, rhs] : llvm::zip(instanceOp.getResults(), connectValues))
1051 if (instanceOp.getPortDirection(lhs.getResultNumber()) == Direction::In)
1052 DomainDefineOp::create(builder, builder.getUnknownLoc(), lhs, rhs);
1054 DomainDefineOp::create(builder, builder.getUnknownLoc(), rhs, lhs);
1058 layerBlock.getLayerName());
1059 instanceOp->setAttr(
"output_file", outputFile);
1061 createdInstances.try_emplace(instanceOp, newModule);
1065 auto builder = OpBuilder::atBlockEnd(
bindFiles[moduleOp][layer].body);
1066 BindOp::create(builder, layerBlock.getLoc(), moduleOp.getModuleNameAttr(),
1067 instanceOp.getInnerSymAttr().getSymName());
1070 LLVM_DEBUG(llvm::dbgs() <<
" moved inner refs:\n");
1071 for (hw::InnerSymAttr innerSym : innerSyms) {
1072 auto oldInnerRef = hw::InnerRefAttr::get(moduleOp.getModuleNameAttr(),
1073 innerSym.getSymName());
1074 auto splice = std::make_pair(instanceOp.getInnerSymAttr(),
1075 newModule.getModuleNameAttr());
1076 innerRefMap.insert({oldInnerRef, splice});
1077 LLVM_DEBUG(llvm::dbgs() <<
" - ref: " << oldInnerRef <<
"\n"
1078 <<
" splice: " << splice.first <<
", "
1079 << splice.second <<
"\n";);
1083 if (!verbatims.empty()) {
1084 mlir::AttrTypeReplacer replacer;
1085 replacer.addReplacement(
1086 [&innerRefMap](hw::InnerRefAttr ref) -> std::optional<Attribute> {
1087 auto it = innerRefMap.find(ref);
1088 if (it != innerRefMap.end())
1089 return hw::InnerRefAttr::get(it->second.second, ref.getName());
1090 return std::nullopt;
1092 for (
auto verbatim : verbatims)
1093 replacer.replaceElementsIn(verbatim);
1098 return WalkResult::advance();
1100 return success(!result.wasInterrupted());
1142 SymbolRefAttr layerName, LayerOp layer) {
1143 assert(layer.getConvention() == LayerConvention::Bind);
1144 auto module = node->getModule<FModuleOp>();
1145 auto loc =
module.getLoc();
1149 auto macroSymbol = ns.
newName(macroName);
1150 auto macroNameAttr = StringAttr::get(&getContext(), macroName);
1151 auto macroSymbolAttr = StringAttr::get(&getContext(), macroSymbol);
1152 auto macroSymbolRefAttr = FlatSymbolRefAttr::get(macroSymbolAttr);
1159 auto dir = layer->getAttrOfType<hw::OutputFileAttr>(
"output_file");
1160 StringAttr filename = StringAttr::get(&getContext(), bindFileName);
1163 path = StringAttr::get(&getContext(),
1164 Twine(dir.getDirectory()) + bindFileName);
1169 sv::MacroDeclOp::create(b, loc, macroSymbolAttr, ArrayAttr{}, macroNameAttr);
1172 auto bindFile = emit::FileOp::create(b, loc, path);
1173 OpBuilder::InsertionGuard _(b);
1174 b.setInsertionPointToEnd(bindFile.getBody());
1177 auto includeGuard = sv::IfDefOp::create(b, loc, macroSymbolRefAttr);
1178 b.createBlock(&includeGuard.getElseRegion());
1181 sv::MacroDefOp::create(b, loc, macroSymbolRefAttr);
1184 auto parent = layer->getParentOfType<LayerOp>();
1188 if (parent.getConvention() == LayerConvention::Bind) {
1189 auto target =
bindFiles[module][parent].filename;
1190 sv::IncludeOp::create(b, loc, IncludeStyle::Local, target);
1196 if (parent.getConvention() == LayerConvention::Inline) {
1197 auto parentMacroSymbolRefAttr =
macroNames[parent];
1198 auto parentGuard = sv::IfDefOp::create(b, loc, parentMacroSymbolRefAttr);
1199 OpBuilder::InsertionGuard guard(b);
1200 b.createBlock(&parentGuard.getElseRegion());
1201 auto message = StringAttr::get(&getContext(),
1202 Twine(parent.getName()) +
" not enabled");
1203 sv::MacroErrorOp::create(b, loc, message);
1204 parent = parent->getParentOfType<LayerOp>();
1209 llvm_unreachable(
"unknown layer convention");
1214 SmallPtrSet<Operation *, 8> seen;
1215 for (
auto *record : *node) {
1216 auto *child = record->getTarget()->getModule().getOperation();
1217 if (!std::get<bool>(seen.insert(child)))
1220 auto lookup = files.find(layer);
1221 if (lookup != files.end())
1222 sv::IncludeOp::create(b, loc, IncludeStyle::Local,
1223 lookup->second.filename);
1228 info.filename = filename;
1229 info.body = includeGuard.getElseBlock();