MLIR 24.0.0git
ControlFlowOps.cpp
Go to the documentation of this file.
1//===- ControlFlowOps.cpp - ControlFlow Operations ------------------------===//
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
10
16#include "mlir/IR/AffineExpr.h"
17#include "mlir/IR/AffineMap.h"
18#include "mlir/IR/Builders.h"
20#include "mlir/IR/IRMapping.h"
21#include "mlir/IR/Matchers.h"
25#include "mlir/IR/Value.h"
27#include "llvm/ADT/STLExtras.h"
28#include <numeric>
29
30#include "mlir/Dialect/ControlFlow/IR/ControlFlowOpsDialect.cpp.inc"
31
32using namespace mlir;
33using namespace mlir::cf;
34
35//===----------------------------------------------------------------------===//
36// ControlFlowDialect Interfaces
37//===----------------------------------------------------------------------===//
38namespace {
39/// This class defines the interface for handling inlining with control flow
40/// operations.
41struct ControlFlowInlinerInterface : public DialectInlinerInterface {
42 using DialectInlinerInterface::DialectInlinerInterface;
43 ~ControlFlowInlinerInterface() override = default;
44
45 /// All control flow operations can be inlined.
46 bool isLegalToInline(Operation *call, Operation *callable,
47 bool wouldBeCloned) const final {
48 return true;
49 }
50 bool isLegalToInline(Operation *, Region *, bool, IRMapping &) const final {
51 return true;
52 }
53
54 /// ControlFlow terminator operations don't really need any special handing.
55 void handleTerminator(Operation *op, Block *newDest) const final {}
56};
57} // namespace
58
59//===----------------------------------------------------------------------===//
60// ControlFlowDialect
61//===----------------------------------------------------------------------===//
62
63void ControlFlowDialect::initialize() {
64 addInterfaces<ControlFlowInlinerInterface>();
65 declarePromisedInterface<ConvertToLLVMPatternInterface, ControlFlowDialect>();
66 declarePromisedInterfaces<bufferization::BufferizableOpInterface, BranchOp,
67 CondBranchOp>();
68 declarePromisedInterface<bufferization::BufferDeallocationOpInterface,
69 CondBranchOp>();
70}
71
72//===----------------------------------------------------------------------===//
73// AssertOp
74//===----------------------------------------------------------------------===//
75
76LogicalResult AssertOp::canonicalize(AssertOp op, PatternRewriter &rewriter) {
77 // Erase assertion if argument is constant true.
78 if (matchPattern(op.getArg(), m_One())) {
79 rewriter.eraseOp(op);
80 return success();
81 }
82 return failure();
83}
84
85// This side effect models "program termination".
86void AssertOp::getEffects(
88 &effects) {
89 effects.emplace_back(MemoryEffects::Write::get());
90}
91
92//===----------------------------------------------------------------------===//
93// BranchOp
94//===----------------------------------------------------------------------===//
95
96/// Given a successor, try to collapse it to a new destination if it only
97/// contains a passthrough unconditional branch. If the successor is
98/// collapsable, `successor` and `successorOperands` are updated to reference
99/// the new destination and values. `argStorage` is used as storage if operands
100/// to the collapsed successor need to be remapped. It must outlive uses of
101/// successorOperands.
102static LogicalResult collapseBranch(Block *&successor,
103 ValueRange &successorOperands,
104 SmallVectorImpl<Value> &argStorage) {
105 // Check that the successor only contains a unconditional branch.
106 if (std::next(successor->begin()) != successor->end())
107 return failure();
108 // Check that the terminator is an unconditional branch.
109 BranchOp successorBranch = dyn_cast<BranchOp>(successor->getTerminator());
110 if (!successorBranch)
111 return failure();
112 // Check that the arguments are only used within the terminator.
113 for (BlockArgument arg : successor->getArguments()) {
114 for (Operation *user : arg.getUsers())
115 if (user != successorBranch)
116 return failure();
117 }
118 // Don't try to collapse branches to infinite loops.
119 Block *successorDest = successorBranch.getDest();
120 if (successorDest == successor)
121 return failure();
122 // Don't try to collapse branches which participate in a cycle.
123 BranchOp nextBranch = dyn_cast<BranchOp>(successorDest->getTerminator());
124 llvm::DenseSet<Block *> visited{successor, successorDest};
125 while (nextBranch) {
126 Block *nextBranchDest = nextBranch.getDest();
127 if (visited.contains(nextBranchDest))
128 return failure();
129 visited.insert(nextBranchDest);
130 nextBranch = dyn_cast<BranchOp>(nextBranchDest->getTerminator());
131 }
132
133 // Update the operands to the successor. If the branch parent has no
134 // arguments, we can use the branch operands directly.
135 OperandRange operands = successorBranch.getOperands();
136 if (successor->args_empty()) {
137 successor = successorDest;
138 successorOperands = operands;
139 return success();
140 }
141
142 // Otherwise, we need to remap any argument operands.
143 for (Value operand : operands) {
144 BlockArgument argOperand = llvm::dyn_cast<BlockArgument>(operand);
145 if (argOperand && argOperand.getOwner() == successor)
146 argStorage.push_back(successorOperands[argOperand.getArgNumber()]);
147 else
148 argStorage.push_back(operand);
149 }
150 successor = successorDest;
151 successorOperands = argStorage;
152 return success();
153}
154
155/// Simplify a branch to a block that has a single predecessor. This effectively
156/// merges the two blocks.
157static LogicalResult
159 // Check that the successor block has a single predecessor.
160 Block *succ = op.getDest();
161 Block *opParent = op->getBlock();
162 if (succ == opParent || !llvm::hasSingleElement(succ->getPredecessors()))
163 return failure();
164
165 // If any branch operand is itself a block argument of the successor, merging
166 // would call replaceAllUsesWith(arg, arg) — a no-op — leaving dangling uses
167 // of that argument after the successor block is erased.
168 for (Value operand : op.getOperands())
169 if (auto ba = dyn_cast<BlockArgument>(operand))
170 if (ba.getOwner() == succ)
171 return failure();
172
173 // Merge the successor into the current block and erase the branch.
174 SmallVector<Value> brOperands(op.getOperands());
175 rewriter.eraseOp(op);
176 rewriter.mergeBlocks(succ, opParent, brOperands);
177 return success();
178}
179
180/// br ^bb1
181/// ^bb1
182/// br ^bbN(...)
183///
184/// -> br ^bbN(...)
185///
186static LogicalResult simplifyPassThroughBr(BranchOp op,
187 PatternRewriter &rewriter) {
188 Block *dest = op.getDest();
189 ValueRange destOperands = op.getOperands();
190 SmallVector<Value, 4> destOperandStorage;
191
192 // Try to collapse the successor if it points somewhere other than this
193 // block.
194 if (dest == op->getBlock() ||
195 failed(collapseBranch(dest, destOperands, destOperandStorage)))
196 return failure();
197
198 // Create a new branch with the collapsed successor.
199 rewriter.replaceOpWithNewOp<BranchOp>(op, dest, destOperands);
200 return success();
201}
202
203/// If all incoming values for a block argument from all predecessors are the
204/// same SSA value, replace uses of the block argument with that value. This
205/// allows the block argument to be removed by dead code elimination.
206///
207/// %c = arith.constant 0 : i32
208/// cf.br ^bb1(%c : i32) // pred 1
209/// cf.br ^bb1(%c : i32) // pred 2
210/// ^bb1(%arg0: i32):
211/// use(%arg0)
212/// ->
213/// ^bb1(%arg0: i32):
214/// use(%c) // %arg0 has no uses and can be removed
215///
216static LogicalResult simplifyUniformBlockArgs(Block *dest,
217 PatternRewriter &rewriter) {
218 if (dest->hasNoPredecessors() ||
219 llvm::hasSingleElement(dest->getPredecessors()))
220 return failure();
221
222 bool changed = false;
223 for (BlockArgument arg : dest->getArguments()) {
224 if (arg.use_empty())
225 continue;
226
227 Value commonValue;
228 for (Block *pred : dest->getPredecessors()) {
229 auto branch = dyn_cast<BranchOpInterface>(pred->getTerminator());
230 if (!branch) {
231 commonValue = Value();
232 break;
233 }
234
235 for (auto [i, succ] : llvm::enumerate(branch->getSuccessors())) {
236 if (succ != dest)
237 continue;
238
239 // Produced operands are modeled by BranchOpInterface as null Values.
240 Value val = branch.getSuccessorOperands(i)[arg.getArgNumber()];
241 if (commonValue && commonValue != val) {
242 commonValue = Value();
243 break;
244 }
245 commonValue = val;
246 }
247
248 if (!commonValue)
249 break;
250 }
251
252 if (commonValue && commonValue != arg) {
253 rewriter.replaceAllUsesWith(arg, commonValue);
254 changed = true;
255 }
256 }
257 return success(changed);
258}
259
260namespace {
261/// Replaces block arguments with a uniform incoming value across all
262/// predecessors, for any op implementing BranchOpInterface.
263struct SimplifyUniformBlockArguments
264 : public OpInterfaceRewritePattern<BranchOpInterface> {
265 using Base::Base;
266 LogicalResult matchAndRewrite(BranchOpInterface op,
267 PatternRewriter &rewriter) const override {
268 bool changed = false;
269 for (Block *succ : op->getSuccessors())
270 changed |= succeeded(simplifyUniformBlockArgs(succ, rewriter));
271 return success(changed);
272 }
273};
274} // namespace
275
276LogicalResult BranchOp::canonicalize(BranchOp op, PatternRewriter &rewriter) {
277 return success(succeeded(simplifyBrToBlockWithSinglePred(op, rewriter)) ||
278 succeeded(simplifyPassThroughBr(op, rewriter)) ||
279 succeeded(simplifyUniformBlockArgs(op.getDest(), rewriter)));
280}
281
282void BranchOp::setDest(Block *block) { return setSuccessor(block); }
283
284void BranchOp::eraseOperand(unsigned index) { (*this)->eraseOperand(index); }
285
286SuccessorOperands BranchOp::getSuccessorOperands(unsigned index) {
287 assert(index == 0 && "invalid successor index");
288 return SuccessorOperands(getDestOperandsMutable());
289}
290
291Block *BranchOp::getSuccessorForOperands(ArrayRef<Attribute>) {
292 return getDest();
293}
294
295//===----------------------------------------------------------------------===//
296// CondBranchOp
297//===----------------------------------------------------------------------===//
298
299namespace {
300/// cf.cond_br true, ^bb1, ^bb2
301/// -> br ^bb1
302/// cf.cond_br false, ^bb1, ^bb2
303/// -> br ^bb2
304///
305struct SimplifyConstCondBranchPred : public OpRewritePattern<CondBranchOp> {
306 using Base::Base;
307
308 LogicalResult matchAndRewrite(CondBranchOp condbr,
309 PatternRewriter &rewriter) const override {
310 if (matchPattern(condbr.getCondition(), m_NonZero())) {
311 // True branch taken.
312 rewriter.replaceOpWithNewOp<BranchOp>(condbr, condbr.getTrueDest(),
313 condbr.getTrueOperands());
314 return success();
315 }
316 if (matchPattern(condbr.getCondition(), m_Zero())) {
317 // False branch taken.
318 rewriter.replaceOpWithNewOp<BranchOp>(condbr, condbr.getFalseDest(),
319 condbr.getFalseOperands());
320 return success();
321 }
322 return failure();
323 }
324};
325
326/// cf.cond_br %cond, ^bb1, ^bb2
327/// ^bb1
328/// br ^bbN(...)
329/// ^bb2
330/// br ^bbK(...)
331///
332/// -> cf.cond_br %cond, ^bbN(...), ^bbK(...)
333///
334struct SimplifyPassThroughCondBranch : public OpRewritePattern<CondBranchOp> {
335 using OpRewritePattern<CondBranchOp>::OpRewritePattern;
336
337 LogicalResult matchAndRewrite(CondBranchOp condbr,
338 PatternRewriter &rewriter) const override {
339 Block *trueDest = condbr.getTrueDest(), *falseDest = condbr.getFalseDest();
340 ValueRange trueDestOperands = condbr.getTrueOperands();
341 ValueRange falseDestOperands = condbr.getFalseOperands();
342 SmallVector<Value, 4> trueDestOperandStorage, falseDestOperandStorage;
343
344 // Try to collapse one of the current successors.
345 LogicalResult collapsedTrue =
346 collapseBranch(trueDest, trueDestOperands, trueDestOperandStorage);
347 LogicalResult collapsedFalse =
348 collapseBranch(falseDest, falseDestOperands, falseDestOperandStorage);
349 if (failed(collapsedTrue) && failed(collapsedFalse))
350 return failure();
351
352 // Create a new branch with the collapsed successors.
353 rewriter.replaceOpWithNewOp<CondBranchOp>(
354 condbr, condbr.getCondition(), trueDest, trueDestOperands, falseDest,
355 falseDestOperands, condbr.getWeights());
356 return success();
357 }
358};
359
360/// cf.cond_br %cond, ^bb1(A, ..., N), ^bb1(A, ..., N)
361/// -> br ^bb1(A, ..., N)
362///
363/// cf.cond_br %cond, ^bb1(A), ^bb1(B)
364/// -> %select = arith.select %cond, A, B
365/// br ^bb1(%select)
366///
367struct SimplifyCondBranchIdenticalSuccessors
368 : public OpRewritePattern<CondBranchOp> {
369 using OpRewritePattern<CondBranchOp>::OpRewritePattern;
370
371 LogicalResult matchAndRewrite(CondBranchOp condbr,
372 PatternRewriter &rewriter) const override {
373 // Check that the true and false destinations are the same and have the same
374 // operands.
375 Block *trueDest = condbr.getTrueDest();
376 if (trueDest != condbr.getFalseDest())
377 return failure();
378
379 // If all of the operands match, no selects need to be generated.
380 OperandRange trueOperands = condbr.getTrueOperands();
381 OperandRange falseOperands = condbr.getFalseOperands();
382 if (trueOperands == falseOperands) {
383 rewriter.replaceOpWithNewOp<BranchOp>(condbr, trueDest, trueOperands);
384 return success();
385 }
386
387 // Otherwise, if the current block is the only predecessor insert selects
388 // for any mismatched branch operands.
389 if (trueDest->getUniquePredecessor() != condbr->getBlock())
390 return failure();
391
392 // Generate a select for any operands that differ between the two.
393 SmallVector<Value, 8> mergedOperands;
394 mergedOperands.reserve(trueOperands.size());
395 Value condition = condbr.getCondition();
396 for (auto it : llvm::zip(trueOperands, falseOperands)) {
397 if (std::get<0>(it) == std::get<1>(it))
398 mergedOperands.push_back(std::get<0>(it));
399 else
400 mergedOperands.push_back(
401 arith::SelectOp::create(rewriter, condbr.getLoc(), condition,
402 std::get<0>(it), std::get<1>(it)));
403 }
404
405 rewriter.replaceOpWithNewOp<BranchOp>(condbr, trueDest, mergedOperands);
406 return success();
407 }
408};
409
410/// ...
411/// cf.cond_br %cond, ^bb1(...), ^bb2(...)
412/// ...
413/// ^bb1: // has single predecessor
414/// ...
415/// cf.cond_br %cond, ^bb3(...), ^bb4(...)
416///
417/// ->
418///
419/// ...
420/// cf.cond_br %cond, ^bb1(...), ^bb2(...)
421/// ...
422/// ^bb1: // has single predecessor
423/// ...
424/// br ^bb3(...)
425///
426struct SimplifyCondBranchFromCondBranchOnSameCondition
427 : public OpRewritePattern<CondBranchOp> {
428 using OpRewritePattern<CondBranchOp>::OpRewritePattern;
429
430 LogicalResult matchAndRewrite(CondBranchOp condbr,
431 PatternRewriter &rewriter) const override {
432 // Check that we have a single distinct predecessor.
433 Block *currentBlock = condbr->getBlock();
434 Block *predecessor = currentBlock->getSinglePredecessor();
435 if (!predecessor)
436 return failure();
437
438 // Check that the predecessor terminates with a conditional branch to this
439 // block and that it branches on the same condition.
440 auto predBranch = dyn_cast<CondBranchOp>(predecessor->getTerminator());
441 if (!predBranch || condbr.getCondition() != predBranch.getCondition())
442 return failure();
443
444 // Fold this branch to an unconditional branch.
445 if (currentBlock == predBranch.getTrueDest())
446 rewriter.replaceOpWithNewOp<BranchOp>(condbr, condbr.getTrueDest(),
447 condbr.getTrueDestOperands());
448 else
449 rewriter.replaceOpWithNewOp<BranchOp>(condbr, condbr.getFalseDest(),
450 condbr.getFalseDestOperands());
451 return success();
452 }
453};
454
455/// cf.cond_br %arg0, ^trueB, ^falseB
456///
457/// ^trueB:
458/// "test.consumer1"(%arg0) : (i1) -> ()
459/// ...
460///
461/// ^falseB:
462/// "test.consumer2"(%arg0) : (i1) -> ()
463/// ...
464///
465/// ->
466///
467/// cf.cond_br %arg0, ^trueB, ^falseB
468/// ^trueB:
469/// "test.consumer1"(%true) : (i1) -> ()
470/// ...
471///
472/// ^falseB:
473/// "test.consumer2"(%false) : (i1) -> ()
474/// ...
475struct CondBranchTruthPropagation : public OpRewritePattern<CondBranchOp> {
476 using OpRewritePattern<CondBranchOp>::OpRewritePattern;
477
478 LogicalResult matchAndRewrite(CondBranchOp condbr,
479 PatternRewriter &rewriter) const override {
480 // Check that we have a single distinct predecessor.
481 bool replaced = false;
482 Type ty = rewriter.getI1Type();
483
484 // These variables serve to prevent creating duplicate constants
485 // and hold constant true or false values.
486 Value constantTrue = nullptr;
487 Value constantFalse = nullptr;
488
489 // TODO These checks can be expanded to encompas any use with only
490 // either the true of false edge as a predecessor. For now, we fall
491 // back to checking the single predecessor is given by the true/fasle
492 // destination, thereby ensuring that only that edge can reach the
493 // op.
494 if (condbr.getTrueDest()->getSinglePredecessor()) {
495 for (OpOperand &use :
496 llvm::make_early_inc_range(condbr.getCondition().getUses())) {
497 if (use.getOwner()->getBlock() == condbr.getTrueDest()) {
498 replaced = true;
499
500 if (!constantTrue)
501 constantTrue = arith::ConstantOp::create(
502 rewriter, condbr.getLoc(), ty, rewriter.getBoolAttr(true));
503
504 rewriter.modifyOpInPlace(use.getOwner(),
505 [&] { use.set(constantTrue); });
506 }
507 }
508 }
509 if (condbr.getFalseDest()->getSinglePredecessor()) {
510 for (OpOperand &use :
511 llvm::make_early_inc_range(condbr.getCondition().getUses())) {
512 if (use.getOwner()->getBlock() == condbr.getFalseDest()) {
513 replaced = true;
514
515 if (!constantFalse)
516 constantFalse = arith::ConstantOp::create(
517 rewriter, condbr.getLoc(), ty, rewriter.getBoolAttr(false));
518
519 rewriter.modifyOpInPlace(use.getOwner(),
520 [&] { use.set(constantFalse); });
521 }
522 }
523 }
524 return success(replaced);
525 }
526};
527
528/// Returns true if `block` contains only `ub.unreachable`.
529static bool isUnreachableBlock(Block *block) {
530 return llvm::hasSingleElement(*block) &&
531 isa<ub::UnreachableOp>(block->getTerminator());
532}
533
534/// If the destination block of a conditional branch contains only
535/// ub.unreachable, unconditionally branch to the other destination.
536struct DropUnreachableCondBranch : public OpRewritePattern<CondBranchOp> {
537 using OpRewritePattern<CondBranchOp>::OpRewritePattern;
538
539 LogicalResult matchAndRewrite(CondBranchOp condbr,
540 PatternRewriter &rewriter) const override {
541 // If the "true" destination is unreachable, branch to the "false"
542 // destination.
543 Block *trueDest = condbr.getTrueDest();
544 Block *falseDest = condbr.getFalseDest();
545 if (isUnreachableBlock(trueDest)) {
546 rewriter.replaceOpWithNewOp<BranchOp>(condbr, falseDest,
547 condbr.getFalseOperands());
548 return success();
549 }
550
551 // If the "false" destination is unreachable, branch to the "true"
552 // destination.
553 if (isUnreachableBlock(falseDest)) {
554 rewriter.replaceOpWithNewOp<BranchOp>(condbr, trueDest,
555 condbr.getTrueOperands());
556 return success();
557 }
558
559 return failure();
560 }
561};
562} // namespace
563
564void CondBranchOp::getCanonicalizationPatterns(RewritePatternSet &results,
565 MLIRContext *context) {
566 results.add<SimplifyConstCondBranchPred, SimplifyPassThroughCondBranch,
567 SimplifyCondBranchIdenticalSuccessors,
568 SimplifyCondBranchFromCondBranchOnSameCondition,
569 CondBranchTruthPropagation, DropUnreachableCondBranch,
570 SimplifyUniformBlockArguments>(context);
571}
572
573SuccessorOperands CondBranchOp::getSuccessorOperands(unsigned index) {
574 assert(index < getNumSuccessors() && "invalid successor index");
575 return SuccessorOperands(index == trueIndex ? getTrueDestOperandsMutable()
576 : getFalseDestOperandsMutable());
577}
578
579Block *CondBranchOp::getSuccessorForOperands(ArrayRef<Attribute> operands) {
580 if (IntegerAttr condAttr =
581 llvm::dyn_cast_or_null<IntegerAttr>(operands.front()))
582 return condAttr.getValue().isOne() ? getTrueDest() : getFalseDest();
583 return nullptr;
584}
585
586//===----------------------------------------------------------------------===//
587// SwitchOp
588//===----------------------------------------------------------------------===//
589
590void SwitchOp::build(OpBuilder &builder, OperationState &result, Value value,
591 Block *defaultDestination, ValueRange defaultOperands,
592 DenseIntElementsAttr caseValues,
593 BlockRange caseDestinations,
594 ArrayRef<ValueRange> caseOperands) {
595 build(builder, result, value, defaultOperands, caseOperands, caseValues,
596 defaultDestination, caseDestinations);
597}
598
599void SwitchOp::build(OpBuilder &builder, OperationState &result, Value value,
600 Block *defaultDestination, ValueRange defaultOperands,
601 ArrayRef<APInt> caseValues, BlockRange caseDestinations,
602 ArrayRef<ValueRange> caseOperands) {
603 DenseIntElementsAttr caseValuesAttr;
604 if (!caseValues.empty()) {
605 ShapedType caseValueType = VectorType::get(
606 static_cast<int64_t>(caseValues.size()), value.getType());
607 caseValuesAttr = DenseIntElementsAttr::get(caseValueType, caseValues);
608 }
609 build(builder, result, value, defaultDestination, defaultOperands,
610 caseValuesAttr, caseDestinations, caseOperands);
611}
612
613void SwitchOp::build(OpBuilder &builder, OperationState &result, Value value,
614 Block *defaultDestination, ValueRange defaultOperands,
615 ArrayRef<int32_t> caseValues, BlockRange caseDestinations,
616 ArrayRef<ValueRange> caseOperands) {
617 DenseIntElementsAttr caseValuesAttr;
618 if (!caseValues.empty()) {
619 ShapedType caseValueType = VectorType::get(
620 static_cast<int64_t>(caseValues.size()), value.getType());
621 caseValuesAttr = DenseIntElementsAttr::get(caseValueType, caseValues);
622 }
623 build(builder, result, value, defaultDestination, defaultOperands,
624 caseValuesAttr, caseDestinations, caseOperands);
625}
626
627/// <cases> ::= `default` `:` bb-id (`(` ssa-use-and-type-list `)`)?
628/// ( `,` integer `:` bb-id (`(` ssa-use-and-type-list `)`)? )*
629static ParseResult parseSwitchOpCases(
630 OpAsmParser &parser, Type &flagType, Block *&defaultDestination,
632 SmallVectorImpl<Type> &defaultOperandTypes,
633 DenseIntElementsAttr &caseValues,
634 SmallVectorImpl<Block *> &caseDestinations,
636 SmallVectorImpl<SmallVector<Type>> &caseOperandTypes) {
637 if (parser.parseKeyword("default") || parser.parseColon() ||
638 parser.parseSuccessor(defaultDestination))
639 return failure();
640 if (succeeded(parser.parseOptionalLParen())) {
641 if (parser.parseOperandList(defaultOperands,
643 parser.parseColonTypeList(defaultOperandTypes) || parser.parseRParen())
644 return failure();
645 }
646
647 SmallVector<APInt> values;
648 unsigned bitWidth = flagType.getIntOrFloatBitWidth();
649 while (succeeded(parser.parseOptionalComma())) {
650 SMLoc valueLoc = parser.getCurrentLocation();
651 APInt value;
652 if (failed(parser.parseInteger(value)))
653 return failure();
654 if (value.isNegative() ? !value.isSignedIntN(bitWidth)
655 : !value.isIntN(bitWidth))
656 return parser.emitError(valueLoc)
657 << "case value is out of range for " << flagType;
658 values.push_back(value.sextOrTrunc(bitWidth));
659
660 Block *destination;
662 SmallVector<Type> operandTypes;
663 if (failed(parser.parseColon()) ||
664 failed(parser.parseSuccessor(destination)))
665 return failure();
666 if (succeeded(parser.parseOptionalLParen())) {
667 if (failed(parser.parseOperandList(operands,
669 failed(parser.parseColonTypeList(operandTypes)) ||
670 failed(parser.parseRParen()))
671 return failure();
672 }
673 caseDestinations.push_back(destination);
674 caseOperands.emplace_back(operands);
675 caseOperandTypes.emplace_back(operandTypes);
676 }
677
678 if (!values.empty()) {
679 ShapedType caseValueType =
680 VectorType::get(static_cast<int64_t>(values.size()), flagType);
681 caseValues = DenseIntElementsAttr::get(caseValueType, values);
682 }
683 return success();
684}
685
687 OpAsmPrinter &p, SwitchOp op, Type flagType, Block *defaultDestination,
688 OperandRange defaultOperands, TypeRange defaultOperandTypes,
689 DenseIntElementsAttr caseValues, SuccessorRange caseDestinations,
690 OperandRangeRange caseOperands, const TypeRangeRange &caseOperandTypes) {
691 p << " default: ";
692 p.printSuccessorAndUseList(defaultDestination, defaultOperands);
693
694 if (!caseValues)
695 return;
696
697 for (const auto &it : llvm::enumerate(caseValues.getValues<APInt>())) {
698 p << ',';
699 p.printNewline();
700 p << " ";
701 p << it.value();
702 p << ": ";
703 p.printSuccessorAndUseList(caseDestinations[it.index()],
704 caseOperands[it.index()]);
705 }
706 p.printNewline();
707}
708
709LogicalResult SwitchOp::verify() {
710 auto caseValues = getCaseValues();
711 auto caseDestinations = getCaseDestinations();
712
713 if (!caseValues && caseDestinations.empty())
714 return success();
715
716 Type flagType = getFlag().getType();
717 Type caseValueType = caseValues->getType().getElementType();
718 if (caseValueType != flagType)
719 return emitOpError() << "'flag' type (" << flagType
720 << ") should match case value type (" << caseValueType
721 << ")";
722
723 if (caseValues &&
724 caseValues->size() != static_cast<int64_t>(caseDestinations.size()))
725 return emitOpError() << "number of case values (" << caseValues->size()
726 << ") should match number of "
727 "case destinations ("
728 << caseDestinations.size() << ")";
729
730 // A repeated case value has no single destination, and LLVM IR rejects it.
731 if (caseValues) {
732 llvm::SmallDenseMap<APInt, unsigned> firstCase;
733 for (auto [index, value] :
734 llvm::enumerate(caseValues->getValues<APInt>())) {
735 auto [it, inserted] = firstCase.try_emplace(value, index);
736 if (inserted)
737 continue;
738 std::string asSigned = llvm::toString(value, 10, /*Signed=*/true);
739 std::string asUnsigned = llvm::toString(value, 10, /*Signed=*/false);
740 InFlightDiagnostic diag = emitOpError() << "case value " << asSigned;
741 if (asSigned != asUnsigned)
742 diag << " (unsigned " << asUnsigned << ")";
743 return diag << " is repeated (cases " << it->second << " and " << index
744 << ")";
745 }
746 }
747 return success();
748}
749
750SuccessorOperands SwitchOp::getSuccessorOperands(unsigned index) {
751 assert(index < getNumSuccessors() && "invalid successor index");
752 return SuccessorOperands(index == 0 ? getDefaultOperandsMutable()
753 : getCaseOperandsMutable(index - 1));
754}
755
756Block *SwitchOp::getSuccessorForOperands(ArrayRef<Attribute> operands) {
757 std::optional<DenseIntElementsAttr> caseValues = getCaseValues();
758
759 if (!caseValues)
760 return getDefaultDestination();
761
762 SuccessorRange caseDests = getCaseDestinations();
763 if (auto value = llvm::dyn_cast_or_null<IntegerAttr>(operands.front())) {
764 for (const auto &it : llvm::enumerate(caseValues->getValues<APInt>()))
765 if (it.value() == value.getValue())
766 return caseDests[it.index()];
767 return getDefaultDestination();
768 }
769 return nullptr;
770}
771
772/// switch %flag : i32, [
773/// default: ^bb1
774/// ]
775/// -> br ^bb1
776static LogicalResult simplifySwitchWithOnlyDefault(SwitchOp op,
777 PatternRewriter &rewriter) {
778 if (!op.getCaseDestinations().empty())
779 return failure();
780
781 rewriter.replaceOpWithNewOp<BranchOp>(op, op.getDefaultDestination(),
782 op.getDefaultOperands());
783 return success();
784}
785
786/// switch %flag : i32, [
787/// default: ^bb1,
788/// 42: ^bb1,
789/// 43: ^bb2
790/// ]
791/// ->
792/// switch %flag : i32, [
793/// default: ^bb1,
794/// 43: ^bb2
795/// ]
796static LogicalResult
798 SmallVector<Block *> newCaseDestinations;
799 SmallVector<ValueRange> newCaseOperands;
800 SmallVector<APInt> newCaseValues;
801 bool requiresChange = false;
802 auto caseValues = op.getCaseValues();
803 auto caseDests = op.getCaseDestinations();
804
805 for (const auto &it : llvm::enumerate(caseValues->getValues<APInt>())) {
806 if (caseDests[it.index()] == op.getDefaultDestination() &&
807 op.getCaseOperands(it.index()) == op.getDefaultOperands()) {
808 requiresChange = true;
809 continue;
810 }
811 newCaseDestinations.push_back(caseDests[it.index()]);
812 newCaseOperands.push_back(op.getCaseOperands(it.index()));
813 newCaseValues.push_back(it.value());
814 }
815
816 if (!requiresChange)
817 return failure();
818
819 rewriter.replaceOpWithNewOp<SwitchOp>(
820 op, op.getFlag(), op.getDefaultDestination(), op.getDefaultOperands(),
821 newCaseValues, newCaseDestinations, newCaseOperands);
822 return success();
823}
824
825/// Drop cases whose destination block contains only ub.unreachable. If the
826/// default destination is unreachable, the last remaining case becomes the new
827/// default destination, or the switch is replaced by ub.unreachable if no case
828/// remains.
829/// switch %flag : i32, [
830/// default: ^bb1,
831/// 42: ^bb2,
832/// 43: ^bb3
833/// ]
834/// ^bb3:
835/// ub.unreachable
836/// -> switch %flag : i32, [
837/// default: ^bb1,
838/// 42: ^bb2
839/// ]
840static LogicalResult dropUnreachableSwitchCases(SwitchOp op,
841 PatternRewriter &rewriter) {
842 std::optional<DenseIntElementsAttr> caseValues = op.getCaseValues();
843 if (!caseValues)
844 return failure();
845
846 SmallVector<APInt> newCaseValues;
847 SmallVector<Block *> newCaseDestinations;
848 SmallVector<ValueRange> newCaseOperands;
849 auto caseDests = op.getCaseDestinations();
850 for (const auto &it : llvm::enumerate(caseValues->getValues<APInt>())) {
851 if (isUnreachableBlock(caseDests[it.index()]))
852 continue;
853 newCaseValues.push_back(it.value());
854 newCaseDestinations.push_back(caseDests[it.index()]);
855 newCaseOperands.push_back(op.getCaseOperands(it.index()));
856 }
857
858 Block *defaultDest = op.getDefaultDestination();
859 ValueRange defaultOperands = op.getDefaultOperands();
860 if (isUnreachableBlock(defaultDest)) {
861 // Every destination is unreachable, so the switch itself is unreachable.
862 if (newCaseDestinations.empty()) {
863 rewriter.replaceOpWithNewOp<ub::UnreachableOp>(op);
864 return success();
865 }
866 // Any value not matching a remaining case is undefined behavior, so the
867 // last remaining case can serve as the default destination.
868 defaultDest = newCaseDestinations.pop_back_val();
869 defaultOperands = newCaseOperands.pop_back_val();
870 newCaseValues.pop_back();
871 } else if (newCaseDestinations.size() == caseDests.size()) {
872 return failure();
873 }
874
875 if (newCaseDestinations.empty()) {
876 rewriter.replaceOpWithNewOp<BranchOp>(op, defaultDest, defaultOperands);
877 return success();
878 }
879 rewriter.replaceOpWithNewOp<SwitchOp>(op, op.getFlag(), defaultDest,
880 defaultOperands, newCaseValues,
881 newCaseDestinations, newCaseOperands);
882 return success();
883}
884
885/// Helper for folding a switch with a constant value.
886/// switch %c_42 : i32, [
887/// default: ^bb1 ,
888/// 42: ^bb2,
889/// 43: ^bb3
890/// ]
891/// -> br ^bb2
892static void foldSwitch(SwitchOp op, PatternRewriter &rewriter,
893 const APInt &caseValue) {
894 auto caseValues = op.getCaseValues();
895 for (const auto &it : llvm::enumerate(caseValues->getValues<APInt>())) {
896 if (it.value() == caseValue) {
897 rewriter.replaceOpWithNewOp<BranchOp>(
898 op, op.getCaseDestinations()[it.index()],
899 op.getCaseOperands(it.index()));
900 return;
901 }
902 }
903 rewriter.replaceOpWithNewOp<BranchOp>(op, op.getDefaultDestination(),
904 op.getDefaultOperands());
905}
906
907/// switch %c_42 : i32, [
908/// default: ^bb1,
909/// 42: ^bb2,
910/// 43: ^bb3
911/// ]
912/// -> br ^bb2
913static LogicalResult simplifyConstSwitchValue(SwitchOp op,
914 PatternRewriter &rewriter) {
915 APInt caseValue;
916 if (!matchPattern(op.getFlag(), m_ConstantInt(&caseValue)))
917 return failure();
918
919 foldSwitch(op, rewriter, caseValue);
920 return success();
921}
922
923/// switch %c_42 : i32, [
924/// default: ^bb1,
925/// 42: ^bb2,
926/// ]
927/// ^bb2:
928/// br ^bb3
929/// ->
930/// switch %c_42 : i32, [
931/// default: ^bb1,
932/// 42: ^bb3,
933/// ]
934static LogicalResult simplifyPassThroughSwitch(SwitchOp op,
935 PatternRewriter &rewriter) {
936 SmallVector<Block *> newCaseDests;
937 SmallVector<ValueRange> newCaseOperands;
939 auto caseValues = op.getCaseValues();
940 argStorage.reserve(caseValues->size() + 1);
941 auto caseDests = op.getCaseDestinations();
942 bool requiresChange = false;
943 for (int64_t i = 0, size = caseValues->size(); i < size; ++i) {
944 Block *caseDest = caseDests[i];
945 ValueRange caseOperands = op.getCaseOperands(i);
946 argStorage.emplace_back();
947 if (succeeded(collapseBranch(caseDest, caseOperands, argStorage.back())))
948 requiresChange = true;
949
950 newCaseDests.push_back(caseDest);
951 newCaseOperands.push_back(caseOperands);
952 }
953
954 Block *defaultDest = op.getDefaultDestination();
955 ValueRange defaultOperands = op.getDefaultOperands();
956 argStorage.emplace_back();
957
958 if (succeeded(
959 collapseBranch(defaultDest, defaultOperands, argStorage.back())))
960 requiresChange = true;
961
962 if (!requiresChange)
963 return failure();
964
965 rewriter.replaceOpWithNewOp<SwitchOp>(op, op.getFlag(), defaultDest,
966 defaultOperands, *caseValues,
967 newCaseDests, newCaseOperands);
968 return success();
969}
970
971/// switch %flag : i32, [
972/// default: ^bb1,
973/// 42: ^bb2,
974/// ]
975/// ^bb2:
976/// switch %flag : i32, [
977/// default: ^bb3,
978/// 42: ^bb4
979/// ]
980/// ->
981/// switch %flag : i32, [
982/// default: ^bb1,
983/// 42: ^bb2,
984/// ]
985/// ^bb2:
986/// br ^bb4
987///
988/// and
989///
990/// switch %flag : i32, [
991/// default: ^bb1,
992/// 42: ^bb2,
993/// ]
994/// ^bb2:
995/// switch %flag : i32, [
996/// default: ^bb3,
997/// 43: ^bb4
998/// ]
999/// ->
1000/// switch %flag : i32, [
1001/// default: ^bb1,
1002/// 42: ^bb2,
1003/// ]
1004/// ^bb2:
1005/// br ^bb3
1006static LogicalResult
1008 PatternRewriter &rewriter) {
1009 // Check that we have a single distinct predecessor.
1010 Block *currentBlock = op->getBlock();
1011 Block *predecessor = currentBlock->getSinglePredecessor();
1012 if (!predecessor)
1013 return failure();
1014
1015 // Check that the predecessor terminates with a switch branch to this block
1016 // and that it branches on the same condition and that this branch isn't the
1017 // default destination.
1018 auto predSwitch = dyn_cast<SwitchOp>(predecessor->getTerminator());
1019 if (!predSwitch || op.getFlag() != predSwitch.getFlag() ||
1020 predSwitch.getDefaultDestination() == currentBlock)
1021 return failure();
1022
1023 // Fold this switch to an unconditional branch.
1024 SuccessorRange predDests = predSwitch.getCaseDestinations();
1025 auto it = llvm::find(predDests, currentBlock);
1026 if (it != predDests.end()) {
1027 std::optional<DenseIntElementsAttr> predCaseValues =
1028 predSwitch.getCaseValues();
1029 foldSwitch(op, rewriter,
1030 predCaseValues->getValues<APInt>()[it - predDests.begin()]);
1031 } else {
1032 rewriter.replaceOpWithNewOp<BranchOp>(op, op.getDefaultDestination(),
1033 op.getDefaultOperands());
1034 }
1035 return success();
1036}
1037
1038/// switch %flag : i32, [
1039/// default: ^bb1,
1040/// 42: ^bb2
1041/// ]
1042/// ^bb1:
1043/// switch %flag : i32, [
1044/// default: ^bb3,
1045/// 42: ^bb4,
1046/// 43: ^bb5
1047/// ]
1048/// ->
1049/// switch %flag : i32, [
1050/// default: ^bb1,
1051/// 42: ^bb2,
1052/// ]
1053/// ^bb1:
1054/// switch %flag : i32, [
1055/// default: ^bb3,
1056/// 43: ^bb5
1057/// ]
1058static LogicalResult
1060 PatternRewriter &rewriter) {
1061 // Check that we have a single distinct predecessor.
1062 Block *currentBlock = op->getBlock();
1063 Block *predecessor = currentBlock->getSinglePredecessor();
1064 if (!predecessor)
1065 return failure();
1066
1067 // Check that the predecessor terminates with a switch branch to this block
1068 // and that it branches on the same condition and that this branch is the
1069 // default destination.
1070 auto predSwitch = dyn_cast<SwitchOp>(predecessor->getTerminator());
1071 if (!predSwitch || op.getFlag() != predSwitch.getFlag() ||
1072 predSwitch.getDefaultDestination() != currentBlock)
1073 return failure();
1074
1075 // Delete case values that are not possible here.
1076 DenseSet<APInt> caseValuesToRemove;
1077 auto predDests = predSwitch.getCaseDestinations();
1078 auto predCaseValues = predSwitch.getCaseValues();
1079 for (int64_t i = 0, size = predCaseValues->size(); i < size; ++i)
1080 if (currentBlock != predDests[i])
1081 caseValuesToRemove.insert(predCaseValues->getValues<APInt>()[i]);
1082
1083 SmallVector<Block *> newCaseDestinations;
1084 SmallVector<ValueRange> newCaseOperands;
1085 SmallVector<APInt> newCaseValues;
1086 bool requiresChange = false;
1087
1088 auto caseValues = op.getCaseValues();
1089 auto caseDests = op.getCaseDestinations();
1090 for (const auto &it : llvm::enumerate(caseValues->getValues<APInt>())) {
1091 if (caseValuesToRemove.contains(it.value())) {
1092 requiresChange = true;
1093 continue;
1094 }
1095 newCaseDestinations.push_back(caseDests[it.index()]);
1096 newCaseOperands.push_back(op.getCaseOperands(it.index()));
1097 newCaseValues.push_back(it.value());
1098 }
1099
1100 if (!requiresChange)
1101 return failure();
1102
1103 rewriter.replaceOpWithNewOp<SwitchOp>(
1104 op, op.getFlag(), op.getDefaultDestination(), op.getDefaultOperands(),
1105 newCaseValues, newCaseDestinations, newCaseOperands);
1106 return success();
1107}
1108
1109void SwitchOp::getCanonicalizationPatterns(RewritePatternSet &results,
1110 MLIRContext *context) {
1118 .add<SimplifyUniformBlockArguments>(context);
1119}
1120
1121//===----------------------------------------------------------------------===//
1122// TableGen'd op method definitions
1123//===----------------------------------------------------------------------===//
1124
1125#define GET_OP_CLASSES
1126#include "mlir/Dialect/ControlFlow/IR/ControlFlowOps.cpp.inc"
return success()
static LogicalResult simplifyUniformBlockArgs(Block *dest, PatternRewriter &rewriter)
If all incoming values for a block argument from all predecessors are the same SSA value,...
static LogicalResult simplifySwitchFromSwitchOnSameCondition(SwitchOp op, PatternRewriter &rewriter)
switch flag : i32, [ default: ^bb1, 42: ^bb2, ] ^bb2: switch flag : i32, [ default: ^bb3,...
static LogicalResult simplifyConstSwitchValue(SwitchOp op, PatternRewriter &rewriter)
switch c_42 : i32, [ default: ^bb1, 42: ^bb2, 43: ^bb3 ] -> br ^bb2
static LogicalResult simplifySwitchWithOnlyDefault(SwitchOp op, PatternRewriter &rewriter)
switch flag : i32, [ default: ^bb1 ] -> br ^bb1
static void foldSwitch(SwitchOp op, PatternRewriter &rewriter, const APInt &caseValue)
Helper for folding a switch with a constant value.
static void printSwitchOpCases(OpAsmPrinter &p, SwitchOp op, Type flagType, Block *defaultDestination, OperandRange defaultOperands, TypeRange defaultOperandTypes, DenseIntElementsAttr caseValues, SuccessorRange caseDestinations, OperandRangeRange caseOperands, const TypeRangeRange &caseOperandTypes)
static LogicalResult simplifyPassThroughBr(BranchOp op, PatternRewriter &rewriter)
br ^bb1 ^bb1 br ^bbN(...)
static LogicalResult simplifyBrToBlockWithSinglePred(BranchOp op, PatternRewriter &rewriter)
Simplify a branch to a block that has a single predecessor.
static LogicalResult collapseBranch(Block *&successor, ValueRange &successorOperands, SmallVectorImpl< Value > &argStorage)
Given a successor, try to collapse it to a new destination if it only contains a passthrough uncondit...
static LogicalResult dropSwitchCasesThatMatchDefault(SwitchOp op, PatternRewriter &rewriter)
switch flag : i32, [ default: ^bb1, 42: ^bb1, 43: ^bb2 ] -> switch flag : i32, [ default: ^bb1,...
static LogicalResult dropUnreachableSwitchCases(SwitchOp op, PatternRewriter &rewriter)
Drop cases whose destination block contains only ub.unreachable.
static LogicalResult simplifyPassThroughSwitch(SwitchOp op, PatternRewriter &rewriter)
switch c_42 : i32, [ default: ^bb1, 42: ^bb2, ] ^bb2: br ^bb3 -> switch c_42 : i32,...
static LogicalResult simplifySwitchFromDefaultSwitchOnSameCondition(SwitchOp op, PatternRewriter &rewriter)
switch flag : i32, [ default: ^bb1, 42: ^bb2 ] ^bb1: switch flag : i32, [ default: ^bb3,...
static ParseResult parseSwitchOpCases(OpAsmParser &parser, Type &flagType, Block *&defaultDestination, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &defaultOperands, SmallVectorImpl< Type > &defaultOperandTypes, DenseIntElementsAttr &caseValues, SmallVectorImpl< Block * > &caseDestinations, SmallVectorImpl< SmallVector< OpAsmParser::UnresolvedOperand > > &caseOperands, SmallVectorImpl< SmallVector< Type > > &caseOperandTypes)
<cases> ::= default : bb-id (( ssa-use-and-type-list ))?
static bool isLegalToInline(InlinerInterface &interface, Region *src, Region *insertRegion, bool shouldCloneInlinedRegion, IRMapping &valueMapping)
Utility to check that all of the operations within 'src' can be inlined.
*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
@ None
Zero or more operands with no delimiters.
virtual ParseResult parseColonTypeList(SmallVectorImpl< Type > &result)=0
Parse a colon followed by a type list, which must have at least one type.
virtual ParseResult parseRParen()=0
Parse a ) token.
virtual InFlightDiagnostic emitError(SMLoc loc, const Twine &message={})=0
Emit a diagnostic at the specified location and return failure.
ParseResult parseInteger(IntT &result)
Parse an integer value from the stream.
virtual SMLoc getCurrentLocation()=0
Get the location of the next token and store it into the argument.
virtual ParseResult parseOptionalComma()=0
Parse a , token if present.
virtual ParseResult parseColon()=0
Parse a : token.
virtual ParseResult parseOptionalLParen()=0
Parse a ( token if present.
ParseResult parseKeyword(StringRef keyword)
Parse a given keyword.
virtual void printNewline()
Print a newline and indent the printer to the start of the current operation/attribute/type.
This class represents an argument of a Block.
Definition Value.h:308
unsigned getArgNumber() const
Returns the number of this argument.
Definition Value.h:320
Block * getOwner() const
Returns the block that owns this argument.
Definition Value.h:317
This class provides an abstraction over the different types of ranges over Blocks.
Block represents an ordered list of Operations.
Definition Block.h:34
iterator_range< pred_iterator > getPredecessors()
Definition Block.h:250
Block * getSinglePredecessor()
If this block has exactly one predecessor, return it.
Definition Block.cpp:285
Operation * getTerminator()
Get the terminator operation of this block.
Definition Block.cpp:249
bool args_empty()
Definition Block.h:124
BlockArgListType getArguments()
Definition Block.h:112
iterator end()
Definition Block.h:169
iterator begin()
Definition Block.h:168
Block * getUniquePredecessor()
If this block has a unique predecessor, i.e., all incoming edges originate from one block,...
Definition Block.cpp:296
bool hasNoPredecessors()
Return true if this block has no predecessors.
Definition Block.h:255
BoolAttr getBoolAttr(bool value)
Definition Builders.cpp:108
IntegerType getI1Type()
Definition Builders.cpp:61
An attribute that represents a reference to a dense integer vector or tensor object.
static DenseIntElementsAttr get(const ShapedType &type, Arg &&arg)
Get an instance of a DenseIntElementsAttr with the given arguments.
This class represents a diagnostic that is inflight and set to be reported.
MLIRContext is the top-level object for a collection of MLIR operations.
Definition MLIRContext.h:71
The OpAsmParser has methods for interacting with the asm parser: parsing things from it,...
virtual ParseResult parseSuccessor(Block *&dest)=0
Parse a single operation successor.
virtual ParseResult parseOperandList(SmallVectorImpl< UnresolvedOperand > &result, Delimiter delimiter=Delimiter::None, bool allowResultNumber=true, int requiredOperandCount=-1)=0
Parse zero or more SSA comma-separated operand references with a specified surrounding delimiter,...
This is a pure-virtual base class that exposes the asmprinter hooks necessary to implement a custom p...
virtual void printSuccessorAndUseList(Block *successor, ValueRange succOperands)=0
Print the successor and its operands.
This class helps build Operations.
Definition Builders.h:210
This class represents a contiguous range of operand ranges, e.g.
Definition ValueRange.h:85
This class implements the operand iterators for the Operation class.
Definition ValueRange.h:44
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
user_range getUsers()
Returns a range of all users.
Definition Operation.h:927
A special type of RewriterBase that coordinates the application of a rewrite pattern on the current I...
RewritePatternSet & add(ConstructorArg &&arg, ConstructorArgs &&...args)
Add an instance of each of the pattern types 'Ts' to the pattern list with the given arguments.
virtual void eraseOp(Operation *op)
This method erases an operation that is known to have no uses.
void mergeBlocks(Block *source, Block *dest, ValueRange argValues={})
Inline the operations of block 'source' into the end of block 'dest'.
void modifyOpInPlace(Operation *root, CallableT &&callable)
This method is a utility wrapper around an in-place modification of an operation.
virtual void replaceAllUsesWith(Value from, Value to)
Find uses of from and replace them with to.
OpTy replaceOpWithNewOp(Operation *op, Args &&...args)
Replace the results of the given (original) op with a new op that is created without verification (re...
This class represents a specific instance of an effect.
This class models how operands are forwarded to block arguments in control flow.
This class implements the successor iterators for Block.
This class provides an abstraction for a range of TypeRange.
Definition TypeRange.h:107
This class provides an abstraction over the various different ranges of value types.
Definition TypeRange.h:40
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
unsigned getIntOrFloatBitWidth() const
Return the bit width of an integer or a float type, assert failure on other types.
Definition Types.cpp:124
This class provides an abstraction over the different types of ranges over Values.
Definition ValueRange.h:392
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
Type getType() const
Return the type of this value.
Definition Value.h:105
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
detail::constant_int_value_binder m_ConstantInt(IntegerAttr::ValueType *bind_value)
Matches a constant holding a scalar/vector/tensor integer (splat) and writes the integer value to bin...
Definition Matchers.h:527
llvm::DenseSet< ValueT, ValueInfoT > DenseSet
Definition LLVM.h:125
detail::constant_int_predicate_matcher m_Zero()
Matches a constant scalar / vector splat / tensor splat integer zero.
Definition Matchers.h:442
detail::constant_int_predicate_matcher m_One()
Matches a constant scalar / vector splat / tensor splat integer one.
Definition Matchers.h:478
detail::constant_int_predicate_matcher m_NonZero()
Matches a constant scalar / vector splat / tensor splat integer that is any non-zero value.
Definition Matchers.h:448
OpInterfaceRewritePattern is a wrapper around RewritePattern that allows for matching and rewriting a...
OpRewritePattern is a wrapper around RewritePattern that allows for matching and rewriting against an...
This represents an operation in an abstracted form, suitable for use with the builder APIs.