CIRCT 22.0.0git
Loading...
Searching...
No Matches
IMDeadCodeElim.cpp
Go to the documentation of this file.
1//===- IMDeadCodeElim.cpp - Intermodule Dead Code Elimination ---*- 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
14#include "circt/Support/Debug.h"
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"
23
24#define DEBUG_TYPE "firrtl-imdeadcodeelim"
25
26namespace circt {
27namespace firrtl {
28#define GEN_PASS_DEF_IMDEADCODEELIM
29#include "circt/Dialect/FIRRTL/Passes.h.inc"
30} // namespace firrtl
31} // namespace circt
32
33using namespace circt;
34using namespace firrtl;
35
36// Return true if this op has side-effects except for alloc and read.
37static bool hasUnknownSideEffect(Operation *op) {
38 return !(mlir::isMemoryEffectFree(op) ||
39 mlir::hasSingleEffect<mlir::MemoryEffects::Allocate>(op) ||
40 mlir::hasSingleEffect<mlir::MemoryEffects::Read>(op));
41}
42
43/// Return true if this is a wire or a register or a node.
44static bool isDeclaration(Operation *op) {
45 return isa<WireOp, RegResetOp, RegOp, NodeOp, MemOp>(op);
46}
47
48/// Return true if this is a wire or register we're allowed to delete.
49static bool isDeletableDeclaration(Operation *op) {
50 if (auto name = dyn_cast<FNamableOp>(op))
51 if (!name.hasDroppableName())
52 return false;
53 return !hasDontTouch(op) && AnnotationSet(op).empty();
54}
55
56namespace {
57struct IMDeadCodeElimPass
58 : public circt::firrtl::impl::IMDeadCodeElimBase<IMDeadCodeElimPass> {
59 void runOnOperation() override;
60
61 void rewriteModuleSignature(FModuleOp module);
62 void rewriteModuleBody(FModuleOp module);
63 void eraseEmptyModule(FModuleOp module);
64 void forwardConstantOutputPort(FModuleOp module);
65
66 /// Return true if the value is known alive.
67 bool isKnownAlive(Value value) const {
68 assert(value && "null should not be used");
69 return liveElements.count(value);
70 }
71
72 /// Return true if the value is assumed dead.
73 bool isAssumedDead(Value value) const { return !isKnownAlive(value); }
74 bool isAssumedDead(Operation *op) const {
75 return llvm::none_of(op->getResults(),
76 [&](Value value) { return isKnownAlive(value); });
77 }
78
79 /// Return true if the block is alive.
80 bool isBlockExecutable(Block *block) const {
81 return executableBlocks.count(block);
82 }
83
84 void visitUser(Operation *op);
85 void visitValue(Value value);
86
87 void visitConnect(FConnectLike connect);
88 void visitSubelement(Operation *op);
89 void markBlockExecutable(Block *block);
90 void markBlockUndeletable(Operation *op) {
91 markAlive(op->getParentOfType<FModuleOp>());
92 }
93
94 void markDeclaration(Operation *op);
95 void markInstanceOp(InstanceOp instanceOp);
96 void markObjectOp(ObjectOp objectOp);
97 void markUnknownSideEffectOp(Operation *op);
98 void visitInstanceOp(InstanceOp instance);
99 void visitHierPathOp(hw::HierPathOp hierpath);
100 void visitModuleOp(FModuleOp module);
101
102private:
103 /// The set of blocks that are known to execute, or are intrinsically alive.
104 DenseSet<Block *> executableBlocks;
105
106 InstanceGraph *instanceGraph;
107
108 // The type with which we associate liveness.
109 using ElementType =
110 std::variant<Value, FModuleOp, InstanceOp, hw::HierPathOp>;
111
112 void markAlive(ElementType element) {
113 if (!liveElements.insert(element).second)
114 return;
115 worklist.push_back(element);
116 }
117
118 /// A worklist of values whose liveness recently changed, indicating
119 /// the users need to be reprocessed.
120 SmallVector<ElementType, 64> worklist;
121 llvm::DenseSet<ElementType> liveElements;
122
123 /// A map from instances to hierpaths whose last path is the associated
124 /// instance.
125 DenseMap<InstanceOp, SmallVector<hw::HierPathOp>> instanceToHierPaths;
126
127 /// Hierpath to its users (=non-local annotation targets).
128 DenseMap<hw::HierPathOp, SetVector<ElementType>> hierPathToElements;
129
130 /// A cache for a (inner)symbol lookp.
131 circt::hw::InnerRefNamespace *innerRefNamespace;
132 mlir::SymbolTable *symbolTable;
133};
134} // namespace
135
136void IMDeadCodeElimPass::visitInstanceOp(InstanceOp instance) {
137 markBlockUndeletable(instance);
138
139 auto module = instance.getReferencedModule<FModuleOp>(*instanceGraph);
140
141 if (!module)
142 return;
143
144 // NOTE: Don't call `markAlive(module)` here as liveness of instance doesn't
145 // imply the global liveness of the module.
146
147 // Propgate liveness through hierpath.
148 for (auto hierPath : instanceToHierPaths[instance])
149 markAlive(hierPath);
150
151 // Input ports get alive only when the instance is alive.
152 for (auto &blockArg : module.getBody().getArguments()) {
153 auto portNo = blockArg.getArgNumber();
154 if (module.getPortDirection(portNo) == Direction::In &&
155 isKnownAlive(module.getArgument(portNo)))
156 markAlive(instance.getResult(portNo));
157 }
158}
159
160void IMDeadCodeElimPass::visitModuleOp(FModuleOp module) {
161 // If the module needs to be alive, so are its instances.
162 for (auto *use : instanceGraph->lookup(module)->uses())
163 markAlive(cast<InstanceOp>(*use->getInstance()));
164}
165
166void IMDeadCodeElimPass::visitHierPathOp(hw::HierPathOp hierPathOp) {
167 // If the hierpath is alive, mark all instances on the path alive.
168 for (auto path : hierPathOp.getNamepathAttr())
169 if (auto innerRef = dyn_cast<hw::InnerRefAttr>(path)) {
170 auto *op = innerRefNamespace->lookupOp(innerRef);
171 if (auto instance = dyn_cast_or_null<InstanceOp>(op))
172 markAlive(instance);
173 }
174
175 for (auto elem : hierPathToElements[hierPathOp])
176 markAlive(elem);
177}
178
179void IMDeadCodeElimPass::markDeclaration(Operation *op) {
180 assert(isDeclaration(op) && "only a declaration is expected");
181 if (!isDeletableDeclaration(op)) {
182 for (auto result : op->getResults())
183 markAlive(result);
184 markBlockUndeletable(op);
185 }
186}
187
188void IMDeadCodeElimPass::markUnknownSideEffectOp(Operation *op) {
189 // For operations with side effects, pessimistically mark results and
190 // operands as alive.
191 for (auto result : op->getResults())
192 markAlive(result);
193 for (auto operand : op->getOperands())
194 markAlive(operand);
195 markBlockUndeletable(op);
196}
197
198void IMDeadCodeElimPass::visitUser(Operation *op) {
199 LLVM_DEBUG(llvm::dbgs() << "Visit: " << *op << "\n");
200 if (auto connectOp = dyn_cast<FConnectLike>(op))
201 return visitConnect(connectOp);
202 if (isa<SubfieldOp, SubindexOp, SubaccessOp, ObjectSubfieldOp>(op))
203 return visitSubelement(op);
204}
205
206void IMDeadCodeElimPass::markInstanceOp(InstanceOp instance) {
207 // Get the module being referenced.
208 Operation *op = instance.getReferencedModule(*instanceGraph);
209
210 // If this is an extmodule, just remember that any inputs and inouts are
211 // alive.
212 if (!isa<FModuleOp>(op)) {
213 auto module = dyn_cast<FModuleLike>(op);
214 for (auto resultNo : llvm::seq(0u, instance.getNumResults())) {
215 // If this is an output to the extmodule, we can ignore it.
216 if (module.getPortDirection(resultNo) == Direction::Out)
217 continue;
218
219 // Otherwise this is an input from it or an inout, mark it as alive.
220 markAlive(instance.getResult(resultNo));
221 }
222 markAlive(instance);
223
224 return;
225 }
226
227 // Otherwise this is a defined module.
228 auto fModule = cast<FModuleOp>(op);
229 markBlockExecutable(fModule.getBodyBlock());
230}
231
232void IMDeadCodeElimPass::markObjectOp(ObjectOp object) {
233 // unconditionally keep all objects alive.
234 markAlive(object);
235}
236
237void IMDeadCodeElimPass::markBlockExecutable(Block *block) {
238 if (!executableBlocks.insert(block).second)
239 return; // Already executable.
240
241 auto fmodule = dyn_cast<FModuleOp>(block->getParentOp());
242 if (fmodule && fmodule.isPublic())
243 markAlive(fmodule);
244
245 // Mark ports with don't touch as alive.
246 for (auto blockArg : block->getArguments())
247 if (hasDontTouch(blockArg)) {
248 markAlive(blockArg);
249 if (fmodule)
250 markAlive(fmodule);
251 }
252
253 for (auto &op : *block) {
254 if (isDeclaration(&op))
255 markDeclaration(&op);
256 else if (auto instance = dyn_cast<InstanceOp>(op))
257 markInstanceOp(instance);
258 else if (auto object = dyn_cast<ObjectOp>(op))
259 markObjectOp(object);
260 else if (isa<FConnectLike>(op))
261 // Skip connect op.
262 continue;
263 else if (hasUnknownSideEffect(&op)) {
264 markUnknownSideEffectOp(&op);
265 // Recursively mark any blocks contained within these operations as
266 // executable.
267 for (auto &region : op.getRegions())
268 for (auto &block : region.getBlocks())
269 markBlockExecutable(&block);
270 }
271
272 // TODO: Handle attach etc.
273 }
274}
275
276void IMDeadCodeElimPass::forwardConstantOutputPort(FModuleOp module) {
277 // This tracks constant values of output ports.
278 SmallVector<std::pair<unsigned, APSInt>> constantPortIndicesAndValues;
279 auto ports = module.getPorts();
280 auto *instanceGraphNode = instanceGraph->lookup(module);
281
282 for (const auto &e : llvm::enumerate(ports)) {
283 unsigned index = e.index();
284 auto port = e.value();
285 auto arg = module.getArgument(index);
286
287 // If the port has don't touch, don't propagate the constant value.
288 if (!port.isOutput() || hasDontTouch(arg))
289 continue;
290
291 // Remember the index and constant value connected to an output port.
292 if (auto connect = getSingleConnectUserOf(arg))
293 if (auto constant = connect.getSrc().getDefiningOp<ConstantOp>())
294 constantPortIndicesAndValues.push_back({index, constant.getValue()});
295 }
296
297 // If there is no constant port, abort.
298 if (constantPortIndicesAndValues.empty())
299 return;
300
301 // Rewrite all uses.
302 for (auto *use : instanceGraphNode->uses()) {
303 auto instance = cast<InstanceOp>(*use->getInstance());
304 ImplicitLocOpBuilder builder(instance.getLoc(), instance);
305 for (auto [index, constant] : constantPortIndicesAndValues) {
306 auto result = instance.getResult(index);
307 assert(ports[index].isOutput() && "must be an output port");
308
309 // Replace the port with the constant.
310 result.replaceAllUsesWith(ConstantOp::create(builder, constant));
311 }
312 }
313}
314
315void IMDeadCodeElimPass::runOnOperation() {
317
318 auto circuits = getOperation().getOps<CircuitOp>();
319 if (circuits.empty())
320 return;
321
322 auto circuit = *circuits.begin();
323
324 if (!llvm::hasSingleElement(circuits)) {
325 mlir::emitError(circuit.getLoc(),
326 "cannot process multiple circuit operations")
327 .attachNote((*std::next(circuits.begin())).getLoc())
328 << "second circuit here";
329 return signalPassFailure();
330 }
331
332 instanceGraph = &getChildAnalysis<InstanceGraph>(circuit);
333 symbolTable = &getChildAnalysis<SymbolTable>(circuit);
334 auto &istc = getChildAnalysis<hw::InnerSymbolTableCollection>(circuit);
335
336 circt::hw::InnerRefNamespace theInnerRefNamespace{*symbolTable, istc};
337 innerRefNamespace = &theInnerRefNamespace;
338
339 // Walk attributes and find unknown uses of inner symbols or hierpaths.
340 getOperation().walk([&](Operation *op) {
341 if (isa<FModuleOp>(op)) // Port or module annotations are ok to ignore.
342 return;
343
344 if (auto hierPath = dyn_cast<hw::HierPathOp>(op)) {
345 auto namePath = hierPath.getNamepath().getValue();
346 // If the hierpath is public or ill-formed, the verifier should have
347 // caught the error. Conservatively mark the symbol as alive.
348 if (hierPath.isPublic() || namePath.size() <= 1 ||
349 isa<hw::InnerRefAttr>(namePath.back()))
350 return markAlive(hierPath);
351
352 if (auto instance =
353 dyn_cast_or_null<firrtl::InstanceOp>(innerRefNamespace->lookupOp(
354 cast<hw::InnerRefAttr>(namePath.drop_back().back()))))
355 instanceToHierPaths[instance].push_back(hierPath);
356 return;
357 }
358
359 // If there is an unknown symbol or inner symbol use, mark all of them
360 // alive.
361 op->getAttrDictionary().walk([&](Attribute attr) {
362 if (auto innerRef = dyn_cast<hw::InnerRefAttr>(attr)) {
363 // Mark instances alive that are targeted by an inner ref.
364 if (auto instance = dyn_cast_or_null<firrtl::InstanceOp>(
365 innerRefNamespace->lookupOp(innerRef)))
366 markAlive(instance);
367 return;
368 }
369
370 if (auto symbolRef = dyn_cast<FlatSymbolRefAttr>(attr)) {
371 auto *symbol = symbolTable->lookup(symbolRef.getAttr());
372 if (!symbol)
373 return;
374
375 // Mark referenced hierarchical paths alive.
376 if (auto hierPath = dyn_cast<hw::HierPathOp>(symbol))
377 markAlive(hierPath);
378
379 // Mark modules referenced by unknown ops alive.
380 if (auto module = dyn_cast<FModuleOp>(symbol)) {
381 if (!isa<firrtl::InstanceOp>(op)) {
382 LLVM_DEBUG(llvm::dbgs()
383 << "Unknown use of " << module.getModuleNameAttr()
384 << " in " << op->getName() << "\n");
385 markAlive(module);
386 markBlockExecutable(module.getBodyBlock());
387 }
388 }
389
390 return;
391 }
392 });
393 });
394
395 // Create a vector of modules in the post order of instance graph.
396 // FIXME: We copy the list of modules into a vector first to avoid iterator
397 // invalidation while we mutate the instance graph. See issue 3387.
398 SmallVector<FModuleOp, 0> modules(llvm::make_filter_range(
399 llvm::map_range(
400 llvm::post_order(instanceGraph),
401 [](auto *node) { return dyn_cast<FModuleOp>(*node->getModule()); }),
402 [](auto module) { return module; }));
403
404 // Forward constant output ports to caller sides so that we can eliminate
405 // constant outputs.
406 for (auto module : modules)
407 forwardConstantOutputPort(module);
408
409 for (auto module : circuit.getBodyBlock()->getOps<FModuleOp>()) {
410 // Mark the ports of public modules as alive.
411 if (module.isPublic()) {
412 markBlockExecutable(module.getBodyBlock());
413 for (auto port : module.getBodyBlock()->getArguments())
414 markAlive(port);
415 }
416
417 // Walk annotations and populate a map from hierpath to attached annotation
418 // targets. `portId` is `-1` for module annotations.
419 auto visitAnnotation = [&](int portId, Annotation anno) -> bool {
420 auto hierPathSym = anno.getMember<FlatSymbolRefAttr>("circt.nonlocal");
421 hw::HierPathOp hierPathOp;
422 if (hierPathSym)
423 hierPathOp =
424 symbolTable->template lookup<hw::HierPathOp>(hierPathSym.getAttr());
425
426 if (hierPathOp)
427 markAlive(hierPathOp);
428 if (portId >= 0)
429 markAlive(module.getArgument(portId));
430 markAlive(module);
431 return false;
432 };
433
434 AnnotationSet::removePortAnnotations(module, visitAnnotation);
436 module, std::bind(visitAnnotation, -1, std::placeholders::_1));
437 }
438
439 // If an element changed liveness then propagate liveness through it.
440 while (!worklist.empty()) {
441 auto v = worklist.pop_back_val();
442 if (auto *value = std::get_if<Value>(&v))
443 visitValue(*value);
444 else if (auto *instance = std::get_if<InstanceOp>(&v))
445 visitInstanceOp(*instance);
446 else if (auto *hierpath = std::get_if<hw::HierPathOp>(&v))
447 visitHierPathOp(*hierpath);
448 else if (auto *module = std::get_if<FModuleOp>(&v))
449 visitModuleOp(*module);
450 }
451
452 // Rewrite module signatures or delete unreachable modules.
453 for (auto module : llvm::make_early_inc_range(
454 circuit.getBodyBlock()->getOps<FModuleOp>())) {
455 if (isBlockExecutable(module.getBodyBlock()))
456 rewriteModuleSignature(module);
457 else {
458 // If the module is unreachable from the toplevel, just delete it.
459 // Note that post-order traversal on the instance graph never visit
460 // unreachable modules so it's safe to erase the module even though
461 // `modules` seems to be capturing module pointers.
462 module.erase();
463 }
464 }
465
466 // Rewrite module bodies parallelly.
467 mlir::parallelForEach(circuit.getContext(),
468 circuit.getBodyBlock()->getOps<FModuleOp>(),
469 [&](auto op) { rewriteModuleBody(op); });
470
471 // Clean up hierpaths.
472 for (auto op : llvm::make_early_inc_range(
473 circuit.getBodyBlock()->getOps<hw::HierPathOp>()))
474 if (!liveElements.count(op))
475 op.erase();
476
477 for (auto module : modules)
478 eraseEmptyModule(module);
479
480 // Clean up data structures.
481 executableBlocks.clear();
482 liveElements.clear();
483 instanceToHierPaths.clear();
484 hierPathToElements.clear();
485}
486
487void IMDeadCodeElimPass::visitValue(Value value) {
488 assert(isKnownAlive(value) && "only alive values reach here");
489
490 // Propagate liveness through users.
491 for (Operation *user : value.getUsers())
492 visitUser(user);
493
494 // Requiring an input port propagates the liveness to each instance.
495 if (auto blockArg = dyn_cast<BlockArgument>(value)) {
496 if (auto module =
497 dyn_cast<FModuleOp>(blockArg.getParentBlock()->getParentOp())) {
498 auto portDirection = module.getPortDirection(blockArg.getArgNumber());
499 // If the port is input, it's necessary to mark corresponding input ports
500 // of instances as alive. We don't have to propagate the liveness of
501 // output ports.
502 if (portDirection == Direction::In) {
503 for (auto *instRec : instanceGraph->lookup(module)->uses()) {
504 auto instance = cast<InstanceOp>(instRec->getInstance());
505 if (liveElements.contains(instance))
506 markAlive(instance.getResult(blockArg.getArgNumber()));
507 }
508 }
509 return;
510 }
511 }
512
513 // Marking an instance port as alive propagates to the corresponding port of
514 // the module.
515 if (auto instance = value.getDefiningOp<InstanceOp>()) {
516 auto instanceResult = cast<mlir::OpResult>(value);
517 // Update the src, when it's an instance op.
518 auto module = instance.getReferencedModule<FModuleOp>(*instanceGraph);
519
520 // Propagate liveness only when a port is output.
521 if (!module || module.getPortDirection(instanceResult.getResultNumber()) ==
522 Direction::In)
523 return;
524
525 markAlive(instance);
526
527 BlockArgument modulePortVal =
528 module.getArgument(instanceResult.getResultNumber());
529 return markAlive(modulePortVal);
530 }
531
532 // If a port of a memory is alive, all other ports are.
533 if (auto mem = value.getDefiningOp<MemOp>()) {
534 for (auto port : mem->getResults())
535 markAlive(port);
536 return;
537 }
538
539 // If the value is defined by an operation, mark its operands alive and any
540 // nested blocks executable.
541 if (auto op = value.getDefiningOp()) {
542 for (auto operand : op->getOperands())
543 markAlive(operand);
544 for (auto &region : op->getRegions())
545 for (auto &block : region)
546 markBlockExecutable(&block);
547 }
548
549 // If either result of a forceable declaration is alive, they both are.
550 if (auto fop = value.getDefiningOp<Forceable>();
551 fop && fop.isForceable() &&
552 (fop.getData() == value || fop.getDataRef() == value)) {
553 markAlive(fop.getData());
554 markAlive(fop.getDataRef());
555 }
556}
557
558void IMDeadCodeElimPass::visitConnect(FConnectLike connect) {
559 // If the dest is alive, mark the source value as alive.
560 if (isKnownAlive(connect.getDest()))
561 markAlive(connect.getSrc());
562}
563
564void IMDeadCodeElimPass::visitSubelement(Operation *op) {
565 if (isKnownAlive(op->getOperand(0)))
566 markAlive(op->getResult(0));
567}
568
569void IMDeadCodeElimPass::rewriteModuleBody(FModuleOp module) {
570 assert(isBlockExecutable(module.getBodyBlock()) &&
571 "unreachable modules must be already deleted");
572
573 auto removeDeadNonLocalAnnotations = [&](int _, Annotation anno) -> bool {
574 auto hierPathSym = anno.getMember<FlatSymbolRefAttr>("circt.nonlocal");
575 if (!hierPathSym)
576 return false;
577 auto hierPathOp =
578 symbolTable->template lookup<hw::HierPathOp>(hierPathSym.getAttr());
579 return !liveElements.count(hierPathOp);
580 };
581
582 AnnotationSet::removePortAnnotations(module, removeDeadNonLocalAnnotations);
584 module,
585 std::bind(removeDeadNonLocalAnnotations, -1, std::placeholders::_1));
586
587 // Walk the IR bottom-up when deleting operations.
588 module.walk<mlir::WalkOrder::PostOrder, mlir::ReverseIterator>(
589 [&](Operation *op) {
590 // Connects to values that we found to be dead can be dropped.
591 LLVM_DEBUG(llvm::dbgs() << "Visit: " << *op << "\n");
592 if (auto connect = dyn_cast<FConnectLike>(op)) {
593 if (isAssumedDead(connect.getDest())) {
594 LLVM_DEBUG(llvm::dbgs() << "DEAD: " << connect << "\n";);
595 connect.erase();
596 ++numErasedOps;
597 }
598 return;
599 }
600
601 // Delete dead wires, regs, nodes and alloc/read ops.
602 if ((isDeclaration(op) || !hasUnknownSideEffect(op)) &&
603 isAssumedDead(op)) {
604 LLVM_DEBUG(llvm::dbgs() << "DEAD: " << *op << "\n";);
605 assert(op->use_empty() && "users should be already removed");
606 op->erase();
607 ++numErasedOps;
608 return;
609 }
610
611 // Remove non-sideeffect op using `isOpTriviallyDead`.
612 if (mlir::isOpTriviallyDead(op)) {
613 op->erase();
614 ++numErasedOps;
615 }
616 });
617}
618
619void IMDeadCodeElimPass::rewriteModuleSignature(FModuleOp module) {
620 assert(isBlockExecutable(module.getBodyBlock()) &&
621 "unreachable modules must be already deleted");
622 InstanceGraphNode *instanceGraphNode = instanceGraph->lookup(module);
623 LLVM_DEBUG(llvm::dbgs() << "Prune ports of module: " << module.getName()
624 << "\n");
625
626 auto replaceInstanceResultWithWire = [&](ImplicitLocOpBuilder &builder,
627 unsigned index,
628 InstanceOp instance) {
629 auto result = instance.getResult(index);
630 if (isAssumedDead(result)) {
631 // If the result is dead, replace the result with an unrealized conversion
632 // cast which works as a dummy placeholder.
633 auto wire =
634 mlir::UnrealizedConversionCastOp::create(
635 builder, ArrayRef<Type>{result.getType()}, ArrayRef<Value>{})
636 ->getResult(0);
637 result.replaceAllUsesWith(wire);
638 return;
639 }
640
641 Value wire = WireOp::create(builder, result.getType()).getResult();
642 result.replaceAllUsesWith(wire);
643 // If a module port is dead but its instance result is alive, the port
644 // is used as a temporary wire so make sure that a replaced wire is
645 // putted into `liveSet`.
646 liveElements.erase(result);
647 liveElements.insert(wire);
648 };
649
650 // First, delete dead instances.
651 for (auto *use : llvm::make_early_inc_range(instanceGraphNode->uses())) {
652 auto instance = cast<InstanceOp>(*use->getInstance());
653 if (!liveElements.count(instance)) {
654 // Replace old instance results with dummy wires.
655 ImplicitLocOpBuilder builder(instance.getLoc(), instance);
656 for (auto index : llvm::seq(0u, instance.getNumResults()))
657 replaceInstanceResultWithWire(builder, index, instance);
658 // Make sure that we update the instance graph.
659 use->erase();
660 instance.erase();
661 }
662 }
663
664 // Ports of public modules cannot be modified.
665 if (module.isPublic())
666 return;
667
668 unsigned numOldPorts = module.getNumPorts();
669 llvm::BitVector deadPortIndexes(numOldPorts);
670
671 ImplicitLocOpBuilder builder(module.getLoc(), module.getContext());
672 builder.setInsertionPointToStart(module.getBodyBlock());
673 auto oldPorts = module.getPorts();
674
675 for (auto index : llvm::seq(0u, numOldPorts)) {
676 auto argument = module.getArgument(index);
677 assert((!hasDontTouch(argument) || isKnownAlive(argument)) &&
678 "If the port has don't touch, it should be known alive");
679
680 // If the port has dontTouch, skip.
681 if (hasDontTouch(argument))
682 continue;
683
684 if (isKnownAlive(argument)) {
685
686 // If an output port is only used internally in the module, then we can
687 // remove the port and replace it with a wire.
688 if (module.getPortDirection(index) == Direction::In)
689 continue;
690
691 // Check if the output port is demanded by any instance. If not, then it
692 // is only demanded internally to the module.
693 if (llvm::any_of(instanceGraph->lookup(module)->uses(),
694 [&](InstanceRecord *record) {
695 return isKnownAlive(
696 record->getInstance()->getResult(index));
697 }))
698 continue;
699
700 // Ok, this port is used only within its defined module. So we can replace
701 // the port with a wire.
702 auto wire = WireOp::create(builder, argument.getType()).getResult();
703
704 // Since `liveSet` contains the port, we have to erase it from the set.
705 liveElements.erase(argument);
706 liveElements.insert(wire);
707 argument.replaceAllUsesWith(wire);
708 deadPortIndexes.set(index);
709 continue;
710 }
711
712 // Replace the port with a dummy wire. This wire should be erased within
713 // `rewriteModuleBody`.
714 Value wire =
715 mlir::UnrealizedConversionCastOp::create(
716 builder, ArrayRef<Type>{argument.getType()}, ArrayRef<Value>{})
717 ->getResult(0);
718
719 argument.replaceAllUsesWith(wire);
720 assert(isAssumedDead(wire) && "dummy wire must be dead");
721 deadPortIndexes.set(index);
722 }
723
724 // If there is nothing to remove, abort.
725 if (deadPortIndexes.none())
726 return;
727
728 // Erase arguments of the old module from liveSet to prevent from creating
729 // dangling pointers.
730 for (auto arg : module.getArguments())
731 liveElements.erase(arg);
732
733 // Delete ports from the module.
734 module.erasePorts(deadPortIndexes);
735
736 // Add arguments of the new module to liveSet.
737 for (auto arg : module.getArguments())
738 liveElements.insert(arg);
739
740 // Rewrite all uses.
741 for (auto *use : llvm::make_early_inc_range(instanceGraphNode->uses())) {
742 auto instance = cast<InstanceOp>(*use->getInstance());
743 ImplicitLocOpBuilder builder(instance.getLoc(), instance);
744 // Replace old instance results with dummy wires.
745 for (auto index : deadPortIndexes.set_bits())
746 replaceInstanceResultWithWire(builder, index, instance);
747
748 // Since we will rewrite instance op, it is necessary to remove old
749 // instance results from liveSet.
750 for (auto oldResult : instance.getResults())
751 liveElements.erase(oldResult);
752
753 // Create a new instance op without dead ports.
754 auto newInstance = instance.erasePorts(builder, deadPortIndexes);
755
756 // Mark new results as alive.
757 for (auto newResult : newInstance.getResults())
758 liveElements.insert(newResult);
759
760 instanceGraph->replaceInstance(instance, newInstance);
761 if (liveElements.contains(instance)) {
762 liveElements.erase(instance);
763 liveElements.insert(newInstance);
764 }
765 // Remove old one.
766 instance.erase();
767 }
768
769 numRemovedPorts += deadPortIndexes.count();
770}
771
772void IMDeadCodeElimPass::eraseEmptyModule(FModuleOp module) {
773 // If the module is not empty, just skip.
774 if (!module.getBodyBlock()->empty())
775 return;
776
777 // We cannot delete public modules so generate a warning.
778 if (module.isPublic()) {
779 mlir::emitWarning(module.getLoc())
780 << "module `" << module.getName()
781 << "` is empty but cannot be removed because the module is public";
782 return;
783 }
784
785 if (!module.getAnnotations().empty()) {
786 module.emitWarning() << "module `" << module.getName()
787 << "` is empty but cannot be removed "
788 "because the module has annotations "
789 << module.getAnnotations();
790 return;
791 }
792
793 if (!module.getBodyBlock()->args_empty()) {
794 auto diag = module.emitWarning()
795 << "module `" << module.getName()
796 << "` is empty but cannot be removed because the "
797 "module has ports ";
798 llvm::interleaveComma(module.getPortNames(), diag);
799 diag << " are referenced by name or dontTouched";
800 return;
801 }
802
803 // Ok, the module is empty. Delete instances unless they have symbols.
804 LLVM_DEBUG(llvm::dbgs() << "Erase " << module.getName() << "\n");
805
806 InstanceGraphNode *instanceGraphNode =
807 instanceGraph->lookup(module.getModuleNameAttr());
808
809 SmallVector<Location> instancesWithSymbols;
810 for (auto *use : llvm::make_early_inc_range(instanceGraphNode->uses())) {
811 auto instance = cast<InstanceOp>(use->getInstance());
812 if (instance.getInnerSym()) {
813 instancesWithSymbols.push_back(instance.getLoc());
814 continue;
815 }
816 use->erase();
817 instance.erase();
818 }
819
820 // If there is an instance with a symbol, we don't delete the module itself.
821 if (!instancesWithSymbols.empty()) {
822 auto diag = module.emitWarning()
823 << "module `" << module.getName()
824 << "` is empty but cannot be removed because an instance is "
825 "referenced by name";
826 diag.attachNote(FusedLoc::get(&getContext(), instancesWithSymbols))
827 << "these are instances with symbols";
828 return;
829 }
830
831 // We cannot delete alive modules.
832 if (liveElements.contains(module))
833 return;
834
835 instanceGraph->erase(instanceGraphNode);
836 module.erase();
837 ++numErasedModules;
838}
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.
static Block * getBodyBlock(FModuleLike mod)
#define CIRCT_DEBUG_SCOPED_PASS_LOGGER(PASS)
Definition Debug.h:70
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.
This class provides a read-only projection of an annotation.
This graph tracks modules and where they are instantiated.
This is a Node in the InstanceGraph.
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.
This is an edge in the InstanceGraph.
connect(destination, source)
Definition support.py:39
bool hasDontTouch(Value value)
Check whether a block argument ("port") or the operation defining a value has a DontTouch annotation,...
MatchingConnectOp getSingleConnectUserOf(Value value)
Scan all the uses of the specified value, checking to see if there is exactly one connect that has th...
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
Definition hw.py:1
Definition seq.py:1
This class represents the namespace in which InnerRef's can be resolved.