15#include "mlir/IR/Iterators.h"
16#include "mlir/IR/Threading.h"
17#include "mlir/Interfaces/SideEffectInterfaces.h"
18#include "mlir/Pass/Pass.h"
19#include "llvm/ADT/BitVector.h"
20#include "llvm/ADT/DenseMapInfoVariant.h"
21#include "llvm/ADT/PostOrderIterator.h"
22#include "llvm/Support/Debug.h"
24#define DEBUG_TYPE "firrtl-imdeadcodeelim"
28#define GEN_PASS_DEF_IMDEADCODEELIM
29#include "circt/Dialect/FIRRTL/Passes.h.inc"
38 return !(mlir::isMemoryEffectFree(op) ||
39 mlir::hasSingleEffect<mlir::MemoryEffects::Allocate>(op) ||
40 mlir::hasSingleEffect<mlir::MemoryEffects::Read>(op));
45 return isa<WireOp, RegResetOp, RegOp, NodeOp, MemOp>(op);
50 if (
auto name = dyn_cast<FNamableOp>(op))
51 if (!name.hasDroppableName())
57struct IMDeadCodeElimPass
58 :
public circt::firrtl::impl::IMDeadCodeElimBase<IMDeadCodeElimPass> {
61 void runOnOperation()
override;
63 void rewriteModuleSignature(FModuleOp module);
64 void rewriteModuleBody(FModuleOp module);
65 void eraseEmptyModule(FModuleOp module);
66 void forwardConstantOutputPort(FModuleOp module);
69 bool isKnownAlive(Value value)
const {
70 assert(value &&
"null should not be used");
71 return liveElements.count(value);
75 bool isAssumedDead(Value value)
const {
return !isKnownAlive(value); }
76 bool isAssumedDead(Operation *op)
const {
77 return llvm::none_of(op->getResults(),
78 [&](Value value) { return isKnownAlive(value); });
82 bool isBlockExecutable(Block *block)
const {
83 return executableBlocks.count(block);
86 void visitUser(Operation *op);
87 void visitValue(Value value);
89 void visitConnect(FConnectLike connect);
90 void visitSubelement(Operation *op);
91 void markBlockExecutable(Block *block);
92 void markBlockUndeletable(Operation *op) {
93 markAlive(op->getParentOfType<FModuleOp>());
96 void markDeclaration(Operation *op);
97 void markFInstanceLikeOp(FInstanceLike instanceLike);
98 void markUnknownSideEffectOp(Operation *op);
99 void visitFInstanceLikeOp(FInstanceLike instanceLike);
100 void visitHierPathOp(hw::HierPathOp hierpath);
101 void visitModuleOp(FModuleOp module);
105 DenseSet<Block *> executableBlocks;
111 std::variant<Value, FModuleOp, FInstanceLike, hw::HierPathOp>;
113 void markAlive(ElementType element) {
114 if (!liveElements.insert(element).second)
116 worklist.push_back(element);
121 SmallVector<ElementType, 64> worklist;
122 llvm::DenseSet<ElementType> liveElements;
126 DenseMap<InstanceOp, SmallVector<hw::HierPathOp>> instanceToHierPaths;
129 circt::hw::InnerRefNamespace *innerRefNamespace;
130 mlir::SymbolTable *symbolTable;
134void IMDeadCodeElimPass::visitFInstanceLikeOp(FInstanceLike instanceLike) {
135 auto instance = dyn_cast<InstanceOp>(*instanceLike);
141 markBlockUndeletable(instance);
143 auto module = instance.getReferencedModule<FModuleOp>(*instanceGraph);
152 for (
auto hierPath : instanceToHierPaths[instance])
156 for (
auto &blockArg : module.getBody().getArguments()) {
157 auto portNo = blockArg.getArgNumber();
158 if (module.getPortDirection(portNo) == Direction::In &&
159 isKnownAlive(module.getArgument(portNo)))
160 markAlive(instance.getResult(portNo));
164void IMDeadCodeElimPass::visitModuleOp(FModuleOp module) {
166 for (
auto *use : instanceGraph->
lookup(module)->
uses()) {
167 if (
auto instance = use->getInstance<FInstanceLike>())
172void IMDeadCodeElimPass::visitHierPathOp(hw::HierPathOp hierPathOp) {
174 for (
auto path : hierPathOp.getNamepathAttr())
175 if (
auto innerRef = dyn_cast<hw::InnerRefAttr>(path)) {
176 auto *op = innerRefNamespace->
lookupOp(innerRef);
177 if (
auto instance = dyn_cast_or_null<InstanceOp>(op))
182void IMDeadCodeElimPass::markDeclaration(Operation *op) {
185 for (
auto result : op->getResults())
187 markBlockUndeletable(op);
191void IMDeadCodeElimPass::markUnknownSideEffectOp(Operation *op) {
194 for (
auto result : op->getResults())
196 for (
auto operand : op->getOperands())
198 markBlockUndeletable(op);
202 for (
auto ®ion : op->getRegions())
203 for (
auto &block : region.getBlocks())
204 markBlockExecutable(&block);
207void IMDeadCodeElimPass::visitUser(Operation *op) {
208 LLVM_DEBUG(llvm::dbgs() <<
"Visit: " << *op <<
"\n");
209 if (
auto connectOp = dyn_cast<FConnectLike>(op))
210 return visitConnect(connectOp);
211 if (isa<SubfieldOp, SubindexOp, SubaccessOp, ObjectSubfieldOp>(op))
212 return visitSubelement(op);
215void IMDeadCodeElimPass::markFInstanceLikeOp(FInstanceLike instanceLike) {
216 if (
auto instance = dyn_cast<InstanceOp>(*instanceLike)) {
218 Operation *op = instance.getReferencedModule(*instanceGraph);
222 if (!isa<FModuleOp>(op)) {
223 auto module = dyn_cast<FModuleLike>(op);
224 for (
auto resultNo : llvm::seq(0u, instance.getNumResults())) {
226 if (module.getPortDirection(resultNo) == Direction::Out)
230 markAlive(instance.getResult(resultNo));
238 auto fModule = cast<FModuleOp>(op);
239 markBlockExecutable(fModule.getBodyBlock());
245 markAlive(instanceLike);
246 markBlockUndeletable(instanceLike);
249 for (
auto result : instanceLike->getResults())
253 for (
auto moduleName : instanceLike.getReferencedModuleNamesAttr()) {
254 auto *node = instanceGraph->
lookup(cast<StringAttr>(moduleName));
258 if (
auto fModule = dyn_cast<FModuleOp>(*node->getModule())) {
259 markBlockExecutable(fModule.getBodyBlock());
260 for (
auto result : fModule.getBodyBlock()->getArguments())
266void IMDeadCodeElimPass::markBlockExecutable(Block *block) {
267 if (!executableBlocks.insert(block).second)
270 auto fmodule = dyn_cast<FModuleOp>(block->getParentOp());
271 if (fmodule && (fmodule.isPublic() || removePortsOnly))
275 for (
auto blockArg : block->getArguments())
282 for (
auto &op : *block) {
283 if (
auto instance = dyn_cast<FInstanceLike>(op)) {
284 markFInstanceLikeOp(instance);
289 if (isa<FConnectLike>(op))
292 if (removePortsOnly) {
294 markUnknownSideEffectOp(&op);
300 markDeclaration(&op);
302 markUnknownSideEffectOp(&op);
308void IMDeadCodeElimPass::forwardConstantOutputPort(FModuleOp module) {
311 SmallVector<std::pair<unsigned, std::optional<APSInt>>>
312 constantPortIndicesAndValues;
313 auto ports =
module.getPorts();
314 auto *instanceGraphNode = instanceGraph->
lookup(module);
316 for (
const auto &e : llvm::enumerate(ports)) {
317 unsigned index = e.index();
318 auto port = e.value();
319 auto arg =
module.getArgument(index);
327 if (
auto constant =
connect.getSrc().getDefiningOp<ConstantOp>())
328 constantPortIndicesAndValues.push_back({index, constant.getValue()});
329 else if (
connect.getSrc().getDefiningOp<InvalidValueOp>())
330 constantPortIndicesAndValues.push_back({index, std::nullopt});
335 if (constantPortIndicesAndValues.empty())
339 for (
auto *use : instanceGraphNode->uses()) {
340 auto instance = use->getInstance<InstanceOp>();
344 ImplicitLocOpBuilder builder(instance.getLoc(), instance);
345 for (
auto [index, constant] : constantPortIndicesAndValues) {
346 auto result = instance.getResult(index);
347 assert(ports[index].isOutput() &&
"must be an output port");
352 replacement = ConstantOp::create(builder, *constant);
354 replacement = InvalidValueOp::create(builder, result.getType());
355 result.replaceAllUsesWith(replacement);
360void IMDeadCodeElimPass::runOnOperation() {
363 auto circuits = getOperation().getOps<CircuitOp>();
364 if (circuits.empty())
367 auto circuit = *circuits.begin();
369 if (!llvm::hasSingleElement(circuits)) {
370 mlir::emitError(circuit.getLoc(),
371 "cannot process multiple circuit operations")
372 .attachNote((*std::next(circuits.begin())).getLoc())
373 <<
"second circuit here";
374 return signalPassFailure();
377 instanceGraph = &getChildAnalysis<InstanceGraph>(circuit);
378 symbolTable = &getChildAnalysis<SymbolTable>(circuit);
379 auto &istc = getChildAnalysis<hw::InnerSymbolTableCollection>(circuit);
381 circt::hw::InnerRefNamespace theInnerRefNamespace{*symbolTable, istc};
382 innerRefNamespace = &theInnerRefNamespace;
385 getOperation().walk([&](Operation *op) {
386 if (isa<FModuleOp>(op))
389 if (
auto hierPath = dyn_cast<hw::HierPathOp>(op)) {
390 auto namePath = hierPath.getNamepath().getValue();
393 if (hierPath.isPublic() || namePath.size() <= 1 ||
394 isa<hw::InnerRefAttr>(namePath.back()))
395 return markAlive(hierPath);
398 dyn_cast_or_null<firrtl::InstanceOp>(innerRefNamespace->
lookupOp(
399 cast<hw::InnerRefAttr>(namePath.drop_back().back()))))
400 instanceToHierPaths[instance].push_back(hierPath);
406 op->getAttrDictionary().walk([&](Attribute attr) {
407 if (
auto innerRef = dyn_cast<hw::InnerRefAttr>(attr)) {
409 if (
auto instance = dyn_cast_or_null<firrtl::InstanceOp>(
410 innerRefNamespace->
lookupOp(innerRef)))
415 if (
auto symbolRef = dyn_cast<FlatSymbolRefAttr>(attr)) {
416 auto *symbol = symbolTable->lookup(symbolRef.getAttr());
421 if (
auto hierPath = dyn_cast<hw::HierPathOp>(symbol))
425 if (
auto module = dyn_cast<FModuleOp>(symbol)) {
426 if (!isa<firrtl::InstanceOp>(op)) {
427 LLVM_DEBUG(llvm::dbgs()
428 <<
"Unknown use of " << module.getModuleNameAttr()
429 <<
" in " << op->getName() <<
"\n");
431 markBlockExecutable(module.getBodyBlock());
443 SmallVector<FModuleOp, 0> modules(llvm::make_filter_range(
445 llvm::post_order(instanceGraph),
446 [](
auto *node) {
return dyn_cast<FModuleOp>(*node->getModule()); }),
447 [](
auto module) {
return module; }));
451 for (
auto module : modules)
452 forwardConstantOutputPort(module);
454 for (
auto module : circuit.getBodyBlock()->getOps<FModuleOp>()) {
455 bool isPublic =
module.isPublic();
456 if (isPublic || removePortsOnly) {
457 markBlockExecutable(module.getBodyBlock());
460 for (
auto port : module.getBodyBlock()->getArguments())
466 auto visitAnnotation = [&](
int portId, Annotation anno) ->
bool {
467 auto hierPathSym = anno.getMember<FlatSymbolRefAttr>(
"circt.nonlocal");
468 hw::HierPathOp hierPathOp;
471 symbolTable->template lookup<hw::HierPathOp>(hierPathSym.getAttr());
474 markAlive(hierPathOp);
476 markAlive(module.getArgument(portId));
483 module, std::bind(visitAnnotation, -1, std::placeholders::_1));
487 while (!worklist.empty()) {
488 auto v = worklist.pop_back_val();
489 if (
auto *value = std::get_if<Value>(&v))
491 else if (
auto *instance = std::get_if<FInstanceLike>(&v))
492 visitFInstanceLikeOp(*instance);
493 else if (
auto *hierpath = std::get_if<hw::HierPathOp>(&v))
494 visitHierPathOp(*hierpath);
495 else if (
auto *module = std::get_if<FModuleOp>(&v))
496 visitModuleOp(*module);
500 for (
auto module : llvm::make_early_inc_range(
501 circuit.getBodyBlock()->getOps<FModuleOp>())) {
502 if (isBlockExecutable(module.getBodyBlock()))
503 rewriteModuleSignature(module);
514 mlir::parallelForEach(circuit.getContext(),
515 circuit.getBodyBlock()->getOps<FModuleOp>(),
516 [&](
auto op) { rewriteModuleBody(op); });
519 for (
auto op : llvm::make_early_inc_range(
520 circuit.getBodyBlock()->getOps<hw::HierPathOp>()))
521 if (!liveElements.count(op))
524 if (!removePortsOnly)
525 for (
auto module : modules)
526 eraseEmptyModule(module);
529 executableBlocks.clear();
530 liveElements.clear();
531 instanceToHierPaths.clear();
534void IMDeadCodeElimPass::visitValue(Value value) {
535 assert(isKnownAlive(value) &&
"only alive values reach here");
538 for (Operation *user : value.getUsers())
541 if (
auto blockArg = dyn_cast<BlockArgument>(value)) {
543 dyn_cast<FModuleOp>(blockArg.getParentBlock()->getParentOp())) {
544 auto portDirection =
module.getPortDirection(blockArg.getArgNumber());
548 if (portDirection == Direction::In) {
549 for (
auto *instRec : instanceGraph->
lookup(module)->
uses()) {
551 if (
auto instance = instRec->getInstance<InstanceOp>()) {
552 if (liveElements.contains(instance))
553 markAlive(instance.getResult(blockArg.getArgNumber()));
560 for (
auto domain : cast<ArrayAttr>(
561 module.getDomainInfoAttrForPort(blockArg.getArgNumber())))
562 markAlive(module.getArgument(
563 cast<IntegerAttr>(domain).getValue().getZExtValue()));
570 if (
auto instance = value.getDefiningOp<InstanceOp>()) {
571 auto instanceResult = cast<mlir::OpResult>(value);
573 auto module = instance.getReferencedModule<FModuleOp>(*instanceGraph);
576 if (!module || module.getPortDirection(instanceResult.getResultNumber()) ==
582 BlockArgument modulePortVal =
583 module.getArgument(instanceResult.getResultNumber());
584 return markAlive(modulePortVal);
588 if (
auto mem = value.getDefiningOp<MemOp>()) {
589 for (
auto port : mem->getResults())
596 if (
auto *op = value.getDefiningOp()) {
597 for (
auto operand : op->getOperands())
599 for (
auto ®ion : op->getRegions())
600 for (
auto &block : region)
601 markBlockExecutable(&block);
605 if (
auto fop = value.getDefiningOp<Forceable>();
606 fop && fop.isForceable() &&
607 (fop.getData() == value || fop.getDataRef() == value)) {
608 markAlive(fop.getData());
609 markAlive(fop.getDataRef());
613void IMDeadCodeElimPass::visitConnect(FConnectLike connect) {
615 if (isKnownAlive(
connect.getDest()))
619void IMDeadCodeElimPass::visitSubelement(Operation *op) {
620 if (isKnownAlive(op->getOperand(0)))
621 markAlive(op->getResult(0));
624void IMDeadCodeElimPass::rewriteModuleBody(FModuleOp module) {
625 assert(isBlockExecutable(module.getBodyBlock()) &&
626 "unreachable modules must be already deleted");
628 auto removeDeadNonLocalAnnotations = [&](
int _, Annotation anno) ->
bool {
629 auto hierPathSym = anno.getMember<FlatSymbolRefAttr>(
"circt.nonlocal");
633 symbolTable->template lookup<hw::HierPathOp>(hierPathSym.getAttr());
634 return !liveElements.count(hierPathOp);
640 std::bind(removeDeadNonLocalAnnotations, -1, std::placeholders::_1));
643 module.walk<mlir::WalkOrder::PostOrder, mlir::ReverseIterator>(
646 LLVM_DEBUG(llvm::dbgs() << "Visit: " << *op << "\n");
647 if (
auto connect = dyn_cast<FConnectLike>(op)) {
648 if (isAssumedDead(
connect.getDest())) {
649 LLVM_DEBUG(llvm::dbgs() <<
"DEAD: " << connect <<
"\n";);
659 LLVM_DEBUG(llvm::dbgs() <<
"DEAD: " << *op <<
"\n";);
660 assert(op->use_empty() &&
"users should be already removed");
667 if (mlir::isOpTriviallyDead(op)) {
674void IMDeadCodeElimPass::rewriteModuleSignature(FModuleOp module) {
675 assert(isBlockExecutable(module.getBodyBlock()) &&
676 "unreachable modules must be already deleted");
678 LLVM_DEBUG(llvm::dbgs() <<
"Prune ports of module: " << module.getName()
681 auto replaceInstanceResultWithWire =
682 [&](ImplicitLocOpBuilder &builder,
unsigned index, InstanceOp instance) {
683 auto result = instance.getResult(index);
684 if (isAssumedDead(result)) {
688 mlir::UnrealizedConversionCastOp::create(
689 builder, ArrayRef<Type>{result.getType()}, ArrayRef<Value>{})
691 result.replaceAllUsesWith(wire);
695 Value wire = WireOp::create(builder, result.getType()).getResult();
696 result.replaceAllUsesWith(wire);
700 liveElements.erase(result);
701 liveElements.insert(wire);
705 for (
auto *use : llvm::make_early_inc_range(instanceGraphNode->
uses())) {
706 auto instanceLike = use->getInstance<FInstanceLike>();
707 if (instanceLike && !liveElements.count(instanceLike)) {
708 auto instance = cast<InstanceOp>(instanceLike);
710 ImplicitLocOpBuilder builder(instance.getLoc(), instance);
711 for (
auto index : llvm::seq(0u, instance.getNumResults()))
712 replaceInstanceResultWithWire(builder, index, instance);
720 if (module.isPublic())
723 unsigned numOldPorts =
module.getNumPorts();
724 llvm::BitVector deadPortIndexes(numOldPorts);
726 ImplicitLocOpBuilder builder(module.getLoc(), module.getContext());
727 builder.setInsertionPointToStart(module.getBodyBlock());
728 auto oldPorts =
module.getPorts();
730 for (
auto index : llvm::seq(0u, numOldPorts)) {
731 auto argument =
module.getArgument(index);
733 "If the port has don't touch, it should be known alive");
739 if (isKnownAlive(argument)) {
743 if (module.getPortDirection(index) == Direction::In)
748 if (llvm::any_of(instanceGraph->
lookup(module)->
uses(),
751 record->getInstance().getOperation()->getResult(
758 auto wire = WireOp::create(builder, argument.getType()).getResult();
761 liveElements.erase(argument);
762 liveElements.insert(wire);
763 argument.replaceAllUsesWith(wire);
764 deadPortIndexes.set(index);
771 mlir::UnrealizedConversionCastOp::create(
772 builder, ArrayRef<Type>{argument.getType()}, ArrayRef<Value>{})
775 argument.replaceAllUsesWith(wire);
776 assert(isAssumedDead(wire) &&
"dummy wire must be dead");
777 deadPortIndexes.set(index);
781 if (deadPortIndexes.none())
786 for (
auto arg : module.getArguments())
787 liveElements.erase(arg);
790 module.erasePorts(deadPortIndexes);
793 for (
auto arg : module.getArguments())
794 liveElements.insert(arg);
797 for (
auto *use : llvm::make_early_inc_range(instanceGraphNode->
uses())) {
798 auto instance = use->getInstance<InstanceOp>();
800 assert(!use->getInstance<FInstanceLike>() &&
801 "if this is not an instance, it must be marked overdefined");
805 ImplicitLocOpBuilder builder(instance.getLoc(), instance);
807 for (
auto index : deadPortIndexes.set_bits())
808 replaceInstanceResultWithWire(builder, index, instance);
812 for (
auto oldResult : instance.getResults())
813 liveElements.erase(oldResult);
817 instance.cloneWithErasedPortsAndReplaceUses(deadPortIndexes);
820 for (
auto newResult : newInstance->getResults())
821 liveElements.insert(newResult);
824 if (liveElements.contains(instance)) {
825 liveElements.erase(instance);
826 liveElements.insert(newInstance);
832 numRemovedPorts += deadPortIndexes.count();
835void IMDeadCodeElimPass::eraseEmptyModule(FModuleOp module) {
837 if (!module.getBodyBlock()->empty())
841 if (module.isPublic()) {
842 mlir::emitWarning(module.getLoc())
843 <<
"module `" <<
module.getName()
844 << "` is empty but cannot be removed because the module is public";
848 if (!module.getAnnotations().empty()) {
849 module.emitWarning() << "module `" << module.getName()
850 << "` is empty but cannot be removed "
851 "because the module has annotations "
852 << module.getAnnotations();
856 if (!module.getBodyBlock()->args_empty()) {
857 auto diag =
module.emitWarning()
858 << "module `" << module.getName()
859 << "` is empty but cannot be removed because the "
861 llvm::interleaveComma(module.getPortNames(), diag);
862 diag <<
" are referenced by name or dontTouched";
867 LLVM_DEBUG(llvm::dbgs() <<
"Erase " << module.getName() <<
"\n");
870 instanceGraph->
lookup(module.getModuleNameAttr());
872 SmallVector<Location> instancesWithSymbols;
873 for (
auto *use : llvm::make_early_inc_range(instanceGraphNode->
uses())) {
874 auto instance = use->getInstance<InstanceOp>();
877 if (instance.getInnerSym()) {
878 instancesWithSymbols.push_back(instance.getLoc());
886 if (!instancesWithSymbols.empty()) {
887 auto diag =
module.emitWarning()
888 << "module `" << module.getName()
889 << "` is empty but cannot be removed because an instance is "
890 "referenced by name";
891 diag.attachNote(FusedLoc::get(&getContext(), instancesWithSymbols))
892 <<
"these are instances with symbols";
897 if (liveElements.contains(module))
900 instanceGraph->
erase(instanceGraphNode);
assert(baseType &&"element must be base type")
static bool isDeletableDeclaration(Operation *op)
Return true if this is a wire or register we're allowed to delete.
static bool hasUnknownSideEffect(Operation *op)
static bool isDeclaration(Operation *op)
Return true if this is a wire or a register or a node.
#define CIRCT_DEBUG_SCOPED_PASS_LOGGER(PASS)
This class provides a read-only projection over the MLIR attributes that represent a set of annotatio...
bool removeAnnotations(llvm::function_ref< bool(Annotation)> predicate)
Remove all annotations from this annotation set for which predicate returns true.
static bool removePortAnnotations(Operation *module, llvm::function_ref< bool(unsigned, Annotation)> predicate)
Remove all port annotations from a module or extmodule for which predicate returns true.
llvm::iterator_range< UseIterator > uses()
virtual void replaceInstance(InstanceOpInterface inst, InstanceOpInterface newInst)
Replaces an instance of a module with another instance.
virtual void erase(InstanceGraphNode *node)
Remove this module from the instance graph.
InstanceGraphNode * lookup(ModuleOpInterface op)
Look up an InstanceGraphNode for a module.
connect(destination, source)
bool hasDontTouch(Value value)
Check whether a block argument ("port") or the operation defining a value has a DontTouch annotation,...
igraph::InstanceRecord InstanceRecord
MatchingConnectOp getSingleConnectUserOf(Value value)
Scan all the uses of the specified value, checking to see if there is exactly one connect that has th...
igraph::InstanceGraphNode InstanceGraphNode
std::map< std::string, std::set< std::string > > InstanceGraph
Iterates over the handshake::FuncOp's in the program to build an instance graph.
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
Operation * lookupOp(hw::InnerRefAttr inner) const
Resolve the InnerRef to its target within this namespace, returning empty target if no such name exis...