11#include "llvm/ADT/TypeSwitch.h"
31#define GEN_PASS_DEF_ARITHINTRANGEOPTS
32#include "mlir/Dialect/Arith/Transforms/Passes.h.inc"
34#define GEN_PASS_DEF_ARITHINTRANGENARROWING
35#include "mlir/Dialect/Arith/Transforms/Passes.h.inc"
44 auto *maybeInferredRange =
46 if (!maybeInferredRange || maybeInferredRange->getValue().isUninitialized())
49 maybeInferredRange->getValue().getValue();
55static std::optional<APInt>
62 if (
auto shaped = dyn_cast<ShapedType>(type);
63 shaped && !shaped.hasStaticShape())
70 if (storageWidth != 0 && maybeConstValue->getBitWidth() != storageWidth)
72 return maybeConstValue;
90 std::optional<APInt> maybeConstValue =
100 maybeDefiningOp ? maybeDefiningOp->
getDialect()
104 if (
auto shaped = dyn_cast<ShapedType>(type)) {
135 void notifyOperationErased(Operation *op)
override {
148 MaterializeKnownConstantValues(MLIRContext *context, DataFlowSolver &s)
149 : RewritePattern::RewritePattern(Pattern::MatchAnyOpTypeTag(),
153 LogicalResult matchAndRewrite(Operation *op,
154 PatternRewriter &rewriter)
const override {
158 bool replacedAny =
false;
162 replacedAny |= replaced;
163 replacedAll &= (replaced || v.use_empty());
170 PatternRewriter::InsertionGuard guard(rewriter);
172 for (
Block &block : region.getBlocks()) {
174 for (BlockArgument &arg : block.getArguments()) {
185 DataFlowSolver &solver;
188template <
typename RemOp>
190 DeleteTrivialRem(MLIRContext *context, DataFlowSolver &s)
191 : OpRewritePattern<RemOp>(context), solver(s) {}
193 LogicalResult matchAndRewrite(RemOp op,
194 PatternRewriter &rewriter)
const override {
195 Value
lhs = op.getOperand(0);
196 Value
rhs = op.getOperand(1);
202 bool isUnsigned = isa<RemUIOp>(op);
206 (!isUnsigned && modulus.isNegative()))
208 auto *maybeLhsRange = solver.lookupState<IntegerValueRangeLattice>(
lhs);
209 if (!maybeLhsRange || maybeLhsRange->getValue().isUninitialized())
211 const ConstantIntRanges &lhsRange = maybeLhsRange->getValue().getValue();
212 const APInt &
min = isUnsigned ? lhsRange.
umin() : lhsRange.
smin();
213 const APInt &
max = isUnsigned ? lhsRange.
umax() : lhsRange.
smax();
214 if (
min.getBitWidth() != modulus.getBitWidth() ||
215 max.getBitWidth() != modulus.getBitWidth())
219 if ((!isUnsigned &&
min.isNegative()) ||
min.uge(modulus))
221 if ((!isUnsigned &&
max.isNegative()) ||
max.uge(modulus))
234 DataFlowSolver &solver;
241 for (
Value val : values) {
242 auto *maybeInferredRange =
244 if (!maybeInferredRange || maybeInferredRange->getValue().isUninitialized())
248 maybeInferredRange->getValue().getValue();
249 ranges.push_back(inferredRange);
256static Type getTargetType(
Type srcType,
unsigned targetBitwidth) {
257 auto dstType = IntegerType::get(srcType.
getContext(), targetBitwidth);
258 if (
auto shaped = dyn_cast<ShapedType>(srcType))
259 return shaped.clone(dstType);
278 unsigned targetWidth) {
279 unsigned srcWidth = range.
smin().getBitWidth();
280 if (srcWidth <= targetWidth)
281 return CastKind::None;
282 unsigned removedWidth = srcWidth - targetWidth;
286 bool canTruncateSigned =
287 range.
smin().getNumSignBits() >= (removedWidth + 1) &&
288 range.
smax().getNumSignBits() >= (removedWidth + 1);
289 bool canTruncateUnsigned = range.
umin().countLeadingZeros() >= removedWidth &&
290 range.
umax().countLeadingZeros() >= removedWidth;
291 if (canTruncateSigned && canTruncateUnsigned)
292 return CastKind::Both;
293 if (canTruncateSigned)
294 return CastKind::Signed;
295 if (canTruncateUnsigned)
296 return CastKind::Unsigned;
297 return CastKind::None;
300static CastKind mergeCastKinds(CastKind lhs, CastKind rhs) {
301 if (lhs == CastKind::None || rhs == CastKind::None)
302 return CastKind::None;
303 if (lhs == CastKind::Both)
305 if (rhs == CastKind::Both)
309 return CastKind::None;
315 assert(isa<VectorType>(srcType) == isa<VectorType>(dstType) &&
316 "Mixing vector and non-vector types");
317 assert(castKind != CastKind::None &&
"Can't cast when casting isn't allowed");
320 assert(srcElemType.
isIntOrIndex() &&
"Invalid src type");
321 assert(dstElemType.
isIntOrIndex() &&
"Invalid dst type");
322 if (srcType == dstType)
325 if (isa<IndexType>(srcElemType) || isa<IndexType>(dstElemType)) {
326 if (castKind == CastKind::Signed)
327 return arith::IndexCastOp::create(builder, loc, dstType, src);
328 return arith::IndexCastUIOp::create(builder, loc, dstType, src);
331 auto srcInt = cast<IntegerType>(srcElemType);
332 auto dstInt = cast<IntegerType>(dstElemType);
333 if (dstInt.getWidth() < srcInt.getWidth())
334 return arith::TruncIOp::create(builder, loc, dstType, src);
336 if (castKind == CastKind::Signed)
337 return arith::ExtSIOp::create(builder, loc, dstType, src);
338 return arith::ExtUIOp::create(builder, loc, dstType, src);
342 NarrowElementwise(MLIRContext *context, DataFlowSolver &s,
343 ArrayRef<unsigned>
target)
344 : OpTraitRewritePattern(context), solver(s), targetBitwidths(
target) {}
347 LogicalResult matchAndRewrite(Operation *op,
348 PatternRewriter &rewriter)
const override {
354 SmallVector<ConstantIntRanges, 4> ranges;
365 [=](Type t) { return t == srcType; }))
367 op,
"no operands or operand types don't match result type");
369 for (
unsigned targetBitwidth : targetBitwidths) {
370 CastKind castKind = CastKind::Both;
371 for (
const ConstantIntRanges &range : ranges) {
372 castKind = mergeCastKinds(castKind,
373 checkTruncatability(range, targetBitwidth));
374 if (castKind == CastKind::None)
380 llvm::TypeSwitch<Operation *, CastKind>(op)
381 .Case<arith::DivSIOp, arith::CeilDivSIOp, arith::FloorDivSIOp,
382 arith::RemSIOp, arith::MaxSIOp, arith::MinSIOp,
383 arith::ShRSIOp>([](
auto) {
return CastKind::Signed; })
384 .Case<arith::DivUIOp, arith::CeilDivUIOp, arith::RemUIOp,
385 arith::ShRUIOp>([](
auto) {
return CastKind::Unsigned; })
386 .Default(CastKind::Both);
387 castKind = mergeCastKinds(castKind, castKindForOp);
388 if (castKind == CastKind::None)
392 if (isa<arith::ShLIOp, arith::ShRSIOp, arith::ShRUIOp>(op) &&
393 !ranges[1].umax().
ult(targetBitwidth))
395 Type targetType = getTargetType(srcType, targetBitwidth);
396 if (targetType == srcType)
399 Location loc = op->
getLoc();
401 for (
auto [arg, argRange] : llvm::zip_first(op->
getOperands(), ranges)) {
402 CastKind argCastKind = castKind;
405 if (argCastKind == CastKind::Signed && argRange.smin().isNonNegative())
406 argCastKind = CastKind::Both;
407 Value newArg = doCast(rewriter, loc, arg, targetType, argCastKind);
408 mapping.
map(arg, newArg);
411 Operation *newOp = rewriter.
clone(*op, mapping);
418 if (
auto overflowOp =
419 dyn_cast<arith::ArithIntegerOverflowFlagsInterface>(newOp)) {
420 auto flags = overflowOp.getOverflowAttr().getValue();
421 if (castKind == CastKind::Unsigned)
422 flags = bitEnumClear(flags, IntegerOverflowFlags::nsw);
423 else if (castKind == CastKind::Signed)
424 flags = bitEnumClear(flags, IntegerOverflowFlags::nuw);
426 overflowOp.getIntegerOverflowAttrName(),
427 IntegerOverflowFlagsAttr::get(rewriter.
getContext(), flags));
430 SmallVector<Value> newResults;
431 for (
auto [newRes, oldRes] :
433 Value castBack = doCast(rewriter, loc, newRes, srcType, castKind);
435 newResults.push_back(castBack);
445 DataFlowSolver &solver;
446 SmallVector<unsigned, 4> targetBitwidths;
450 NarrowCmpI(MLIRContext *context, DataFlowSolver &s, ArrayRef<unsigned>
target)
451 : OpRewritePattern(context), solver(s), targetBitwidths(
target) {}
453 LogicalResult matchAndRewrite(arith::CmpIOp op,
454 PatternRewriter &rewriter)
const override {
455 Value
lhs = op.getLhs();
456 Value
rhs = op.getRhs();
458 SmallVector<ConstantIntRanges> ranges;
459 if (
failed(collectRanges(solver, op.getOperands(), ranges)))
461 const ConstantIntRanges &lhsRange = ranges[0];
462 const ConstantIntRanges &rhsRange = ranges[1];
464 auto isSignedCmpPredicate = [](arith::CmpIPredicate pred) ->
bool {
465 return pred == arith::CmpIPredicate::sge ||
466 pred == arith::CmpIPredicate::sgt ||
467 pred == arith::CmpIPredicate::sle ||
468 pred == arith::CmpIPredicate::slt;
472 CastKind predicateBasedCastRestriction =
473 isSignedCmpPredicate(op.getPredicate()) ? CastKind::Signed
476 Type srcType =
lhs.getType();
477 for (
unsigned targetBitwidth : targetBitwidths) {
478 CastKind lhsCastKind = checkTruncatability(lhsRange, targetBitwidth);
479 CastKind rhsCastKind = checkTruncatability(rhsRange, targetBitwidth);
480 CastKind castKind = mergeCastKinds(lhsCastKind, rhsCastKind);
481 castKind = mergeCastKinds(castKind, predicateBasedCastRestriction);
484 if (castKind == CastKind::None)
487 Type targetType = getTargetType(srcType, targetBitwidth);
488 if (targetType == srcType)
491 Location loc = op->getLoc();
493 Value lhsCast = doCast(rewriter, loc,
lhs, targetType, lhsCastKind);
494 Value rhsCast = doCast(rewriter, loc,
rhs, targetType, rhsCastKind);
495 mapping.
map(
lhs, lhsCast);
496 mapping.
map(
rhs, rhsCast);
498 Operation *newOp = rewriter.
clone(*op, mapping);
507 DataFlowSolver &solver;
508 SmallVector<unsigned, 4> targetBitwidths;
514template <
typename CastOp>
516 FoldIndexCastChain(MLIRContext *context, ArrayRef<unsigned>
target)
517 : OpRewritePattern<CastOp>(context), targetBitwidths(
target) {}
519 LogicalResult matchAndRewrite(CastOp op,
520 PatternRewriter &rewriter)
const override {
521 auto srcOp = op.getIn().template getDefiningOp<CastOp>();
525 Value src = srcOp.getIn();
526 if (src.
getType() != op.getType())
529 if (!srcOp.getType().isIndex())
532 auto intType = dyn_cast<IntegerType>(op.getType());
533 if (!intType || !llvm::is_contained(targetBitwidths, intType.getWidth()))
541 SmallVector<unsigned, 4> targetBitwidths;
545 NarrowLoopBounds(MLIRContext *context, DataFlowSolver &s,
546 ArrayRef<unsigned>
target)
547 : OpInterfaceRewritePattern<LoopLikeOpInterface>(context), solver(s),
549 boundsNarrowingFailedAttr(
550 StringAttr::
get(context,
"arith.bounds_narrowing_failed")) {}
552 LogicalResult matchAndRewrite(LoopLikeOpInterface loopLike,
553 PatternRewriter &rewriter)
const override {
555 if (loopLike->hasDiscardableAttr(boundsNarrowingFailedAttr))
557 "bounds narrowing previously failed");
559 std::optional<SmallVector<Value>> inductionVars =
560 loopLike.getLoopInductionVars();
561 if (!inductionVars.has_value() || inductionVars->empty())
564 std::optional<SmallVector<OpFoldResult>> lowerBounds =
565 loopLike.getLoopLowerBounds();
566 std::optional<SmallVector<OpFoldResult>> upperBounds =
567 loopLike.getLoopUpperBounds();
568 std::optional<SmallVector<OpFoldResult>> steps = loopLike.getLoopSteps();
570 if (!lowerBounds.has_value() || !upperBounds.has_value() ||
574 if (lowerBounds->size() != inductionVars->size() ||
575 upperBounds->size() != inductionVars->size() ||
576 steps->size() != inductionVars->size())
578 "mismatched bounds/steps count");
580 Location loc = loopLike->getLoc();
581 SmallVector<OpFoldResult> newLowerBounds(*lowerBounds);
582 SmallVector<OpFoldResult> newUpperBounds(*upperBounds);
583 SmallVector<OpFoldResult> newSteps(*steps);
584 SmallVector<std::tuple<size_t, Type, CastKind>> narrowings;
587 for (
auto [idx, indVar, lbOFR, ubOFR, stepOFR] :
588 llvm::enumerate(*inductionVars, *lowerBounds, *upperBounds, *steps)) {
591 auto maybeLb = dyn_cast<Value>(lbOFR);
592 auto maybeUb = dyn_cast<Value>(ubOFR);
593 auto maybeStep = dyn_cast<Value>(stepOFR);
595 if (!maybeLb || !maybeUb || !maybeStep)
599 SmallVector<ConstantIntRanges> ranges;
601 solver,
ValueRange{maybeLb, maybeUb, maybeStep, indVar}, ranges)))
604 const ConstantIntRanges &stepRange = ranges[2];
605 const ConstantIntRanges &indVarRange = ranges[3];
607 Type srcType = maybeLb.getType();
610 for (
unsigned targetBitwidth : targetBitwidths) {
611 Type targetType = getTargetType(srcType, targetBitwidth);
612 if (targetType == srcType)
617 if (!loopLike.isValidInductionVarType(targetType))
621 CastKind castKind = CastKind::Both;
622 for (
const ConstantIntRanges &range : ranges) {
623 castKind = mergeCastKinds(castKind,
624 checkTruncatability(range, targetBitwidth));
625 if (castKind == CastKind::None)
629 if (castKind == CastKind::None)
639 ConstantIntRanges indVarPlusStepRange(
640 indVarRange.
smin().sadd_sat(stepRange.
smin()),
641 indVarRange.
smax().sadd_sat(stepRange.
smax()),
642 indVarRange.
umin().uadd_sat(stepRange.
umin()),
643 indVarRange.
umax().uadd_sat(stepRange.
umax()));
645 if (checkTruncatability(indVarPlusStepRange, targetBitwidth) !=
650 Value newLb = doCast(rewriter, loc, maybeLb, targetType, castKind);
651 Value newUb = doCast(rewriter, loc, maybeUb, targetType, castKind);
652 Value newStep = doCast(rewriter, loc, maybeStep, targetType, castKind);
654 newLowerBounds[idx] = newLb;
655 newUpperBounds[idx] = newUb;
656 newSteps[idx] = newStep;
657 narrowings.push_back({idx, targetType, castKind});
662 if (narrowings.empty())
666 SmallVector<Type> origTypes;
667 for (
auto [idx, targetType, castKind] : narrowings) {
668 Value indVar = (*inductionVars)[idx];
669 origTypes.push_back(indVar.
getType());
674 bool updateFailed =
false;
677 if (
failed(loopLike.setLoopLowerBounds(newLowerBounds)) ||
678 failed(loopLike.setLoopUpperBounds(newUpperBounds)) ||
679 failed(loopLike.setLoopSteps(newSteps))) {
682 loopLike->setDiscardableAttr(boundsNarrowingFailedAttr,
689 for (
auto [idx, targetType, castKind] : narrowings) {
690 Value indVar = (*inductionVars)[idx];
691 auto blockArg = cast<BlockArgument>(indVar);
694 blockArg.setType(targetType);
702 for (
auto [narrowingIdx, narrowingInfo] : llvm::enumerate(narrowings)) {
703 auto [idx, targetType, castKind] = narrowingInfo;
704 Value indVar = (*inductionVars)[idx];
705 auto blockArg = cast<BlockArgument>(indVar);
706 Type origType = origTypes[narrowingIdx];
708 OpBuilder::InsertionGuard guard(rewriter);
710 Value casted = doCast(rewriter, loc, blockArg, origType, castKind);
721 DataFlowSolver &solver;
722 SmallVector<unsigned, 4> targetBitwidths;
723 StringAttr boundsNarrowingFailedAttr;
726struct IntRangeOptimizationsPass final
727 : arith::impl::ArithIntRangeOptsBase<IntRangeOptimizationsPass> {
729 void runOnOperation()
override {
730 Operation *op = getOperation();
732 DataFlowSolver solver;
734 solver.
load<IntegerRangeAnalysis>();
736 return signalPassFailure();
738 DataFlowListener listener(solver);
740 RewritePatternSet patterns(ctx);
751 GreedyRewriteConfig()
752 .enableFolding(
false)
753 .setRegionSimplificationLevel(
754 GreedySimplifyRegionLevel::Disabled)
755 .setListener(&listener))))
760struct IntRangeNarrowingPass final
761 : arith::impl::ArithIntRangeNarrowingBase<IntRangeNarrowingPass> {
762 using ArithIntRangeNarrowingBase::ArithIntRangeNarrowingBase;
764 void runOnOperation()
override {
765 Operation *op = getOperation();
767 DataFlowSolver solver;
769 solver.
load<IntegerRangeAnalysis>();
771 return signalPassFailure();
773 DataFlowListener listener(solver);
775 RewritePatternSet patterns(ctx);
783 op, std::move(patterns),
784 GreedyRewriteConfig().setUseTopDownTraversal(
false).setListener(
793 patterns.
add<MaterializeKnownConstantValues, DeleteTrivialRem<RemSIOp>,
794 DeleteTrivialRem<RemUIOp>>(patterns.
getContext(), solver);
800 patterns.
add<NarrowElementwise, NarrowCmpI>(patterns.
getContext(), solver,
802 patterns.
add<FoldIndexCastChain<arith::IndexCastUIOp>,
803 FoldIndexCastChain<arith::IndexCastOp>>(patterns.
getContext(),
810 patterns.
add<NarrowLoopBounds>(patterns.
getContext(), solver,
815 return std::make_unique<IntRangeOptimizationsPass>();
static Operation * materializeConstant(Dialect *dialect, OpBuilder &builder, Attribute value, Type type, Location loc)
A utility function used to materialize a constant for a given attribute and type.
static std::optional< APInt > getMaterializableConstantValue(DataFlowSolver &solver, Value value)
Return the inferred constant value for value if it can be represented as an IntegerAttr or DenseIntEl...
static void copyIntegerRange(DataFlowSolver &solver, Value oldVal, Value newVal)
static std::optional< APInt > getMaybeConstantValue(DataFlowSolver &solver, Value value)
static Value max(ImplicitLocOpBuilder &builder, Value value, Value bound)
static Value min(ImplicitLocOpBuilder &builder, Value value, Value bound)
Attributes are known-constant values of operations.
IntegerAttr getIntegerAttr(Type type, int64_t value)
MLIRContext * getContext() const
A set of arbitrary-precision integers representing bounds on a given integer value.
const APInt & smax() const
The maximum value of an integer when it is interpreted as signed.
const APInt & smin() const
The minimum value of an integer when it is interpreted as signed.
static unsigned getStorageBitwidth(Type type)
Return the bitwidth that should be used for integer ranges describing type.
std::optional< APInt > getConstantValue() const
If either the signed or unsigned interpretations of the range indicate that the value it bounds is a ...
const APInt & umax() const
The maximum value of an integer when it is interpreted as unsigned.
const APInt & umin() const
The minimum value of an integer when it is interpreted as unsigned.
The general data-flow analysis solver.
LogicalResult initializeAndRun(Operation *top, llvm::function_ref< bool(DataFlowAnalysis &)> analysisFilter=nullptr)
Initialize analyses starting from the provided top-level operation and run the analysis until fixpoin...
void eraseState(AnchorT anchor)
Erase any analysis state associated with the given lattice anchor.
const StateT * lookupState(AnchorT anchor) const
Lookup an analysis state for the given lattice anchor.
StateT * getOrCreateState(AnchorT anchor)
Get the state associated with the given lattice anchor.
AnalysisT * load(Args &&...args)
Load an analysis into the solver. Return the analysis instance.
static DenseIntElementsAttr get(const ShapedType &type, Arg &&arg)
Get an instance of a DenseIntElementsAttr with the given arguments.
Dialects are groups of MLIR operations, types and attributes, as well as behavior associated with the...
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...
void map(Value from, Value to)
Inserts a new mapping for 'from' to 'to'.
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Dialect * getLoadedDialect(StringRef name)
Get a registered IR dialect with the given namespace.
This class helps build Operations.
Operation * clone(Operation &op, IRMapping &mapper)
Creates a deep copy of the specified operation, remapping any operands that use values outside of the...
void setInsertionPointToStart(Block *block)
Sets the insertion point to the start of the specified block.
This is a value defined by a result of an operation.
OpTraitRewritePattern is a wrapper around RewritePattern that allows for matching and rewriting again...
Operation is the basic unit of execution within MLIR.
Dialect * getDialect()
Return the dialect this operation is associated with, or nullptr if the associated dialect is not loa...
OpResult getResult(unsigned idx)
Get the 'idx'th result of this operation.
Location getLoc()
The source location the operation was defined or derived from.
unsigned getNumOperands()
void setAttr(StringAttr name, Attribute value)
If the an attribute exists with the specified name, change it to the new value.
operand_type_range getOperandTypes()
MutableArrayRef< Region > getRegions()
Returns the regions held by this operation.
result_type_range getResultTypes()
operand_range getOperands()
Returns an iterator on the underlying Value's.
result_range getResults()
MLIRContext * getContext()
Return the context this operation is associated with.
unsigned getNumResults()
Return the number of results held by this operation.
Operation * getParentOp()
Return the parent operation this region is attached to.
MLIRContext * getContext() const
RewritePatternSet & add(ConstructorArg &&arg, ConstructorArgs &&...args)
Add an instance of each of the pattern types 'Ts' to the pattern list with the given arguments.
RewritePattern is the common base class for all DAG to DAG replacements.
This class coordinates the application of a rewrite on a set of IR, providing a way for clients to tr...
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.
void replaceAllUsesExcept(Value from, Value to, Operation *exceptedUser)
Find uses of from and replace them with to except if the user is exceptedUser.
std::enable_if_t<!std::is_convertible< CallbackT, Twine >::value, LogicalResult > notifyMatchFailure(Location loc, CallbackT &&reasonCallback)
Used to notify the listener that the IR failed to be rewritten because of a match failure,...
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.
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
MLIRContext * getContext() const
Return the MLIRContext in which this type was uniqued.
bool isIntOrIndex() const
Return true if this is an integer (of any signedness) or an index type.
This class provides an abstraction over the different types of ranges over Values.
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
bool use_empty() const
Returns true if this value has no uses.
void setType(Type newType)
Mutate the type of this Value to be of the specified type.
Type getType() const
Return the type of this value.
Location getLoc() const
Return the location of this value.
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
Region * getParentRegion()
Return the Region in which this Value is defined.
This lattice element represents the integer value range of an SSA value.
ChangeResult join(const AbstractSparseLattice &rhs) override
Join the information contained in 'rhs' into this lattice.
std::unique_ptr< Pass > createIntRangeOptimizationsPass()
Create a pass which do optimizations based on integer range analysis.
void populateControlFlowValuesNarrowingPatterns(RewritePatternSet &patterns, DataFlowSolver &solver, ArrayRef< unsigned > bitwidthsSupported)
Add patterns for narrowing control flow values (loop bounds, steps, etc.) based on int range analysis...
void populateIntRangeOptimizationsPatterns(RewritePatternSet &patterns, DataFlowSolver &solver)
Add patterns for int range based optimizations.
void populateIntRangeNarrowingPatterns(RewritePatternSet &patterns, DataFlowSolver &solver, ArrayRef< unsigned > bitwidthsSupported)
Add patterns for int range based narrowing.
LogicalResult maybeReplaceWithConstant(DataFlowSolver &solver, RewriterBase &rewriter, Value value)
Patterned after SCCP.
void loadBaselineAnalyses(DataFlowSolver &solver)
Populates a DataFlowSolver with analyses that are required to ensure user-defined analyses are run pr...
Include the generated interface declarations.
bool matchPattern(Value value, const Pattern &pattern)
Entry point for matching a pattern over a Value.
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...
LogicalResult applyPatternsGreedily(Region ®ion, 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...
Type getElementTypeOrSelf(Type type)
Return the element type or return the type itself.
bool isOpTriviallyDead(Operation *op)
Return true if the given operation is unused, and has no side effects on memory that prevent erasing.
auto get(MLIRContext *context, Ts &&...params)
Helper method that injects context only if needed, this helps unify some of the attribute constructio...
detail::constant_op_matcher m_Constant()
Matches a constant foldable operation.
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...