MLIR 24.0.0git
GreedyPatternRewriteDriver.cpp
Go to the documentation of this file.
1//===- GreedyPatternRewriteDriver.cpp - A greedy rewriter -----------------===//
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//
9// This file implements mlir::applyPatternsGreedily.
10//
11//===----------------------------------------------------------------------===//
12
14
15#include "mlir/Config/mlir-config.h"
16#include "mlir/IR/Action.h"
17#include "mlir/IR/Dominance.h"
18#include "mlir/IR/Matchers.h"
19#include "mlir/IR/Operation.h"
21#include "mlir/IR/Verifier.h"
24#include "mlir/Transforms/CSE.h"
27#include "llvm/ADT/BitVector.h"
28#include "llvm/ADT/DenseMap.h"
29#include "llvm/ADT/ScopeExit.h"
30#include "llvm/ADT/SetVector.h"
31#include "llvm/ADT/SmallPtrSet.h"
32#include "llvm/Support/DebugLog.h"
33#include "llvm/Support/ScopedPrinter.h"
34#include "llvm/Support/raw_ostream.h"
35
36#ifdef MLIR_GREEDY_REWRITE_RANDOMIZER_SEED
37#include <random>
38#endif // MLIR_GREEDY_REWRITE_RANDOMIZER_SEED
39
40using namespace mlir;
41
42#define DEBUG_TYPE "greedy-rewriter"
43
44namespace {
45
46//===----------------------------------------------------------------------===//
47// Debugging Infrastructure
48//===----------------------------------------------------------------------===//
49
50#if MLIR_ENABLE_EXPENSIVE_PATTERN_API_CHECKS
51/// A helper struct that performs various "expensive checks" to detect broken
52/// rewrite patterns use the rewriter API incorrectly. A rewrite pattern is
53/// broken if:
54/// * IR does not verify after pattern application / folding.
55/// * Pattern returns "failure" but the IR has changed.
56/// * Pattern returns "success" but the IR has not changed.
57///
58/// This struct stores finger prints of ops to determine whether the IR has
59/// changed or not.
60struct ExpensiveChecks : public RewriterBase::ForwardingListener {
61 ExpensiveChecks(RewriterBase::Listener *listener, Operation *topLevel)
62 : RewriterBase::ForwardingListener(listener), topLevel(topLevel) {}
63
64 /// Compute finger prints of the given op and its nested ops.
65 void computeFingerPrints(Operation *topLevel) {
66 this->topLevel = topLevel;
67 this->topLevelFingerPrint.emplace(topLevel);
68 topLevel->walk([&](Operation *op) {
69 fingerprints.try_emplace(op, op, /*includeNested=*/false);
70 });
71 }
72
73 /// Clear all finger prints.
74 void clear() {
75 topLevel = nullptr;
76 topLevelFingerPrint.reset();
77 fingerprints.clear();
78 }
79
80 void notifyRewriteSuccess() {
81 if (!topLevel)
82 return;
83
84 // Make sure that the IR still verifies.
85 if (failed(verify(topLevel)))
86 llvm::report_fatal_error("IR failed to verify after pattern application");
87
88 // Pattern application success => IR must have changed.
89 OperationFingerPrint afterFingerPrint(topLevel);
90 if (*topLevelFingerPrint == afterFingerPrint) {
91 // Note: Run "mlir-opt -debug" to see which pattern is broken.
92 llvm::report_fatal_error(
93 "pattern returned success but IR did not change");
94 }
95 for (const auto &it : fingerprints) {
96 // Skip top-level op, its finger print is never invalidated.
97 if (it.first == topLevel)
98 continue;
99 // Note: Finger print computation may crash when an op was erased
100 // without notifying the rewriter. (Run with ASAN to see where the op was
101 // erased; the op was probably erased directly, bypassing the rewriter
102 // API.) Finger print computation does may not crash if a new op was
103 // created at the same memory location. (But then the finger print should
104 // have changed.)
105 if (it.second !=
106 OperationFingerPrint(it.first, /*includeNested=*/false)) {
107 // Note: Run "mlir-opt -debug" to see which pattern is broken.
108 llvm::report_fatal_error("operation finger print changed");
109 }
110 }
111 }
112
113 void notifyRewriteFailure() {
114 if (!topLevel)
115 return;
116
117 // Pattern application failure => IR must not have changed.
118 OperationFingerPrint afterFingerPrint(topLevel);
119 if (*topLevelFingerPrint != afterFingerPrint) {
120 // Note: Run "mlir-opt -debug" to see which pattern is broken.
121 llvm::report_fatal_error("pattern returned failure but IR did change");
122 }
123 }
124
125 void notifyFoldingSuccess() {
126 if (!topLevel)
127 return;
128
129 // Make sure that the IR still verifies.
130 if (failed(verify(topLevel)))
131 llvm::report_fatal_error("IR failed to verify after folding");
132 }
133
134protected:
135 /// Invalidate the finger print of the given op, i.e., remove it from the map.
136 void invalidateFingerPrint(Operation *op) { fingerprints.erase(op); }
137
138 void notifyBlockInserted(Block *block, Region *previous,
139 Region::iterator previousIt) override {
141 previousIt);
142
143 // Inserting or moving a block changes the region structure of both the
144 // new and previous owners. Either region may be detached.
145 invalidateFingerPrint(block->getParentOp());
146 if (previous)
147 invalidateFingerPrint(previous->getParentOp());
148 }
149
150 void notifyBlockErased(Block *block) override {
152
153 // The block structure (number of blocks, types of block arguments, etc.)
154 // is part of the fingerprint of the parent op.
155 // TODO: The parent op fingerprint should also be invalidated when modifying
156 // the block arguments of a block, but we do not have a
157 // `notifyBlockModified` callback yet.
158 invalidateFingerPrint(block->getParentOp());
159 }
160
162 OpBuilder::InsertPoint previous) override {
164 invalidateFingerPrint(op->getParentOp());
165 }
166
167 void notifyOperationModified(Operation *op) override {
169 invalidateFingerPrint(op);
170 }
171
172 void notifyOperationErased(Operation *op) override {
174 op->walk([this](Operation *op) { invalidateFingerPrint(op); });
175 }
176
177 /// Operation finger prints to detect invalid pattern API usage. IR is checked
178 /// against these finger prints after pattern application to detect cases
179 /// where IR was modified directly, bypassing the rewriter API.
181
182 /// Top-level operation of the current greedy rewrite.
183 Operation *topLevel = nullptr;
184
185 /// Finger print of the top-level operation.
186 std::optional<OperationFingerPrint> topLevelFingerPrint;
187};
188#endif // MLIR_ENABLE_EXPENSIVE_PATTERN_API_CHECKS
189
190#ifndef NDEBUG
191static Operation *getDumpRootOp(Operation *op) {
192 // Dump the parent op so that materialized constants are visible. If the op
193 // is a top-level op, dump it directly.
194 if (Operation *parentOp = op->getParentOp())
195 return parentOp;
196 return op;
197}
198static void logSuccessfulFolding(Operation *op) {
199 LDBG() << "// *** IR Dump After Successful Folding ***\n"
200 << OpWithFlags(op, OpPrintingFlags().elideLargeElementsAttrs());
201}
202#endif // NDEBUG
203
204//===----------------------------------------------------------------------===//
205// Worklist
206//===----------------------------------------------------------------------===//
207
208/// A LIFO worklist of operations with efficient removal and set semantics.
209///
210/// This class maintains a vector of operations and a mapping of operations to
211/// positions in the vector, so that operations can be removed efficiently at
212/// random. When an operation is removed, it is replaced with nullptr. Such
213/// nullptr are skipped when pop'ing elements.
214class Worklist {
215public:
216 Worklist();
217
218 /// Clear the worklist.
219 void clear();
220
221 /// Return whether the worklist is empty.
222 bool empty() const;
223
224 /// Push an operation to the end of the worklist, unless the operation is
225 /// already on the worklist.
226 void push(Operation *op);
227
228 /// Pop the an operation from the end of the worklist. Only allowed on
229 /// non-empty worklists.
230 Operation *pop();
231
232 /// Remove an operation from the worklist.
233 void remove(Operation *op);
234
235 /// Reverse the worklist.
236 void reverse();
237
238protected:
239 /// The worklist of operations.
240 std::vector<Operation *> list;
241
242 /// A mapping of operations to positions in `list`.
244};
245
246Worklist::Worklist() { list.reserve(64); }
247
248void Worklist::clear() {
249 list.clear();
250 map.clear();
251}
252
253bool Worklist::empty() const {
254 // Skip all nullptr.
255 return !llvm::any_of(list,
256 [](Operation *op) { return static_cast<bool>(op); });
257}
258
259void Worklist::push(Operation *op) {
260 assert(op && "cannot push nullptr to worklist");
261 // Check to see if the worklist already contains this op.
262 if (!map.insert({op, list.size()}).second)
263 return;
264 list.push_back(op);
265}
266
267Operation *Worklist::pop() {
268 assert(!empty() && "cannot pop from empty worklist");
269 // Skip and remove all trailing nullptr.
270 while (!list.back())
271 list.pop_back();
272 Operation *op = list.back();
273 list.pop_back();
274 map.erase(op);
275 // Cleanup: Remove all trailing nullptr.
276 while (!list.empty() && !list.back())
277 list.pop_back();
278 return op;
279}
280
281void Worklist::remove(Operation *op) {
282 assert(op && "cannot remove nullptr from worklist");
283 auto it = map.find(op);
284 if (it != map.end()) {
285 assert(list[it->second] == op && "malformed worklist data structure");
286 list[it->second] = nullptr;
287 map.erase(it);
288 }
289}
290
291void Worklist::reverse() {
292 std::reverse(list.begin(), list.end());
293 for (size_t i = 0, e = list.size(); i != e; ++i)
294 map[list[i]] = i;
295}
296
297#ifdef MLIR_GREEDY_REWRITE_RANDOMIZER_SEED
298/// A worklist that pops elements at a random position. This worklist is for
299/// testing/debugging purposes only. It can be used to ensure that lowering
300/// pipelines work correctly regardless of the order in which ops are processed
301/// by the GreedyPatternRewriteDriver.
302class RandomizedWorklist : public Worklist {
303public:
304 RandomizedWorklist() : Worklist() {
305 generator.seed(MLIR_GREEDY_REWRITE_RANDOMIZER_SEED);
306 }
307
308 /// Pop a random non-empty op from the worklist.
309 Operation *pop() {
310 Operation *op = nullptr;
311 do {
312 assert(!list.empty() && "cannot pop from empty worklist");
313 int64_t pos = generator() % list.size();
314 op = list[pos];
315 list.erase(list.begin() + pos);
316 for (int64_t i = pos, e = list.size(); i < e; ++i)
317 map[list[i]] = i;
318 map.erase(op);
319 } while (!op);
320 return op;
321 }
322
323private:
324 std::minstd_rand0 generator;
325};
326#endif // MLIR_GREEDY_REWRITE_RANDOMIZER_SEED
327
328//===----------------------------------------------------------------------===//
329// GreedyPatternRewriteDriver
330//===----------------------------------------------------------------------===//
331
332/// Tracks which blocks are reachable from their region's entry block while
333/// patterns rewrite the CFG, so that the driver can skip operations in blocks
334/// that a rewrite disconnected. Notifications only record what changed; the
335/// queries, which the driver issues between rewrites, bring the cache up to
336/// date. `Block::isReachable` is not used because it traverses the region on
337/// every call, while the driver queries once per processed operation. All
338/// notifications are forwarded to the wrapped listener.
339class ReachabilityListener : public RewriterBase::ForwardingListener {
340public:
341 ReachabilityListener(RewriterBase::Listener *listener, Region *scope)
342 : RewriterBase::ForwardingListener(listener), scope(scope) {}
343
344 /// Return whether `op` is reachable: its block is reachable from the entry
345 /// block of its region, and so is every containing block up to `scope`.
346 /// Must be called between rewrites, when the IR is in a consistent state.
347 bool isReachable(Operation *op);
348
349 /// Drop all cached reachability information.
350 void clear() { regionStates.clear(); }
351
352 void notifyBlockInserted(Block *block, Region *previous,
353 Region::iterator previousIt) override;
354 void notifyBlockErased(Block *block) override;
355 void notifyOperationInserted(Operation *op,
356 OpBuilder::InsertPoint previous) override;
357 void notifyOperationModified(Operation *op) override;
358 void notifyOperationErased(Operation *op) override;
359
360private:
361 /// The reachability cache of one region.
362 struct RegionState {
363 /// The entry block at the time of the traversal. The traversal starts
364 /// from the entry block, so a different entry block invalidates the cache.
365 Block *entry = nullptr;
366 /// The reachable blocks, mapped to their successors within the region as
367 /// of the last query. The snapshots let the next query tell lost edges
368 /// from added ones.
370 /// Blocks of `reachable` whose reachability could not be decided
371 /// incrementally. A query for one of them traverses the region. Marking
372 /// and traversing both cost O(blocks), so a lost edge into a loop whose
373 /// target keeps other predecessors costs O(blocks) per rewrite if one of
374 /// the marked blocks is queried before the next change. Bottom-up
375 /// processing has usually popped the operations of these blocks already;
376 /// top-down processing pops them next.
377 llvm::SmallDenseSet<Block *, 4> uncertain;
378 /// Blocks whose terminator changed since the last query, in notification
379 /// order, so that the cache evolves deterministically.
380 llvm::SmallSetVector<Block *, 4> changedBlocks;
381 /// Blocks erased from or moved out of the region since the last query.
382 /// Their pointers are only compared, never dereferenced.
383 llvm::SmallDenseSet<Block *, 4> removedBlocks;
384
385 /// Rebuild the cache from the entry block of `region`.
386 void traverse(Region *region);
387 /// Add `roots` and every block reachable from them to `reachable`. The
388 /// added blocks are uncertain if `isUncertain` is set.
389 void addReachable(SmallVector<Block *> roots, bool isUncertain);
390 /// Mark `block` and every block behind it in the snapshots uncertain.
391 void markUncertain(Block *block);
392 /// Apply the pending changes, if any. On failure, the state is
393 /// inconsistent and the region must be traversed again.
394 LogicalResult applyChanges();
395 };
396
397 /// Record that the terminator of `block` changed. Only tracked regions
398 /// record changes, so no pointer to a block of an untracked region is kept.
399 void markChanged(Block *block) {
400 if (!block)
401 return;
402 auto it = regionStates.find(block->getParent());
403 if (it != regionStates.end())
404 it->second.changedBlocks.insert(block);
405 }
406 /// Record that `block` left `region`.
407 void markRemoved(Region *region, Block *block) {
408 auto it = regionStates.find(region);
409 if (it != regionStates.end())
410 it->second.removedBlocks.insert(block);
411 }
412 bool isBlockReachable(Block *block);
413
414 /// The tracked regions. A region without an entry is traversed by the next
415 /// query that needs it.
417
418 Region *const scope;
419};
420
421/// Provides cached deadness queries that stay valid across rewriter
422/// notifications. All notifications are forwarded to the wrapped listener
423/// after reporting the change to the cache.
424class DeadnessListener : public RewriterBase::ForwardingListener {
425public:
426 explicit DeadnessListener(RewriterBase::Listener *listener)
428
429 /// Return true if the operation is unused and can be erased.
430 bool isOpTriviallyDead(Operation *op) { return cache.isOpTriviallyDead(op); }
431
432 void notifyBlockInserted(Block *block, Region *previous,
433 Region::iterator previousIt) override {
434 cache.scheduleBlockInvalidation(block);
435 if (previous)
436 if (Operation *parent = previous->getParentOp())
437 cache.scheduleAncestorInvalidation(parent);
438 ForwardingListener::notifyBlockInserted(block, previous, previousIt);
439 }
440
441 void notifyBlockErased(Block *block) override {
442 cache.notifyBlockErased(block);
443 ForwardingListener::notifyBlockErased(block);
444 }
445
446 void notifyOperationInserted(Operation *op,
447 OpBuilder::InsertPoint previous) override {
448 // The old parent loses a child, but its remaining descendants are
449 // unchanged. Scanning them for every move would make block merging
450 // quadratic.
451 if (previous.isSet())
452 if (Operation *parent = previous.getBlock()->getParentOp())
453 cache.scheduleAncestorInvalidation(parent);
454 cache.scheduleInvalidation(op);
455 ForwardingListener::notifyOperationInserted(op, previous);
456 }
457
458 void notifyOperationModified(Operation *op) override {
459 cache.scheduleInvalidation(op);
460 ForwardingListener::notifyOperationModified(op);
461 }
462
463 void notifyOperationErased(Operation *op) override {
464 cache.notifyOperationErased(op);
465 ForwardingListener::notifyOperationErased(op);
466 }
467
468private:
469 DeadnessCache cache;
470};
471
472/// This is a worklist-driven driver for the PatternMatcher, which repeatedly
473/// applies the locally optimal patterns.
474///
475/// This abstract class manages the worklist and contains helper methods for
476/// rewriting ops on the worklist. Derived classes specify how ops are added
477/// to the worklist in the beginning.
478class GreedyPatternRewriteDriver : public RewriterBase::Listener {
479protected:
480 explicit GreedyPatternRewriteDriver(MLIRContext *ctx,
481 const FrozenRewritePatternSet &patterns,
482 const GreedyRewriteConfig &config);
483
484 /// Add the given operation to the worklist.
485 void addSingleOpToWorklist(Operation *op);
486
487 /// Add the given operation and its ancestors to the worklist.
488 void addToWorklist(Operation *op);
489
490 /// Notify the driver that the specified operation may have been modified
491 /// in-place. The operation is added to the worklist.
492 void notifyOperationModified(Operation *op) override;
493
494 /// Notify the driver that the specified operation was inserted. Update the
495 /// worklist as needed: The operation is enqueued depending on scope and
496 /// strict mode.
497 void notifyOperationInserted(Operation *op,
498 OpBuilder::InsertPoint previous) override;
499
500 /// Notify the driver that the specified operation was removed. Update the
501 /// worklist as needed: The operation and its children are removed from the
502 /// worklist.
503 void notifyOperationErased(Operation *op) override;
504
505 /// Notify the driver that the specified operation was replaced. Update the
506 /// worklist as needed: New users are added enqueued.
507 void notifyOperationReplaced(Operation *op, ValueRange replacement) override;
508
509 /// Process ops until the worklist is empty or `config.maxNumRewrites` is
510 /// reached. Skip operations in unreachable blocks. Return `true` if any IR
511 /// was changed.
512 bool processWorklist();
513
514 /// The pattern rewriter that is used for making IR modifications and is
515 /// passed to rewrite patterns.
516 PatternRewriter rewriter;
517
518 /// The worklist for this transformation keeps track of the operations that
519 /// need to be (re)visited.
520#ifdef MLIR_GREEDY_REWRITE_RANDOMIZER_SEED
521 RandomizedWorklist worklist;
522#else
523 Worklist worklist;
524#endif // MLIR_GREEDY_REWRITE_RANDOMIZER_SEED
525
526 /// Configuration information for how to simplify.
527 const GreedyRewriteConfig config;
528
529 /// The list of ops we are restricting our rewrites to. These include the
530 /// supplied set of ops as well as new ops created while rewriting those ops
531 /// depending on `strictMode`. This set is not maintained when
532 /// `config.strictMode` is GreedyRewriteStrictness::AnyOp.
533 llvm::SmallDenseSet<Operation *, 4> strictModeFilteredOps;
534
535 /// Tracks block reachability while the worklist is processed. The rewriter
536 /// notifies this listener, which forwards to the driver.
537 ReachabilityListener reachabilityListener;
538
539private:
540 /// Look over the provided operands for any defining operations that should
541 /// be re-added to the worklist. This function should be called when an
542 /// operation is modified or removed, as it may trigger further
543 /// simplifications.
544 void addOperandsToWorklist(Operation *op);
545
546 /// Notify the driver that the given block was inserted.
547 void notifyBlockInserted(Block *block, Region *previous,
548 Region::iterator previousIt) override;
549
550 /// Notify the driver that the given block is about to be removed.
551 void notifyBlockErased(Block *block) override;
552
553 /// For debugging only: Notify the driver of a pattern match failure.
554 void
555 notifyMatchFailure(Location loc,
556 function_ref<void(Diagnostic &)> reasonCallback) override;
557
558#ifndef NDEBUG
559 /// A raw output stream used to prefix the debug log.
560
561 llvm::impl::raw_ldbg_ostream os{(Twine("[") + DEBUG_TYPE + ":1] ").str(),
562 llvm::dbgs()};
563 /// A logger used to emit information during the application process.
564 llvm::ScopedPrinter logger{os};
565#endif
566
567 /// The low-level pattern applicator.
568 PatternApplicator matcher;
569
570 DeadnessListener deadnessListener;
571
572#if MLIR_ENABLE_EXPENSIVE_PATTERN_API_CHECKS
573 ExpensiveChecks expensiveChecks;
574#endif // MLIR_ENABLE_EXPENSIVE_PATTERN_API_CHECKS
575};
576} // namespace
577
578/// Return whether `op` may define successors of its block.
581 op->getNumSuccessors() != 0;
582}
583
584/// Collect the distinct successors of `block` that are in the same region.
585/// A successor in another region is invalid IR that cannot make
586/// a block of this region reachable.
588 SmallPtrSet<Block *, 2> successors;
589 for (Block *successor : block->getSuccessors())
590 if (successor->getParent() == block->getParent())
591 successors.insert(successor);
592 return successors;
593}
594
595void ReachabilityListener::RegionState::traverse(Region *region) {
596 // Clear rather than reassign, to keep the allocations for the next
597 // traversal.
598 reachable.clear();
599 uncertain.clear();
600 changedBlocks.clear();
601 removedBlocks.clear();
602 entry = &region->front();
603 addReachable({entry}, /*isUncertain=*/false);
604}
605
606void ReachabilityListener::RegionState::addReachable(SmallVector<Block *> roots,
607 bool isUncertain) {
608 while (!roots.empty()) {
609 auto [it, inserted] = reachable.try_emplace(roots.pop_back_val());
610 if (!inserted)
611 continue;
612 auto successors = getRegionSuccessors(it->first);
613 it->second.append(successors.begin(), successors.end());
614 if (isUncertain)
615 uncertain.insert(it->first);
616 roots.append(it->second);
617 }
618}
619
620void ReachabilityListener::RegionState::markUncertain(Block *block) {
621 SmallVector<Block *> worklist{block};
622 while (!worklist.empty()) {
623 Block *current = worklist.pop_back_val();
624 auto it = reachable.find(current);
625 if (it == reachable.end() || !uncertain.insert(current).second)
626 continue;
627 worklist.append(it->second);
628 }
629}
630
631LogicalResult ReachabilityListener::RegionState::applyChanges() {
632 if (changedBlocks.empty() && removedBlocks.empty())
633 return success();
634 // Blocks are dropped after the loop, so that the snapshot of a lost block
635 // remains available to every changed block that lost an edge to it.
636 SmallVector<Block *> unreachable;
637 for (Block *changed : changedBlocks) {
638 // A removed block is no longer part of the region, and a change in an
639 // uncached block cannot make any block reachable.
640 if (removedBlocks.contains(changed))
641 continue;
642 auto it = reachable.find(changed);
643 if (it == reachable.end())
644 continue;
645 // Keep even a disconnected block's snapshot up to date: a later rewrite
646 // may reconnect it without querying the block itself. Its added successors
647 // must remain uncertain until a traversal establishes their reachability.
648 if (changed != entry && changed->hasNoPredecessors())
649 markUncertain(changed);
650 // Keep the snapshot available while marking lost successors uncertain.
651 // A lost self-edge can make that traversal visit `changed` itself.
652 const auto &old = it->second;
653 auto current = getRegionSuccessors(changed);
654 for (Block *lost : old) {
655 if (current.contains(lost))
656 continue;
657 // The successors of a reachable block are reachable, so `lost` has a
658 // snapshot unless the cache is inconsistent. This is not expected to
659 // happen; the failure is a safety net that forces a traversal.
660 auto lostIt = reachable.find(lost);
661 if (lostIt == reachable.end())
662 return failure();
663 // `lost` and every block behind it may have become unreachable. When
664 // `lost` is gone or has no predecessors left, it is unreachable; if all
665 // of its cached successors are still successors of `changed`, nothing
666 // else changed. This is the shape left by folding a constant conditional
667 // branch and by merging a block into its predecessor. Any other lost
668 // edge leaves the blocks behind `lost` uncertain until a query for one
669 // of them traverses the region.
670 bool isGone = removedBlocks.contains(lost) || lost->hasNoPredecessors();
671 if (isGone && llvm::all_of(lostIt->second, [&](Block *successor) {
672 return current.contains(successor);
673 })) {
674 unreachable.push_back(lost);
675 continue;
676 }
677 markUncertain(lost);
678 }
679 // Added edges can only make more blocks reachable. Blocks reached from an
680 // uncertain block are uncertain as well.
681 SmallVector<Block *> roots;
682 for (Block *successor : current)
683 if (!reachable.contains(successor))
684 roots.push_back(successor);
685 // Nothing was inserted into `reachable` since `it` was looked up.
686 it->second.assign(current.begin(), current.end());
687 addReachable(std::move(roots), uncertain.contains(changed));
688 }
689 // Drop every block that left the region, so that no stale key can match a
690 // block inserted later at the same address.
691 unreachable.append(removedBlocks.begin(), removedBlocks.end());
692 for (Block *block : unreachable) {
693 reachable.erase(block);
694 uncertain.erase(block);
695 }
696 changedBlocks.clear();
697 removedBlocks.clear();
698 return success();
699}
700
701bool ReachabilityListener::isBlockReachable(Block *block) {
702 Region *region = block->getParent();
703 // A detached block is treated as reachable, as is the entry block.
704 if (!region || block == &region->front())
705 return true;
706 if (block->hasNoPredecessors())
707 return false;
708 auto [it, inserted] = regionStates.try_emplace(region);
709 RegionState &state = it->second;
710 bool isStale = inserted || state.entry != &region->front();
711 if (isStale || failed(state.applyChanges()) ||
712 state.uncertain.contains(block))
713 state.traverse(region);
714 bool result = state.reachable.contains(block);
715#if MLIR_ENABLE_EXPENSIVE_PATTERN_API_CHECKS
716 assert(result == region->front().isReachable(block) &&
717 "reachability cache disagrees with a traversal");
718#endif // MLIR_ENABLE_EXPENSIVE_PATTERN_API_CHECKS
719 return result;
720}
721
722bool ReachabilityListener::isReachable(Operation *op) {
723 // A nested region can be locally reachable while its owning operation is in
724 // an unreachable block, so check every containing block up to the scope.
725 while (Block *block = op->getBlock()) {
726 if (!isBlockReachable(block))
727 return false;
728 Region *region = block->getParent();
729 if (!region || region == scope)
730 break;
731 op = region->getParentOp();
732 }
733 return true;
734}
735
736void ReachabilityListener::notifyBlockInserted(Block *block, Region *previous,
737 Region::iterator previousIt) {
738 Region *region = block->getParent();
739 // A block moved within its region keeps its reachability, unless it becomes
740 // the entry block, which the next query detects. A block that is new to the
741 // region is unreachable until a recorded terminator change adds an edge to
742 // it, but a stale entry from an earlier removal cannot be trusted.
743 if (previous != region) {
744 if (previous)
745 markRemoved(previous, block);
746 auto it = regionStates.find(region);
747 if (it != regionStates.end() && (it->second.removedBlocks.contains(block) ||
748 it->second.reachable.contains(block)))
749 regionStates.erase(it);
750 }
752 previousIt);
753}
754
755void ReachabilityListener::notifyBlockErased(Block *block) {
756 markRemoved(block->getParent(), block);
758}
759
760void ReachabilityListener::notifyOperationInserted(
761 Operation *op, OpBuilder::InsertPoint previous) {
762 if (mayDefineSuccessors(op)) {
763 markChanged(op->getBlock());
764 if (previous.isSet())
765 markChanged(previous.getBlock());
766 }
768}
769
770void ReachabilityListener::notifyOperationModified(Operation *op) {
771 if (mayDefineSuccessors(op))
772 markChanged(op->getBlock());
774}
775
776void ReachabilityListener::notifyOperationErased(Operation *op) {
777 if (mayDefineSuccessors(op))
778 markChanged(op->getBlock());
779 // Do not retain keys for regions that are about to be destroyed.
780 for (Region &region : op->getRegions())
781 regionStates.erase(&region);
783}
784
785GreedyPatternRewriteDriver::GreedyPatternRewriteDriver(
786 MLIRContext *ctx, const FrozenRewritePatternSet &patterns,
787 const GreedyRewriteConfig &config)
788 : rewriter(ctx), config(config),
789 reachabilityListener(this, config.getScope()), matcher(patterns),
790 deadnessListener(&reachabilityListener)
791#if MLIR_ENABLE_EXPENSIVE_PATTERN_API_CHECKS
792 // clang-format off
793 , expensiveChecks(
794 /*listener=*/&deadnessListener,
795 /*topLevel=*/config.getScope() ? config.getScope()->getParentOp()
796 : nullptr)
797// clang-format on
798#endif // MLIR_ENABLE_EXPENSIVE_PATTERN_API_CHECKS
799{
800 // Apply a simple cost model based solely on pattern benefit.
801 matcher.applyDefaultCostModel();
802
803 // Set up listener.
804#if MLIR_ENABLE_EXPENSIVE_PATTERN_API_CHECKS
805 // Forward notifications through expensive checks, deadness, reachability,
806 // and the worklist driver, in that order.
807 rewriter.setListener(&expensiveChecks);
808#else
809 rewriter.setListener(&deadnessListener);
810#endif // MLIR_ENABLE_EXPENSIVE_PATTERN_API_CHECKS
811}
812
813bool GreedyPatternRewriteDriver::processWorklist() {
814 // The cache is only maintained while this worklist pass runs. Between
815 // passes, the IR changes without notifications, e.g. in region
816 // simplification and in the unreachable-block sweep.
817 llvm::scope_exit clearReachability([&] { reachabilityListener.clear(); });
818
819#ifndef NDEBUG
820 const char *logLineComment =
821 "//===-------------------------------------------===//\n";
822
823 /// A utility function to log a process result for the given reason.
824 auto logResult = [&](StringRef result, const llvm::Twine &msg = {}) {
825 logger.unindent();
826 logger.startLine() << "} -> " << result;
827 if (!msg.isTriviallyEmpty())
828 logger.getOStream() << " : " << msg;
829 logger.getOStream() << "\n";
830 };
831 auto logResultWithLine = [&](StringRef result, const llvm::Twine &msg = {}) {
832 logResult(result, msg);
833 logger.startLine() << logLineComment;
834 };
835#endif
836
837 bool changed = false;
838 int64_t numRewrites = 0;
839 while (!worklist.empty() &&
840 (numRewrites < config.getMaxNumRewrites() ||
842 auto *op = worklist.pop();
843 if (!reachabilityListener.isReachable(op)) {
844 LLVM_DEBUG(logger.startLine() << "Skipping unreachable operation : '"
845 << op->getName() << "'(" << op << ")\n");
846 continue;
847 }
848
849 LLVM_DEBUG({
850 logger.getOStream() << "\n";
851 logger.startLine() << logLineComment;
852 logger.startLine() << "Processing operation : '" << op->getName() << "'("
853 << op << ") {\n";
854 logger.indent();
855
856 // If the operation has no regions, just print it here.
857 if (op->getNumRegions() == 0) {
858 op->print(
859 logger.startLine(),
860 OpPrintingFlags().printGenericOpForm().elideLargeElementsAttrs());
861 logger.getOStream() << "\n\n";
862 }
863 });
864
865 // If the operation is trivially dead - remove it.
866 if (deadnessListener.isOpTriviallyDead(op)) {
867 rewriter.eraseOp(op);
868 changed = true;
869
870 LLVM_DEBUG(logResultWithLine("success", "operation is trivially dead"));
871 continue;
872 }
873
874 // Try to fold this op. Do not fold constant ops. That would lead to an
875 // infinite folding loop, as every constant op would be folded to an
876 // Attribute and then immediately be rematerialized as a constant op, which
877 // is then put on the worklist.
878 if (config.isFoldingEnabled() && !op->hasTrait<OpTrait::ConstantLike>()) {
879 SmallVector<OpFoldResult> foldResults;
880 if (succeeded(op->fold(foldResults))) {
881 LLVM_DEBUG(logResultWithLine("success", "operation was folded"));
882#ifndef NDEBUG
883 Operation *dumpRootOp = getDumpRootOp(op);
884#endif // NDEBUG
885 if (foldResults.empty()) {
886 // Folding modified the op without using the rewriter. Notify the
887 // cache listeners, which forward the modification to the driver.
888 deadnessListener.notifyOperationModified(op);
889 changed = true;
890 LLVM_DEBUG(logSuccessfulFolding(dumpRootOp));
891#if MLIR_ENABLE_EXPENSIVE_PATTERN_API_CHECKS
892 expensiveChecks.notifyFoldingSuccess();
893#endif // MLIR_ENABLE_EXPENSIVE_PATTERN_API_CHECKS
894 continue;
895 }
896
897 // Op results can be replaced with `foldResults`.
898 assert(foldResults.size() == op->getNumResults() &&
899 "folder produced incorrect number of results");
900 OpBuilder::InsertionGuard g(rewriter);
901 rewriter.setInsertionPoint(op);
902 SmallVector<Value> replacements;
903 bool materializationSucceeded = true;
904 for (auto [ofr, resultType] :
905 llvm::zip_equal(foldResults, op->getResultTypes())) {
906 if (auto value = dyn_cast<Value>(ofr)) {
907 assert(value.getType() == resultType &&
908 "folder produced value of incorrect type");
909 replacements.push_back(value);
910 continue;
911 }
912 // Materialize Attributes as SSA values.
913 Operation *constOp = op->getDialect()->materializeConstant(
914 rewriter, cast<Attribute>(ofr), resultType, op->getLoc());
915
916 if (!constOp) {
917 // If materialization fails, cleanup any operations generated for
918 // the previous results.
919 llvm::SmallDenseSet<Operation *> replacementOps;
920 for (Value replacement : replacements) {
921 assert(replacement.use_empty() &&
922 "folder reused existing op for one result but constant "
923 "materialization failed for another result");
924 replacementOps.insert(replacement.getDefiningOp());
925 }
926 for (Operation *op : replacementOps) {
927 rewriter.eraseOp(op);
928 }
929
930 materializationSucceeded = false;
931 break;
932 }
933
934 assert(constOp->hasTrait<OpTrait::ConstantLike>() &&
935 "materializeConstant produced op that is not a ConstantLike");
936 assert(constOp->getResultTypes()[0] == resultType &&
937 "materializeConstant produced incorrect result type");
938 replacements.push_back(constOp->getResult(0));
939 }
940
941 if (materializationSucceeded) {
942 rewriter.replaceOp(op, replacements);
943 changed = true;
944 LLVM_DEBUG(logSuccessfulFolding(dumpRootOp));
945#if MLIR_ENABLE_EXPENSIVE_PATTERN_API_CHECKS
946 expensiveChecks.notifyFoldingSuccess();
947#endif // MLIR_ENABLE_EXPENSIVE_PATTERN_API_CHECKS
948 continue;
949 }
950 }
951 }
952
953 // Try to match one of the patterns. The rewriter is automatically
954 // notified of any necessary changes, so there is nothing else to do
955 // here.
956 auto canApplyCallback = [&](const Pattern &pattern) {
957 LLVM_DEBUG({
958 logger.getOStream() << "\n";
959 logger.startLine() << "* Pattern " << pattern.getDebugName() << " : '"
960 << op->getName() << " -> (";
961 llvm::interleaveComma(pattern.getGeneratedOps(), logger.getOStream());
962 logger.getOStream() << ")' {\n";
963 logger.indent();
964 });
965 if (RewriterBase::Listener *listener = config.getListener())
966 listener->notifyPatternBegin(pattern, op);
967 return true;
968 };
969 function_ref<bool(const Pattern &)> canApply = canApplyCallback;
970 auto onFailureCallback = [&](const Pattern &pattern) {
971 LLVM_DEBUG(logResult("failure", "pattern failed to match"));
972 if (RewriterBase::Listener *listener = config.getListener())
973 listener->notifyPatternEnd(pattern, failure());
974 };
975 function_ref<void(const Pattern &)> onFailure = onFailureCallback;
976 auto onSuccessCallback = [&](const Pattern &pattern) {
977 LLVM_DEBUG(logResult("success", "pattern applied successfully"));
978 if (RewriterBase::Listener *listener = config.getListener())
979 listener->notifyPatternEnd(pattern, success());
980 return success();
981 };
982 function_ref<LogicalResult(const Pattern &)> onSuccess = onSuccessCallback;
983
984#ifdef NDEBUG
985 // Optimization: PatternApplicator callbacks are not needed when running in
986 // optimized mode and without a listener.
987 if (!config.getListener()) {
988 canApply = nullptr;
989 onFailure = nullptr;
990 onSuccess = nullptr;
991 }
992#endif // NDEBUG
993
994#if MLIR_ENABLE_EXPENSIVE_PATTERN_API_CHECKS
995 if (config.getScope()) {
996 expensiveChecks.computeFingerPrints(config.getScope()->getParentOp());
997 }
998 llvm::scope_exit clearFingerprints([&]() { expensiveChecks.clear(); });
999#endif // MLIR_ENABLE_EXPENSIVE_PATTERN_API_CHECKS
1000
1001 LogicalResult matchResult =
1002 matcher.matchAndRewrite(op, rewriter, canApply, onFailure, onSuccess);
1003
1004 if (succeeded(matchResult)) {
1005 LLVM_DEBUG(logResultWithLine("success", "at least one pattern matched"));
1006#if MLIR_ENABLE_EXPENSIVE_PATTERN_API_CHECKS
1007 expensiveChecks.notifyRewriteSuccess();
1008#endif // MLIR_ENABLE_EXPENSIVE_PATTERN_API_CHECKS
1009 changed = true;
1010 ++numRewrites;
1011 } else {
1012 LLVM_DEBUG(logResultWithLine("failure", "all patterns failed to match"));
1013#if MLIR_ENABLE_EXPENSIVE_PATTERN_API_CHECKS
1014 expensiveChecks.notifyRewriteFailure();
1015#endif // MLIR_ENABLE_EXPENSIVE_PATTERN_API_CHECKS
1016 }
1017 }
1018
1019 return changed;
1020}
1021
1022void GreedyPatternRewriteDriver::addToWorklist(Operation *op) {
1023 assert(op && "expected valid op");
1024 // Gather potential ancestors while looking for a "scope" parent region.
1025 SmallVector<Operation *, 8> ancestors;
1026 Region *region = nullptr;
1027 do {
1028 ancestors.push_back(op);
1029 region = op->getParentRegion();
1030 if (config.getScope() == region) {
1031 // Scope (can be `nullptr`) was reached. Stop traveral and enqueue ops.
1032 for (Operation *op : ancestors)
1033 addSingleOpToWorklist(op);
1034 return;
1035 }
1036 if (region == nullptr)
1037 return;
1038 } while ((op = region->getParentOp()));
1039}
1040
1041void GreedyPatternRewriteDriver::addSingleOpToWorklist(Operation *op) {
1042 if (config.getStrictness() == GreedyRewriteStrictness::AnyOp ||
1043 strictModeFilteredOps.contains(op))
1044 worklist.push(op);
1045}
1046
1047void GreedyPatternRewriteDriver::notifyBlockInserted(
1048 Block *block, Region *previous, Region::iterator previousIt) {
1049 if (RewriterBase::Listener *listener = config.getListener())
1050 listener->notifyBlockInserted(block, previous, previousIt);
1051}
1052
1053void GreedyPatternRewriteDriver::notifyBlockErased(Block *block) {
1054 if (RewriterBase::Listener *listener = config.getListener())
1055 listener->notifyBlockErased(block);
1056}
1057
1058void GreedyPatternRewriteDriver::notifyOperationInserted(
1059 Operation *op, OpBuilder::InsertPoint previous) {
1060 LLVM_DEBUG({
1061 logger.startLine() << "** Insert : '" << op->getName() << "'(" << op
1062 << ")\n";
1063 });
1064 if (RewriterBase::Listener *listener = config.getListener())
1065 listener->notifyOperationInserted(op, previous);
1066 if (config.getStrictness() == GreedyRewriteStrictness::ExistingAndNewOps)
1067 strictModeFilteredOps.insert(op);
1068 addToWorklist(op);
1069}
1070
1071void GreedyPatternRewriteDriver::notifyOperationModified(Operation *op) {
1072 LLVM_DEBUG({
1073 logger.startLine() << "** Modified: '" << op->getName() << "'(" << op
1074 << ")\n";
1075 });
1076 if (RewriterBase::Listener *listener = config.getListener())
1077 listener->notifyOperationModified(op);
1078 addToWorklist(op);
1079}
1080
1081void GreedyPatternRewriteDriver::addOperandsToWorklist(Operation *op) {
1082 for (Value operand : op->getOperands()) {
1083 // If this operand currently has at most 2 users, add its defining op to the
1084 // worklist. Indeed, after the op is deleted, then the operand will have at
1085 // most 1 user left. If it has 0 users left, it can be deleted too,
1086 // and if it has 1 user left, there may be further canonicalization
1087 // opportunities.
1088 if (!operand)
1089 continue;
1090
1091 auto *defOp = operand.getDefiningOp();
1092 if (!defOp)
1093 continue;
1094
1095 Operation *otherUser = nullptr;
1096 bool hasMoreThanTwoUses = false;
1097 for (auto *user : operand.getUsers()) {
1098 if (user == op || user == otherUser)
1099 continue;
1100 if (!otherUser) {
1101 otherUser = user;
1102 continue;
1103 }
1104 hasMoreThanTwoUses = true;
1105 break;
1106 }
1107 if (hasMoreThanTwoUses)
1108 continue;
1109
1110 addToWorklist(defOp);
1111 }
1112}
1113
1114void GreedyPatternRewriteDriver::notifyOperationErased(Operation *op) {
1115 LLVM_DEBUG({
1116 logger.startLine() << "** Erase : '" << op->getName() << "'(" << op
1117 << ")\n";
1118 });
1119
1120#ifndef NDEBUG
1121 // Only ops that are within the configured scope are added to the worklist of
1122 // the greedy pattern rewriter. Moreover, the parent op of the scope region is
1123 // the part of the IR that is taken into account for the "expensive checks".
1124 // A greedy pattern rewrite is not allowed to erase the parent op of the scope
1125 // region, as that would break the worklist handling and the expensive checks.
1126 if (Region *scope = config.getScope(); scope->getParentOp() == op)
1127 llvm_unreachable(
1128 "scope region must not be erased during greedy pattern rewrite");
1129#endif // NDEBUG
1130
1131 if (RewriterBase::Listener *listener = config.getListener())
1132 listener->notifyOperationErased(op);
1133
1134 addOperandsToWorklist(op);
1135 worklist.remove(op);
1136
1137 if (config.getStrictness() != GreedyRewriteStrictness::AnyOp)
1138 strictModeFilteredOps.erase(op);
1139}
1140
1141void GreedyPatternRewriteDriver::notifyOperationReplaced(
1142 Operation *op, ValueRange replacement) {
1143 LLVM_DEBUG({
1144 logger.startLine() << "** Replace : '" << op->getName() << "'(" << op
1145 << ")\n";
1146 });
1147 if (RewriterBase::Listener *listener = config.getListener())
1148 listener->notifyOperationReplaced(op, replacement);
1149}
1150
1151void GreedyPatternRewriteDriver::notifyMatchFailure(
1152 Location loc, function_ref<void(Diagnostic &)> reasonCallback) {
1153 LLVM_DEBUG({
1154 Diagnostic diag(loc, DiagnosticSeverity::Remark);
1155 reasonCallback(diag);
1156 logger.startLine() << "** Match Failure : " << diag.str() << "\n";
1157 });
1158 if (RewriterBase::Listener *listener = config.getListener())
1159 listener->notifyMatchFailure(loc, reasonCallback);
1160}
1161
1162//===----------------------------------------------------------------------===//
1163// RegionPatternRewriteDriver
1164//===----------------------------------------------------------------------===//
1165
1166namespace {
1167/// This driver simplfies all ops in a region. If a scope is set in the
1168/// config, the provided region must be within that scope.
1169class RegionPatternRewriteDriver : public GreedyPatternRewriteDriver {
1170public:
1171 explicit RegionPatternRewriteDriver(MLIRContext *ctx,
1172 const FrozenRewritePatternSet &patterns,
1173 const GreedyRewriteConfig &config,
1174 Region &regions);
1175
1176 /// Simplify ops inside `region` and simplify the region itself. Return
1177 /// success if the transformation converged.
1178 LogicalResult simplify(bool *changed) &&;
1179
1180private:
1181 /// The region that is simplified.
1182 Region &region;
1183};
1184} // namespace
1185
1186RegionPatternRewriteDriver::RegionPatternRewriteDriver(
1187 MLIRContext *ctx, const FrozenRewritePatternSet &patterns,
1188 const GreedyRewriteConfig &config, Region &region)
1189 : GreedyPatternRewriteDriver(ctx, patterns, config), region(region) {
1190 // Populate strict mode ops.
1192 region.walk([&](Operation *op) { strictModeFilteredOps.insert(op); });
1193 }
1194#ifndef NDEBUG
1195 // Verify that the region is within the configured scope (if any).
1196 if (Region *scope = config.getScope()) {
1197 Region *r = &region;
1198 while (r && r != scope)
1199 r = r->getParentRegion();
1200 assert(r && "provided region is not within the config scope");
1201 }
1202#endif
1203}
1204
1205namespace {
1206class GreedyPatternRewriteIteration
1207 : public tracing::ActionImpl<GreedyPatternRewriteIteration> {
1208public:
1209 MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(GreedyPatternRewriteIteration)
1210 GreedyPatternRewriteIteration(ArrayRef<IRUnit> units, int64_t iteration)
1211 : tracing::ActionImpl<GreedyPatternRewriteIteration>(units),
1212 iteration(iteration) {}
1213 static constexpr StringLiteral tag = "GreedyPatternRewriteIteration";
1214 void print(raw_ostream &os) const override {
1215 os << "GreedyPatternRewriteIteration(" << iteration << ")";
1216 }
1217
1218private:
1219 int64_t iteration = 0;
1220};
1221} // namespace
1222
1223LogicalResult RegionPatternRewriteDriver::simplify(bool *changed) && {
1224 bool continueRewrites = false;
1225 bool anyChanged = false;
1226 int64_t iteration = 0;
1227 MLIRContext *ctx = rewriter.getContext();
1228 do {
1229 // Check if the iteration limit was reached.
1230 if (++iteration > config.getMaxIterations() &&
1232 break;
1233
1234 // New iteration: start with an empty worklist.
1235 worklist.clear();
1236
1237 // `OperationFolder` CSE's constant ops (and may move them into parents
1238 // regions to enable more aggressive CSE'ing).
1239 OperationFolder folder(ctx, rewriter.getListener());
1240 auto insertKnownConstant = [&](Operation *op) {
1241 // Check for existing constants when populating the worklist. This avoids
1242 // accidentally reversing the constant order during processing.
1243 Attribute constValue;
1244 if (!matchPattern(op, m_Constant(&constValue)))
1245 return false;
1246 auto result = folder.insertKnownConstant(op, constValue);
1247 anyChanged |=
1250 };
1251
1252 if (!config.getUseTopDownTraversal()) {
1253 // Add operations to the worklist in postorder.
1254 region.walk([&](Operation *op) {
1255 if (!config.isConstantCSEEnabled() || !insertKnownConstant(op))
1256 addToWorklist(op);
1257 });
1258 } else {
1259 // Add all nested operations to the worklist in preorder.
1260 region.walk<WalkOrder::PreOrder>([&](Operation *op) {
1261 if (!config.isConstantCSEEnabled() || !insertKnownConstant(op)) {
1262 addToWorklist(op);
1263 return WalkResult::advance();
1264 }
1265 return WalkResult::skip();
1266 });
1267
1268 // Reverse the list so our pop-back loop processes them in-order.
1269 worklist.reverse();
1270 }
1271
1272 ctx->executeAction<GreedyPatternRewriteIteration>(
1273 [&] {
1274 continueRewrites = false;
1275
1276 // Erase unreachable blocks
1277 // Operations like:
1278 // %add = arith.addi %add, %add : i64
1279 // are legal in unreachable code. Unfortunately many patterns would be
1280 // unsafe to apply on such IR and can lead to crashes or infinite
1281 // loops. A rewrite can disconnect more blocks while processWorklist()
1282 // runs; processWorklist() skips their queued operations until the
1283 // next sweep, since repeated rewrites on such IR can prevent the
1284 // worklist pass from returning.
1285 continueRewrites |=
1286 succeeded(eraseUnreachableBlocks(rewriter, region));
1287
1288 continueRewrites |= processWorklist();
1289
1290 // After applying patterns, make sure that the CFG of each of the
1291 // regions is kept up to date.
1292 if (config.getRegionSimplificationLevel() !=
1294 continueRewrites |= succeeded(simplifyRegions(
1295 rewriter, region,
1296 /*mergeBlocks=*/config.getRegionSimplificationLevel() ==
1298 }
1299
1300 // Optionally run full CSE. If CSE changes the IR we iterate again so
1301 // that patterns can fire on the deduplicated operations.
1302 if (config.isCSEBetweenIterationsEnabled()) {
1303 DominanceInfo domInfo;
1304 bool cseChanged = false;
1305 eliminateCommonSubExpressions(rewriter, domInfo, region,
1306 &cseChanged);
1307 continueRewrites |= cseChanged;
1308 }
1309 },
1310 {&region}, iteration);
1311 anyChanged |= continueRewrites;
1312 } while (continueRewrites);
1313
1314 if (changed)
1315 *changed = anyChanged;
1316
1317 // Whether the rewrite converges, i.e. wasn't changed in the last iteration.
1318 return success(!continueRewrites);
1319}
1320
1321LogicalResult
1323 const FrozenRewritePatternSet &patterns,
1324 GreedyRewriteConfig config, bool *changed) {
1325 // The top-level operation must be known to be isolated from above to
1326 // prevent performing canonicalizations on operations defined at or above
1327 // the region containing 'op'.
1329 "patterns can only be applied to operations IsolatedFromAbove");
1330
1331 // Set scope if not specified.
1332 if (!config.getScope())
1333 config.setScope(&region);
1334
1335#if MLIR_ENABLE_EXPENSIVE_PATTERN_API_CHECKS
1336 if (failed(verify(config.getScope()->getParentOp())))
1337 llvm::report_fatal_error(
1338 "greedy pattern rewriter input IR failed to verify");
1339#endif // MLIR_ENABLE_EXPENSIVE_PATTERN_API_CHECKS
1340
1341#ifdef EXPENSIVE_CHECKS
1342 OperationFingerPrint before(config.getScope()->getParentOp());
1343#endif // EXPENSIVE_CHECKS
1344 bool rewriteChanged = false;
1345
1346 // Start the pattern driver.
1347 RegionPatternRewriteDriver driver(region.getContext(), patterns, config,
1348 region);
1349 LogicalResult converged = std::move(driver).simplify(&rewriteChanged);
1350#ifdef EXPENSIVE_CHECKS
1351 if (rewriteChanged !=
1352 (before != OperationFingerPrint(config.getScope()->getParentOp())))
1353 llvm::report_fatal_error(
1354 "greedy pattern rewriter changed flag does not match the IR");
1355#endif // EXPENSIVE_CHECKS
1356 if (changed)
1357 *changed = rewriteChanged;
1358 if (failed(converged))
1359 LDBG() << "The pattern rewrite did not converge after scanning "
1360 << config.getMaxIterations() << " times";
1361 return converged;
1362}
1363
1364//===----------------------------------------------------------------------===//
1365// MultiOpPatternRewriteDriver
1366//===----------------------------------------------------------------------===//
1367
1368namespace {
1369/// This driver simplfies a list of ops.
1370class MultiOpPatternRewriteDriver : public GreedyPatternRewriteDriver {
1371public:
1372 explicit MultiOpPatternRewriteDriver(
1373 MLIRContext *ctx, const FrozenRewritePatternSet &patterns,
1374 const GreedyRewriteConfig &config, ArrayRef<Operation *> ops,
1375 llvm::SmallDenseSet<Operation *, 4> *survivingOps = nullptr);
1376
1377 /// Simplify `ops`. Return `success` if the transformation converged.
1378 LogicalResult simplify(ArrayRef<Operation *> ops, bool *changed = nullptr) &&;
1379
1380private:
1381 void notifyOperationErased(Operation *op) override {
1382 GreedyPatternRewriteDriver::notifyOperationErased(op);
1383 if (survivingOps)
1384 survivingOps->erase(op);
1385 }
1386
1387 /// An optional set of ops that survived the rewrite. This set is populated
1388 /// at the beginning of `simplifyLocally` with the inititally provided list
1389 /// of ops.
1390 llvm::SmallDenseSet<Operation *, 4> *const survivingOps = nullptr;
1391};
1392} // namespace
1393
1394MultiOpPatternRewriteDriver::MultiOpPatternRewriteDriver(
1395 MLIRContext *ctx, const FrozenRewritePatternSet &patterns,
1396 const GreedyRewriteConfig &config, ArrayRef<Operation *> ops,
1397 llvm::SmallDenseSet<Operation *, 4> *survivingOps)
1398 : GreedyPatternRewriteDriver(ctx, patterns, config),
1399 survivingOps(survivingOps) {
1401 strictModeFilteredOps.insert_range(ops);
1402
1403 if (survivingOps) {
1404 survivingOps->clear();
1405 survivingOps->insert_range(ops);
1406 }
1407}
1408
1409LogicalResult MultiOpPatternRewriteDriver::simplify(ArrayRef<Operation *> ops,
1410 bool *changed) && {
1411 // Populate the initial worklist.
1412 for (Operation *op : ops)
1413 addSingleOpToWorklist(op);
1414
1415 // Process ops on the worklist.
1416 bool result = processWorklist();
1417 if (changed)
1418 *changed = result;
1419
1420 return success(worklist.empty());
1421}
1422
1423/// Find the region that is the closest common ancestor of all given ops.
1424///
1425/// Note: This function returns `nullptr` if there is a top-level op among the
1426/// given list of ops.
1428 assert(!ops.empty() && "expected at least one op");
1429 // Fast path in case there is only one op.
1430 if (ops.size() == 1)
1431 return ops.front()->getParentRegion();
1432
1433 Region *region = ops.front()->getParentRegion();
1434 ops = ops.drop_front();
1435 int sz = ops.size();
1436 llvm::BitVector remainingOps(sz, true);
1437 while (region) {
1438 int pos = -1;
1439 // Iterate over all remaining ops.
1440 while ((pos = remainingOps.find_first_in(pos + 1, sz)) != -1) {
1441 // Is this op contained in `region`?
1442 if (region->findAncestorOpInRegion(*ops[pos]))
1443 remainingOps.reset(pos);
1444 }
1445 if (remainingOps.none())
1446 break;
1447 region = region->getParentRegion();
1448 }
1449 return region;
1450}
1451
1454 GreedyRewriteConfig config, bool *changed, bool *allErased) {
1455 if (ops.empty()) {
1456 if (changed)
1457 *changed = false;
1458 if (allErased)
1459 *allErased = true;
1460 return success();
1461 }
1462
1463 // Determine scope of rewrite.
1464 if (!config.getScope()) {
1465 // Compute scope if none was provided. The scope will remain `nullptr` if
1466 // there is a top-level op among `ops`.
1467 config.setScope(findCommonAncestor(ops));
1468 } else {
1469 // If a scope was provided, make sure that all ops are in scope.
1470#ifndef NDEBUG
1471 bool allOpsInScope = llvm::all_of(ops, [&](Operation *op) {
1472 return static_cast<bool>(config.getScope()->findAncestorOpInRegion(*op));
1473 });
1474 assert(allOpsInScope && "ops must be within the specified scope");
1475#endif // NDEBUG
1476 }
1477
1478#if MLIR_ENABLE_EXPENSIVE_PATTERN_API_CHECKS
1479 if (config.getScope() && failed(verify(config.getScope()->getParentOp())))
1480 llvm::report_fatal_error(
1481 "greedy pattern rewriter input IR failed to verify");
1482#endif // MLIR_ENABLE_EXPENSIVE_PATTERN_API_CHECKS
1483
1484#ifdef EXPENSIVE_CHECKS
1485 std::optional<OperationFingerPrint> before;
1486 if (config.getScope())
1487 before.emplace(config.getScope()->getParentOp());
1488#endif // EXPENSIVE_CHECKS
1489 bool rewriteChanged = false;
1490
1491 // Start the pattern driver.
1492 llvm::SmallDenseSet<Operation *, 4> surviving;
1493 MultiOpPatternRewriteDriver driver(ops.front()->getContext(), patterns,
1494 config, ops,
1495 allErased ? &surviving : nullptr);
1496 LogicalResult converged = std::move(driver).simplify(ops, &rewriteChanged);
1497#ifdef EXPENSIVE_CHECKS
1498 if (before &&
1499 rewriteChanged !=
1500 (*before != OperationFingerPrint(config.getScope()->getParentOp())))
1501 llvm::report_fatal_error(
1502 "greedy pattern rewriter changed flag does not match the IR");
1503#endif // EXPENSIVE_CHECKS
1504 if (changed)
1505 *changed = rewriteChanged;
1506 if (allErased)
1507 *allErased = surviving.empty();
1508 if (failed(converged))
1509 LDBG() << "The pattern rewrite did not converge after "
1510 << config.getMaxNumRewrites() << " rewrites";
1511 return converged;
1512}
return success()
return MutableOperandRange * this
static bool mayDefineSuccessors(Operation *op)
Return whether op may define successors of its block.
static Region * findCommonAncestor(ArrayRef< Operation * > ops)
Find the region that is the closest common ancestor of all given ops.
static SmallPtrSet< Block *, 2 > getRegionSuccessors(Block *block)
Collect the distinct successors of block that are in the same region.
#define DEBUG_TYPE
if(!isCopyOut)
*if copies could not be generated due to yet unimplemented cases *copyInPlacementStart and copyOutPlacementStart in copyPlacementBlock *specify the insertion points where the incoming copies and outgoing should be inserted(the insertion happens right before the *insertion point). Since `begin` can itself be invalidated due to the memref *rewriting done from this method
*if copies could not be generated due to yet unimplemented cases *copyInPlacementStart and copyOutPlacementStart in copyPlacementBlock *specify the insertion points where the incoming copies and outgoing should be the output argument nBegin is set to its * replacement(set to `begin` if no invalidation happens). Since outgoing *copies could have been inserted at `end`
static const mlir::GenInfo * generator
values clear()
static Operation * getDumpRootOp(Operation *op)
Log IR after pattern application.
static void print(spirv::VerCapExtAttr triple, DialectAsmPrinter &printer)
#define MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(CLASS_NAME)
Definition TypeID.h:331
static Operation * findAncestorOpInRegion(Region *region, Operation *op)
Return the ancestor op in the region or nullptr if the region is not an ancestor of the op.
Attributes are known-constant values of operations.
Definition Attributes.h:25
Block represents an ordered list of Operations.
Definition Block.h:34
Region * getParent() const
Provide a 'getParent' method for ilist_node_with_parent methods.
Definition Block.cpp:27
SuccessorRange getSuccessors()
Definition Block.h:280
bool isReachable(Block *other, SmallPtrSet< Block *, 16 > &&except={})
Return "true" if there is a path from this block to the given block (according to the successors rela...
Definition Block.cpp:368
bool hasNoPredecessors()
Return true if this block has no predecessors.
Definition Block.h:255
Operation * getParentOp()
Returns the closest surrounding operation that contains this block.
Definition Block.cpp:31
A cache for repeated deadness queries on nested operations.
void scheduleBlockInvalidation(Block *block)
Report a change to a block and its contents.
bool isOpTriviallyDead(Operation *op)
Return true if the operation is unused and can be erased.
void scheduleAncestorInvalidation(Operation *op)
Invalidate the cached effects of this operation and its ancestors.
void notifyOperationErased(Operation *op)
Call once for each erased operation before it is detached or destroyed.
void scheduleInvalidation(Operation *op)
Report a change to this operation or its nested IR.
void notifyBlockErased(Block *block)
Call before an empty block is detached and destroyed.
This class contains all of the information necessary to report a diagnostic to the DiagnosticEngine.
virtual Operation * materializeConstant(OpBuilder &builder, Attribute value, Type type, Location loc)
Registered hook to materialize a single constant operation from a given attribute value with the desi...
Definition Dialect.h:83
A class for computing basic dominance information.
Definition Dominance.h:143
This class represents a frozen set of patterns that can be processed by a pattern applicator.
This class allows control over how the GreedyPatternRewriteDriver works.
static constexpr int64_t kNoLimit
bool isFoldingEnabled() const
Whether this should fold while greedily rewriting.
RewriterBase::Listener * getListener() const
An optional listener that should be notified about IR modifications.
bool isConstantCSEEnabled() const
If set to "true", constants are CSE'd (even across multiple regions that are in a parent-ancestor rel...
Region * getScope() const
Only ops within the scope are added to the worklist.
GreedyRewriteStrictness getStrictness() const
Strict mode can restrict the ops that are added to the worklist during the rewrite.
bool isCSEBetweenIterationsEnabled() const
If set to "true", full common-subexpression elimination is run on the scoped region between each patt...
bool getUseTopDownTraversal() const
This specifies the order of initial traversal that populates the rewriters worklist.
GreedyRewriteConfig & setScope(Region *scope)
GreedyRewriteConfig & setListener(RewriterBase::Listener *listener)
int64_t getMaxNumRewrites() const
This specifies the maximum number of rewrites within an iteration.
int64_t getMaxIterations() const
This specifies the maximum number of times the rewriter will iterate between applying patterns and si...
GreedySimplifyRegionLevel getRegionSimplificationLevel() const
Perform control flow optimizations to the region tree after applying all patterns.
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition Location.h:76
MLIRContext is the top-level object for a collection of MLIR operations.
Definition MLIRContext.h:71
void executeAction(function_ref< void()> actionFn, const tracing::Action &action)
Dispatch the provided action to the handler if any, or just execute it.
This class represents a saved insertion point.
Definition Builders.h:330
bool isSet() const
Returns true if this insert point is set.
Definition Builders.h:340
Block * getBlock() const
Definition Builders.h:342
void setInsertionPoint(Block *block, Block::iterator insertPoint)
Set the insertion point to the specified location.
Definition Builders.h:401
Set of flags used to control the behavior of the various IR print methods (e.g.
This class provides the API for ops that are known to be isolated from above.
This class provides the API for ops that are known to be terminators.
A wrapper class that allows for printing an operation with a set of flags, useful to act as a "stream...
Definition Operation.h:1171
A unique fingerprint for a specific operation, and all of it's internal operations (if includeNested ...
A utility class for folding operations, and unifying duplicated constants generated along the way.
Definition FoldUtils.h:33
@ Unchanged
The operation was retained without modifying the IR.
Definition FoldUtils.h:51
@ Replaced
The operation was replaced with an existing constant and erased.
Definition FoldUtils.h:55
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
Dialect * getDialect()
Return the dialect this operation is associated with, or nullptr if the associated dialect is not loa...
Definition Operation.h:237
LogicalResult fold(ArrayRef< Attribute > operands, SmallVectorImpl< OpFoldResult > &results)
Attempt to fold this operation with the specified constant operand values.
bool hasTrait()
Returns true if the operation was registered with a particular trait, e.g.
Definition Operation.h:803
unsigned getNumSuccessors()
Definition Operation.h:760
bool mightHaveTrait()
Returns true if the operation might have the provided trait.
Definition Operation.h:811
Block * getBlock()
Returns the operation block that contains this operation.
Definition Operation.h:230
OpResult getResult(unsigned idx)
Get the 'idx'th result of this operation.
Definition Operation.h:434
unsigned getNumRegions()
Returns the number of regions held by this operation.
Definition Operation.h:728
Location getLoc()
The source location the operation was defined or derived from.
Definition Operation.h:240
Operation * getParentOp()
Returns the closest surrounding operation that contains this operation or nullptr if this is a top-le...
Definition Operation.h:251
OperationName getName()
The name of an operation is the key identifier for it.
Definition Operation.h:115
void print(raw_ostream &os, const OpPrintingFlags &flags={})
MutableArrayRef< Region > getRegions()
Returns the regions held by this operation.
Definition Operation.h:731
result_type_range getResultTypes()
Definition Operation.h:455
operand_range getOperands()
Returns an iterator on the underlying Value's.
Definition Operation.h:405
std::enable_if_t< llvm::function_traits< std::decay_t< FnT > >::num_args==1, RetT > walk(FnT &&callback)
Walk the operation by calling the callback for each nested operation (including this one),...
Definition Operation.h:851
Region * getParentRegion()
Returns the region to which the instruction belongs.
Definition Operation.h:247
void erase()
Remove this operation from its parent block and delete it.
unsigned getNumResults()
Return the number of results held by this operation.
Definition Operation.h:431
This class manages the application of a group of rewrite patterns, with a user-provided cost model.
LogicalResult matchAndRewrite(Operation *op, PatternRewriter &rewriter, function_ref< bool(const Pattern &)> canApply={}, function_ref< void(const Pattern &)> onFailure={}, function_ref< LogicalResult(const Pattern &)> onSuccess={})
Attempt to match and rewrite the given op with any pattern, allowing a predicate to decide if a patte...
A special type of RewriterBase that coordinates the application of a rewrite pattern on the current I...
This class contains a list of basic blocks and a link to the parent operation it is attached to.
Definition Region.h:26
Block & front()
Definition Region.h:65
Region * getParentRegion()
Return the region containing this region or nullptr if the region is attached to a top-level operatio...
Definition Region.cpp:45
Operation * findAncestorOpInRegion(Operation &op)
Returns 'op' if 'op' lies in this region, or otherwise finds the ancestor of 'op' that lies in this r...
Definition Region.cpp:168
Operation * getParentOp()
Return the parent operation this region is attached to.
Definition Region.h:198
MLIRContext * getContext()
Return the context this region is inserted in.
Definition Region.cpp:24
BlockListType::iterator iterator
Definition Region.h:52
RetT walk(FnT &&callback)
Walk all nested operations, blocks or regions (including this region), depending on the type of callb...
Definition Region.h:297
virtual void replaceOp(Operation *op, ValueRange newValues)
Replace the results of the given (original) operation with the specified list of values (replacements...
virtual void eraseOp(Operation *op)
This method erases an operation that is known to have no uses.
This class provides an abstraction over the different types of ranges over Values.
Definition ValueRange.h:392
static WalkResult skip()
Definition WalkResult.h:48
static WalkResult advance()
Definition WalkResult.h:47
CRTP Implementation of an action.
Definition Action.h:76
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:886
Include the generated interface declarations.
bool matchPattern(Value value, const Pattern &pattern)
Entry point for matching a pattern over a Value.
Definition Matchers.h:490
void eliminateCommonSubExpressions(RewriterBase &rewriter, DominanceInfo &domInfo, Operation *op, bool *changed=nullptr, int64_t *numCSE=nullptr, int64_t *numDCE=nullptr)
Eliminate common subexpressions within the given operation.
Definition CSE.cpp:408
LogicalResult eraseUnreachableBlocks(RewriterBase &rewriter, MutableArrayRef< Region > regions, bool recurse=true)
Erase the unreachable blocks within the provided regions.
@ Aggressive
Run extra simplificiations (e.g.
@ Disabled
Disable region control-flow simplification.
LogicalResult applyPatternsGreedily(Region &region, const FrozenRewritePatternSet &patterns, GreedyRewriteConfig config=GreedyRewriteConfig(), bool *changed=nullptr)
Rewrite ops in the given region, which must be isolated from above, by repeatedly applying the highes...
LogicalResult applyOpPatternsGreedily(ArrayRef< Operation * > ops, const FrozenRewritePatternSet &patterns, GreedyRewriteConfig config=GreedyRewriteConfig(), bool *changed=nullptr, bool *allErased=nullptr)
Rewrite the specified ops by repeatedly applying the highest benefit patterns in a greedy worklist dr...
bool isOpTriviallyDead(Operation *op)
Return true if the given operation is unused, and has no side effects on memory that prevent erasing.
llvm::DenseMap< KeyT, ValueT, KeyInfoT, BucketT > DenseMap
Definition LLVM.h:123
@ AnyOp
No restrictions wrt. which ops are processed.
LogicalResult simplifyRegions(RewriterBase &rewriter, MutableArrayRef< Region > regions, bool mergeBlocks=true)
Run a set of structural simplifications over the given regions.
detail::constant_op_matcher m_Constant()
Matches a constant foldable operation.
Definition Matchers.h:369
LogicalResult verify(Operation *op, bool verifyRecursively=true)
Perform (potentially expensive) checks of invariants, used to detect compiler bugs,...
Definition Verifier.cpp:566
llvm::function_ref< Fn > function_ref
Definition LLVM.h:155
A listener that forwards all notifications to another listener.
void notifyOperationInserted(Operation *op, InsertPoint previous) override
Notify the listener that the specified operation was inserted.
void notifyOperationModified(Operation *op) override
Notify the listener that the specified operation was modified in-place.
void notifyOperationErased(Operation *op) override
Notify the listener that the specified operation is about to be erased.
void notifyBlockErased(Block *block) override
Notify the listener that the specified block is about to be erased.
void notifyBlockInserted(Block *block, Region *previous, Region::iterator previousIt) override
Notify the listener that the specified block was inserted.