MLIR 24.0.0git
IndexOps.cpp
Go to the documentation of this file.
1//===- IndexOps.cpp - Index operation definitions --------------------------==//
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
12#include "mlir/IR/Builders.h"
13#include "mlir/IR/Matchers.h"
16#include "llvm/ADT/SmallString.h"
17#include "llvm/ADT/TypeSwitch.h"
18
19using namespace mlir;
20using namespace mlir::index;
21
22//===----------------------------------------------------------------------===//
23// IndexDialect
24//===----------------------------------------------------------------------===//
25
26Operation *IndexDialect::materializeConstant(OpBuilder &b, Attribute value,
27 Type type, Location loc) {
28 // Materialize bool constants as `i1`.
29 if (auto boolValue = dyn_cast<BoolAttr>(value)) {
30 if (!type.isSignlessInteger(1))
31 return nullptr;
32 return BoolConstantOp::create(b, loc, type, boolValue);
33 }
34
35 // Materialize integer attributes as `index`.
36 if (auto indexValue = dyn_cast<IntegerAttr>(value)) {
37 if (!llvm::isa<IndexType>(indexValue.getType()) ||
38 !llvm::isa<IndexType>(type))
39 return nullptr;
40 assert(indexValue.getValue().getBitWidth() ==
41 IndexType::kInternalStorageBitWidth);
42 return ConstantOp::create(b, loc, indexValue);
43 }
44
45 return nullptr;
46}
47
48//===----------------------------------------------------------------------===//
49// Fold Utilities
50//===----------------------------------------------------------------------===//
51
52/// Fold an index operation irrespective of the target bitwidth. The
53/// operation must satisfy the property:
54///
55/// ```
56/// trunc(f(a, b)) = f(trunc(a), trunc(b))
57/// ```
58///
59/// For all values of `a` and `b`. The function accepts a lambda that computes
60/// the integer result, which in turn must satisfy the above property.
62 ArrayRef<Attribute> operands,
63 function_ref<std::optional<APInt>(const APInt &, const APInt &)>
64 calculate) {
65 assert(operands.size() == 2 && "binary operation expected 2 operands");
66 auto lhs = dyn_cast_if_present<IntegerAttr>(operands[0]);
67 auto rhs = dyn_cast_if_present<IntegerAttr>(operands[1]);
68 if (!lhs || !rhs)
69 return {};
70
71 std::optional<APInt> result = calculate(lhs.getValue(), rhs.getValue());
72 if (!result)
73 return {};
74 assert(result->trunc(32) ==
75 calculate(lhs.getValue().trunc(32), rhs.getValue().trunc(32)));
76 return IntegerAttr::get(IndexType::get(lhs.getContext()), *result);
77}
78
79/// Fold an index operation only if the truncated 64-bit result matches the
80/// 32-bit result for operations that don't satisfy the above property. These
81/// are operations where the upper bits of the operands can affect the lower
82/// bits of the results.
83///
84/// The function accepts a lambda that computes the integer result in both
85/// 64-bit and 32-bit. If either call returns `std::nullopt`, the operation is
86/// not folded.
88 ArrayRef<Attribute> operands,
89 function_ref<std::optional<APInt>(const APInt &, const APInt &lhs)>
90 calculate) {
91 assert(operands.size() == 2 && "binary operation expected 2 operands");
92 auto lhs = dyn_cast_if_present<IntegerAttr>(operands[0]);
93 auto rhs = dyn_cast_if_present<IntegerAttr>(operands[1]);
94 // Only fold index operands.
95 if (!lhs || !rhs)
96 return {};
97
98 // Compute the 64-bit result and the 32-bit result.
99 std::optional<APInt> result64 = calculate(lhs.getValue(), rhs.getValue());
100 if (!result64)
101 return {};
102 std::optional<APInt> result32 =
103 calculate(lhs.getValue().trunc(32), rhs.getValue().trunc(32));
104 if (!result32)
105 return {};
106 // Compare the truncated 64-bit result to the 32-bit result.
107 if (result64->trunc(32) != *result32)
108 return {};
109 // The operation can be folded for these particular operands.
110 return IntegerAttr::get(IndexType::get(lhs.getContext()), *result64);
111}
112
113/// Helper for associative and commutative binary ops that can be transformed:
114/// `x = op(v, c1); y = op(x, c2)` -> `tmp = op(c1, c2); y = op(v, tmp)`
115/// where c1 and c2 are constants. It is expected that `tmp` will be folded.
116template <typename BinaryOp>
117static LogicalResult
119 PatternRewriter &rewriter) {
120 if (!mlir::matchPattern(op.getRhs(), mlir::m_Constant()))
121 return rewriter.notifyMatchFailure(op.getLoc(), "RHS is not a constant");
122
123 auto lhsOp = op.getLhs().template getDefiningOp<BinaryOp>();
124 if (!lhsOp)
125 return rewriter.notifyMatchFailure(op.getLoc(), "LHS is not the same BinaryOp");
126
127 if (!mlir::matchPattern(lhsOp.getRhs(), mlir::m_Constant()))
128 return rewriter.notifyMatchFailure(op.getLoc(), "RHS of LHS op is not a constant");
129
130 Value c = rewriter.createOrFold<BinaryOp>(op->getLoc(), op.getRhs(),
131 lhsOp.getRhs());
132 if (c.getDefiningOp<BinaryOp>())
133 return rewriter.notifyMatchFailure(op.getLoc(), "new BinaryOp was not folded");
134
135 rewriter.replaceOpWithNewOp<BinaryOp>(op, lhsOp.getLhs(), c);
136 return success();
137}
138
139//===----------------------------------------------------------------------===//
140// AddOp
141//===----------------------------------------------------------------------===//
142
143OpFoldResult AddOp::fold(FoldAdaptor adaptor) {
145 adaptor.getOperands(),
146 [](const APInt &lhs, const APInt &rhs) { return lhs + rhs; }))
147 return result;
148
149 if (auto rhs = dyn_cast_or_null<IntegerAttr>(adaptor.getRhs())) {
150 // Fold `add(x, 0) -> x`.
151 if (rhs.getValue().isZero())
152 return getLhs();
153 }
154
155 return {};
156}
157
158LogicalResult AddOp::canonicalize(AddOp op, PatternRewriter &rewriter) {
160}
161
162//===----------------------------------------------------------------------===//
163// SubOp
164//===----------------------------------------------------------------------===//
165
166OpFoldResult SubOp::fold(FoldAdaptor adaptor) {
168 adaptor.getOperands(),
169 [](const APInt &lhs, const APInt &rhs) { return lhs - rhs; }))
170 return result;
171
172 if (auto rhs = dyn_cast_or_null<IntegerAttr>(adaptor.getRhs())) {
173 // Fold `sub(x, 0) -> x`.
174 if (rhs.getValue().isZero())
175 return getLhs();
176 }
177
178 return {};
179}
180
181//===----------------------------------------------------------------------===//
182// MulOp
183//===----------------------------------------------------------------------===//
184
185OpFoldResult MulOp::fold(FoldAdaptor adaptor) {
187 adaptor.getOperands(),
188 [](const APInt &lhs, const APInt &rhs) { return lhs * rhs; }))
189 return result;
190
191 if (auto rhs = dyn_cast_or_null<IntegerAttr>(adaptor.getRhs())) {
192 // Fold `mul(x, 1) -> x`.
193 if (rhs.getValue().isOne())
194 return getLhs();
195 // Fold `mul(x, 0) -> 0`.
196 if (rhs.getValue().isZero())
197 return rhs;
198 }
199
200 return {};
201}
202
203LogicalResult MulOp::canonicalize(MulOp op, PatternRewriter &rewriter) {
205}
206
207//===----------------------------------------------------------------------===//
208// DivSOp
209//===----------------------------------------------------------------------===//
210
211OpFoldResult DivSOp::fold(FoldAdaptor adaptor) {
212 return foldBinaryOpChecked(
213 adaptor.getOperands(),
214 [](const APInt &lhs, const APInt &rhs) -> std::optional<APInt> {
215 // Don't fold division by zero.
216 if (rhs.isZero())
217 return std::nullopt;
218 return lhs.sdiv(rhs);
219 });
220}
221
222//===----------------------------------------------------------------------===//
223// DivUOp
224//===----------------------------------------------------------------------===//
225
226OpFoldResult DivUOp::fold(FoldAdaptor adaptor) {
227 return foldBinaryOpChecked(
228 adaptor.getOperands(),
229 [](const APInt &lhs, const APInt &rhs) -> std::optional<APInt> {
230 // Don't fold division by zero.
231 if (rhs.isZero())
232 return std::nullopt;
233 return lhs.udiv(rhs);
234 });
235}
236
237//===----------------------------------------------------------------------===//
238// CeilDivSOp
239//===----------------------------------------------------------------------===//
240
241/// Compute `ceildivs(n, m)` as `x = m > 0 ? -1 : 1` and then
242/// `n*m > 0 ? (n+x)/m + 1 : -(-n/m)`.
243static std::optional<APInt> calculateCeilDivS(const APInt &n, const APInt &m) {
244 // Don't fold division by zero.
245 if (m.isZero())
246 return std::nullopt;
247 // Short-circuit the zero case.
248 if (n.isZero())
249 return n;
250
251 bool mGtZ = m.sgt(0);
252 if (n.sgt(0) != mGtZ) {
253 // If the operands have different signs, compute the negative result. Signed
254 // division overflow is not possible, since if `m == -1`, `n` can be at most
255 // `INT_MAX`, and `-INT_MAX != INT_MIN` in two's complement.
256 return -(-n).sdiv(m);
257 }
258 // Otherwise, compute the positive result. Signed division overflow is not
259 // possible since if `m == -1`, `x` will be `1`.
260 int64_t x = mGtZ ? -1 : 1;
261 return (n + x).sdiv(m) + 1;
262}
263
264OpFoldResult CeilDivSOp::fold(FoldAdaptor adaptor) {
265 return foldBinaryOpChecked(adaptor.getOperands(), calculateCeilDivS);
266}
267
268//===----------------------------------------------------------------------===//
269// CeilDivUOp
270//===----------------------------------------------------------------------===//
271
272OpFoldResult CeilDivUOp::fold(FoldAdaptor adaptor) {
273 // Compute `ceildivu(n, m)` as `n == 0 ? 0 : (n-1)/m + 1`.
274 return foldBinaryOpChecked(
275 adaptor.getOperands(),
276 [](const APInt &n, const APInt &m) -> std::optional<APInt> {
277 // Don't fold division by zero.
278 if (m.isZero())
279 return std::nullopt;
280 // Short-circuit the zero case.
281 if (n.isZero())
282 return n;
283
284 return (n - 1).udiv(m) + 1;
285 });
286}
287
288//===----------------------------------------------------------------------===//
289// FloorDivSOp
290//===----------------------------------------------------------------------===//
291
292/// Compute `floordivs(n, m)` as `x = m < 0 ? 1 : -1` and then
293/// `n*m < 0 ? -1 - (x-n)/m : n/m`.
294static std::optional<APInt> calculateFloorDivS(const APInt &n, const APInt &m) {
295 // Don't fold division by zero.
296 if (m.isZero())
297 return std::nullopt;
298 // Short-circuit the zero case.
299 if (n.isZero())
300 return n;
301
302 bool mLtZ = m.slt(0);
303 if (n.slt(0) == mLtZ) {
304 // If the operands have the same sign, compute the positive result.
305 return n.sdiv(m);
306 }
307 // If the operands have different signs, compute the negative result. Signed
308 // division overflow is not possible since if `m == -1`, `x` will be 1 and
309 // `n` can be at most `INT_MAX`.
310 int64_t x = mLtZ ? 1 : -1;
311 return -1 - (x - n).sdiv(m);
312}
313
314OpFoldResult FloorDivSOp::fold(FoldAdaptor adaptor) {
315 return foldBinaryOpChecked(adaptor.getOperands(), calculateFloorDivS);
316}
317
318//===----------------------------------------------------------------------===//
319// RemSOp
320//===----------------------------------------------------------------------===//
321
322OpFoldResult RemSOp::fold(FoldAdaptor adaptor) {
323 return foldBinaryOpChecked(
324 adaptor.getOperands(),
325 [](const APInt &lhs, const APInt &rhs) -> std::optional<APInt> {
326 // Don't fold division by zero.
327 if (rhs.isZero())
328 return std::nullopt;
329 return lhs.srem(rhs);
330 });
331}
332
333//===----------------------------------------------------------------------===//
334// RemUOp
335//===----------------------------------------------------------------------===//
336
337OpFoldResult RemUOp::fold(FoldAdaptor adaptor) {
338 return foldBinaryOpChecked(
339 adaptor.getOperands(),
340 [](const APInt &lhs, const APInt &rhs) -> std::optional<APInt> {
341 // Don't fold division by zero.
342 if (rhs.isZero())
343 return std::nullopt;
344 return lhs.urem(rhs);
345 });
346}
347
348//===----------------------------------------------------------------------===//
349// MaxSOp
350//===----------------------------------------------------------------------===//
351
352OpFoldResult MaxSOp::fold(FoldAdaptor adaptor) {
353 return foldBinaryOpChecked(adaptor.getOperands(),
354 [](const APInt &lhs, const APInt &rhs) {
355 return lhs.sgt(rhs) ? lhs : rhs;
356 });
357}
358
359LogicalResult MaxSOp::canonicalize(MaxSOp op, PatternRewriter &rewriter) {
361}
362
363//===----------------------------------------------------------------------===//
364// MaxUOp
365//===----------------------------------------------------------------------===//
366
367OpFoldResult MaxUOp::fold(FoldAdaptor adaptor) {
368 return foldBinaryOpChecked(adaptor.getOperands(),
369 [](const APInt &lhs, const APInt &rhs) {
370 return lhs.ugt(rhs) ? lhs : rhs;
371 });
372}
373
374LogicalResult MaxUOp::canonicalize(MaxUOp op, PatternRewriter &rewriter) {
376}
377
378//===----------------------------------------------------------------------===//
379// MinSOp
380//===----------------------------------------------------------------------===//
381
382OpFoldResult MinSOp::fold(FoldAdaptor adaptor) {
383 return foldBinaryOpChecked(adaptor.getOperands(),
384 [](const APInt &lhs, const APInt &rhs) {
385 return lhs.slt(rhs) ? lhs : rhs;
386 });
387}
388
389LogicalResult MinSOp::canonicalize(MinSOp op, PatternRewriter &rewriter) {
391}
392
393//===----------------------------------------------------------------------===//
394// MinUOp
395//===----------------------------------------------------------------------===//
396
397OpFoldResult MinUOp::fold(FoldAdaptor adaptor) {
398 return foldBinaryOpChecked(adaptor.getOperands(),
399 [](const APInt &lhs, const APInt &rhs) {
400 return lhs.ult(rhs) ? lhs : rhs;
401 });
402}
403
404LogicalResult MinUOp::canonicalize(MinUOp op, PatternRewriter &rewriter) {
406}
407
408//===----------------------------------------------------------------------===//
409// ShlOp
410//===----------------------------------------------------------------------===//
411
412OpFoldResult ShlOp::fold(FoldAdaptor adaptor) {
414 adaptor.getOperands(),
415 [](const APInt &lhs, const APInt &rhs) -> std::optional<APInt> {
416 // We cannot fold if the RHS is greater than or equal to 32 because
417 // this would be UB in 32-bit systems but not on 64-bit systems. RHS is
418 // already treated as unsigned.
419 if (rhs.uge(32))
420 return {};
421 return lhs << rhs;
422 });
423}
424
425//===----------------------------------------------------------------------===//
426// ShrSOp
427//===----------------------------------------------------------------------===//
428
429OpFoldResult ShrSOp::fold(FoldAdaptor adaptor) {
430 return foldBinaryOpChecked(
431 adaptor.getOperands(),
432 [](const APInt &lhs, const APInt &rhs) -> std::optional<APInt> {
433 // Don't fold if RHS is greater than or equal to 32.
434 if (rhs.uge(32))
435 return {};
436 return lhs.ashr(rhs);
437 });
438}
439
440//===----------------------------------------------------------------------===//
441// ShrUOp
442//===----------------------------------------------------------------------===//
443
444OpFoldResult ShrUOp::fold(FoldAdaptor adaptor) {
445 return foldBinaryOpChecked(
446 adaptor.getOperands(),
447 [](const APInt &lhs, const APInt &rhs) -> std::optional<APInt> {
448 // Don't fold if RHS is greater than or equal to 32.
449 if (rhs.uge(32))
450 return {};
451 return lhs.lshr(rhs);
452 });
453}
454
455//===----------------------------------------------------------------------===//
456// AndOp
457//===----------------------------------------------------------------------===//
458
459OpFoldResult AndOp::fold(FoldAdaptor adaptor) {
461 adaptor.getOperands(),
462 [](const APInt &lhs, const APInt &rhs) { return lhs & rhs; });
463}
464
465LogicalResult AndOp::canonicalize(AndOp op, PatternRewriter &rewriter) {
467}
468
469//===----------------------------------------------------------------------===//
470// OrOp
471//===----------------------------------------------------------------------===//
472
473OpFoldResult OrOp::fold(FoldAdaptor adaptor) {
475 adaptor.getOperands(),
476 [](const APInt &lhs, const APInt &rhs) { return lhs | rhs; });
477}
478
479LogicalResult OrOp::canonicalize(OrOp op, PatternRewriter &rewriter) {
481}
482
483//===----------------------------------------------------------------------===//
484// XOrOp
485//===----------------------------------------------------------------------===//
486
487OpFoldResult XOrOp::fold(FoldAdaptor adaptor) {
489 adaptor.getOperands(),
490 [](const APInt &lhs, const APInt &rhs) { return lhs ^ rhs; });
491}
492
493LogicalResult XOrOp::canonicalize(XOrOp op, PatternRewriter &rewriter) {
495}
496
497//===----------------------------------------------------------------------===//
498// CastSOp
499//===----------------------------------------------------------------------===//
500
501static OpFoldResult
503 function_ref<APInt(const APInt &, unsigned)> extFn,
504 function_ref<APInt(const APInt &, unsigned)> extOrTruncFn) {
505 auto attr = dyn_cast_if_present<IntegerAttr>(input);
506 if (!attr)
507 return {};
508 const APInt &value = attr.getValue();
509
510 if (isa<IndexType>(type)) {
511 // When casting to an index type, perform the cast assuming a 64-bit target.
512 // The result can be truncated to 32 bits as needed and always be correct.
513 // This is because `cast32(cast64(value)) == cast32(value)`.
514 APInt result = extOrTruncFn(value, 64);
515 return IntegerAttr::get(type, result);
516 }
517
518 // When casting from an index type, we must ensure the results respect
519 // `cast_t(value) == cast_t(trunc32(value))`.
520 auto intType = cast<IntegerType>(type);
521 unsigned width = intType.getWidth();
522
523 // If the result type is at most 32 bits, then the cast can always be folded
524 // because it is always a truncation.
525 if (width <= 32) {
526 APInt result = value.trunc(width);
527 return IntegerAttr::get(type, result);
528 }
529
530 // If the result type is at least 64 bits, then the cast is always a
531 // extension. The results will differ if `trunc32(value) != value)`.
532 if (width >= 64) {
533 if (extFn(value.trunc(32), 64) != value)
534 return {};
535 APInt result = extFn(value, width);
536 return IntegerAttr::get(type, result);
537 }
538
539 // Otherwise, we just have to check the property directly.
540 APInt result = value.trunc(width);
541 if (result != extFn(value.trunc(32), width))
542 return {};
543 return IntegerAttr::get(type, result);
544}
545
546bool CastSOp::areCastCompatible(TypeRange lhsTypes, TypeRange rhsTypes) {
547 return llvm::isa<IndexType>(lhsTypes.front()) !=
548 llvm::isa<IndexType>(rhsTypes.front());
549}
550
551OpFoldResult CastSOp::fold(FoldAdaptor adaptor) {
552 return foldCastOp(
553 adaptor.getInput(), getType(),
554 [](const APInt &x, unsigned width) { return x.sext(width); },
555 [](const APInt &x, unsigned width) { return x.sextOrTrunc(width); });
556}
557
558//===----------------------------------------------------------------------===//
559// CastUOp
560//===----------------------------------------------------------------------===//
561
562bool CastUOp::areCastCompatible(TypeRange lhsTypes, TypeRange rhsTypes) {
563 return llvm::isa<IndexType>(lhsTypes.front()) !=
564 llvm::isa<IndexType>(rhsTypes.front());
565}
566
567OpFoldResult CastUOp::fold(FoldAdaptor adaptor) {
568 return foldCastOp(
569 adaptor.getInput(), getType(),
570 [](const APInt &x, unsigned width) { return x.zext(width); },
571 [](const APInt &x, unsigned width) { return x.zextOrTrunc(width); });
572}
573
574//===----------------------------------------------------------------------===//
575// CmpOp
576//===----------------------------------------------------------------------===//
577
578/// Compare two integers according to the comparison predicate.
579static bool compareIndices(const APInt &lhs, const APInt &rhs,
580 IndexCmpPredicate pred) {
581 switch (pred) {
582 case IndexCmpPredicate::EQ:
583 return lhs.eq(rhs);
584 case IndexCmpPredicate::NE:
585 return lhs.ne(rhs);
586 case IndexCmpPredicate::SGE:
587 return lhs.sge(rhs);
588 case IndexCmpPredicate::SGT:
589 return lhs.sgt(rhs);
590 case IndexCmpPredicate::SLE:
591 return lhs.sle(rhs);
592 case IndexCmpPredicate::SLT:
593 return lhs.slt(rhs);
594 case IndexCmpPredicate::UGE:
595 return lhs.uge(rhs);
596 case IndexCmpPredicate::UGT:
597 return lhs.ugt(rhs);
598 case IndexCmpPredicate::ULE:
599 return lhs.ule(rhs);
600 case IndexCmpPredicate::ULT:
601 return lhs.ult(rhs);
602 }
603 llvm_unreachable("unhandled IndexCmpPredicate predicate");
604}
605
606/// `cmp(max/min(x, cstA), cstB)` can be folded to a constant depending on the
607/// values of `cstA` and `cstB`, the max or min operation, and the comparison
608/// predicate. Check whether the value folds in both 32-bit and 64-bit
609/// arithmetic and to the same value.
610static std::optional<bool> foldCmpOfMaxOrMin(Operation *lhsOp,
611 const APInt &cstA,
612 const APInt &cstB, unsigned width,
613 IndexCmpPredicate pred) {
615 .Case([&](MinSOp op) {
617 APInt::getSignedMinValue(width), cstA);
618 })
619 .Case([&](MinUOp op) {
621 APInt::getMinValue(width), cstA);
622 })
623 .Case([&](MaxSOp op) {
625 cstA, APInt::getSignedMaxValue(width));
626 })
627 .Case([&](MaxUOp op) {
629 cstA, APInt::getMaxValue(width));
630 });
631 return intrange::evaluatePred(static_cast<intrange::CmpPredicate>(pred),
632 lhsRange, ConstantIntRanges::constant(cstB));
633}
634
635/// Return the result of `cmp(pred, x, x)`
636static bool compareSameArgs(IndexCmpPredicate pred) {
637 switch (pred) {
638 case IndexCmpPredicate::EQ:
639 case IndexCmpPredicate::SGE:
640 case IndexCmpPredicate::SLE:
641 case IndexCmpPredicate::UGE:
642 case IndexCmpPredicate::ULE:
643 return true;
644 case IndexCmpPredicate::NE:
645 case IndexCmpPredicate::SGT:
646 case IndexCmpPredicate::SLT:
647 case IndexCmpPredicate::UGT:
648 case IndexCmpPredicate::ULT:
649 return false;
650 }
651 llvm_unreachable("unknown predicate in compareSameArgs");
652}
653
654OpFoldResult CmpOp::fold(FoldAdaptor adaptor) {
655 // Attempt to fold if both inputs are constant.
656 auto lhs = dyn_cast_if_present<IntegerAttr>(adaptor.getLhs());
657 auto rhs = dyn_cast_if_present<IntegerAttr>(adaptor.getRhs());
658 if (lhs && rhs) {
659 // Perform the comparison in 64-bit and 32-bit.
660 bool result64 = compareIndices(lhs.getValue(), rhs.getValue(), getPred());
661 bool result32 = compareIndices(lhs.getValue().trunc(32),
662 rhs.getValue().trunc(32), getPred());
663 if (result64 == result32)
664 return BoolAttr::get(getContext(), result64);
665 }
666
667 // Fold `cmp(max/min(x, cstA), cstB)`.
668 Operation *lhsOp = getLhs().getDefiningOp();
669 IntegerAttr cstA;
670 if (isa_and_nonnull<MinSOp, MinUOp, MaxSOp, MaxUOp>(lhsOp) &&
671 matchPattern(lhsOp->getOperand(1), m_Constant(&cstA)) && rhs) {
672 std::optional<bool> result64 = foldCmpOfMaxOrMin(
673 lhsOp, cstA.getValue(), rhs.getValue(), 64, getPred());
674 std::optional<bool> result32 =
675 foldCmpOfMaxOrMin(lhsOp, cstA.getValue().trunc(32),
676 rhs.getValue().trunc(32), 32, getPred());
677 // Fold if the 32-bit and 64-bit results are the same.
678 if (result64 && result32 && *result64 == *result32)
679 return BoolAttr::get(getContext(), *result64);
680 }
681
682 // Fold `cmp(x, x)`
683 if (getLhs() == getRhs())
684 return BoolAttr::get(getContext(), compareSameArgs(getPred()));
685
686 return {};
687}
688
689/// Canonicalize `(x - y) == 0` to `x == y` and `(x - y) != 0` to `x != y`.
690/// Likewise, canonicalize `0 == (x - y)` and `0 != (x - y)`.
691///
692/// Ordered comparisons cannot be canonicalized this way because subtraction
693/// may wrap at the target index bitwidth.
694LogicalResult CmpOp::canonicalize(CmpOp op, PatternRewriter &rewriter) {
695 IntegerAttr cmpRhs;
696 IntegerAttr cmpLhs;
697
698 bool rhsIsZero = matchPattern(op.getRhs(), m_Constant(&cmpRhs)) &&
699 cmpRhs.getValue().isZero();
700 bool lhsIsZero = matchPattern(op.getLhs(), m_Constant(&cmpLhs)) &&
701 cmpLhs.getValue().isZero();
702 if (!rhsIsZero && !lhsIsZero)
703 return rewriter.notifyMatchFailure(op.getLoc(),
704 "cmp is not comparing something with 0");
705
706 SubOp subOp = rhsIsZero ? op.getLhs().getDefiningOp<index::SubOp>()
707 : op.getRhs().getDefiningOp<index::SubOp>();
708 if (!subOp)
709 return rewriter.notifyMatchFailure(
710 op.getLoc(), "non-zero operand is not a result of subtraction");
711
712 if (op.getPred() != IndexCmpPredicate::EQ &&
713 op.getPred() != IndexCmpPredicate::NE)
714 return rewriter.notifyMatchFailure(
715 op.getLoc(),
716 "only eq and ne comparisons can be canonicalized through subtraction");
717
718 index::CmpOp newCmp;
719 if (rhsIsZero)
720 newCmp = index::CmpOp::create(rewriter, op.getLoc(), op.getPred(),
721 subOp.getLhs(), subOp.getRhs());
722 else
723 newCmp = index::CmpOp::create(rewriter, op.getLoc(), op.getPred(),
724 subOp.getRhs(), subOp.getLhs());
725
726 rewriter.replaceOp(op, newCmp);
727 return success();
728}
729
730//===----------------------------------------------------------------------===//
731// ConstantOp
732//===----------------------------------------------------------------------===//
733
734void ConstantOp::getAsmResultNames(
735 function_ref<void(Value, StringRef)> setNameFn) {
736 SmallString<32> specialNameBuffer;
737 llvm::raw_svector_ostream specialName(specialNameBuffer);
738 specialName << "idx" << getValueAttr().getValue();
739 setNameFn(getResult(), specialName.str());
740}
741
742OpFoldResult ConstantOp::fold(FoldAdaptor adaptor) { return getValueAttr(); }
743
744void ConstantOp::build(OpBuilder &b, OperationState &state, int64_t value) {
745 build(b, state, b.getIndexType(), b.getIndexAttr(value));
746}
747
748//===----------------------------------------------------------------------===//
749// BoolConstantOp
750//===----------------------------------------------------------------------===//
751
752OpFoldResult BoolConstantOp::fold(FoldAdaptor adaptor) {
753 return getValueAttr();
754}
755
756void BoolConstantOp::getAsmResultNames(
757 function_ref<void(Value, StringRef)> setNameFn) {
758 setNameFn(getResult(), getValue() ? "true" : "false");
759}
760
761//===----------------------------------------------------------------------===//
762// ODS-Generated Definitions
763//===----------------------------------------------------------------------===//
764
765#define GET_OP_CLASSES
766#include "mlir/Dialect/Index/IR/IndexOps.cpp.inc"
return success()
static OpFoldResult foldBinaryOpUnchecked(ArrayRef< Attribute > operands, function_ref< std::optional< APInt >(const APInt &, const APInt &)> calculate)
Fold an index operation irrespective of the target bitwidth.
Definition IndexOps.cpp:61
static std::optional< APInt > calculateFloorDivS(const APInt &n, const APInt &m)
Compute floordivs(n, m) as x = m < 0 ?
Definition IndexOps.cpp:294
static std::optional< APInt > calculateCeilDivS(const APInt &n, const APInt &m)
Compute ceildivs(n, m) as x = m > 0 ?
Definition IndexOps.cpp:243
static std::optional< bool > foldCmpOfMaxOrMin(Operation *lhsOp, const APInt &cstA, const APInt &cstB, unsigned width, IndexCmpPredicate pred)
cmp(max/min(x, cstA), cstB) can be folded to a constant depending on the values of cstA and cstB,...
Definition IndexOps.cpp:610
static LogicalResult canonicalizeAssociativeCommutativeBinaryOp(BinaryOp op, PatternRewriter &rewriter)
Helper for associative and commutative binary ops that can be transformed: x = op(v,...
Definition IndexOps.cpp:118
static bool compareIndices(const APInt &lhs, const APInt &rhs, IndexCmpPredicate pred)
Compare two integers according to the comparison predicate.
Definition IndexOps.cpp:579
static OpFoldResult foldBinaryOpChecked(ArrayRef< Attribute > operands, function_ref< std::optional< APInt >(const APInt &, const APInt &lhs)> calculate)
Fold an index operation only if the truncated 64-bit result matches the 32-bit result for operations ...
Definition IndexOps.cpp:87
static OpFoldResult foldCastOp(Attribute input, Type type, function_ref< APInt(const APInt &, unsigned)> extFn, function_ref< APInt(const APInt &, unsigned)> extOrTruncFn)
Definition IndexOps.cpp:502
static bool compareSameArgs(IndexCmpPredicate pred)
Return the result of cmp(pred, x, x)
Definition IndexOps.cpp:636
b
Return true if permutation is a valid permutation of the outer_dims_perm (case OuterOrInnerPerm::Oute...
if(!isCopyOut)
b getContext())
Attributes are known-constant values of operations.
Definition Attributes.h:25
static BoolAttr get(MLIRContext *context, bool value)
A set of arbitrary-precision integers representing bounds on a given integer value.
static ConstantIntRanges constant(const APInt &value)
Create a ConstantIntRanges with a constant value - that is, with the bounds [value,...
static ConstantIntRanges fromUnsigned(const APInt &umin, const APInt &umax)
Create an ConstantIntRanges with the unsigned minimum and maximum equal to umin and umax and the sign...
static ConstantIntRanges fromSigned(const APInt &smin, const APInt &smax)
Create an ConstantIntRanges with the signed minimum and maximum equal to smin and smax,...
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition Location.h:76
This class helps build Operations.
Definition Builders.h:210
void createOrFold(SmallVectorImpl< Value > &results, Location location, Args &&...args)
Create an operation of specific op type at the current insertion point, and immediately try to fold i...
Definition Builders.h:528
This class represents a single result from folding an operation.
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
Value getOperand(unsigned idx)
Definition Operation.h:377
A special type of RewriterBase that coordinates the application of a rewrite pattern on the current I...
virtual void replaceOp(Operation *op, ValueRange newValues)
Replace the results of the given (original) operation with the specified list of values (replacements...
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,...
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 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
bool isSignlessInteger() const
Return true if this is a signless integer type (with the specified width).
Definition Types.cpp:66
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
Definition Value.cpp:18
std::optional< bool > evaluatePred(CmpPredicate pred, const ConstantIntRanges &lhs, const ConstantIntRanges &rhs)
Returns a boolean value if pred is statically true or false for anypossible inputs falling within lhs...
CmpPredicate
Copy of the enum from arith and index to allow the common integer range infrastructure to not depend ...
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
Type getType(OpFoldResult ofr)
Returns the int type of the integer in ofr.
Definition Utils.cpp:311
llvm::TypeSwitch< T, ResultT > TypeSwitch
Definition LLVM.h:147
detail::constant_op_matcher m_Constant()
Matches a constant foldable operation.
Definition Matchers.h:369
llvm::function_ref< Fn > function_ref
Definition LLVM.h:155
This represents an operation in an abstracted form, suitable for use with the builder APIs.