28#include "llvm/ADT/APFloat.h"
29#include "llvm/ADT/APInt.h"
30#include "llvm/ADT/APSInt.h"
31#include "llvm/ADT/DenseMap.h"
32#include "llvm/ADT/FloatingPointMode.h"
33#include "llvm/ADT/STLExtras.h"
34#include "llvm/ADT/SmallVector.h"
35#include "llvm/ADT/TypeSwitch.h"
42 llvm::RoundingMode::NearestTiesToEven;
51 function_ref<APInt(
const APInt &,
const APInt &)> binFn) {
52 const APInt &lhsVal = llvm::cast<IntegerAttr>(lhs).getValue();
53 const APInt &rhsVal = llvm::cast<IntegerAttr>(rhs).getValue();
54 APInt value = binFn(lhsVal, rhsVal);
55 return IntegerAttr::get(res.getType(), value);
90static IntegerOverflowFlagsAttr
92 IntegerOverflowFlagsAttr val2) {
93 return IntegerOverflowFlagsAttr::get(val1.getContext(),
94 val1.getValue() & val2.getValue());
103 IntegerOverflowFlagsAttr val1, IntegerOverflowFlagsAttr val2,
Attribute lhs,
106 IntegerOverflowFlags flags = val1.getValue() & val2.getValue();
107 if (flags == IntegerOverflowFlags::none)
108 return IntegerOverflowFlagsAttr::get(val1.getContext(), flags);
110 auto lhsAttr = llvm::cast<IntegerAttr>(lhs);
111 auto rhsAttr = llvm::cast<IntegerAttr>(rhs);
113 if (isa<IndexType>(lhsAttr.getType()))
114 return IntegerOverflowFlagsAttr::get(val1.getContext(), flags);
116 const APInt &lhsValue = lhsAttr.getValue();
117 const APInt &rhsValue = rhsAttr.getValue();
119 if (bitEnumContainsAny(flags, IntegerOverflowFlags::nsw)) {
120 (
void)(lhsValue.*signedOp)(rhsValue, overflow);
122 flags = bitEnumClear(flags, IntegerOverflowFlags::nsw);
124 if (bitEnumContainsAny(flags, IntegerOverflowFlags::nuw)) {
125 (
void)(lhsValue.*unsignedOp)(rhsValue, overflow);
127 flags = bitEnumClear(flags, IntegerOverflowFlags::nuw);
129 return IntegerOverflowFlagsAttr::get(val1.getContext(), flags);
135 case arith::CmpIPredicate::eq:
136 return arith::CmpIPredicate::ne;
137 case arith::CmpIPredicate::ne:
138 return arith::CmpIPredicate::eq;
139 case arith::CmpIPredicate::slt:
140 return arith::CmpIPredicate::sge;
141 case arith::CmpIPredicate::sle:
142 return arith::CmpIPredicate::sgt;
143 case arith::CmpIPredicate::sgt:
144 return arith::CmpIPredicate::sle;
145 case arith::CmpIPredicate::sge:
146 return arith::CmpIPredicate::slt;
147 case arith::CmpIPredicate::ult:
148 return arith::CmpIPredicate::uge;
149 case arith::CmpIPredicate::ule:
150 return arith::CmpIPredicate::ugt;
151 case arith::CmpIPredicate::ugt:
152 return arith::CmpIPredicate::ule;
153 case arith::CmpIPredicate::uge:
154 return arith::CmpIPredicate::ult;
156 llvm_unreachable(
"unknown cmpi predicate kind");
165static llvm::RoundingMode
169 switch (*roundingMode) {
170 case RoundingMode::downward:
171 return llvm::RoundingMode::TowardNegative;
172 case RoundingMode::to_nearest_away:
173 return llvm::RoundingMode::NearestTiesToAway;
174 case RoundingMode::to_nearest_even:
175 return llvm::RoundingMode::NearestTiesToEven;
176 case RoundingMode::toward_zero:
177 return llvm::RoundingMode::TowardZero;
178 case RoundingMode::upward:
179 return llvm::RoundingMode::TowardPositive;
181 llvm_unreachable(
"Unhandled rounding mode");
185 return arith::CmpIPredicateAttr::get(pred.getContext(),
205 if (!fpTy || intWidth <= 0)
207 const llvm::fltSemantics &semantics = fpTy.getFloatSemantics();
209 if (!APFloat::semanticsHasZero(semantics) ||
210 (isSigned && !APFloat::semanticsHasSignedRepr(semantics)))
213 int64_t magnitudeBits = intWidth - (isSigned ? 1 : 0);
214 return magnitudeBits <= fpTy.getFPMantissaWidth() &&
215 intWidth - 1 <= APFloat::semanticsMaxExponent(semantics);
228 ShapedType shapedType = dyn_cast_or_null<ShapedType>(type);
232 if (!shapedType.hasStaticShape())
242 ShapedType shapedType = dyn_cast<ShapedType>(type);
245 if (!shapedType.hasStaticShape())
255#include "ArithCanonicalization.inc"
264 auto i1Type = IntegerType::get(type.
getContext(), 1);
265 if (
auto shapedType = dyn_cast<ShapedType>(type))
266 return shapedType.cloneWith(std::nullopt, i1Type);
267 if (llvm::isa<UnrankedTensorType>(type))
268 return UnrankedTensorType::get(i1Type);
276void arith::ConstantOp::getAsmResultNames(
279 if (
auto intCst = dyn_cast<IntegerAttr>(getValue())) {
280 auto intType = dyn_cast<IntegerType>(type);
283 if (intType && intType.getWidth() == 1)
284 return setNameFn(getResult(), (intCst.getInt() ?
"true" :
"false"));
287 SmallString<32> specialNameBuffer;
288 llvm::raw_svector_ostream specialName(specialNameBuffer);
289 specialName <<
'c' << intCst.getValue();
291 specialName <<
'_' << type;
292 setNameFn(getResult(), specialName.str());
294 setNameFn(getResult(),
"cst");
300LogicalResult arith::ConstantOp::verify() {
304 intType && !intType.isSignless())
305 return emitOpError(
"integer return type must be signless");
307 if (!llvm::isa<IntegerAttr, FloatAttr, ElementsAttr>(getValue())) {
309 "value must be an integer, float, or elements attribute");
315 if (isa<ScalableVectorType>(type) && !isa<SplatElementsAttr>(getValue()))
317 "initializing scalable vectors with elements attribute is not supported"
318 " unless it's a vector splat");
322bool arith::ConstantOp::isBuildableWith(Attribute value, Type type) {
324 auto typedAttr = dyn_cast<TypedAttr>(value);
325 if (!typedAttr || typedAttr.getType() != type)
329 if (!intType.isSignless())
333 return llvm::isa<IntegerAttr, FloatAttr, ElementsAttr>(value);
336ConstantOp arith::ConstantOp::materialize(OpBuilder &builder, Attribute value,
337 Type type, Location loc) {
338 if (isBuildableWith(value, type))
339 return arith::ConstantOp::create(builder, loc, cast<TypedAttr>(value));
343OpFoldResult arith::ConstantOp::fold(FoldAdaptor adaptor) {
return getValue(); }
348 arith::ConstantOp::build(builder,
result, type,
358 auto result = dyn_cast<ConstantIntOp>(builder.
create(state));
359 assert(
result &&
"builder didn't return the right type");
371 arith::ConstantOp::build(builder,
result, type,
380 auto result = dyn_cast<ConstantIntOp>(builder.
create(state));
381 assert(
result &&
"builder didn't return the right type");
392 arith::ConstantOp::build(builder,
result, type,
398 const APInt &
value) {
401 auto result = dyn_cast<ConstantIntOp>(builder.
create(state));
402 assert(
result &&
"builder didn't return the right type");
408 const APInt &
value) {
413 if (
auto constOp = dyn_cast_or_null<arith::ConstantOp>(op))
414 return constOp.getType().isSignlessInteger();
419 FloatType type,
const APFloat &
value) {
420 arith::ConstantOp::build(builder,
result, type,
427 const APFloat &
value) {
430 auto result = dyn_cast<ConstantFloatOp>(builder.
create(state));
431 assert(
result &&
"builder didn't return the right type");
437 const APFloat &
value) {
442 if (
auto constOp = dyn_cast_or_null<arith::ConstantOp>(op))
443 return llvm::isa<FloatType>(constOp.getType());
458 auto result = dyn_cast<ConstantIndexOp>(builder.
create(state));
459 assert(
result &&
"builder didn't return the right type");
469 if (
auto constOp = dyn_cast_or_null<arith::ConstantOp>(op))
470 return constOp.getType().isIndex();
478 "type doesn't have a zero representation");
480 assert(zeroAttr &&
"unsupported type for zero attribute");
481 return arith::ConstantOp::create(builder, loc, zeroAttr);
494 if (
auto sub = getLhs().getDefiningOp<SubIOp>())
495 if (getRhs() == sub.getRhs())
499 if (
auto sub = getRhs().getDefiningOp<SubIOp>())
500 if (getLhs() == sub.getRhs())
504 adaptor.getOperands(),
505 [](APInt a,
const APInt &
b) { return std::move(a) + b; });
510 patterns.
add<AddIAddConstant, AddISubConstantRHS, AddISubConstantLHS,
511 AddIMulNegativeOneRhs, AddIMulNegativeOneLhs>(context);
518std::optional<SmallVector<int64_t, 4>>
519arith::AddUIExtendedOp::getIterationShapeToUnroll() {
520 if (
auto vt = dyn_cast<VectorType>(
getType(0)))
521 return llvm::to_vector<4>(vt.getShape());
528 return sum.ult(operand) ? APInt::getAllOnes(1) : APInt::getZero(1);
532arith::AddUIExtendedOp::fold(FoldAdaptor adaptor,
533 SmallVectorImpl<OpFoldResult> &results) {
534 Type overflowTy = getOverflow().getType();
540 results.push_back(getLhs());
541 results.push_back(falseValue);
550 adaptor.getOperands(),
551 [](APInt a,
const APInt &
b) { return std::move(a) + b; })) {
554 results.push_back(sumAttr);
555 results.push_back(sumAttr);
559 ArrayRef({sumAttr, adaptor.getLhs()}),
565 results.push_back(sumAttr);
566 results.push_back(overflowAttr);
573void arith::AddUIExtendedOp::getCanonicalizationPatterns(
574 RewritePatternSet &patterns, MLIRContext *context) {
575 patterns.
add<AddUIExtendedToAddI>(context);
582std::optional<SmallVector<int64_t, 4>>
583arith::SubUIExtendedOp::getIterationShapeToUnroll() {
584 if (
auto vt = dyn_cast<VectorType>(
getType(0)))
585 return llvm::to_vector<4>(vt.getShape());
592 return lhs.ult(rhs) ? APInt::getAllOnes(1) : APInt::getZero(1);
596arith::SubUIExtendedOp::fold(FoldAdaptor adaptor,
597 SmallVectorImpl<OpFoldResult> &results) {
598 Type borrowTy = getBorrow().getType();
604 results.push_back(getLhs());
605 results.push_back(falseValue);
610 if (getLhs() == getRhs()) {
613 auto shapedType = dyn_cast<ShapedType>(getDiff().
getType());
614 if (shapedType && !shapedType.hasStaticShape())
622 results.push_back(zeroDiff);
623 results.push_back(falseValue);
629 adaptor.getOperands(),
630 [](APInt a,
const APInt &
b) { return std::move(a) - b; })) {
633 results.push_back(diffAttr);
634 results.push_back(diffAttr);
638 adaptor.getOperands(),
644 results.push_back(diffAttr);
645 results.push_back(borrowAttr);
652void arith::SubUIExtendedOp::getCanonicalizationPatterns(
653 RewritePatternSet &patterns, MLIRContext *context) {
654 patterns.
add<SubUIExtendedToSubI>(context);
661OpFoldResult arith::SubIOp::fold(FoldAdaptor adaptor) {
663 if (getOperand(0) == getOperand(1)) {
664 auto shapedType = dyn_cast<ShapedType>(
getType());
666 if (!shapedType || shapedType.hasStaticShape())
673 if (
auto add = getLhs().getDefiningOp<AddIOp>()) {
675 if (getRhs() ==
add.getRhs())
678 if (getRhs() ==
add.getLhs())
683 if (
auto sub = getRhs().getDefiningOp<SubIOp>())
684 if (getLhs() == sub.getLhs())
688 adaptor.getOperands(),
689 [](APInt a,
const APInt &
b) { return std::move(a) - b; });
692void arith::SubIOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
693 MLIRContext *context) {
694 patterns.
add<SubIRHSAddConstant, SubILHSAddConstant, SubIRHSSubConstantRHS,
695 SubIRHSSubConstantLHS, SubILHSSubConstantRHS,
696 SubILHSSubConstantLHS, SubISubILHSRHSLHS>(context);
703OpFoldResult arith::MulIOp::fold(FoldAdaptor adaptor) {
714 adaptor.getOperands(),
715 [](
const APInt &a,
const APInt &
b) { return a * b; });
718void arith::MulIOp::getAsmResultNames(
720 if (!isa<IndexType>(
getType()))
725 auto isVscale = [](Operation *op) {
726 return op && op->getName().getStringRef() ==
"vector.vscale";
729 IntegerAttr baseValue;
730 auto isVscaleExpr = [&](Value a, Value
b) {
732 isVscale(
b.getDefiningOp());
735 if (!isVscaleExpr(getLhs(), getRhs()) && !isVscaleExpr(getRhs(), getLhs()))
739 SmallString<32> specialNameBuffer;
740 llvm::raw_svector_ostream specialName(specialNameBuffer);
741 specialName <<
'c' << baseValue.getInt() <<
"_vscale";
742 setNameFn(getResult(), specialName.str());
745void arith::MulIOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
746 MLIRContext *context) {
747 patterns.
add<MulIMulIConstant>(context);
754std::optional<SmallVector<int64_t, 4>>
755arith::MulSIExtendedOp::getIterationShapeToUnroll() {
756 if (
auto vt = dyn_cast<VectorType>(
getType(0)))
757 return llvm::to_vector<4>(vt.getShape());
762arith::MulSIExtendedOp::fold(FoldAdaptor adaptor,
763 SmallVectorImpl<OpFoldResult> &results) {
766 Attribute zero = adaptor.getRhs();
767 results.push_back(zero);
768 results.push_back(zero);
774 adaptor.getOperands(),
775 [](
const APInt &a,
const APInt &
b) { return a * b; })) {
778 llvm::APIntOps::mulhs);
779 assert(highAttr &&
"Unexpected constant-folding failure");
781 results.push_back(lowAttr);
782 results.push_back(highAttr);
789void arith::MulSIExtendedOp::getCanonicalizationPatterns(
790 RewritePatternSet &patterns, MLIRContext *context) {
791 patterns.
add<MulSIExtendedToMulI, MulSIExtendedRHSOne>(context);
798std::optional<SmallVector<int64_t, 4>>
799arith::MulUIExtendedOp::getIterationShapeToUnroll() {
800 if (
auto vt = dyn_cast<VectorType>(
getType(0)))
801 return llvm::to_vector<4>(vt.getShape());
806arith::MulUIExtendedOp::fold(FoldAdaptor adaptor,
807 SmallVectorImpl<OpFoldResult> &results) {
810 Attribute zero = adaptor.getRhs();
811 results.push_back(zero);
812 results.push_back(zero);
820 results.push_back(getLhs());
821 results.push_back(zero);
827 adaptor.getOperands(),
828 [](
const APInt &a,
const APInt &
b) { return a * b; })) {
831 llvm::APIntOps::mulhu);
832 assert(highAttr &&
"Unexpected constant-folding failure");
834 results.push_back(lowAttr);
835 results.push_back(highAttr);
842void arith::MulUIExtendedOp::getCanonicalizationPatterns(
843 RewritePatternSet &patterns, MLIRContext *context) {
844 patterns.
add<MulUIExtendedToMulI>(context);
853 arith::IntegerOverflowFlags ovfFlags) {
854 auto mul = lhs.getDefiningOp<mlir::arith::MulIOp>();
855 if (!
mul || !bitEnumContainsAll(
mul.getOverflowFlags(), ovfFlags))
858 if (
mul.getLhs() == rhs)
861 if (
mul.getRhs() == rhs)
867OpFoldResult arith::DivUIOp::fold(FoldAdaptor adaptor) {
881 if (getLhs() == getRhs())
885 if (Value val =
foldDivMul(getLhs(), getRhs(), IntegerOverflowFlags::nuw))
891 [&](APInt a,
const APInt &
b) {
899 return div0 ? Attribute() :
result;
919OpFoldResult arith::DivSIOp::fold(FoldAdaptor adaptor) {
933 if (getLhs() == getRhs())
937 if (Value val =
foldDivMul(getLhs(), getRhs(), IntegerOverflowFlags::nsw))
941 bool overflowOrDiv0 =
false;
943 adaptor.getOperands(), [&](APInt a,
const APInt &
b) {
944 if (overflowOrDiv0 || !b) {
945 overflowOrDiv0 = true;
948 return a.sdiv_ov(
b, overflowOrDiv0);
951 return overflowOrDiv0 ? Attribute() :
result;
975OpFoldResult arith::CeilDivUIOp::fold(FoldAdaptor adaptor) {
989 if (getLhs() == getRhs())
992 bool overflowOrDiv0 =
false;
994 adaptor.getOperands(), [&](APInt a,
const APInt &
b) {
995 if (overflowOrDiv0 || !b) {
996 overflowOrDiv0 = true;
999 APInt quotient = a.udiv(
b);
1002 APInt one(a.getBitWidth(), 1,
true);
1003 return quotient.uadd_ov(one, overflowOrDiv0);
1006 return overflowOrDiv0 ? Attribute() :
result;
1017OpFoldResult arith::CeilDivSIOp::fold(FoldAdaptor adaptor) {
1031 if (getLhs() == getRhs())
1035 bool overflowOrDiv0 =
false;
1037 adaptor.getOperands(), [&](
const APInt &a,
const APInt &
b) {
1038 if (overflowOrDiv0 || !b) {
1039 overflowOrDiv0 = true;
1049 bool overflowDiv =
false;
1050 APInt quotient = a.sdiv_ov(
b, overflowDiv);
1054 overflowOrDiv0 =
true;
1057 if (a.isNegative() !=
b.isNegative() || quotient *
b == a)
1063 APInt one(a.getBitWidth(), 1,
true);
1064 return quotient.sadd_ov(one, overflowOrDiv0);
1067 return overflowOrDiv0 ? Attribute() :
result;
1078OpFoldResult arith::FloorDivSIOp::fold(FoldAdaptor adaptor) {
1092 if (getLhs() == getRhs())
1096 bool overflowOrDiv =
false;
1098 adaptor.getOperands(), [&](APInt a,
const APInt &
b) {
1100 overflowOrDiv = true;
1103 return a.sfloordiv_ov(
b, overflowOrDiv);
1106 return overflowOrDiv ? Attribute() :
result;
1112 Value divisor = getRhs();
1124OpFoldResult arith::RemUIOp::fold(FoldAdaptor adaptor) {
1141 [&](APInt a,
const APInt &
b) {
1142 if (div0 || b.isZero()) {
1149 return div0 ? Attribute() :
result;
1160OpFoldResult arith::RemSIOp::fold(FoldAdaptor adaptor) {
1177 [&](APInt a,
const APInt &
b) {
1178 if (div0 || b.isZero()) {
1185 return div0 ? Attribute() :
result;
1203template <
typename OpTy>
1205 for (
bool reversePrev : {
false,
true}) {
1206 auto prev = (reversePrev ? op.getRhs() : op.getLhs())
1207 .template getDefiningOp<OpTy>();
1211 Value other = (reversePrev ? op.getLhs() : op.getRhs());
1212 if (other != prev.getLhs() && other != prev.getRhs())
1215 return prev.getResult();
1220OpFoldResult arith::AndIOp::fold(FoldAdaptor adaptor) {
1227 intValue.isAllOnes())
1232 intValue.isAllOnes())
1237 intValue.isAllOnes())
1245 adaptor.getOperands(),
1246 [](APInt a,
const APInt &
b) { return std::move(a) & b; });
1253OpFoldResult arith::OrIOp::fold(FoldAdaptor adaptor) {
1256 if (rhsVal.isZero())
1259 if (rhsVal.isAllOnes())
1260 return adaptor.getRhs();
1267 intValue.isAllOnes())
1268 return getRhs().getDefiningOp<XOrIOp>().getRhs();
1272 intValue.isAllOnes())
1273 return getLhs().getDefiningOp<XOrIOp>().getRhs();
1280 adaptor.getOperands(),
1281 [](APInt a,
const APInt &
b) { return std::move(a) | b; });
1288OpFoldResult arith::XOrIOp::fold(FoldAdaptor adaptor) {
1293 if (getLhs() == getRhs()) {
1296 auto shapedType = dyn_cast<ShapedType>(
getType());
1297 if (!shapedType || shapedType.hasStaticShape())
1302 if (arith::XOrIOp prev = getLhs().getDefiningOp<arith::XOrIOp>()) {
1303 if (prev.getRhs() == getRhs())
1304 return prev.getLhs();
1305 if (prev.getLhs() == getRhs())
1306 return prev.getRhs();
1310 if (arith::XOrIOp prev = getRhs().getDefiningOp<arith::XOrIOp>()) {
1311 if (prev.getRhs() == getLhs())
1312 return prev.getLhs();
1313 if (prev.getLhs() == getLhs())
1314 return prev.getRhs();
1318 adaptor.getOperands(),
1319 [](APInt a,
const APInt &
b) { return std::move(a) ^ b; });
1322void arith::XOrIOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
1323 MLIRContext *context) {
1324 patterns.
add<XOrIXOrIConstant, XOrINotCmpI, XOrIOfExtUI, XOrIOfExtSI>(
1332OpFoldResult arith::NegFOp::fold(FoldAdaptor adaptor) {
1334 if (
auto op = this->getOperand().getDefiningOp<arith::NegFOp>())
1335 return op.getOperand();
1337 adaptor.getOperands(), [](
const APFloat &a) -> std::optional<APFloat> {
1338 if (!APFloat::semanticsHasSignedRepr(a.getSemantics()))
1339 return std::nullopt;
1348OpFoldResult arith::FlushDenormalsOp::fold(FoldAdaptor adaptor) {
1354 if (
auto op = this->getOperand().getDefiningOp<arith::FlushDenormalsOp>())
1355 return op.getResult();
1359 adaptor.getOperands(), [](
const APFloat &a) {
1361 return APFloat::getZero(a.getSemantics(), a.isNegative());
1370OpFoldResult arith::AddFOp::fold(FoldAdaptor adaptor) {
1375 bitEnumContainsAll(adaptor.getFastmath(), FastMathFlags::nsz))
1378 auto rm = getRoundingmode();
1380 adaptor.getOperands(), [rm](
const APFloat &a,
const APFloat &
b) {
1382 result.add(b, convertArithRoundingModeToLLVMIR(rm));
1387void arith::AddFOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
1388 MLIRContext *context) {
1389 patterns.
add<AddFOfNegFLhs, AddFOfNegFRhs>(context);
1396OpFoldResult arith::SubFOp::fold(FoldAdaptor adaptor) {
1401 bitEnumContainsAll(adaptor.getFastmath(), FastMathFlags::nsz))
1404 auto rm = getRoundingmode();
1406 adaptor.getOperands(),
1407 [rm](
const APFloat &a,
const APFloat &
b) -> std::optional<APFloat> {
1410 if (!APFloat::semanticsHasSignedRepr(a.getSemantics()) &&
1411 a.compare(b) == APFloat::cmpLessThan)
1412 return std::nullopt;
1414 result.subtract(b, convertArithRoundingModeToLLVMIR(rm));
1419void arith::SubFOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
1420 MLIRContext *context) {
1421 patterns.
add<SubFOfNegZero>(context);
1434template <
typename TruncOp,
typename ExtOp,
typename ExtremumOp>
1435struct NarrowExtremum final : OpRewritePattern<TruncOp> {
1436 using OpRewritePattern<TruncOp>::OpRewritePattern;
1438 LogicalResult matchAndRewrite(TruncOp truncOp,
1439 PatternRewriter &rewriter)
const override {
1440 auto extremumOp = truncOp.getIn().template getDefiningOp<ExtremumOp>();
1441 if (!extremumOp || !extremumOp->hasOneUse())
1444 auto lhsExt = extremumOp.getLhs().template getDefiningOp<ExtOp>();
1445 auto rhsExt = extremumOp.getRhs().template getDefiningOp<ExtOp>();
1446 if (!lhsExt || !rhsExt)
1449 Value
lhs = lhsExt.getIn();
1450 Value
rhs = rhsExt.getIn();
1451 Type narrowType = truncOp.getType();
1452 if (
lhs.getType() != narrowType ||
rhs.getType() != narrowType)
1461 if (
auto narrowFloatType =
1463 auto wideFloatType =
1468 const llvm::fltSemantics &narrowSemantics =
1469 narrowFloatType.getFloatSemantics();
1470 const llvm::fltSemantics &wideSemantics =
1471 wideFloatType.getFloatSemantics();
1472 bool ignoreNaNs =
false;
1473 if constexpr (std::is_same_v<TruncOp, TruncFOp>)
1475 bitEnumContainsAll(extremumOp.getFastmath(), FastMathFlags::nnan);
1476 if (!llvm::APFloatBase::isLosslesslyConvertibleTo(
1477 narrowSemantics, wideSemantics, ignoreNaNs))
1483 extremumOp.getProperties(),
1484 extremumOp->getDiscardableAttrDictionary().getValue());
1495OpFoldResult arith::MaximumFOp::fold(FoldAdaptor adaptor) {
1497 if (getLhs() == getRhs())
1511OpFoldResult arith::MaxNumFOp::fold(FoldAdaptor adaptor) {
1513 if (getLhs() == getRhs())
1527OpFoldResult arith::MaximumNumFOp::fold(FoldAdaptor adaptor) {
1529 if (getLhs() == getRhs())
1543OpFoldResult MaxSIOp::fold(FoldAdaptor adaptor) {
1545 if (getLhs() == getRhs())
1551 if (intValue.isMaxSignedValue())
1554 if (intValue.isMinSignedValue())
1559 llvm::APIntOps::smax);
1566OpFoldResult MaxUIOp::fold(FoldAdaptor adaptor) {
1568 if (getLhs() == getRhs())
1574 if (intValue.isMaxValue())
1577 if (intValue.isMinValue())
1582 llvm::APIntOps::umax);
1589OpFoldResult arith::MinimumFOp::fold(FoldAdaptor adaptor) {
1591 if (getLhs() == getRhs())
1605OpFoldResult arith::MinNumFOp::fold(FoldAdaptor adaptor) {
1607 if (getLhs() == getRhs())
1621OpFoldResult arith::MinimumNumFOp::fold(FoldAdaptor adaptor) {
1623 if (getLhs() == getRhs())
1637OpFoldResult MinSIOp::fold(FoldAdaptor adaptor) {
1639 if (getLhs() == getRhs())
1645 if (intValue.isMinSignedValue())
1648 if (intValue.isMaxSignedValue())
1653 llvm::APIntOps::smin);
1660OpFoldResult MinUIOp::fold(FoldAdaptor adaptor) {
1662 if (getLhs() == getRhs())
1668 if (intValue.isMinValue())
1671 if (intValue.isMaxValue())
1676 llvm::APIntOps::umin);
1683OpFoldResult arith::MulFOp::fold(FoldAdaptor adaptor) {
1691 if (arith::bitEnumContainsAll(getFastmath(), arith::FastMathFlags::nnan |
1692 arith::FastMathFlags::nsz) &&
1693 !(adaptor.getLhs() && adaptor.getRhs())) {
1701 auto rm = getRoundingmode();
1703 adaptor.getOperands(), [rm](
const APFloat &a,
const APFloat &
b) {
1705 result.multiply(b, convertArithRoundingModeToLLVMIR(rm));
1710void arith::MulFOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
1711 MLIRContext *context) {
1712 patterns.
add<MulFOfNegF>(context);
1719OpFoldResult arith::DivFOp::fold(FoldAdaptor adaptor) {
1724 auto rm = getRoundingmode();
1726 adaptor.getOperands(), [rm](
const APFloat &a,
const APFloat &
b) {
1728 result.divide(b, convertArithRoundingModeToLLVMIR(rm));
1733void arith::DivFOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
1734 MLIRContext *context) {
1735 patterns.
add<DivFOfNegF>(context);
1742OpFoldResult arith::RemFOp::fold(FoldAdaptor adaptor) {
1744 [](
const APFloat &a,
const APFloat &
b) {
1749 (void)result.mod(b);
1758template <
typename... Types>
1764template <
typename... ShapedTypes,
typename... ElementTypes>
1767 if (llvm::isa<ShapedType>(type) && !llvm::isa<ShapedTypes...>(type))
1771 if (!llvm::isa<ElementTypes...>(underlyingType))
1774 return underlyingType;
1778template <
typename... ElementTypes>
1785template <
typename... ElementTypes>
1794 auto rankedTensorA = dyn_cast<RankedTensorType>(typeA);
1795 auto rankedTensorB = dyn_cast<RankedTensorType>(typeB);
1796 if (!rankedTensorA || !rankedTensorB)
1798 return rankedTensorA.getEncoding() == rankedTensorB.getEncoding();
1802 if (inputs.size() != 1 || outputs.size() != 1)
1814template <
typename ValType,
typename Op>
1819 if (llvm::cast<ValType>(srcType).getWidth() >=
1820 llvm::cast<ValType>(dstType).getWidth())
1822 << dstType <<
" must be wider than operand type " << srcType;
1828template <
typename ValType,
typename Op>
1833 if (llvm::cast<ValType>(srcType).getWidth() <=
1834 llvm::cast<ValType>(dstType).getWidth())
1836 << dstType <<
" must be shorter than operand type " << srcType;
1842template <
template <
typename>
class WidthComparator,
typename... ElementTypes>
1847 auto srcType =
getTypeIfLike<ElementTypes...>(inputs.front());
1848 auto dstType =
getTypeIfLike<ElementTypes...>(outputs.front());
1849 if (!srcType || !dstType)
1852 return WidthComparator<unsigned>()(dstType.getIntOrFloatBitWidth(),
1853 srcType.getIntOrFloatBitWidth());
1858static FailureOr<APFloat>
1860 const llvm::fltSemantics &targetSemantics,
1864 using fltNonfiniteBehavior = llvm::fltNonfiniteBehavior;
1865 if (sourceValue.isInfinity() &&
1866 (targetSemantics.nonFiniteBehavior == fltNonfiniteBehavior::NanOnly ||
1867 targetSemantics.nonFiniteBehavior == fltNonfiniteBehavior::FiniteOnly))
1869 if (sourceValue.isNaN() &&
1870 targetSemantics.nonFiniteBehavior == fltNonfiniteBehavior::FiniteOnly)
1874 if (sourceValue.isNegative() &&
1875 !APFloat::semanticsHasSignedRepr(targetSemantics))
1878 bool losesInfo =
false;
1879 auto status = sourceValue.convert(targetSemantics, roundingMode, &losesInfo);
1880 if (losesInfo || status != APFloat::opOK)
1890OpFoldResult arith::ExtUIOp::fold(FoldAdaptor adaptor) {
1891 if (
auto lhs = getIn().getDefiningOp<ExtUIOp>()) {
1894 setNonNeg(
lhs.getNonNeg());
1895 getInMutable().assign(
lhs.getIn());
1900 unsigned bitWidth = llvm::cast<IntegerType>(resType).getWidth();
1902 adaptor.getOperands(),
getType(),
1903 [bitWidth](
const APInt &a,
bool &castStatus) {
1904 return a.zext(bitWidth);
1912LogicalResult arith::ExtUIOp::verify() {
1920OpFoldResult arith::ExtSIOp::fold(FoldAdaptor adaptor) {
1921 if (
auto lhs = getIn().getDefiningOp<ExtSIOp>()) {
1922 getInMutable().assign(
lhs.getIn());
1927 unsigned bitWidth = llvm::cast<IntegerType>(resType).getWidth();
1929 adaptor.getOperands(),
getType(),
1930 [bitWidth](
const APInt &a,
bool &castStatus) {
1931 return a.sext(bitWidth);
1939void arith::ExtSIOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
1940 MLIRContext *context) {
1941 patterns.
add<ExtSIOfExtUI>(context);
1944LogicalResult arith::ExtSIOp::verify() {
1954OpFoldResult arith::ExtFOp::fold(FoldAdaptor adaptor) {
1955 if (
auto truncFOp = getOperand().getDefiningOp<TruncFOp>()) {
1956 if (truncFOp.getOperand().getType() ==
getType()) {
1957 arith::FastMathFlags truncFMF =
1958 truncFOp.getFastmath().value_or(arith::FastMathFlags::none);
1959 bool isTruncContract =
1960 bitEnumContainsAll(truncFMF, arith::FastMathFlags::contract);
1961 arith::FastMathFlags extFMF =
1962 getFastmath().value_or(arith::FastMathFlags::none);
1963 bool isExtContract =
1964 bitEnumContainsAll(extFMF, arith::FastMathFlags::contract);
1965 if (isTruncContract && isExtContract) {
1966 return truncFOp.getOperand();
1972 const llvm::fltSemantics &targetSemantics = resElemType.getFloatSemantics();
1974 adaptor.getOperands(),
getType(),
1975 [&targetSemantics](
const APFloat &a,
bool &castStatus) {
2000 function_ref<std::optional<APFloat>(
const APFloat &,
const APFloat &)>
2003 if (isa_and_nonnull<ub::PoisonAttr>(inAttr))
2005 if (isa_and_nonnull<ub::PoisonAttr>(scaleAttr))
2008 if (!inAttr || !scaleAttr || !resultType)
2011 if (
auto inFloat = dyn_cast<FloatAttr>(inAttr)) {
2012 auto scaleFloat = dyn_cast<FloatAttr>(scaleAttr);
2015 std::optional<APFloat>
result =
2016 calculate(inFloat.getValue(), scaleFloat.getValue());
2019 return FloatAttr::get(resultType, *
result);
2022 auto inElements = dyn_cast<DenseFPElementsAttr>(inAttr);
2023 auto scaleElements = dyn_cast<DenseFPElementsAttr>(scaleAttr);
2024 auto shapedResultType = dyn_cast<ShapedType>(resultType);
2025 if (!inElements || !scaleElements || !shapedResultType ||
2026 !shapedResultType.hasStaticShape() ||
2027 inElements.getNumElements() != scaleElements.getNumElements())
2031 if (inElements.isSplat() && scaleElements.isSplat()) {
2032 std::optional<APFloat>
result =
2033 calculate(inElements.getSplatValue<APFloat>(),
2034 scaleElements.getSplatValue<APFloat>());
2041 results.reserve(inElements.getNumElements());
2042 for (
const auto &[in, scale] : llvm::zip_equal(inElements, scaleElements)) {
2043 std::optional<APFloat>
result = calculate(in, scale);
2046 results.push_back(*
result);
2059OpFoldResult arith::ScalingExtFOp::fold(FoldAdaptor adaptor) {
2067 const llvm::fltSemantics &resSemantics = resElemType.getFloatSemantics();
2069 adaptor.getIn(), adaptor.getScale(),
getType(),
2070 [&resSemantics](
const APFloat &in,
2071 const APFloat &scale) -> std::optional<APFloat> {
2075 return std::nullopt;
2082bool arith::ScalingExtFOp::areCastCompatible(
TypeRange inputs,
2087LogicalResult arith::ScalingExtFOp::verify() {
2095OpFoldResult arith::TruncIOp::fold(FoldAdaptor adaptor) {
2098 Value src = getOperand().getDefiningOp()->getOperand(0);
2103 if (llvm::cast<IntegerType>(srcType).getWidth() >
2104 llvm::cast<IntegerType>(dstType).getWidth()) {
2111 if (srcType == dstType)
2116 if (
auto truncOp = getOperand().getDefiningOp<arith::TruncIOp>()) {
2118 setOverflowFlags(getOverflowFlags() & truncOp.getOverflowFlags());
2119 setOperand(truncOp.getIn());
2124 unsigned bitWidth = llvm::cast<IntegerType>(resType).getWidth();
2126 adaptor.getOperands(),
getType(),
2127 [bitWidth](
const APInt &a,
bool &castStatus) {
2128 return a.trunc(bitWidth);
2136void arith::TruncIOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
2137 MLIRContext *context) {
2138 patterns.
add<NarrowExtremum<TruncIOp, ExtSIOp, MaxSIOp>,
2139 NarrowExtremum<TruncIOp, ExtSIOp, MinSIOp>,
2140 NarrowExtremum<TruncIOp, ExtUIOp, MaxUIOp>,
2141 NarrowExtremum<TruncIOp, ExtUIOp, MinUIOp>, TruncIExtSIToExtSI,
2142 TruncIExtUIToExtUI, TruncIShrSIToTrunciShrUI>(context);
2145LogicalResult arith::TruncIOp::verify() {
2155OpFoldResult arith::TruncFOp::fold(FoldAdaptor adaptor) {
2157 if (
auto extOp = getOperand().getDefiningOp<arith::ExtFOp>()) {
2158 Value src = extOp.getIn();
2160 auto intermediateType =
2164 if (llvm::APFloatBase::isLosslesslyConvertibleTo(
2165 srcType.getFloatSemantics(),
2166 intermediateType.getFloatSemantics())) {
2168 if (srcType.getWidth() > resElemType.getWidth()) {
2174 if (srcType == resElemType)
2179 const llvm::fltSemantics &targetSemantics = resElemType.getFloatSemantics();
2181 adaptor.getOperands(),
getType(),
2182 [
this, &targetSemantics](
const APFloat &a,
bool &castStatus) {
2183 llvm::RoundingMode llvmRoundingMode =
2185 FailureOr<APFloat>
result =
2195void arith::TruncFOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
2196 MLIRContext *context) {
2197 patterns.
add<NarrowExtremum<TruncFOp, ExtFOp, MaximumFOp>,
2198 NarrowExtremum<TruncFOp, ExtFOp, MaxNumFOp>,
2199 NarrowExtremum<TruncFOp, ExtFOp, MaximumNumFOp>,
2200 NarrowExtremum<TruncFOp, ExtFOp, MinimumFOp>,
2201 NarrowExtremum<TruncFOp, ExtFOp, MinNumFOp>,
2202 NarrowExtremum<TruncFOp, ExtFOp, MinimumNumFOp>,
2203 TruncFSIToFPToSIToFP, TruncFUIToFPToUIToFP>(context);
2210LogicalResult arith::TruncFOp::verify() {
2218OpFoldResult arith::ConvertFOp::fold(FoldAdaptor adaptor) {
2220 const llvm::fltSemantics &targetSemantics = resElemType.getFloatSemantics();
2222 adaptor.getOperands(),
getType(),
2223 [
this, &targetSemantics](
const APFloat &a,
bool &castStatus) {
2224 llvm::RoundingMode llvmRoundingMode =
2226 FailureOr<APFloat>
result =
2241 if (!srcType || !dstType)
2243 return srcType != dstType &&
2247LogicalResult arith::ConvertFOp::verify() {
2250 if (srcType == dstType)
2251 return emitError(
"result element type ")
2252 << dstType <<
" must be different from operand element type "
2254 if (srcType.getWidth() != dstType.getWidth())
2255 return emitError(
"result element type ")
2256 << dstType <<
" must have the same bitwidth as operand element type "
2265OpFoldResult arith::ScalingTruncFOp::fold(FoldAdaptor adaptor) {
2274 const llvm::fltSemantics &inSemantics = inElemType.getFloatSemantics();
2275 const llvm::fltSemantics &resSemantics = resElemType.getFloatSemantics();
2276 llvm::RoundingMode roundingMode =
2279 adaptor.getIn(), adaptor.getScale(),
getType(),
2280 [&](
const APFloat &in,
const APFloat &scale) -> std::optional<APFloat> {
2283 return std::nullopt;
2284 APFloat quotient(in);
2286 FailureOr<APFloat>
result =
2289 return std::nullopt;
2294bool arith::ScalingTruncFOp::areCastCompatible(
TypeRange inputs,
2299LogicalResult arith::ScalingTruncFOp::verify() {
2307void arith::AndIOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
2308 MLIRContext *context) {
2309 patterns.
add<AndIAndIConstant, AndOfExtUI, AndOfExtSI>(context);
2316void arith::OrIOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
2317 MLIRContext *context) {
2318 patterns.
add<OrIOrIConstant, OrOfExtUI, OrOfExtSI>(context);
2325template <
typename From,
typename To>
2333 return srcType && dstType;
2344OpFoldResult arith::UIToFPOp::fold(FoldAdaptor adaptor) {
2347 adaptor.getOperands(),
getType(),
2348 [&resEleType](
const APInt &a,
bool &castStatus) {
2349 FloatType floatTy = llvm::cast<FloatType>(resEleType);
2350 APFloat apf(floatTy.getFloatSemantics(),
2351 APInt::getZero(floatTy.getWidth()));
2352 apf.convertFromAPInt(a,
false,
2353 APFloat::rmNearestTiesToEven);
2358void arith::UIToFPOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
2359 MLIRContext *context) {
2360 patterns.
add<UIToFPOfExtUI>(context);
2371OpFoldResult arith::SIToFPOp::fold(FoldAdaptor adaptor) {
2374 adaptor.getOperands(),
getType(),
2375 [&resEleType](
const APInt &a,
bool &castStatus) {
2376 FloatType floatTy = llvm::cast<FloatType>(resEleType);
2377 APFloat apf(floatTy.getFloatSemantics(),
2378 APInt::getZero(floatTy.getWidth()));
2379 if (a.isNegative() &&
2380 !APFloat::semanticsHasSignedRepr(floatTy.getFloatSemantics())) {
2384 apf.convertFromAPInt(a,
true,
2385 APFloat::rmNearestTiesToEven);
2390void arith::SIToFPOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
2391 MLIRContext *context) {
2392 patterns.
add<SIToFPOfExtSI, SIToFPOfExtUI>(context);
2403OpFoldResult arith::FPToUIOp::fold(FoldAdaptor adaptor) {
2405 unsigned bitWidth = llvm::cast<IntegerType>(resType).getWidth();
2407 adaptor.getOperands(),
getType(),
2408 [&bitWidth](
const APFloat &a,
bool &castStatus) {
2410 APSInt api(bitWidth,
true);
2411 castStatus = APFloat::opInvalidOp !=
2412 a.convertToInteger(api, APFloat::rmTowardZero, &ignored);
2425OpFoldResult arith::FPToSIOp::fold(FoldAdaptor adaptor) {
2427 unsigned bitWidth = llvm::cast<IntegerType>(resType).getWidth();
2429 adaptor.getOperands(),
getType(),
2430 [&bitWidth](
const APFloat &a,
bool &castStatus) {
2432 APSInt api(bitWidth,
false);
2433 castStatus = APFloat::opInvalidOp !=
2434 a.convertToInteger(api, APFloat::rmTowardZero, &ignored);
2448 return intTy.getWidth();
2449 return IndexType::kInternalStorageBitWidth;
2458 if (!srcType || !dstType)
2462 (srcType.isSignlessInteger() && dstType.
isIndex());
2465bool arith::IndexCastOp::areCastCompatible(
TypeRange inputs,
2470OpFoldResult arith::IndexCastOp::fold(FoldAdaptor adaptor) {
2472 unsigned resultBitwidth = 64;
2474 resultBitwidth = intTy.getWidth();
2477 adaptor.getOperands(),
getType(),
2478 [resultBitwidth](
const APInt &a,
bool & ) {
2479 return a.sextOrTrunc(resultBitwidth);
2486 if (
auto inner = getOperand().getDefiningOp<arith::IndexCastOp>()) {
2487 Value x = inner.getOperand();
2496void arith::IndexCastOp::getCanonicalizationPatterns(
2497 RewritePatternSet &patterns, MLIRContext *context) {
2498 patterns.
add<IndexCastOfExtSI>(context);
2505bool arith::IndexCastUIOp::areCastCompatible(
TypeRange inputs,
2510OpFoldResult arith::IndexCastUIOp::fold(FoldAdaptor adaptor) {
2512 unsigned resultBitwidth = 64;
2514 resultBitwidth = intTy.getWidth();
2517 adaptor.getOperands(),
getType(),
2518 [resultBitwidth](
const APInt &a,
bool & ) {
2519 return a.zextOrTrunc(resultBitwidth);
2526 if (
auto inner = getOperand().getDefiningOp<arith::IndexCastUIOp>()) {
2527 Value x = inner.getOperand();
2536void arith::IndexCastUIOp::getCanonicalizationPatterns(
2537 RewritePatternSet &patterns, MLIRContext *context) {
2538 patterns.
add<IndexCastUIOfExtUI>(context);
2551 if (!srcType || !dstType)
2557OpFoldResult arith::BitcastOp::fold(FoldAdaptor adaptor) {
2559 auto operand = adaptor.getIn();
2564 if (
auto denseAttr = dyn_cast_or_null<DenseElementsAttr>(operand))
2565 return denseAttr.bitcast(llvm::cast<ShapedType>(resType).
getElementType());
2567 if (llvm::isa<ShapedType>(resType))
2575 if (!llvm::isa<FloatAttr, IntegerAttr>(operand))
2578 APInt bits = llvm::isa<FloatAttr>(operand)
2579 ? llvm::cast<FloatAttr>(operand).getValue().bitcastToAPInt()
2580 : llvm::cast<IntegerAttr>(operand).getValue();
2582 "trying to fold on broken IR: operands have incompatible types");
2584 if (
auto resFloatType = dyn_cast<FloatType>(resType))
2585 return FloatAttr::get(resType,
2586 APFloat(resFloatType.getFloatSemantics(), bits));
2587 return IntegerAttr::get(resType, bits);
2590void arith::BitcastOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
2591 MLIRContext *context) {
2592 patterns.
add<BitcastOfBitcast>(context);
2602 const APInt &lhs,
const APInt &rhs) {
2603 switch (predicate) {
2604 case arith::CmpIPredicate::eq:
2606 case arith::CmpIPredicate::ne:
2608 case arith::CmpIPredicate::slt:
2609 return lhs.slt(rhs);
2610 case arith::CmpIPredicate::sle:
2611 return lhs.sle(rhs);
2612 case arith::CmpIPredicate::sgt:
2613 return lhs.sgt(rhs);
2614 case arith::CmpIPredicate::sge:
2615 return lhs.sge(rhs);
2616 case arith::CmpIPredicate::ult:
2617 return lhs.ult(rhs);
2618 case arith::CmpIPredicate::ule:
2619 return lhs.ule(rhs);
2620 case arith::CmpIPredicate::ugt:
2621 return lhs.ugt(rhs);
2622 case arith::CmpIPredicate::uge:
2623 return lhs.uge(rhs);
2625 llvm_unreachable(
"unknown cmpi predicate kind");
2630 switch (predicate) {
2631 case arith::CmpIPredicate::eq:
2632 case arith::CmpIPredicate::sle:
2633 case arith::CmpIPredicate::sge:
2634 case arith::CmpIPredicate::ule:
2635 case arith::CmpIPredicate::uge:
2637 case arith::CmpIPredicate::ne:
2638 case arith::CmpIPredicate::slt:
2639 case arith::CmpIPredicate::sgt:
2640 case arith::CmpIPredicate::ult:
2641 case arith::CmpIPredicate::ugt:
2644 llvm_unreachable(
"unknown cmpi predicate kind");
2648 if (
auto intType = dyn_cast<IntegerType>(t)) {
2649 return intType.getWidth();
2651 if (
auto vectorIntType = dyn_cast<VectorType>(t)) {
2652 return llvm::cast<IntegerType>(vectorIntType.getElementType()).getWidth();
2654 return std::nullopt;
2657OpFoldResult arith::CmpIOp::fold(FoldAdaptor adaptor) {
2659 if (getLhs() == getRhs()) {
2665 if (
auto extOp = getLhs().getDefiningOp<ExtSIOp>()) {
2667 std::optional<int64_t> integerWidth =
2669 if (integerWidth && integerWidth.value() == 1 &&
2670 getPredicate() == arith::CmpIPredicate::ne)
2671 return extOp.getOperand();
2673 if (
auto extOp = getLhs().getDefiningOp<ExtUIOp>()) {
2675 std::optional<int64_t> integerWidth =
2677 if (integerWidth && integerWidth.value() == 1 &&
2678 getPredicate() == arith::CmpIPredicate::ne)
2679 return extOp.getOperand();
2684 getPredicate() == arith::CmpIPredicate::ne)
2691 getPredicate() == arith::CmpIPredicate::eq)
2696 if (adaptor.getLhs() && !adaptor.getRhs()) {
2698 using Pred = CmpIPredicate;
2699 const std::pair<Pred, Pred> invPreds[] = {
2700 {Pred::slt, Pred::sgt}, {Pred::sgt, Pred::slt}, {Pred::sle, Pred::sge},
2701 {Pred::sge, Pred::sle}, {Pred::ult, Pred::ugt}, {Pred::ugt, Pred::ult},
2702 {Pred::ule, Pred::uge}, {Pred::uge, Pred::ule}, {Pred::eq, Pred::eq},
2703 {Pred::ne, Pred::ne},
2705 Pred origPred = getPredicate();
2706 for (
auto pred : invPreds) {
2707 if (origPred == pred.first) {
2708 setPredicate(pred.second);
2709 Value
lhs = getLhs();
2710 Value
rhs = getRhs();
2711 getLhsMutable().assign(
rhs);
2712 getRhsMutable().assign(
lhs);
2716 llvm_unreachable(
"unknown cmpi predicate kind");
2721 if (
auto lhs = dyn_cast_if_present<TypedAttr>(adaptor.getLhs())) {
2724 [pred = getPredicate()](
const APInt &
lhs,
const APInt &
rhs) {
2733void arith::CmpIOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
2734 MLIRContext *context) {
2735 patterns.
insert<CmpIExtSI, CmpIExtUI>(context);
2745 const APFloat &lhs,
const APFloat &rhs) {
2746 auto cmpResult = lhs.compare(rhs);
2747 switch (predicate) {
2748 case arith::CmpFPredicate::AlwaysFalse:
2750 case arith::CmpFPredicate::OEQ:
2751 return cmpResult == APFloat::cmpEqual;
2752 case arith::CmpFPredicate::OGT:
2753 return cmpResult == APFloat::cmpGreaterThan;
2754 case arith::CmpFPredicate::OGE:
2755 return cmpResult == APFloat::cmpGreaterThan ||
2756 cmpResult == APFloat::cmpEqual;
2757 case arith::CmpFPredicate::OLT:
2758 return cmpResult == APFloat::cmpLessThan;
2759 case arith::CmpFPredicate::OLE:
2760 return cmpResult == APFloat::cmpLessThan || cmpResult == APFloat::cmpEqual;
2761 case arith::CmpFPredicate::ONE:
2762 return cmpResult != APFloat::cmpUnordered && cmpResult != APFloat::cmpEqual;
2763 case arith::CmpFPredicate::ORD:
2764 return cmpResult != APFloat::cmpUnordered;
2765 case arith::CmpFPredicate::UEQ:
2766 return cmpResult == APFloat::cmpUnordered || cmpResult == APFloat::cmpEqual;
2767 case arith::CmpFPredicate::UGT:
2768 return cmpResult == APFloat::cmpUnordered ||
2769 cmpResult == APFloat::cmpGreaterThan;
2770 case arith::CmpFPredicate::UGE:
2771 return cmpResult == APFloat::cmpUnordered ||
2772 cmpResult == APFloat::cmpGreaterThan ||
2773 cmpResult == APFloat::cmpEqual;
2774 case arith::CmpFPredicate::ULT:
2775 return cmpResult == APFloat::cmpUnordered ||
2776 cmpResult == APFloat::cmpLessThan;
2777 case arith::CmpFPredicate::ULE:
2778 return cmpResult == APFloat::cmpUnordered ||
2779 cmpResult == APFloat::cmpLessThan || cmpResult == APFloat::cmpEqual;
2780 case arith::CmpFPredicate::UNE:
2781 return cmpResult != APFloat::cmpEqual;
2782 case arith::CmpFPredicate::UNO:
2783 return cmpResult == APFloat::cmpUnordered;
2784 case arith::CmpFPredicate::AlwaysTrue:
2787 llvm_unreachable(
"unknown cmpf predicate kind");
2791 auto lhs = dyn_cast_if_present<FloatAttr>(adaptor.getLhs());
2792 auto rhs = dyn_cast_if_present<FloatAttr>(adaptor.getRhs());
2795 if (lhs && lhs.getValue().isNaN())
2797 if (rhs && rhs.getValue().isNaN())
2808class CmpFIntToFPConst final :
public OpRewritePattern<CmpFOp> {
2812 static CmpIPredicate convertToIntegerPredicate(CmpFPredicate pred,
2814 using namespace arith;
2816 case CmpFPredicate::UEQ:
2817 case CmpFPredicate::OEQ:
2818 return CmpIPredicate::eq;
2819 case CmpFPredicate::UGT:
2820 case CmpFPredicate::OGT:
2821 return isUnsigned ? CmpIPredicate::ugt : CmpIPredicate::sgt;
2822 case CmpFPredicate::UGE:
2823 case CmpFPredicate::OGE:
2824 return isUnsigned ? CmpIPredicate::uge : CmpIPredicate::sge;
2825 case CmpFPredicate::ULT:
2826 case CmpFPredicate::OLT:
2827 return isUnsigned ? CmpIPredicate::ult : CmpIPredicate::slt;
2828 case CmpFPredicate::ULE:
2829 case CmpFPredicate::OLE:
2830 return isUnsigned ? CmpIPredicate::ule : CmpIPredicate::sle;
2831 case CmpFPredicate::UNE:
2832 case CmpFPredicate::ONE:
2833 return CmpIPredicate::ne;
2835 llvm_unreachable(
"Unexpected predicate!");
2839 LogicalResult matchAndRewrite(CmpFOp op,
2840 PatternRewriter &rewriter)
const override {
2845 const APFloat &
rhs = flt.getValue();
2853 FloatType floatTy = llvm::cast<FloatType>(op.getRhs().getType());
2854 int mantissaWidth = floatTy.getFPMantissaWidth();
2855 if (mantissaWidth <= 0)
2861 if (
auto si = op.getLhs().getDefiningOp<SIToFPOp>()) {
2863 intVal = si.getIn();
2864 }
else if (
auto ui = op.getLhs().getDefiningOp<UIToFPOp>()) {
2866 intVal = ui.getIn();
2873 auto intTy = llvm::cast<IntegerType>(intVal.
getType());
2874 auto intWidth = intTy.getWidth();
2877 auto valueBits = isUnsigned ? intWidth : (intWidth - 1);
2879 const llvm::fltSemantics &semantics = floatTy.getFloatSemantics();
2883 if (!APFloat::semanticsHasZero(semantics))
2888 if (!isUnsigned && !APFloat::semanticsHasSignedRepr(semantics))
2891 if (!APFloat::semanticsHasInf(semantics)) {
2902 if (APFloat::semanticsMaxExponent(semantics) <
2903 static_cast<int>(valueBits))
2910 if ((
int)intWidth > mantissaWidth) {
2912 int exponent = ilogb(
rhs);
2913 if (exponent == APFloat::IEK_Inf) {
2914 int maxExponent = ilogb(APFloat::getLargest(
rhs.getSemantics()));
2915 if (maxExponent <
static_cast<int>(valueBits)) {
2923 if (mantissaWidth <= exponent && exponent <= (
int)valueBits) {
2932 switch (op.getPredicate()) {
2933 case CmpFPredicate::AlwaysTrue:
2934 case CmpFPredicate::ORD:
2939 case CmpFPredicate::AlwaysFalse:
2940 case CmpFPredicate::UNO:
2946 pred = convertToIntegerPredicate(op.getPredicate(), isUnsigned);
2953 APFloat signedMax(
rhs.getSemantics());
2954 signedMax.convertFromAPInt(APInt::getSignedMaxValue(intWidth),
true,
2955 APFloat::rmNearestTiesToEven);
2956 if (signedMax <
rhs) {
2957 if (pred == CmpIPredicate::ne || pred == CmpIPredicate::slt ||
2958 pred == CmpIPredicate::sle)
2969 APFloat unsignedMax(
rhs.getSemantics());
2970 unsignedMax.convertFromAPInt(APInt::getMaxValue(intWidth),
false,
2971 APFloat::rmNearestTiesToEven);
2972 if (unsignedMax <
rhs) {
2973 if (pred == CmpIPredicate::ne || pred == CmpIPredicate::ult ||
2974 pred == CmpIPredicate::ule)
2986 APFloat signedMin(
rhs.getSemantics());
2987 signedMin.convertFromAPInt(APInt::getSignedMinValue(intWidth),
true,
2988 APFloat::rmNearestTiesToEven);
2989 if (signedMin >
rhs) {
2990 if (pred == CmpIPredicate::ne || pred == CmpIPredicate::sgt ||
2991 pred == CmpIPredicate::sge)
3001 APFloat unsignedMin(
rhs.getSemantics());
3002 unsignedMin.convertFromAPInt(APInt::getMinValue(intWidth),
false,
3003 APFloat::rmNearestTiesToEven);
3004 if (unsignedMin >
rhs) {
3005 if (pred == CmpIPredicate::ne || pred == CmpIPredicate::ugt ||
3006 pred == CmpIPredicate::uge)
3021 APSInt rhsInt(intWidth, isUnsigned);
3022 if (APFloat::opInvalidOp ==
3023 rhs.convertToInteger(rhsInt, APFloat::rmTowardZero, &ignored)) {
3029 if (!
rhs.isZero()) {
3030 APFloat apf(floatTy.getFloatSemantics(),
3031 APInt::getZero(floatTy.getWidth()));
3032 apf.convertFromAPInt(rhsInt, !isUnsigned, APFloat::rmNearestTiesToEven);
3034 bool equal = apf ==
rhs;
3040 case CmpIPredicate::ne:
3044 case CmpIPredicate::eq:
3048 case CmpIPredicate::ule:
3051 if (
rhs.isNegative()) {
3057 case CmpIPredicate::sle:
3060 if (
rhs.isNegative())
3061 pred = CmpIPredicate::slt;
3063 case CmpIPredicate::ult:
3066 if (
rhs.isNegative()) {
3071 pred = CmpIPredicate::ule;
3073 case CmpIPredicate::slt:
3076 if (!
rhs.isNegative())
3077 pred = CmpIPredicate::sle;
3079 case CmpIPredicate::ugt:
3082 if (
rhs.isNegative()) {
3088 case CmpIPredicate::sgt:
3091 if (
rhs.isNegative())
3092 pred = CmpIPredicate::sge;
3094 case CmpIPredicate::uge:
3097 if (
rhs.isNegative()) {
3102 pred = CmpIPredicate::ugt;
3104 case CmpIPredicate::sge:
3107 if (!
rhs.isNegative())
3108 pred = CmpIPredicate::sgt;
3118 ConstantOp::create(rewriter, op.getLoc(), intVal.getType(),
3125void arith::CmpFOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
3126 MLIRContext *context) {
3127 patterns.
insert<CmpFIntToFPConst>(context);
3136struct SelectToExtUI :
public OpRewritePattern<arith::SelectOp> {
3139 LogicalResult matchAndRewrite(arith::SelectOp op,
3140 PatternRewriter &rewriter)
const override {
3142 if (!llvm::isa<IntegerType>(op.getType()) || op.getType().isInteger(1))
3158 arith::XOrIOp::create(
3159 rewriter, op.getLoc(), op.getCondition(),
3161 op.getCondition().getType(), 1)));
3220 Operation *lhs = op.getTrueValue().getDefiningOp();
3221 Operation *rhs = op.getFalseValue().getDefiningOp();
3222 if (!lhs || !rhs || lhs == rhs)
3229 if (isa<arith::SelectOp>(lhs))
3232 for (
Operation *producer : {lhs, rhs}) {
3236 if (producer->getBlock() != op->getBlock())
3241 if (producer->getNumResults() != 1 || !producer->hasOneUse() ||
3242 producer->getNumRegions() != 0 || producer->getNumSuccessors() != 0 ||
3257 Type conditionType = op.getCondition().getType();
3258 for (
auto [a,
b] : llvm::zip(lhs->getOperands(), rhs->getOperands())) {
3262 operands.push_back(a);
3266 (!isa<VectorType, TensorType>(a.getType()) ||
3267 cast<ShapedType>(a.getType()).clone(rewriter.
getI1Type()) !=
3270 for (
Operation *created : llvm::reverse(createdSelects))
3276 auto [it,
inserted] = selected.try_emplace(std::make_pair(a,
b));
3278 auto select = arith::SelectOp::create(rewriter, op.getLoc(),
3279 op.getCondition(), a,
b);
3280 it->second = select;
3281 createdSelects.push_back(select);
3283 operands.push_back(it->second);
3293void arith::SelectOp::getCanonicalizationPatterns(RewritePatternSet &results,
3294 MLIRContext *context) {
3295 results.
add<RedundantSelectFalse, RedundantSelectTrue, SelectNotCond,
3296 SelectI1ToNot, SelectCmpISgeToMaxSI, SelectCmpISgeToMinSI,
3297 SelectCmpISgtToMaxSI, SelectCmpISgtToMinSI, SelectCmpISleToMaxSI,
3298 SelectCmpISleToMinSI, SelectCmpISltToMaxSI, SelectCmpISltToMinSI,
3299 SelectCmpIUgeToMaxUI, SelectCmpIUgeToMinUI, SelectCmpIUgtToMaxUI,
3300 SelectCmpIUgtToMinUI, SelectCmpIUleToMaxUI, SelectCmpIUleToMinUI,
3301 SelectCmpIUltToMaxUI, SelectCmpIUltToMinUI, SelectToExtUI>(
3303 results.
add<SelectCommonElementwiseOp>(context);
3306OpFoldResult arith::SelectOp::fold(FoldAdaptor adaptor) {
3307 Value trueVal = getTrueValue();
3308 Value falseVal = getFalseValue();
3309 if (trueVal == falseVal)
3312 Value condition = getCondition();
3330 if (
getType().isSignlessInteger(1) &&
3336 auto pred = cmp.getPredicate();
3337 if (pred == arith::CmpIPredicate::eq || pred == arith::CmpIPredicate::ne) {
3338 auto cmpLhs = cmp.getLhs();
3339 auto cmpRhs = cmp.getRhs();
3347 if ((cmpLhs == trueVal && cmpRhs == falseVal) ||
3348 (cmpRhs == trueVal && cmpLhs == falseVal))
3349 return pred == arith::CmpIPredicate::ne ? trueVal : falseVal;
3356 dyn_cast_if_present<DenseElementsAttr>(adaptor.getCondition())) {
3358 assert(cond.getType().hasStaticShape() &&
3359 "DenseElementsAttr must have static shape");
3361 dyn_cast_if_present<DenseElementsAttr>(adaptor.getTrueValue())) {
3363 dyn_cast_if_present<DenseElementsAttr>(adaptor.getFalseValue())) {
3364 SmallVector<Attribute> results;
3365 results.reserve(
static_cast<size_t>(cond.getNumElements()));
3366 auto condVals = llvm::make_range(cond.value_begin<BoolAttr>(),
3367 cond.value_end<BoolAttr>());
3368 auto lhsVals = llvm::make_range(
lhs.value_begin<Attribute>(),
3369 lhs.value_end<Attribute>());
3370 auto rhsVals = llvm::make_range(
rhs.value_begin<Attribute>(),
3371 rhs.value_end<Attribute>());
3373 for (
auto [condVal, lhsVal, rhsVal] :
3374 llvm::zip_equal(condVals, lhsVals, rhsVals))
3375 results.push_back(condVal.getValue() ? lhsVal : rhsVal);
3385ParseResult SelectOp::parse(OpAsmParser &parser, OperationState &
result) {
3386 Type conditionType, resultType;
3387 SmallVector<OpAsmParser::UnresolvedOperand, 3> operands;
3395 conditionType = resultType;
3402 result.addTypes(resultType);
3404 {conditionType, resultType, resultType},
3408void arith::SelectOp::print(OpAsmPrinter &p) {
3409 p <<
" " << getOperands();
3412 if (ShapedType condType = dyn_cast<ShapedType>(getCondition().
getType()))
3413 p << condType <<
", ";
3417LogicalResult arith::SelectOp::verify() {
3418 Type conditionType = getCondition().getType();
3425 if (!llvm::isa<TensorType, VectorType>(resultType))
3426 return emitOpError() <<
"expected condition to be a signless i1, but got "
3429 if (conditionType != shapedConditionType) {
3430 return emitOpError() <<
"expected condition type to have the same shape "
3431 "as the result type, expected "
3432 << shapedConditionType <<
", but got "
3441OpFoldResult arith::ShLIOp::fold(FoldAdaptor adaptor) {
3455 bool bounded =
false;
3457 adaptor.getOperands(), [&](
const APInt &a,
const APInt &
b) {
3458 bounded = b.ult(b.getBitWidth());
3461 return bounded ?
result : Attribute();
3468OpFoldResult arith::ShRUIOp::fold(FoldAdaptor adaptor) {
3483 if (getLhs() == getRhs())
3486 bool bounded =
false;
3488 adaptor.getOperands(), [&](
const APInt &a,
const APInt &
b) {
3489 bounded = b.ult(b.getBitWidth());
3492 return bounded ?
result : Attribute();
3499OpFoldResult arith::ShRSIOp::fold(FoldAdaptor adaptor) {
3514 if (getLhs() == getRhs())
3522 bool bounded =
false;
3524 adaptor.getOperands(), [&](
const APInt &a,
const APInt &
b) {
3525 bounded = b.ult(b.getBitWidth());
3528 return bounded ?
result : Attribute();
3538 bool useOnlyFiniteValue) {
3540 case AtomicRMWKind::maximumf: {
3541 const llvm::fltSemantics &semantic =
3542 llvm::cast<FloatType>(resultType).getFloatSemantics();
3543 APFloat identity = useOnlyFiniteValue
3544 ? APFloat::getLargest(semantic,
true)
3545 : APFloat::getInf(semantic,
true);
3548 case AtomicRMWKind::maxnumf: {
3549 const llvm::fltSemantics &semantic =
3550 llvm::cast<FloatType>(resultType).getFloatSemantics();
3551 APFloat identity = useOnlyFiniteValue
3552 ? APFloat::getLargest(semantic,
true)
3553 : APFloat::getNaN(semantic,
true);
3556 case AtomicRMWKind::addf:
3557 case AtomicRMWKind::addi:
3558 case AtomicRMWKind::maxu:
3559 case AtomicRMWKind::ori:
3560 case AtomicRMWKind::xori:
3562 case AtomicRMWKind::andi:
3565 APInt::getAllOnes(llvm::cast<IntegerType>(resultType).getWidth()));
3566 case AtomicRMWKind::maxs:
3568 resultType, APInt::getSignedMinValue(
3569 llvm::cast<IntegerType>(resultType).getWidth()));
3570 case AtomicRMWKind::minimumf: {
3571 const llvm::fltSemantics &semantic =
3572 llvm::cast<FloatType>(resultType).getFloatSemantics();
3573 APFloat identity = useOnlyFiniteValue
3574 ? APFloat::getLargest(semantic,
false)
3575 : APFloat::getInf(semantic,
false);
3579 case AtomicRMWKind::minnumf: {
3580 const llvm::fltSemantics &semantic =
3581 llvm::cast<FloatType>(resultType).getFloatSemantics();
3582 APFloat identity = useOnlyFiniteValue
3583 ? APFloat::getLargest(semantic,
false)
3584 : APFloat::getNaN(semantic,
false);
3587 case AtomicRMWKind::mins:
3589 resultType, APInt::getSignedMaxValue(
3590 llvm::cast<IntegerType>(resultType).getWidth()));
3591 case AtomicRMWKind::minu:
3594 APInt::getMaxValue(llvm::cast<IntegerType>(resultType).getWidth()));
3595 case AtomicRMWKind::muli:
3597 case AtomicRMWKind::mulf:
3600 case AtomicRMWKind::assign:
3609 std::optional<AtomicRMWKind> maybeKind =
3612 .Case([](arith::AddFOp op) {
return AtomicRMWKind::addf; })
3613 .Case([](arith::MulFOp op) {
return AtomicRMWKind::mulf; })
3614 .Case([](arith::MaximumFOp op) {
return AtomicRMWKind::maximumf; })
3615 .Case([](arith::MinimumFOp op) {
return AtomicRMWKind::minimumf; })
3616 .Case([](arith::MaxNumFOp op) {
return AtomicRMWKind::maxnumf; })
3617 .Case([](arith::MinNumFOp op) {
return AtomicRMWKind::minnumf; })
3619 .Case([](arith::AddIOp op) {
return AtomicRMWKind::addi; })
3620 .Case([](arith::OrIOp op) {
return AtomicRMWKind::ori; })
3621 .Case([](arith::XOrIOp op) {
return AtomicRMWKind::xori; })
3622 .Case([](arith::AndIOp op) {
return AtomicRMWKind::andi; })
3623 .Case([](arith::MaxUIOp op) {
return AtomicRMWKind::maxu; })
3624 .Case([](arith::MinUIOp op) {
return AtomicRMWKind::minu; })
3625 .Case([](arith::MaxSIOp op) {
return AtomicRMWKind::maxs; })
3626 .Case([](arith::MinSIOp op) {
return AtomicRMWKind::mins; })
3627 .Case([](arith::MulIOp op) {
return AtomicRMWKind::muli; })
3628 .Default(std::nullopt);
3630 return std::nullopt;
3633 bool useOnlyFiniteValue =
false;
3634 auto fmfOpInterface = dyn_cast<ArithFastMathInterface>(op);
3635 if (fmfOpInterface) {
3636 arith::FastMathFlagsAttr fmfAttr = fmfOpInterface.getFastMathFlagsAttr();
3637 useOnlyFiniteValue =
3638 bitEnumContainsAny(fmfAttr.getValue(), arith::FastMathFlags::ninf);
3639 if (*maybeKind == AtomicRMWKind::maxnumf ||
3640 *maybeKind == AtomicRMWKind::minnumf) {
3641 if (bitEnumContainsAny(fmfAttr.getValue(), arith::FastMathFlags::nnan)) {
3642 *maybeKind = *maybeKind == AtomicRMWKind::maxnumf
3643 ? AtomicRMWKind::maximumf
3644 : AtomicRMWKind::minimumf;
3646 useOnlyFiniteValue =
false;
3656 useOnlyFiniteValue);
3662 bool useOnlyFiniteValue) {
3664 useOnlyFiniteValue))
3665 return arith::ConstantOp::create(builder, loc, attr);
3674 case AtomicRMWKind::addf:
3675 return arith::AddFOp::create(builder, loc, lhs, rhs);
3676 case AtomicRMWKind::addi:
3677 return arith::AddIOp::create(builder, loc, lhs, rhs);
3678 case AtomicRMWKind::mulf:
3679 return arith::MulFOp::create(builder, loc, lhs, rhs);
3680 case AtomicRMWKind::muli:
3681 return arith::MulIOp::create(builder, loc, lhs, rhs);
3682 case AtomicRMWKind::maximumf:
3683 return arith::MaximumFOp::create(builder, loc, lhs, rhs);
3684 case AtomicRMWKind::minimumf:
3685 return arith::MinimumFOp::create(builder, loc, lhs, rhs);
3686 case AtomicRMWKind::maxnumf:
3687 return arith::MaxNumFOp::create(builder, loc, lhs, rhs);
3688 case AtomicRMWKind::minnumf:
3689 return arith::MinNumFOp::create(builder, loc, lhs, rhs);
3690 case AtomicRMWKind::maxs:
3691 return arith::MaxSIOp::create(builder, loc, lhs, rhs);
3692 case AtomicRMWKind::mins:
3693 return arith::MinSIOp::create(builder, loc, lhs, rhs);
3694 case AtomicRMWKind::maxu:
3695 return arith::MaxUIOp::create(builder, loc, lhs, rhs);
3696 case AtomicRMWKind::minu:
3697 return arith::MinUIOp::create(builder, loc, lhs, rhs);
3698 case AtomicRMWKind::ori:
3699 return arith::OrIOp::create(builder, loc, lhs, rhs);
3700 case AtomicRMWKind::andi:
3701 return arith::AndIOp::create(builder, loc, lhs, rhs);
3702 case AtomicRMWKind::xori:
3703 return arith::XOrIOp::create(builder, loc, lhs, rhs);
3705 case AtomicRMWKind::assign:
3716#define GET_OP_CLASSES
3717#include "mlir/Dialect/Arith/IR/ArithOps.cpp.inc"
3723#include "mlir/Dialect/Arith/IR/ArithOpsEnums.cpp.inc"
static Speculation::Speculatability getDivUISpeculatability(Value divisor)
Returns whether an unsigned division by divisor is speculatable.
static bool checkWidthChangeCast(TypeRange inputs, TypeRange outputs)
Validate a cast that changes the width of a type.
static IntegerAttr mulIntegerAttrs(PatternRewriter &builder, Value res, Attribute lhs, Attribute rhs)
static IntegerOverflowFlagsAttr mergeOverflowFlags(IntegerOverflowFlagsAttr val1, IntegerOverflowFlagsAttr val2)
static Value foldIdempotentOfSameOp(OpTy op)
Fold op(a, op(a, b)) to op(a, b) for an associative, commutative and idempotent op (e....
static constexpr llvm::RoundingMode kDefaultRoundingMode
Default rounding mode according to default LLVM floating-point environment.
static Type getTypeIfLike(Type type)
Get allowed underlying types for vectors and tensors.
static bool applyCmpPredicateToEqualOperands(arith::CmpIPredicate predicate)
Returns true if the predicate is true for two equal operands.
static FailureOr< APFloat > convertFloatValue(APFloat sourceValue, const llvm::fltSemantics &targetSemantics, llvm::RoundingMode roundingMode=kDefaultRoundingMode)
Attempts to convert sourceValue to an APFloat value with targetSemantics and roundingMode,...
static Attribute foldScalingCastOp(Attribute inAttr, Attribute scaleAttr, Type resultType, function_ref< std::optional< APFloat >(const APFloat &, const APFloat &)> calculate)
Fold calculate element-wise over the operands of a scaling cast op.
static Value foldDivMul(Value lhs, Value rhs, arith::IntegerOverflowFlags ovfFlags)
Fold (a * b) / b -> a
static bool hasSameEncoding(Type typeA, Type typeB)
Return false if both types are ranked tensor with mismatching encoding.
static llvm::RoundingMode convertArithRoundingModeToLLVMIR(std::optional< RoundingMode > roundingMode)
Equivalent to convertRoundingModeToLLVM(convertArithRoundingModeToLLVM(roundingMode)).
static Type getUnderlyingType(Type type, type_list< ShapedTypes... >, type_list< ElementTypes... >)
Returns a non-null type only if the provided type is one of the allowed types or one of the allowed s...
static std::optional< int64_t > getIntegerWidth(Type t)
APInt(APInt::*)(const APInt &, bool &) const OverflowCheckedBinaryOp
static Speculation::Speculatability getDivSISpeculatability(Value divisor)
Returns whether a signed division by divisor is speculatable.
static IntegerAttr orIntegerAttrs(PatternRewriter &builder, Value res, Attribute lhs, Attribute rhs)
static IntegerAttr addIntegerAttrs(PatternRewriter &builder, Value res, Attribute lhs, Attribute rhs)
static Attribute getBoolAttribute(Type type, bool value)
static bool areIndexCastCompatible(TypeRange inputs, TypeRange outputs)
static bool isFoldableScalingScale(Value scale)
Only scales that already are f8E8M0FNU fold.
static bool checkIntFloatCast(TypeRange inputs, TypeRange outputs)
static LogicalResult verifyExtOp(Op op)
static IntegerAttr subIntegerAttrs(PatternRewriter &builder, Value res, Attribute lhs, Attribute rhs)
static Attribute getIntegerAttrOfType(Type type, int64_t value)
Return a scalar or splat integer attribute of type (an integer/index type or a shaped type thereof) h...
static IntegerAttr andIntegerAttrs(PatternRewriter &builder, Value res, Attribute lhs, Attribute rhs)
static int64_t getScalarOrElementWidth(Type type)
static Type getTypeIfLikeOrMemRef(Type type)
Get allowed underlying types for vectors, tensors, and memrefs.
static Type getI1SameShape(Type type)
Return the type of the same shape (scalar, vector or tensor) containing i1.
static bool areValidCastInputsAndOutputs(TypeRange inputs, TypeRange outputs)
static IntegerOverflowFlagsAttr mergeOverflowFlagsForReassociation(IntegerOverflowFlagsAttr val1, IntegerOverflowFlagsAttr val2, Attribute lhs, Attribute rhs, OverflowCheckedBinaryOp signedOp, OverflowCheckedBinaryOp unsignedOp)
static IntegerAttr xorIntegerAttrs(PatternRewriter &builder, Value res, Attribute lhs, Attribute rhs)
static APInt calculateUnsignedBorrow(const APInt &lhs, const APInt &rhs)
static bool isExactIntToFPCast(Value intValue, Value fpValue, bool isSigned)
Returns true if every value of intValue's integer type converts exactly.
std::tuple< Types... > * type_list
static IntegerAttr applyToIntegerAttrs(PatternRewriter &builder, Value res, Attribute lhs, Attribute rhs, function_ref< APInt(const APInt &, const APInt &)> binFn)
static APInt calculateUnsignedOverflow(const APInt &sum, const APInt &operand)
static FailureOr< APInt > getIntOrSplatIntValue(Attribute attr)
static unsigned getIndexCastWidth(Type t)
Return the bit-width of t for the purpose of index_cast width checks.
static LogicalResult verifyTruncateOp(Op op)
*if copies could not be generated due to yet unimplemented cases *copyInPlacementStart and copyOutPlacementStart in copyPlacementBlock *specify the insertion points where the incoming copies and outgoing should be inserted(the insertion happens right before the *insertion point). Since `begin` can itself be invalidated due to the memref *rewriting done from this method
static Type getElementType(Type type, ArrayRef< int32_t > indices, function_ref< InFlightDiagnostic(StringRef)> emitErrorFn)
Walks the given type hierarchy with the given indices, potentially down to component granularity,...
virtual Builder & getBuilder() const =0
Return a builder which provides useful access to MLIRContext, global objects like types and attribute...
virtual ParseResult parseOptionalAttrDict(NamedAttrList &result)=0
Parse a named dictionary into 'result' if it is present.
virtual ParseResult parseColonType(Type &result)=0
Parse a colon followed by a type.
virtual ParseResult parseOptionalComma()=0
Parse a , token if present.
virtual SMLoc getNameLoc() const =0
Return the location of the original name token.
virtual ParseResult parseType(Type &result)=0
Parse a type.
Attributes are known-constant values of operations.
static BoolAttr get(MLIRContext *context, bool value)
IntegerAttr getIndexAttr(int64_t value)
IntegerAttr getIntegerAttr(Type type, int64_t value)
FloatAttr getFloatAttr(Type type, double value)
IntegerType getIntegerType(unsigned width)
TypedAttr getZeroAttr(Type type)
static DenseElementsAttr get(ShapedType type, ArrayRef< Attribute > values)
Constructs a dense elements attribute from an array of element values.
ImplicitLocOpBuilder maintains a 'current location', allowing use of the create<> method without spec...
Location getLoc() const
Accessors for the implied location.
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
MLIRContext is the top-level object for a collection of MLIR operations.
ParseResult resolveOperands(Operands &&operands, Type type, SmallVectorImpl< Value > &result)
Resolve a list of operands to SSA values, emitting an error on failure, or appending the results to t...
virtual ParseResult parseOperandList(SmallVectorImpl< UnresolvedOperand > &result, Delimiter delimiter=Delimiter::None, bool allowResultNumber=true, int requiredOperandCount=-1)=0
Parse zero or more SSA comma-separated operand references with a specified surrounding delimiter,...
virtual void printOptionalAttrDict(ArrayRef< NamedAttribute > attrs, ArrayRef< StringRef > elidedAttrs={})=0
If the specified operation has attributes, print out an attribute dictionary with their values.
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...
Operation * create(const OperationState &state)
Creates an operation given the fields represented as an OperationState.
This class represents a single result from folding an operation.
InFlightDiagnostic emitError(const Twine &message={})
Emit an error about fatal conditions with this operation, reporting up to any diagnostic handlers tha...
This provides public APIs that all operations should have.
Operation is the basic unit of execution within MLIR.
OpResult getResult(unsigned idx)
Get the 'idx'th result of this operation.
Location getLoc()
The source location the operation was defined or derived from.
void setOperands(ValueRange operands)
Replace the current operands of this operation with the ones provided in 'operands'.
result_range getResults()
MLIRContext * getContext()
Return the context this operation is associated with.
A special type of RewriterBase that coordinates the application of a rewrite pattern on the current I...
RewritePatternSet & insert(ConstructorArg &&arg, ConstructorArgs &&...args)
Add an instance of each of the pattern types 'Ts' to the pattern list with the given arguments.
RewritePatternSet & add(ConstructorArg &&arg, ConstructorArgs &&...args)
Add an instance of each of the pattern types 'Ts' to the pattern list with the given arguments.
virtual void 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.
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.
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 isSignlessInteger() const
Return true if this is a signless integer type (with the specified width).
bool isIntOrFloat() const
Return true if this is an integer (of any signedness) or a float type.
unsigned getIntOrFloatBitWidth() const
Return the bit width of an integer or a float type, assert failure on other types.
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Type getType() const
Return the type of this value.
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
Specialization of arith.constant op that returns a floating point value.
static ConstantFloatOp create(OpBuilder &builder, Location location, FloatType type, const APFloat &value)
static bool classof(Operation *op)
static void build(OpBuilder &builder, OperationState &result, FloatType type, const APFloat &value)
Build a constant float op that produces a float of the specified type.
Specialization of arith.constant op that returns an integer of index type.
static void build(OpBuilder &builder, OperationState &result, int64_t value)
Build a constant int op that produces an index.
static bool classof(Operation *op)
static ConstantIndexOp create(OpBuilder &builder, Location location, int64_t value)
Specialization of arith.constant op that returns an integer value.
static ConstantIntOp create(OpBuilder &builder, Location location, int64_t value, unsigned width)
static void build(OpBuilder &builder, OperationState &result, int64_t value, unsigned width)
Build a constant int op that produces an integer of the specified width.
static bool classof(Operation *op)
Speculatability
This enum is returned from the getSpeculatability method in the ConditionallySpeculatable op interfac...
constexpr auto Speculatable
constexpr auto NotSpeculatable
std::optional< TypedAttr > getNeutralElement(Operation *op)
Return the identity numeric value associated to the give op.
bool applyCmpPredicate(arith::CmpIPredicate predicate, const APInt &lhs, const APInt &rhs)
Compute lhs pred rhs, where pred is one of the known integer comparison predicates.
TypedAttr getIdentityValueAttr(AtomicRMWKind kind, Type resultType, OpBuilder &builder, Location loc, bool useOnlyFiniteValue=false)
Returns the identity value attribute associated with an AtomicRMWKind op.
Value getReductionOp(AtomicRMWKind op, OpBuilder &builder, Location loc, Value lhs, Value rhs)
Returns the value obtained by applying the reduction operation kind associated with a binary AtomicRM...
Value getIdentityValue(AtomicRMWKind op, Type resultType, OpBuilder &builder, Location loc, bool useOnlyFiniteValue=false)
Returns the identity value associated with an AtomicRMWKind op.
arith::CmpIPredicate invertPredicate(arith::CmpIPredicate pred)
Invert an integer comparison predicate.
Value getZeroConstant(OpBuilder &builder, Location loc, Type type)
Creates an arith.constant operation with a zero value of type type.
detail::poison_attr_matcher m_Poison()
Matches a poison constant (any attribute implementing PoisonAttrInterface).
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...
Attribute constFoldBinaryOpConditional(ArrayRef< Attribute > operands, Type resultType, CalculationT &&calculate)
Performs constant folding calculate with element-wise behavior on the two attributes in operands and ...
detail::constant_float_predicate_matcher m_NaNFloat()
Matches a constant scalar / vector splat / tensor splat float ones.
LogicalResult verifyCompatibleShapes(TypeRange types1, TypeRange types2)
Returns success if the given two arrays have the same number of elements and each pair wise entries h...
Attribute constFoldCastOp(ArrayRef< Attribute > operands, Type resType, CalculationT &&calculate)
Attribute constFoldBinaryOp(ArrayRef< Attribute > operands, Type resultType, CalculationT &&calculate)
Type getType(OpFoldResult ofr)
Returns the int type of the integer in ofr.
detail::constant_int_range_predicate_matcher m_IntRangeWithoutNegOneS()
Matches a constant scalar / vector splat / tensor splat integer or a signed integer range that does n...
LogicalResult emitOptionalError(std::optional< Location > loc, Args &&...args)
Overloads of the above emission functions that take an optionally null location.
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.
bool isPure(Operation *op)
Returns true if the given operation is pure, i.e., is speculatable that does not touch memory.
detail::constant_float_predicate_matcher m_PosZeroFloat()
Matches a constant scalar / vector splat / tensor splat float positive zero.
detail::constant_int_predicate_matcher m_Zero()
Matches a constant scalar / vector splat / tensor splat integer zero.
Type getElementTypeOrSelf(Type type)
Return the element type or return the type itself.
Attribute constFoldUnaryOpConditional(ArrayRef< Attribute > operands, Type resultType, CalculationT &&calculate)
Performs constant folding calculate with element-wise behavior on the one attributes in operands and ...
detail::constant_float_predicate_matcher m_AnyZeroFloat()
Matches a constant scalar / vector splat / tensor splat float (both positive and negative) zero.
detail::constant_int_predicate_matcher m_One()
Matches a constant scalar / vector splat / tensor splat integer one.
detail::constant_float_predicate_matcher m_NegInfFloat()
Matches a constant scalar / vector splat / tensor splat float negative infinity.
detail::constant_float_predicate_matcher m_NegZeroFloat()
Matches a constant scalar / vector splat / tensor splat float negative zero.
detail::constant_int_range_predicate_matcher m_IntRangeWithoutZeroS()
Matches a constant scalar / vector splat / tensor splat integer or a signed integer range that does n...
llvm::DenseMap< KeyT, ValueT, KeyInfoT, BucketT > DenseMap
detail::op_matcher< OpClass > m_Op()
Matches the given OpClass.
detail::constant_op_matcher m_Constant()
Matches a constant foldable operation.
Attribute constFoldUnaryOp(ArrayRef< Attribute > operands, Type resultType, CalculationT &&calculate)
detail::constant_float_predicate_matcher m_PosInfFloat()
Matches a constant scalar / vector splat / tensor splat float positive infinity.
llvm::function_ref< Fn > function_ref
detail::constant_float_predicate_matcher m_OneFloat()
Matches a constant scalar / vector splat / tensor splat float ones.
detail::constant_int_range_predicate_matcher m_IntRangeWithoutZeroU()
Matches a constant scalar / vector splat / tensor splat integer or a unsigned integer range that does...
select(M, F(a0, a1, ..., a_n), F(b0, b1, ..., b_n)) -> F(select(M, a0, b0), select(M,...
LogicalResult matchAndRewrite(arith::SelectOp op, PatternRewriter &rewriter) const override
OpRewritePattern Base
Type alias to allow derived classes to inherit constructors with using Base::Base;.
OpRewritePattern(MLIRContext *context, PatternBenefit benefit=1, ArrayRef< StringRef > generatedNames={})
This trait tags element-wise ops on vectors or tensors.
static bool isEquivalentTo(Operation *lhs, Operation *rhs, function_ref< LogicalResult(Value, Value)> checkEquivalent, function_ref< void(Value, Value)> markEquivalent=nullptr, Flags flags=Flags::None, function_ref< LogicalResult(ValueRange, ValueRange)> checkCommutativeEquivalent=nullptr)
Compare two operations (including their regions) and return if they are equivalent.
static LogicalResult ignoreValueEquivalence(Value lhs, Value rhs)
Helper that can be used with isEquivalentTo above to consider ops equivalent even if their operands a...
This represents an operation in an abstracted form, suitable for use with the builder APIs.