MLIR 24.0.0git
IntRangeOptimizations.cpp
Go to the documentation of this file.
1//===- IntRangeOptimizations.cpp - Optimizations based on integer ranges --===//
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#include <utility>
10
11#include "llvm/ADT/TypeSwitch.h"
12
17
21#include "mlir/IR/IRMapping.h"
22#include "mlir/IR/Matchers.h"
29
30namespace mlir::arith {
31#define GEN_PASS_DEF_ARITHINTRANGEOPTS
32#include "mlir/Dialect/Arith/Transforms/Passes.h.inc"
33
34#define GEN_PASS_DEF_ARITHINTRANGENARROWING
35#include "mlir/Dialect/Arith/Transforms/Passes.h.inc"
36} // namespace mlir::arith
37
38using namespace mlir;
39using namespace mlir::arith;
40using namespace mlir::dataflow;
41
42static std::optional<APInt> getMaybeConstantValue(DataFlowSolver &solver,
43 Value value) {
44 auto *maybeInferredRange =
46 if (!maybeInferredRange || maybeInferredRange->getValue().isUninitialized())
47 return std::nullopt;
48 const ConstantIntRanges &inferredRange =
49 maybeInferredRange->getValue().getValue();
50 return inferredRange.getConstantValue();
51}
52
53/// Return the inferred constant value for `value` if it can be represented as
54/// an `IntegerAttr` or `DenseIntElementsAttr` of `value`'s type.
55static std::optional<APInt>
57 Type type = value.getType();
58 // IntegerAttr and DenseIntElementsAttr require integer or index types, and
59 // shaped types must have a static shape.
60 if (!getElementTypeOrSelf(type).isIntOrIndex())
61 return std::nullopt;
62 if (auto shaped = dyn_cast<ShapedType>(type);
63 shaped && !shaped.hasStaticShape())
64 return std::nullopt;
65 std::optional<APInt> maybeConstValue = getMaybeConstantValue(solver, value);
66 if (!maybeConstValue)
67 return std::nullopt;
68 // The inferred APInt bitwidth must match the storage width of the IR type.
69 unsigned storageWidth = ConstantIntRanges::getStorageBitwidth(type);
70 if (storageWidth != 0 && maybeConstValue->getBitWidth() != storageWidth)
71 return std::nullopt;
72 return maybeConstValue;
73}
74
75static void copyIntegerRange(DataFlowSolver &solver, Value oldVal,
76 Value newVal) {
77 auto *oldState = solver.lookupState<IntegerValueRangeLattice>(oldVal);
78 if (!oldState)
79 return;
81 *oldState);
82}
83
84namespace mlir::dataflow {
85/// Patterned after SCCP
87 RewriterBase &rewriter, Value value) {
88 if (value.use_empty())
89 return failure();
90 std::optional<APInt> maybeConstValue =
91 getMaterializableConstantValue(solver, value);
92 if (!maybeConstValue)
93 return failure();
94
95 Type type = value.getType();
96
97 Location loc = value.getLoc();
98 Operation *maybeDefiningOp = value.getDefiningOp();
99 Dialect *valueDialect =
100 maybeDefiningOp ? maybeDefiningOp->getDialect()
101 : value.getParentRegion()->getParentOp()->getDialect();
102
103 Attribute constAttr;
104 if (auto shaped = dyn_cast<ShapedType>(type)) {
105 constAttr = mlir::DenseIntElementsAttr::get(shaped, *maybeConstValue);
106 } else {
107 constAttr = rewriter.getIntegerAttr(type, *maybeConstValue);
108 }
109 Operation *constOp =
110 valueDialect->materializeConstant(rewriter, constAttr, type, loc);
111 // Fall back to arith.constant if the dialect materializer doesn't know what
112 // to do with an integer constant.
113 if (!constOp)
114 constOp = rewriter.getContext()
115 ->getLoadedDialect<ArithDialect>()
116 ->materializeConstant(rewriter, constAttr, type, loc);
117 if (!constOp)
118 return failure();
119
120 OpResult res = constOp->getResult(0);
122 solver.eraseState(res);
123 copyIntegerRange(solver, value, res);
124 rewriter.replaceAllUsesWith(value, res);
125 return success();
126}
127} // namespace mlir::dataflow
128
129namespace {
130class DataFlowListener : public RewriterBase::Listener {
131public:
132 DataFlowListener(DataFlowSolver &s) : s(s) {}
133
134protected:
135 void notifyOperationErased(Operation *op) override {
136 s.eraseState(s.getProgramPointAfter(op));
137 for (Value res : op->getResults())
138 s.eraseState(res);
139 }
140
141 DataFlowSolver &s;
142};
143
144/// Replace uses of `op`'s results and region block arguments inferred to be
145/// constant with materialized constants. Erase `op` if replacing its results
146/// leaves it trivially dead, and return success if any value was replaced.
147struct MaterializeKnownConstantValues : public RewritePattern {
148 MaterializeKnownConstantValues(MLIRContext *context, DataFlowSolver &s)
149 : RewritePattern::RewritePattern(Pattern::MatchAnyOpTypeTag(),
150 /*benefit=*/1, context),
151 solver(s) {}
152
153 LogicalResult matchAndRewrite(Operation *op,
154 PatternRewriter &rewriter) const override {
155 if (matchPattern(op, m_Constant()))
156 return failure();
157
158 bool replacedAny = false;
159 bool replacedAll = (op->getNumResults() != 0);
160 for (Value v : op->getResults()) {
161 bool replaced = succeeded(maybeReplaceWithConstant(solver, rewriter, v));
162 replacedAny |= replaced;
163 replacedAll &= (replaced || v.use_empty());
164 }
165 if (replacedAny && replacedAll && isOpTriviallyDead(op)) {
166 rewriter.eraseOp(op);
167 return success();
168 }
169
170 PatternRewriter::InsertionGuard guard(rewriter);
171 for (Region &region : op->getRegions()) {
172 for (Block &block : region.getBlocks()) {
173 rewriter.setInsertionPointToStart(&block);
174 for (BlockArgument &arg : block.getArguments()) {
175 replacedAny |=
176 succeeded(maybeReplaceWithConstant(solver, rewriter, arg));
177 }
178 }
179 }
180
181 return success(replacedAny);
182 }
183
184private:
185 DataFlowSolver &solver;
186};
187
188template <typename RemOp>
189struct DeleteTrivialRem : public OpRewritePattern<RemOp> {
190 DeleteTrivialRem(MLIRContext *context, DataFlowSolver &s)
191 : OpRewritePattern<RemOp>(context), solver(s) {}
192
193 LogicalResult matchAndRewrite(RemOp op,
194 PatternRewriter &rewriter) const override {
195 Value lhs = op.getOperand(0);
196 Value rhs = op.getOperand(1);
197 // TODO: Support index types once integer range inference can use the target
198 // index bitwidth, e.g. from DLTI.
199 if (isa<IndexType>(getElementTypeOrSelf(lhs.getType())))
200 return failure();
201 APInt modulus;
202 bool isUnsigned = isa<RemUIOp>(op);
203 // Any nonzero bit pattern is a valid unsigned modulus. Keep the existing
204 // positive-modulus restriction for signed remainder.
205 if (!matchPattern(rhs, m_ConstantInt(&modulus)) || modulus.isZero() ||
206 (!isUnsigned && modulus.isNegative()))
207 return failure();
208 auto *maybeLhsRange = solver.lookupState<IntegerValueRangeLattice>(lhs);
209 if (!maybeLhsRange || maybeLhsRange->getValue().isUninitialized())
210 return failure();
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())
216 return failure();
217 // The minima and maxima here are given as closed ranges, we must be
218 // non-negative for signed remainder and strictly less than the modulus.
219 if ((!isUnsigned && min.isNegative()) || min.uge(modulus))
220 return failure();
221 if ((!isUnsigned && max.isNegative()) || max.uge(modulus))
222 return failure();
223 if (!min.ule(max))
224 return failure();
225
226 // With all those conditions out of the way, we know thas this invocation of
227 // a remainder is a noop because the input is strictly within the range
228 // [0, modulus), so get rid of it.
229 rewriter.replaceOp(op, ValueRange{lhs});
230 return success();
231 }
232
233private:
234 DataFlowSolver &solver;
235};
236
237/// Gather ranges for all the values in `values`. Appends to the existing
238/// vector.
239static LogicalResult collectRanges(DataFlowSolver &solver, ValueRange values,
241 for (Value val : values) {
242 auto *maybeInferredRange =
244 if (!maybeInferredRange || maybeInferredRange->getValue().isUninitialized())
245 return failure();
246
247 const ConstantIntRanges &inferredRange =
248 maybeInferredRange->getValue().getValue();
249 ranges.push_back(inferredRange);
250 }
251 return success();
252}
253
254/// Return int type truncated to `targetBitwidth`. If `srcType` is shaped,
255/// return shaped type as well.
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);
260
261 assert(srcType.isIntOrIndex() && "Invalid src type");
262 return dstType;
263}
264
265namespace {
266// Enum for tracking which type of truncation should be performed
267// to narrow an operation, if any.
268enum class CastKind : uint8_t { None, Signed, Unsigned, Both };
269} // namespace
270
271/// If the values within `range` can be represented using only `width` bits,
272/// return the kind of truncation needed to preserve that property.
273///
274/// This check relies on the fact that the signed and unsigned ranges are both
275/// always correct, but that one might be an approximation of the other,
276/// so we want to use the correct truncation operation.
277static CastKind checkTruncatability(const ConstantIntRanges &range,
278 unsigned targetWidth) {
279 unsigned srcWidth = range.smin().getBitWidth();
280 if (srcWidth <= targetWidth)
281 return CastKind::None;
282 unsigned removedWidth = srcWidth - targetWidth;
283 // The sign bits need to extend into the sign bit of the target width. For
284 // example, if we're truncating 64 bits to 32, we need 64 - 32 + 1 = 33 sign
285 // bits.
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;
298}
299
300static CastKind mergeCastKinds(CastKind lhs, CastKind rhs) {
301 if (lhs == CastKind::None || rhs == CastKind::None)
302 return CastKind::None;
303 if (lhs == CastKind::Both)
304 return rhs;
305 if (rhs == CastKind::Both)
306 return lhs;
307 if (lhs == rhs)
308 return lhs;
309 return CastKind::None;
310}
311
312static Value doCast(OpBuilder &builder, Location loc, Value src, Type dstType,
313 CastKind castKind) {
314 Type srcType = src.getType();
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");
318 Type srcElemType = getElementTypeOrSelf(srcType);
319 Type dstElemType = getElementTypeOrSelf(dstType);
320 assert(srcElemType.isIntOrIndex() && "Invalid src type");
321 assert(dstElemType.isIntOrIndex() && "Invalid dst type");
322 if (srcType == dstType)
323 return src;
324
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);
329 }
330
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);
335
336 if (castKind == CastKind::Signed)
337 return arith::ExtSIOp::create(builder, loc, dstType, src);
338 return arith::ExtUIOp::create(builder, loc, dstType, src);
339}
340
341struct NarrowElementwise final : OpTraitRewritePattern<OpTrait::Elementwise> {
342 NarrowElementwise(MLIRContext *context, DataFlowSolver &s,
343 ArrayRef<unsigned> target)
344 : OpTraitRewritePattern(context), solver(s), targetBitwidths(target) {}
345
346 using Base::Base;
347 LogicalResult matchAndRewrite(Operation *op,
348 PatternRewriter &rewriter) const override {
349 if (op->getNumResults() == 0)
350 return rewriter.notifyMatchFailure(op, "can't narrow resultless op");
351
352 // Inline size chosen empirically based on compilation profiling.
353 // Profiled: 2.6M calls, avg=1.7+-1.3. N=4 covers >95% of cases inline.
354 SmallVector<ConstantIntRanges, 4> ranges;
355 if (failed(collectRanges(solver, op->getOperands(), ranges)))
356 return rewriter.notifyMatchFailure(op, "input without specified range");
357 if (failed(collectRanges(solver, op->getResults(), ranges)))
358 return rewriter.notifyMatchFailure(op, "output without specified range");
359
360 Type srcType = op->getResult(0).getType();
361 if (!llvm::all_equal(op->getResultTypes()))
362 return rewriter.notifyMatchFailure(op, "mismatched result types");
363 if (op->getNumOperands() == 0 ||
364 !llvm::all_of(op->getOperandTypes(),
365 [=](Type t) { return t == srcType; }))
366 return rewriter.notifyMatchFailure(
367 op, "no operands or operand types don't match result type");
368
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)
375 break;
376 }
377 // Constrain the cast kind to preserve the interpretation required by the
378 // operation.
379 auto castKindForOp =
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)
389 continue;
390 // A shift by an amount >= the bitwidth is poison, so only narrow shifts
391 // when the shift amount (second operand) stays below the target width.
392 if (isa<arith::ShLIOp, arith::ShRSIOp, arith::ShRUIOp>(op) &&
393 !ranges[1].umax().ult(targetBitwidth))
394 continue;
395 Type targetType = getTargetType(srcType, targetBitwidth);
396 if (targetType == srcType)
397 continue;
398
399 Location loc = op->getLoc();
400 IRMapping mapping;
401 for (auto [arg, argRange] : llvm::zip_first(op->getOperands(), ranges)) {
402 CastKind argCastKind = castKind;
403 // When dealing with `index` values, preserve non-negativity in the
404 // index_casts since we can't recover this in unsigned when equivalent.
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);
409 }
410
411 Operation *newOp = rewriter.clone(*op, mapping);
412 rewriter.modifyOpInPlace(newOp, [&]() {
413 for (OpResult res : newOp->getResults()) {
414 res.setType(targetType);
415 }
416 // Retain an overflow flag only when the casts preserve operand and
417 // result values in the flag's signed or unsigned interpretation.
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);
425 newOp->setAttr(
426 overflowOp.getIntegerOverflowAttrName(),
427 IntegerOverflowFlagsAttr::get(rewriter.getContext(), flags));
428 }
429 });
430 SmallVector<Value> newResults;
431 for (auto [newRes, oldRes] :
432 llvm::zip_equal(newOp->getResults(), op->getResults())) {
433 Value castBack = doCast(rewriter, loc, newRes, srcType, castKind);
434 copyIntegerRange(solver, oldRes, castBack);
435 newResults.push_back(castBack);
436 }
437
438 rewriter.replaceOp(op, newResults);
439 return success();
440 }
441 return failure();
442 }
443
444private:
445 DataFlowSolver &solver;
446 SmallVector<unsigned, 4> targetBitwidths;
447};
448
449struct NarrowCmpI final : OpRewritePattern<arith::CmpIOp> {
450 NarrowCmpI(MLIRContext *context, DataFlowSolver &s, ArrayRef<unsigned> target)
451 : OpRewritePattern(context), solver(s), targetBitwidths(target) {}
452
453 LogicalResult matchAndRewrite(arith::CmpIOp op,
454 PatternRewriter &rewriter) const override {
455 Value lhs = op.getLhs();
456 Value rhs = op.getRhs();
457
458 SmallVector<ConstantIntRanges> ranges;
459 if (failed(collectRanges(solver, op.getOperands(), ranges)))
460 return failure();
461 const ConstantIntRanges &lhsRange = ranges[0];
462 const ConstantIntRanges &rhsRange = ranges[1];
463
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;
469 };
470 // If we're to narrow the input values via a cast, we should preserve the
471 // sign.
472 CastKind predicateBasedCastRestriction =
473 isSignedCmpPredicate(op.getPredicate()) ? CastKind::Signed
474 : CastKind::Both;
475
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);
482 // Note: this includes target width > src width, as well as the unsigned
483 // truncatability & signed predicate scenario.
484 if (castKind == CastKind::None)
485 continue;
486
487 Type targetType = getTargetType(srcType, targetBitwidth);
488 if (targetType == srcType)
489 continue;
490
491 Location loc = op->getLoc();
492 IRMapping mapping;
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);
497
498 Operation *newOp = rewriter.clone(*op, mapping);
499 copyIntegerRange(solver, op.getResult(), newOp->getResult(0));
500 rewriter.replaceOp(op, newOp->getResults());
501 return success();
502 }
503 return failure();
504 }
505
506private:
507 DataFlowSolver &solver;
508 SmallVector<unsigned, 4> targetBitwidths;
509};
510
511/// Fold index_cast(index_cast(%arg: i8, index), i8) -> %arg
512/// This pattern assumes all passed `targetBitwidths` are not wider than index
513/// type.
514template <typename CastOp>
515struct FoldIndexCastChain final : OpRewritePattern<CastOp> {
516 FoldIndexCastChain(MLIRContext *context, ArrayRef<unsigned> target)
517 : OpRewritePattern<CastOp>(context), targetBitwidths(target) {}
518
519 LogicalResult matchAndRewrite(CastOp op,
520 PatternRewriter &rewriter) const override {
521 auto srcOp = op.getIn().template getDefiningOp<CastOp>();
522 if (!srcOp)
523 return rewriter.notifyMatchFailure(op, "doesn't come from an index cast");
524
525 Value src = srcOp.getIn();
526 if (src.getType() != op.getType())
527 return rewriter.notifyMatchFailure(op, "outer types don't match");
528
529 if (!srcOp.getType().isIndex())
530 return rewriter.notifyMatchFailure(op, "intermediate type isn't index");
531
532 auto intType = dyn_cast<IntegerType>(op.getType());
533 if (!intType || !llvm::is_contained(targetBitwidths, intType.getWidth()))
534 return failure();
535
536 rewriter.replaceOp(op, src);
537 return success();
538 }
539
540private:
541 SmallVector<unsigned, 4> targetBitwidths;
542};
543
544struct NarrowLoopBounds final : OpInterfaceRewritePattern<LoopLikeOpInterface> {
545 NarrowLoopBounds(MLIRContext *context, DataFlowSolver &s,
546 ArrayRef<unsigned> target)
547 : OpInterfaceRewritePattern<LoopLikeOpInterface>(context), solver(s),
548 targetBitwidths(target),
549 boundsNarrowingFailedAttr(
550 StringAttr::get(context, "arith.bounds_narrowing_failed")) {}
551
552 LogicalResult matchAndRewrite(LoopLikeOpInterface loopLike,
553 PatternRewriter &rewriter) const override {
554 // Skip ops where bounds narrowing previously failed.
555 if (loopLike->hasDiscardableAttr(boundsNarrowingFailedAttr))
556 return rewriter.notifyMatchFailure(loopLike,
557 "bounds narrowing previously failed");
558
559 std::optional<SmallVector<Value>> inductionVars =
560 loopLike.getLoopInductionVars();
561 if (!inductionVars.has_value() || inductionVars->empty())
562 return rewriter.notifyMatchFailure(loopLike, "no induction variables");
563
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();
569
570 if (!lowerBounds.has_value() || !upperBounds.has_value() ||
571 !steps.has_value())
572 return rewriter.notifyMatchFailure(loopLike, "no loop bounds or steps");
573
574 if (lowerBounds->size() != inductionVars->size() ||
575 upperBounds->size() != inductionVars->size() ||
576 steps->size() != inductionVars->size())
577 return rewriter.notifyMatchFailure(loopLike,
578 "mismatched bounds/steps count");
579
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;
585
586 // Check each (indVar, lb, ub, step) tuple.
587 for (auto [idx, indVar, lbOFR, ubOFR, stepOFR] :
588 llvm::enumerate(*inductionVars, *lowerBounds, *upperBounds, *steps)) {
589
590 // Only process value operands, skip attributes.
591 auto maybeLb = dyn_cast<Value>(lbOFR);
592 auto maybeUb = dyn_cast<Value>(ubOFR);
593 auto maybeStep = dyn_cast<Value>(stepOFR);
594
595 if (!maybeLb || !maybeUb || !maybeStep)
596 continue;
597
598 // Collect ranges for (lb, ub, step, indVar).
599 SmallVector<ConstantIntRanges> ranges;
600 if (failed(collectRanges(
601 solver, ValueRange{maybeLb, maybeUb, maybeStep, indVar}, ranges)))
602 continue;
603
604 const ConstantIntRanges &stepRange = ranges[2];
605 const ConstantIntRanges &indVarRange = ranges[3];
606
607 Type srcType = maybeLb.getType();
608
609 // Try each target bitwidth.
610 for (unsigned targetBitwidth : targetBitwidths) {
611 Type targetType = getTargetType(srcType, targetBitwidth);
612 if (targetType == srcType)
613 continue;
614
615 // Check if the target type is valid for this loop's induction
616 // variables.
617 if (!loopLike.isValidInductionVarType(targetType))
618 continue;
619
620 // Check if all values in this tuple can be truncated.
621 CastKind castKind = CastKind::Both;
622 for (const ConstantIntRanges &range : ranges) {
623 castKind = mergeCastKinds(castKind,
624 checkTruncatability(range, targetBitwidth));
625 if (castKind == CastKind::None)
626 break;
627 }
628
629 if (castKind == CastKind::None)
630 continue;
631
632 // Check if indVar + step fits in the narrowed type.
633 // This is critical for loop correctness: the loop computes
634 // iv_next = iv_current + step in the narrowed type, then compares
635 // iv_next < ub. If iv_current + step overflows, the comparison may
636 // produce incorrect results and break loop termination.
637 // Both signed and unsigned interpretations must fit because loop
638 // semantics are unknown (integer types are signless).
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()));
644
645 if (checkTruncatability(indVarPlusStepRange, targetBitwidth) !=
646 CastKind::Both)
647 continue;
648
649 // Narrow the bounds and step values.
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);
653
654 newLowerBounds[idx] = newLb;
655 newUpperBounds[idx] = newUb;
656 newSteps[idx] = newStep;
657 narrowings.push_back({idx, targetType, castKind});
658 break;
659 }
660 }
661
662 if (narrowings.empty())
663 return rewriter.notifyMatchFailure(loopLike, "no narrowings found");
664
665 // Save original types before modifying.
666 SmallVector<Type> origTypes;
667 for (auto [idx, targetType, castKind] : narrowings) {
668 Value indVar = (*inductionVars)[idx];
669 origTypes.push_back(indVar.getType());
670 }
671
672 // Attempt to update bounds and induction variable types.
673 // If this fails, mark the op so we don't try again.
674 bool updateFailed = false;
675 rewriter.modifyOpInPlace(loopLike, [&]() {
676 // Update the loop bounds and steps.
677 if (failed(loopLike.setLoopLowerBounds(newLowerBounds)) ||
678 failed(loopLike.setLoopUpperBounds(newUpperBounds)) ||
679 failed(loopLike.setLoopSteps(newSteps))) {
680 // Mark op to prevent future attempts. IR was modified (attribute
681 // added), so we must return success() from the pattern.
682 loopLike->setDiscardableAttr(boundsNarrowingFailedAttr,
683 rewriter.getUnitAttr());
684 updateFailed = true;
685 return;
686 }
687
688 // Update induction variable types.
689 for (auto [idx, targetType, castKind] : narrowings) {
690 Value indVar = (*inductionVars)[idx];
691 auto blockArg = cast<BlockArgument>(indVar);
692
693 // Change the block argument type.
694 blockArg.setType(targetType);
695 }
696 });
697
698 if (updateFailed)
699 return success();
700
701 // Insert casts back to original type for uses.
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];
707
708 OpBuilder::InsertionGuard guard(rewriter);
709 rewriter.setInsertionPointToStart(blockArg.getOwner());
710 Value casted = doCast(rewriter, loc, blockArg, origType, castKind);
711 copyIntegerRange(solver, blockArg, casted);
712
713 // Replace all uses of the narrowed indVar with the casted value.
714 rewriter.replaceAllUsesExcept(blockArg, casted, casted.getDefiningOp());
715 }
716
717 return success();
718 }
719
720private:
721 DataFlowSolver &solver;
722 SmallVector<unsigned, 4> targetBitwidths;
723 StringAttr boundsNarrowingFailedAttr;
724};
725
726struct IntRangeOptimizationsPass final
727 : arith::impl::ArithIntRangeOptsBase<IntRangeOptimizationsPass> {
728
729 void runOnOperation() override {
730 Operation *op = getOperation();
731 MLIRContext *ctx = op->getContext();
732 DataFlowSolver solver;
733 loadBaselineAnalyses(solver);
734 solver.load<IntegerRangeAnalysis>();
735 if (failed(solver.initializeAndRun(op)))
736 return signalPassFailure();
737
738 DataFlowListener listener(solver);
739
740 RewritePatternSet patterns(ctx);
742
743 // Disable folding and region simplification to avoid breaking the solver
744 // state. Both can remove block arguments (folding via control-flow
745 // simplification, region simplification via dead-arg elimination), which
746 // frees their underlying storage. A subsequent allocation may reuse the
747 // same address for a different block argument, causing stale solver state
748 // to be associated with the new argument and producing incorrect constants.
749 if (failed(
750 applyPatternsGreedily(op, std::move(patterns),
751 GreedyRewriteConfig()
752 .enableFolding(false)
753 .setRegionSimplificationLevel(
754 GreedySimplifyRegionLevel::Disabled)
755 .setListener(&listener))))
756 signalPassFailure();
757 }
758};
759
760struct IntRangeNarrowingPass final
761 : arith::impl::ArithIntRangeNarrowingBase<IntRangeNarrowingPass> {
762 using ArithIntRangeNarrowingBase::ArithIntRangeNarrowingBase;
763
764 void runOnOperation() override {
765 Operation *op = getOperation();
766 MLIRContext *ctx = op->getContext();
767 DataFlowSolver solver;
768 loadBaselineAnalyses(solver);
769 solver.load<IntegerRangeAnalysis>();
770 if (failed(solver.initializeAndRun(op)))
771 return signalPassFailure();
772
773 DataFlowListener listener(solver);
774
775 RewritePatternSet patterns(ctx);
776 populateIntRangeNarrowingPatterns(patterns, solver, bitwidthsSupported);
778 bitwidthsSupported);
779
780 // We specifically need bottom-up traversal as cmpi pattern needs range
781 // data, attached to its original argument values.
783 op, std::move(patterns),
784 GreedyRewriteConfig().setUseTopDownTraversal(false).setListener(
785 &listener))))
786 signalPassFailure();
787 }
788};
789} // namespace
790
792 RewritePatternSet &patterns, DataFlowSolver &solver) {
793 patterns.add<MaterializeKnownConstantValues, DeleteTrivialRem<RemSIOp>,
794 DeleteTrivialRem<RemUIOp>>(patterns.getContext(), solver);
795}
796
798 RewritePatternSet &patterns, DataFlowSolver &solver,
799 ArrayRef<unsigned> bitwidthsSupported) {
800 patterns.add<NarrowElementwise, NarrowCmpI>(patterns.getContext(), solver,
801 bitwidthsSupported);
802 patterns.add<FoldIndexCastChain<arith::IndexCastUIOp>,
803 FoldIndexCastChain<arith::IndexCastOp>>(patterns.getContext(),
804 bitwidthsSupported);
805}
806
808 RewritePatternSet &patterns, DataFlowSolver &solver,
809 ArrayRef<unsigned> bitwidthsSupported) {
810 patterns.add<NarrowLoopBounds>(patterns.getContext(), solver,
811 bitwidthsSupported);
812}
813
815 return std::make_unique<IntRangeOptimizationsPass>();
816}
return success()
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.
Definition FoldUtils.cpp:51
lhs
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)
@ None
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.
Definition Attributes.h:25
UnitAttr getUnitAttr()
Definition Builders.cpp:106
IntegerAttr getIntegerAttr(Type type, int64_t value)
Definition Builders.cpp:237
MLIRContext * getContext() const
Definition Builders.h:56
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...
Definition Dialect.h:38
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
void map(Value from, Value to)
Inserts a new mapping for 'from' to 'to'.
Definition IRMapping.h:30
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition Location.h:76
Dialect * getLoadedDialect(StringRef name)
Get a registered IR dialect with the given namespace.
This class helps build Operations.
Definition Builders.h:210
Operation * clone(Operation &op, IRMapping &mapper)
Creates a deep copy of the specified operation, remapping any operands that use values outside of the...
Definition Builders.cpp:581
void setInsertionPointToStart(Block *block)
Sets the insertion point to the start of the specified block.
Definition Builders.h:434
This is a value defined by a result of an operation.
Definition Value.h:456
OpTraitRewritePattern is a wrapper around RewritePattern that allows for matching and rewriting again...
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
OpResult getResult(unsigned idx)
Get the 'idx'th result of this operation.
Definition Operation.h:434
Location getLoc()
The source location the operation was defined or derived from.
Definition Operation.h:240
unsigned getNumOperands()
Definition Operation.h:373
void setAttr(StringAttr name, Attribute value)
If the an attribute exists with the specified name, change it to the new value.
Definition Operation.h:636
operand_type_range getOperandTypes()
Definition Operation.h:424
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
result_range getResults()
Definition Operation.h:442
MLIRContext * getContext()
Return the context this operation is associated with.
Definition Operation.h:233
unsigned getNumResults()
Return the number of results held by this operation.
Definition Operation.h:431
Operation * getParentOp()
Return the parent operation this region is attached to.
Definition Region.h:198
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...
Definition Types.h:74
MLIRContext * getContext() const
Return the MLIRContext in which this type was uniqued.
Definition Types.cpp:35
bool isIntOrIndex() const
Return true if this is an integer (of any signedness) or an index type.
Definition Types.cpp:114
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
bool use_empty() const
Returns true if this value has no uses.
Definition Value.h:208
void setType(Type newType)
Mutate the type of this Value to be of the specified type.
Definition Value.h:116
Type getType() const
Return the type of this value.
Definition Value.h:105
Location getLoc() const
Return the location of this value.
Definition Value.cpp:24
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
Definition Value.cpp:18
Region * getParentRegion()
Return the Region in which this Value is defined.
Definition Value.cpp:39
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...
Definition Utils.h:29
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
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...
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.
Definition Matchers.h:369
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...