25#include "llvm/ADT/STLExtras.h"
26#include "llvm/ADT/SmallBitVector.h"
27#include "llvm/ADT/SmallVectorExtras.h"
28#include "llvm/ADT/TypeSwitch.h"
29#include "llvm/Support/DebugLog.h"
30#include "llvm/Support/LogicalResult.h"
31#include "llvm/Support/MathExtras.h"
38using llvm::divideCeilSigned;
39using llvm::divideFloorSigned;
42#define DEBUG_TYPE "affine-ops"
44#include "mlir/Dialect/Affine/IR/AffineOpsDialect.cpp.inc"
51 if (
auto arg = dyn_cast<BlockArgument>(value))
52 return arg.getParentRegion() == region;
75 if (llvm::isa<BlockArgument>(value))
76 return legalityCheck(mapping.
lookup(value), dest);
83 bool isDimLikeOp = isa<ShapedDimOpInterface>(value.
getDefiningOp());
94 return llvm::all_of(values, [&](
Value v) {
101template <
typename OpTy>
104 static_assert(llvm::is_one_of<OpTy, AffineReadOpInterface,
105 AffineWriteOpInterface>::value,
106 "only ops with affine read/write interface are supported");
113 dimOperands, src, dest, mapping,
117 symbolOperands, src, dest, mapping,
134 op.getMapOperands(), src, dest, mapping,
139 op.getMapOperands(), src, dest, mapping,
150struct AffineInlinerInterface :
public DialectInlinerInterface {
151 using DialectInlinerInterface::DialectInlinerInterface;
162 IRMapping &valueMapping)
const final {
166 if (!isa<AffineParallelOp, AffineForOp, AffineIfOp>(destOp))
177 for (Operation &op : srcBlock) {
179 if (
auto iface = dyn_cast<MemoryEffectOpInterface>(op)) {
180 if (iface.hasNoEffect())
187 llvm::TypeSwitch<Operation *, bool>(&op)
188 .Case<AffineApplyOp, AffineReadOpInterface,
189 AffineWriteOpInterface>([&](
auto op) {
192 .Default([](Operation *) {
206 bool isLegalToInline(Operation *op, Region *region,
bool wouldBeCloned,
207 IRMapping &valueMapping)
const final {
212 Operation *parentOp = region->getParentOp();
213 return parentOp->
hasTrait<OpTrait::AffineScope>() ||
214 isa<AffineForOp, AffineParallelOp, AffineIfOp>(parentOp);
218 bool shouldAnalyzeRecursively(Operation *op)
const final {
return true; }
226void AffineDialect::initialize() {
227 addInterfaces<AffineInlinerInterface>();
228 declarePromisedInterfaces<ValueBoundsOpInterface, AffineApplyOp, AffineMaxOp,
237 if (
auto poison = dyn_cast<ub::PoisonAttr>(value))
238 return ub::PoisonOp::create(builder, loc, type, poison);
239 return arith::ConstantOp::materialize(builder, value, type, loc);
247 if (
auto arg = dyn_cast<BlockArgument>(value)) {
263 while (
auto *parentOp = curOp->getParentOp()) {
265 return curOp->getParentRegion();
274 if (!isa<AffineForOp, AffineIfOp, AffineParallelOp>(parentOp))
299 auto *parentOp = llvm::cast<BlockArgument>(value).getOwner()->getParentOp();
327 if (
auto applyOp = dyn_cast<AffineApplyOp>(op))
328 return applyOp.isValidDim(region);
331 if (isa<AffineDelinearizeIndexOp, AffineLinearizeIndexOp>(op))
332 return llvm::all_of(op->getOperands(),
333 [&](
Value arg) { return ::isValidDim(arg, region); });
336 if (
auto dimOp = dyn_cast<ShapedDimOpInterface>(op))
344template <
typename AnyMemRefDefOp>
347 MemRefType memRefType = memrefDefOp.getType();
350 if (
index >= memRefType.getRank()) {
355 if (!memRefType.isDynamicDim(
index))
358 unsigned dynamicDimPos = memRefType.getDynamicDimIndex(
index);
359 return isValidSymbol(*(memrefDefOp.getDynamicSizes().begin() + dynamicDimPos),
371 if (llvm::isa<BlockArgument>(dimOp.getShapedValue()))
379 if (!
index.has_value())
383 Operation *op = dimOp.getShapedValue().getDefiningOp();
384 while (
auto castOp = dyn_cast<memref::CastOp>(op)) {
386 if (isa<UnrankedMemRefType>(castOp.getSource().getType()))
388 op = castOp.getSource().getDefiningOp();
395 .Case<memref::ViewOp, memref::SubViewOp, memref::AllocOp>(
397 .Default([](
Operation *) {
return false; });
431 if (parentRegion == region)
472 if (
isPure(defOp) && llvm::all_of(defOp->getOperands(), [&](
Value operand) {
473 return affine::isValidSymbol(operand, region);
479 if (
auto dimOp = dyn_cast<ShapedDimOpInterface>(defOp))
497 printer <<
'(' << operands.take_front(numDims) <<
')';
498 if (operands.size() > numDims)
499 printer <<
'[' << operands.drop_front(numDims) <<
']';
509 numDims = opInfos.size();
523template <
typename OpTy>
528 for (
auto operand : operands) {
529 if (opIt++ < numDims) {
531 return op.emitOpError(
"operand cannot be used as a dimension id");
533 return op.emitOpError(
"operand cannot be used as a symbol");
544 return AffineValueMap(getAffineMap(), getOperands(), getResult());
551 AffineMapAttr mapAttr;
557 auto map = mapAttr.getValue();
559 if (map.getNumDims() != numDims ||
560 numDims + map.getNumSymbols() !=
result.operands.size()) {
562 "dimension or symbol index mismatch");
565 result.types.append(map.getNumResults(), indexTy);
570 p <<
" " << getMapAttr();
572 getAffineMap().getNumDims(), p);
576LogicalResult AffineApplyOp::verify() {
583 "operand count and affine map dimension and symbol count must match");
587 return emitOpError(
"mapping must produce one value");
593 for (
Value operand : getMapOperands().drop_front(affineMap.
getNumDims())) {
595 return emitError(
"dimensional operand cannot be used as a symbol");
603bool AffineApplyOp::isValidDim() {
604 return llvm::all_of(getOperands(),
611bool AffineApplyOp::isValidDim(
Region *region) {
612 return llvm::all_of(getOperands(),
613 [&](
Value op) { return ::isValidDim(op, region); });
618bool AffineApplyOp::isValidSymbol() {
619 return llvm::all_of(getOperands(),
625bool AffineApplyOp::isValidSymbol(
Region *region) {
626 return llvm::all_of(getOperands(), [&](
Value operand) {
632 auto map = getAffineMap();
635 auto expr = map.getResult(0);
636 if (
auto dim = dyn_cast<AffineDimExpr>(expr))
637 return getOperand(dim.getPosition());
638 if (
auto sym = dyn_cast<AffineSymbolExpr>(expr))
639 return getOperand(map.getNumDims() + sym.getPosition());
643 bool hasPoison =
false;
645 map.constantFold(adaptor.getMapOperands(),
result, &hasPoison);
665 auto dimExpr = dyn_cast<AffineDimExpr>(e);
675 Value operand = operands[dimExpr.getPosition()];
680 if (forOp.hasConstantLowerBound() && forOp.getConstantLowerBound() == 0) {
681 operandDivisor = forOp.getStepAsInt();
683 uint64_t lbLargestKnownDivisor =
684 forOp.getLowerBoundMap().getLargestKnownDivisorOfMapExprs();
685 operandDivisor = std::gcd(lbLargestKnownDivisor, forOp.getStepAsInt());
688 return operandDivisor;
695 if (
auto constExpr = dyn_cast<AffineConstantExpr>(e)) {
696 int64_t constVal = constExpr.getValue();
697 return constVal >= 0 && constVal < k;
699 auto dimExpr = dyn_cast<AffineDimExpr>(e);
702 Value operand = operands[dimExpr.getPosition()];
706 if (forOp.hasConstantLowerBound() && forOp.getConstantLowerBound() >= 0 &&
707 forOp.hasConstantUpperBound() && forOp.getConstantUpperBound() <= k) {
723 auto bin = dyn_cast<AffineBinaryOpExpr>(e);
731 quotientTimesDiv = llhs;
737 quotientTimesDiv = rlhs;
747 if (forOp && forOp.hasConstantLowerBound())
748 return forOp.getConstantLowerBound();
755 if (!forOp || !forOp.hasConstantUpperBound())
760 if (forOp.hasConstantLowerBound()) {
761 return forOp.getConstantUpperBound() - 1 -
762 (forOp.getConstantUpperBound() - forOp.getConstantLowerBound() - 1) %
763 forOp.getStepAsInt();
765 return forOp.getConstantUpperBound() - 1;
774 if (
auto constExpr = dyn_cast<AffineConstantExpr>(expr))
775 return constExpr.getValue();
779 constLowerBounds.reserve(operands.size());
780 constUpperBounds.reserve(operands.size());
781 for (
Value operand : operands) {
797 if (
auto constExpr = dyn_cast<AffineConstantExpr>(expr))
798 return constExpr.getValue();
802 constLowerBounds.reserve(operands.size());
803 constUpperBounds.reserve(operands.size());
804 for (
Value operand : operands) {
819 auto binExpr = dyn_cast<AffineBinaryOpExpr>(expr);
830 binExpr = dyn_cast<AffineBinaryOpExpr>(expr);
838 lhs = binExpr.getLHS();
839 rhs = binExpr.getRHS();
840 auto rhsConst = dyn_cast<AffineConstantExpr>(rhs);
844 int64_t rhsConstVal = rhsConst.getValue();
846 if (rhsConstVal <= 0)
851 std::optional<int64_t> lhsLbConst =
853 std::optional<int64_t> lhsUbConst =
855 if (lhsLbConst && lhsUbConst) {
856 int64_t lhsLbConstVal = *lhsLbConst;
857 int64_t lhsUbConstVal = *lhsUbConst;
861 divideFloorSigned(lhsLbConstVal, rhsConstVal) ==
862 divideFloorSigned(lhsUbConstVal, rhsConstVal)) {
864 divideFloorSigned(lhsLbConstVal, rhsConstVal), context);
870 divideCeilSigned(lhsLbConstVal, rhsConstVal) ==
871 divideCeilSigned(lhsUbConstVal, rhsConstVal)) {
878 lhsLbConstVal < rhsConstVal && lhsUbConstVal < rhsConstVal) {
891 if (rhsConstVal % divisor == 0 &&
893 expr = quotientTimesDiv.
floorDiv(rhsConst);
894 }
else if (divisor % rhsConstVal == 0 &&
896 expr =
rem % rhsConst;
922 if (operands.empty())
928 constLowerBounds.reserve(operands.size());
929 constUpperBounds.reserve(operands.size());
930 for (
Value operand : operands) {
944 if (
auto constExpr = dyn_cast<AffineConstantExpr>(e)) {
945 lowerBounds.push_back(constExpr.getValue());
946 upperBounds.push_back(constExpr.getValue());
948 lowerBounds.push_back(
950 constLowerBounds, constUpperBounds,
952 upperBounds.push_back(
954 constLowerBounds, constUpperBounds,
961 for (
auto exprEn : llvm::enumerate(map.
getResults())) {
963 unsigned i = exprEn.index();
965 if (lowerBounds[i] && upperBounds[i] && *lowerBounds[i] == *upperBounds[i])
970 if (!upperBounds[i]) {
971 irredundantExprs.push_back(e);
976 if (!llvm::any_of(llvm::enumerate(lowerBounds), [&](
const auto &en) {
977 auto otherLowerBound = en.value();
978 unsigned pos = en.index();
979 if (pos == i || !otherLowerBound)
981 if (*otherLowerBound > *upperBounds[i])
983 if (*otherLowerBound < *upperBounds[i])
988 if (upperBounds[pos] && lowerBounds[i] &&
989 lowerBounds[i] == upperBounds[i] &&
990 otherLowerBound == *upperBounds[pos] && i < pos)
994 irredundantExprs.push_back(e);
996 if (!lowerBounds[i]) {
997 irredundantExprs.push_back(e);
1001 if (!llvm::any_of(llvm::enumerate(upperBounds), [&](
const auto &en) {
1002 auto otherUpperBound = en.value();
1003 unsigned pos = en.index();
1004 if (pos == i || !otherUpperBound)
1006 if (*otherUpperBound < *lowerBounds[i])
1008 if (*otherUpperBound > *lowerBounds[i])
1010 if (lowerBounds[pos] && upperBounds[i] &&
1011 lowerBounds[i] == upperBounds[i] &&
1012 otherUpperBound == lowerBounds[pos] && i < pos)
1016 irredundantExprs.push_back(e);
1030 assert(map.
getNumInputs() == operands.size() &&
"invalid operands for map");
1036 newResults.push_back(expr);
1059 LDBG() <<
"replaceAffineMinBoundingBoxExpression: `" << minOp <<
"`";
1060 AffineMap affineMinMap = minOp.getAffineMap();
1063 for (
unsigned i = 0, e = affineMinMap.
getNumResults(); i < e; ++i) {
1069 minOp.getOperands())))
1077 for (
auto [i, dim] : llvm::enumerate(minOp.getDimOperands())) {
1078 auto it = llvm::find(dims, dim);
1079 if (it == dims.end()) {
1080 unmappedDims.push_back(i);
1086 for (
auto [i, sym] : llvm::enumerate(minOp.getSymbolOperands())) {
1087 auto it = llvm::find(syms, sym);
1088 if (it == syms.end()) {
1089 unmappedSyms.push_back(i);
1102 if (llvm::any_of(unmappedDims,
1103 [&](
unsigned i) {
return expr.isFunctionOfDim(i); }) ||
1104 llvm::any_of(unmappedSyms,
1105 [&](
unsigned i) {
return expr.isFunctionOfSymbol(i); }))
1111 repl[dimOrSym.
ceilDiv(convertedExpr)] = c1;
1113 repl[(dimOrSym + convertedExpr - 1).floorDiv(convertedExpr)] = c1;
1118 return success(*map != initialMap);
1127 AffineExpr e,
const llvm::SmallDenseSet<AffineExpr, 4> &exprsToRemove,
1129 auto binOp = dyn_cast<AffineBinaryOpExpr>(e);
1140 llvm::SmallDenseSet<AffineExpr, 4> ourTracker(exprsToRemove);
1145 if (!ourTracker.erase(thisTerm)) {
1146 toPreserve.push_back(thisTerm);
1150 auto nextBinOp = dyn_cast_if_present<AffineBinaryOpExpr>(nextTerm);
1152 thisTerm = nextTerm;
1155 thisTerm = nextBinOp.getRHS();
1156 nextTerm = nextBinOp.getLHS();
1159 if (!ourTracker.empty())
1164 for (
AffineExpr preserved : llvm::reverse(toPreserve))
1165 newExpr = newExpr + preserved;
1166 replacementsMap.insert({e, newExpr});
1184 AffineDelinearizeIndexOp delinOp,
Value resultToReplace,
AffineMap *map,
1186 if (!delinOp.getDynamicBasis().empty())
1188 if (resultToReplace != delinOp.getMultiIndex().back())
1193 for (
auto [pos, dim] : llvm::enumerate(dims)) {
1194 auto asResult = dyn_cast_if_present<OpResult>(dim);
1197 if (asResult.getOwner() == delinOp.getOperation())
1200 for (
auto [pos, sym] : llvm::enumerate(syms)) {
1201 auto asResult = dyn_cast_if_present<OpResult>(sym);
1204 if (asResult.getOwner() == delinOp.getOperation())
1207 if (llvm::is_contained(resToExpr,
AffineExpr()))
1210 bool isDimReplacement = llvm::all_of(resToExpr, llvm::IsaPred<AffineDimExpr>);
1212 llvm::SmallDenseSet<AffineExpr, 4> expectedExprs;
1215 for (
auto [binding, size] : llvm::zip(
1216 llvm::reverse(resToExpr), llvm::reverse(delinOp.getStaticBasis()))) {
1220 if (resToExpr.size() != delinOp.getStaticBasis().size())
1221 expectedExprs.insert(resToExpr[0] * stride);
1230 if (replacements.empty())
1234 if (isDimReplacement)
1235 dims.push_back(delinOp.getLinearIndex());
1237 syms.push_back(delinOp.getLinearIndex());
1238 *map = origMap.
replace(replacements, dims.size(), syms.size());
1242 if (
auto d = dyn_cast<AffineDimExpr>(e)) {
1243 unsigned pos = d.getPosition();
1245 dims[pos] =
nullptr;
1247 if (
auto s = dyn_cast<AffineSymbolExpr>(e)) {
1248 unsigned pos = s.getPosition();
1250 syms[pos] =
nullptr;
1269 unsigned dimOrSymbolPosition,
1272 bool replaceAffineMin) {
1274 bool isDimReplacement = (dimOrSymbolPosition < dims.size());
1275 unsigned pos = isDimReplacement ? dimOrSymbolPosition
1276 : dimOrSymbolPosition - dims.size();
1277 Value &v = isDimReplacement ? dims[pos] : syms[pos];
1281 if (
auto minOp = v.
getDefiningOp<AffineMinOp>(); minOp && replaceAffineMin) {
1288 if (
auto delinOp = v.
getDefiningOp<affine::AffineDelinearizeIndexOp>()) {
1302 AffineMap composeMap = affineApply.getAffineMap();
1303 assert(composeMap.
getNumResults() == 1 &&
"affine.apply with >1 results");
1305 affineApply.getMapOperands().end());
1319 dims.append(composeDims.begin(), composeDims.end());
1320 syms.append(composeSyms.begin(), composeSyms.end());
1321 *map = map->
replace(toReplace, replacementExpr, dims.size(), syms.size());
1331 bool composeAffineMin =
false) {
1350 bool changed =
false;
1351 for (
unsigned pos = 0; pos != dims.size() + syms.size(); ++pos)
1364 unsigned nDims = 0, nSyms = 0;
1366 dimReplacements.reserve(dims.size());
1367 symReplacements.reserve(syms.size());
1368 for (
auto *container : {&dims, &syms}) {
1369 bool isDim = (container == &dims);
1370 auto &repls = isDim ? dimReplacements : symReplacements;
1371 for (
const auto &en : llvm::enumerate(*container)) {
1372 Value v = en.value();
1376 "map is function of unexpected expr@pos");
1382 operands->push_back(v);
1395 while (llvm::any_of(*operands, [](
Value v) {
1401 if (composeAffineMin && llvm::any_of(*operands, [](
Value v) {
1411 bool composeAffineMin) {
1416 return AffineApplyOp::create(
b, loc, map, valueOperands);
1422 bool composeAffineMin) {
1427 operands, composeAffineMin);
1434 bool composeAffineMin =
false) {
1440 for (
unsigned i : llvm::seq<unsigned>(0, map.
getNumResults())) {
1448 llvm::append_range(dims,
1450 llvm::append_range(symbols,
1457 operands = llvm::to_vector(llvm::concat<Value>(dims, symbols));
1464 bool composeAffineMin) {
1465 assert(map.
getNumResults() == 1 &&
"building affine.apply with !=1 result");
1475 AffineApplyOp applyOp =
1480 for (
unsigned i = 0, e = constOperands.size(); i != e; ++i)
1485 if (failed(applyOp->fold(constOperands, foldResults)) ||
1486 foldResults.empty()) {
1488 listener->notifyOperationInserted(applyOp, {});
1489 return applyOp.getResult();
1493 return llvm::getSingleElement(foldResults);
1503 operands, composeAffineMin);
1509 bool composeAffineMin) {
1510 return llvm::map_to_vector(
1511 llvm::seq<unsigned>(0, map.
getNumResults()), [&](
unsigned i) {
1512 return makeComposedFoldedAffineApply(b, loc, map.getSubMap({i}),
1513 operands, composeAffineMin);
1517template <
typename OpTy>
1523 return OpTy::create(
b, loc,
b.getIndexType(), map, valueOperands);
1532template <
typename OpTy>
1548 for (
unsigned i = 0, e = constOperands.size(); i != e; ++i)
1553 if (failed(minMaxOp->fold(constOperands, foldResults)) ||
1554 foldResults.empty()) {
1556 listener->notifyOperationInserted(minMaxOp, {});
1557 return minMaxOp.getResult();
1561 return llvm::getSingleElement(foldResults);
1580template <
class MapOrSet>
1583 if (!mapOrSet || operands->empty())
1586 assert(mapOrSet->getNumInputs() == operands->size() &&
1587 "map/set inputs must match number of operands");
1589 auto *context = mapOrSet->getContext();
1591 resultOperands.reserve(operands->size());
1593 remappedSymbols.reserve(operands->size());
1594 unsigned nextDim = 0;
1595 unsigned nextSym = 0;
1596 unsigned oldNumSyms = mapOrSet->getNumSymbols();
1598 for (
unsigned i = 0, e = mapOrSet->getNumInputs(); i != e; ++i) {
1599 if (i < mapOrSet->getNumDims()) {
1603 remappedSymbols.push_back((*operands)[i]);
1606 resultOperands.push_back((*operands)[i]);
1609 resultOperands.push_back((*operands)[i]);
1613 resultOperands.append(remappedSymbols.begin(), remappedSymbols.end());
1614 *operands = std::move(resultOperands);
1615 *mapOrSet = mapOrSet->replaceDimsAndSymbols(
1616 dimRemapping, {}, nextDim, oldNumSyms + nextSym);
1618 assert(mapOrSet->getNumInputs() == operands->size() &&
1619 "map/set inputs must match number of operands");
1628template <
class MapOrSet>
1631 if (!mapOrSet || operands.empty())
1634 unsigned numOperands = operands.size();
1636 assert(mapOrSet.getNumInputs() == numOperands &&
1637 "map/set inputs must match number of operands");
1639 auto *context = mapOrSet.getContext();
1641 resultOperands.reserve(numOperands);
1643 remappedDims.reserve(numOperands);
1645 symOperands.reserve(mapOrSet.getNumSymbols());
1646 unsigned nextSym = 0;
1647 unsigned nextDim = 0;
1648 unsigned oldNumDims = mapOrSet.getNumDims();
1650 resultOperands.assign(operands.begin(), operands.begin() + oldNumDims);
1651 for (
unsigned i = oldNumDims, e = mapOrSet.getNumInputs(); i != e; ++i) {
1654 symRemapping[i - oldNumDims] =
1656 remappedDims.push_back(operands[i]);
1659 symOperands.push_back(operands[i]);
1663 append_range(resultOperands, remappedDims);
1664 append_range(resultOperands, symOperands);
1665 operands = std::move(resultOperands);
1666 mapOrSet = mapOrSet.replaceDimsAndSymbols(
1667 {}, symRemapping, oldNumDims + nextDim, nextSym);
1669 assert(mapOrSet.getNumInputs() == operands.size() &&
1670 "map/set inputs must match number of operands");
1674template <
class MapOrSet>
1677 static_assert(llvm::is_one_of<MapOrSet, AffineMap, IntegerSet>::value,
1678 "Argument must be either of AffineMap or IntegerSet type");
1680 if (!mapOrSet || operands->empty())
1683 assert(mapOrSet->getNumInputs() == operands->size() &&
1684 "map/set inputs must match number of operands");
1690 llvm::SmallBitVector usedDims(mapOrSet->getNumDims());
1691 llvm::SmallBitVector usedSyms(mapOrSet->getNumSymbols());
1693 if (
auto dimExpr = dyn_cast<AffineDimExpr>(expr))
1694 usedDims[dimExpr.getPosition()] =
true;
1695 else if (
auto symExpr = dyn_cast<AffineSymbolExpr>(expr))
1696 usedSyms[symExpr.getPosition()] =
true;
1699 auto *context = mapOrSet->getContext();
1702 resultOperands.reserve(operands->size());
1704 llvm::SmallDenseMap<Value, AffineExpr, 8> seenDims;
1706 unsigned nextDim = 0;
1707 for (
unsigned i = 0, e = mapOrSet->getNumDims(); i != e; ++i) {
1710 auto it = seenDims.find((*operands)[i]);
1711 if (it == seenDims.end()) {
1713 resultOperands.push_back((*operands)[i]);
1714 seenDims.insert(std::make_pair((*operands)[i], dimRemapping[i]));
1716 dimRemapping[i] = it->second;
1720 llvm::SmallDenseMap<Value, AffineExpr, 8> seenSymbols;
1722 unsigned nextSym = 0;
1723 for (
unsigned i = 0, e = mapOrSet->getNumSymbols(); i != e; ++i) {
1729 IntegerAttr operandCst;
1730 if (
matchPattern((*operands)[i + mapOrSet->getNumDims()],
1737 auto it = seenSymbols.find((*operands)[i + mapOrSet->getNumDims()]);
1738 if (it == seenSymbols.end()) {
1740 resultOperands.push_back((*operands)[i + mapOrSet->getNumDims()]);
1741 seenSymbols.insert(std::make_pair((*operands)[i + mapOrSet->getNumDims()],
1744 symRemapping[i] = it->second;
1747 *mapOrSet = mapOrSet->replaceDimsAndSymbols(dimRemapping, symRemapping,
1749 *operands = std::move(resultOperands);
1766template <
typename AffineOpTy>
1775 LogicalResult matchAndRewrite(AffineOpTy affineOp,
1778 llvm::is_one_of<AffineOpTy, AffineLoadOp, AffinePrefetchOp,
1779 AffineStoreOp, AffineApplyOp, AffineMinOp, AffineMaxOp,
1780 AffineVectorStoreOp, AffineVectorLoadOp>::value,
1781 "affine load/store/vectorstore/vectorload/apply/prefetch/min/max op "
1783 auto map = affineOp.getAffineMap();
1785 auto oldOperands = affineOp.getMapOperands();
1790 if (map == oldMap && std::equal(oldOperands.begin(), oldOperands.end(),
1791 resultOperands.begin()))
1794 replaceAffineOp(rewriter, affineOp, map, resultOperands);
1802void SimplifyAffineOp<AffineLoadOp>::replaceAffineOp(
1806 mapOperands,
load.getMaybeAlign());
1809void SimplifyAffineOp<AffinePrefetchOp>::replaceAffineOp(
1813 prefetch, prefetch.getMemref(), map, mapOperands, prefetch.getIsWrite(),
1814 prefetch.getLocalityHint(), prefetch.getIsDataCache());
1817void SimplifyAffineOp<AffineStoreOp>::replaceAffineOp(
1821 store, store.getValueToStore(), store.getMemRef(), map, mapOperands,
1822 store.getMaybeAlign());
1825void SimplifyAffineOp<AffineVectorLoadOp>::replaceAffineOp(
1829 vectorload, vectorload.getVectorType(), vectorload.getMemRef(), map,
1830 mapOperands, vectorload.getMaybeAlign());
1833void SimplifyAffineOp<AffineVectorStoreOp>::replaceAffineOp(
1837 vectorstore, vectorstore.getValueToStore(), vectorstore.getMemRef(), map,
1838 mapOperands, vectorstore.getMaybeAlign());
1842template <
typename AffineOpTy>
1843void SimplifyAffineOp<AffineOpTy>::replaceAffineOp(
1852 results.
add<SimplifyAffineOp<AffineApplyOp>>(context);
1867 result.addOperands(srcMemRef);
1868 result.addAttribute(getSrcMapAttrStrName(), AffineMapAttr::get(srcMap));
1869 result.addOperands(srcIndices);
1870 result.addOperands(destMemRef);
1871 result.addAttribute(getDstMapAttrStrName(), AffineMapAttr::get(dstMap));
1872 result.addOperands(destIndices);
1873 result.addOperands(tagMemRef);
1874 result.addAttribute(getTagMapAttrStrName(), AffineMapAttr::get(tagMap));
1875 result.addOperands(tagIndices);
1876 result.addOperands(numElements);
1878 result.addOperands({stride, elementsPerStride});
1883 p <<
" " << getSrcMemRef() <<
'[';
1885 p <<
"], " << getDstMemRef() <<
'[';
1887 p <<
"], " << getTagMemRef() <<
'[';
1891 p <<
", " << getStride();
1892 p <<
", " << getNumElementsPerStride();
1894 p <<
" : " << getSrcMemRefType() <<
", " << getDstMemRefType() <<
", "
1895 << getTagMemRefType();
1904ParseResult AffineDmaStartOp::parse(
OpAsmParser &parser,
1907 AffineMapAttr srcMapAttr;
1910 AffineMapAttr dstMapAttr;
1913 AffineMapAttr tagMapAttr;
1928 getSrcMapAttrStrName(),
1932 getDstMapAttrStrName(),
1936 getTagMapAttrStrName(),
1945 if (!strideInfo.empty() && strideInfo.size() != 2) {
1947 "expected two stride related operands");
1949 bool isStrided = strideInfo.size() == 2;
1954 if (types.size() != 3)
1972 if (srcMapOperands.size() != srcMapAttr.getValue().getNumInputs() ||
1973 dstMapOperands.size() != dstMapAttr.getValue().getNumInputs() ||
1974 tagMapOperands.size() != tagMapAttr.getValue().getNumInputs())
1976 "memref operand count not equal to map.numInputs");
1980LogicalResult AffineDmaStartOp::verify() {
1981 if (!llvm::isa<MemRefType>(getOperand(getSrcMemRefOperandIndex()).
getType()))
1982 return emitOpError(
"expected DMA source to be of memref type");
1983 if (!llvm::isa<MemRefType>(getOperand(getDstMemRefOperandIndex()).
getType()))
1984 return emitOpError(
"expected DMA destination to be of memref type");
1985 if (!llvm::isa<MemRefType>(getOperand(getTagMemRefOperandIndex()).
getType()))
1986 return emitOpError(
"expected DMA tag to be of memref type");
1988 unsigned numInputsAllMaps = getSrcMap().getNumInputs() +
1989 getDstMap().getNumInputs() +
1990 getTagMap().getNumInputs();
1991 if (getNumOperands() != numInputsAllMaps + 3 + 1 &&
1992 getNumOperands() != numInputsAllMaps + 3 + 1 + 2) {
1993 return emitOpError(
"incorrect number of operands");
1997 for (
auto idx : getSrcIndices()) {
1998 if (!idx.getType().isIndex())
1999 return emitOpError(
"src index to dma_start must have 'index' type");
2002 "src index must be a valid dimension or symbol identifier");
2004 for (
auto idx : getDstIndices()) {
2005 if (!idx.getType().isIndex())
2006 return emitOpError(
"dst index to dma_start must have 'index' type");
2009 "dst index must be a valid dimension or symbol identifier");
2011 for (
auto idx : getTagIndices()) {
2012 if (!idx.getType().isIndex())
2013 return emitOpError(
"tag index to dma_start must have 'index' type");
2016 "tag index must be a valid dimension or symbol identifier");
2021LogicalResult AffineDmaStartOp::fold(FoldAdaptor adaptor,
2027void AffineDmaStartOp::getEffects(
2046 result.addOperands(tagMemRef);
2047 result.addAttribute(getTagMapAttrStrName(), AffineMapAttr::get(tagMap));
2048 result.addOperands(tagIndices);
2049 result.addOperands(numElements);
2053 p <<
" " << getTagMemRef() <<
'[';
2058 p <<
" : " << getTagMemRef().getType();
2066ParseResult AffineDmaWaitOp::parse(
OpAsmParser &parser,
2069 AffineMapAttr tagMapAttr;
2078 getTagMapAttrStrName(),
2087 if (!llvm::isa<MemRefType>(type))
2089 "expected tag to be of memref type");
2091 if (tagMapOperands.size() != tagMapAttr.getValue().getNumInputs())
2093 "tag memref operand count != to map.numInputs");
2097LogicalResult AffineDmaWaitOp::verify() {
2098 if (!llvm::isa<MemRefType>(getOperand(0).
getType()))
2099 return emitOpError(
"expected DMA tag to be of memref type");
2101 for (
auto idx : getTagIndices()) {
2102 if (!idx.getType().isIndex())
2103 return emitOpError(
"index to dma_wait must have 'index' type");
2106 "index must be a valid dimension or symbol identifier");
2111LogicalResult AffineDmaWaitOp::fold(FoldAdaptor adaptor,
2117void AffineDmaWaitOp::getEffects(
2133 ValueRange iterArgs, BodyBuilderFn bodyBuilder) {
2134 assert(((!lbMap && lbOperands.empty()) ||
2136 "lower bound operand count does not match the affine map");
2137 assert(((!ubMap && ubOperands.empty()) ||
2139 "upper bound operand count does not match the affine map");
2140 assert(step > 0 &&
"step has to be a positive integer constant");
2142 OpBuilder::InsertionGuard guard(builder);
2146 getOperandSegmentSizeAttr(),
2148 static_cast<int32_t>(ubOperands.size()),
2149 static_cast<int32_t>(iterArgs.size())}));
2151 for (Value val : iterArgs)
2152 result.addTypes(val.getType());
2159 result.addAttribute(getLowerBoundMapAttrName(
result.name),
2160 AffineMapAttr::get(lbMap));
2161 result.addOperands(lbOperands);
2164 result.addAttribute(getUpperBoundMapAttrName(
result.name),
2165 AffineMapAttr::get(ubMap));
2166 result.addOperands(ubOperands);
2168 result.addOperands(iterArgs);
2171 Region *bodyRegion =
result.addRegion();
2173 Value inductionVar =
2175 for (Value val : iterArgs)
2176 bodyBlock->
addArgument(val.getType(), val.getLoc());
2181 if (iterArgs.empty() && !bodyBuilder) {
2182 ensureTerminator(*bodyRegion, builder,
result.location);
2183 }
else if (bodyBuilder) {
2184 OpBuilder::InsertionGuard guard(builder);
2186 bodyBuilder(builder,
result.location, inductionVar,
2193 BodyBuilderFn bodyBuilder) {
2196 return build(builder,
result, {}, lbMap, {}, ubMap, step, iterArgs,
2200LogicalResult AffineForOp::verify() {
2201 auto *body = getBody();
2202 if (body->getNumArguments() == 0 || !getInductionVar().
getType().isIndex())
2203 return emitOpError(
"expected body to have an index argument for the "
2204 "induction variable");
2209LogicalResult AffineForOp::verifyRegions() {
2211 if (getStepAsInt() <= 0)
2212 return emitOpError(
"expected step to be a positive integer, got ")
2217 if (getLowerBoundMap().getNumInputs() > 0)
2219 getLowerBoundMap().getNumDims())))
2222 if (getUpperBoundMap().getNumInputs() > 0)
2224 getUpperBoundMap().getNumDims())))
2226 if (getLowerBoundMap().getNumResults() < 1)
2227 return emitOpError(
"expected lower bound map to have at least one result");
2228 if (getUpperBoundMap().getNumResults() < 1)
2229 return emitOpError(
"expected upper bound map to have at least one result");
2231 unsigned opNumResults = getNumResults();
2232 if (opNumResults == 0)
2238 if (getNumIterOperands() != opNumResults)
2240 "mismatch between the number of loop-carried values and results");
2241 if (getNumRegionIterArgs() != opNumResults)
2243 "mismatch between the number of basic block args and results");
2253 bool failedToParsedMinMax =
2257 auto boundAttrStrName =
2258 isLower ? AffineForOp::getLowerBoundMapAttrName(
result.name)
2259 : AffineForOp::getUpperBoundMapAttrName(
result.name);
2266 if (!boundOpInfos.empty()) {
2268 if (boundOpInfos.size() > 1)
2270 "expected only one loop bound operand");
2282 result.addAttribute(boundAttrStrName, AffineMapAttr::get(map));
2295 if (
auto affineMapAttr = dyn_cast<AffineMapAttr>(boundAttr)) {
2296 unsigned currentNumOperands =
result.operands.size();
2301 auto map = affineMapAttr.getValue();
2302 if (map.getNumDims() != numDims)
2305 "dim operand count and affine map dim count must match");
2307 unsigned numDimAndSymbolOperands =
2308 result.operands.size() - currentNumOperands;
2309 if (numDims + map.getNumSymbols() != numDimAndSymbolOperands)
2312 "symbol operand count and affine map symbol count must match");
2316 if (map.getNumResults() > 1 && failedToParsedMinMax) {
2318 return p.
emitError(attrLoc,
"lower loop bound affine map with "
2319 "multiple results requires 'max' prefix");
2321 return p.
emitError(attrLoc,
"upper loop bound affine map with multiple "
2322 "results requires 'min' prefix");
2328 if (
auto integerAttr = dyn_cast<IntegerAttr>(boundAttr)) {
2329 result.attributes.pop_back();
2338 "expected valid affine map representation for loop bounds");
2343 OpAsmParser::Argument inductionVariable;
2350 int64_t numOperands =
result.operands.size();
2353 int64_t numLbOperands =
result.operands.size() - numOperands;
2356 numOperands =
result.operands.size();
2359 int64_t numUbOperands =
result.operands.size() - numOperands;
2364 getStepAttrName(
result.name),
2368 IntegerAttr stepAttr;
2370 getStepAttrName(
result.name).data(),
2374 if (!stepAttr.getValue().isStrictlyPositive())
2377 "expected step to be representable as a positive signed integer");
2381 SmallVector<OpAsmParser::Argument, 4> regionArgs;
2382 SmallVector<OpAsmParser::UnresolvedOperand, 4> operands;
2385 regionArgs.push_back(inductionVariable);
2393 for (
auto argOperandType :
2394 llvm::zip(llvm::drop_begin(regionArgs), operands,
result.types)) {
2395 Type type = std::get<2>(argOperandType);
2396 std::get<0>(argOperandType).type = type;
2404 getOperandSegmentSizeAttr(),
2406 static_cast<int32_t>(numUbOperands),
2407 static_cast<int32_t>(operands.size())}));
2410 Region *body =
result.addRegion();
2411 if (regionArgs.size() !=
result.types.size() + 1)
2414 "mismatch between the number of loop-carried values and results");
2418 AffineForOp::ensureTerminator(*body, builder,
result.location);
2440 if (
auto constExpr = dyn_cast<AffineConstantExpr>(expr)) {
2441 p << constExpr.getValue();
2449 if (isa<AffineSymbolExpr>(expr)) {
2465unsigned AffineForOp::getNumIterOperands() {
2466 AffineMap lbMap = getLowerBoundMapAttr().getValue();
2467 AffineMap ubMap = getUpperBoundMapAttr().getValue();
2472std::optional<MutableArrayRef<OpOperand>>
2473AffineForOp::getYieldedValuesMutable() {
2474 return cast<AffineYieldOp>(getBody()->getTerminator()).getOperandsMutable();
2486 if (getStepAsInt() != 1)
2487 p <<
" step " << getStepAsInt();
2489 bool printBlockTerminators =
false;
2490 if (getNumIterOperands() > 0) {
2492 auto regionArgs = getRegionIterArgs();
2493 auto operands = getInits();
2495 llvm::interleaveComma(llvm::zip(regionArgs, operands), p, [&](
auto it) {
2496 p << std::get<0>(it) <<
" = " << std::get<1>(it);
2498 p <<
") -> (" << getResultTypes() <<
")";
2499 printBlockTerminators =
true;
2504 printBlockTerminators);
2510 auto foldLowerOrUpperBound = [&forOp](
bool lower) {
2514 auto boundOperands =
2515 lower ? forOp.getLowerBoundOperands() : forOp.getUpperBoundOperands();
2516 for (
auto operand : boundOperands) {
2519 operandConstants.push_back(operandCst);
2523 lower ? forOp.getLowerBoundMap() : forOp.getUpperBoundMap();
2525 "bound maps should have at least one result");
2527 if (failed(boundMap.
constantFold(operandConstants, foldedResults)))
2531 assert(!foldedResults.empty() &&
"bounds should have at least one result");
2532 auto maxOrMin = llvm::cast<IntegerAttr>(foldedResults[0]).getValue();
2533 for (
unsigned i = 1, e = foldedResults.size(); i < e; i++) {
2534 auto foldedResult = llvm::cast<IntegerAttr>(foldedResults[i]).getValue();
2535 maxOrMin = lower ? llvm::APIntOps::smax(maxOrMin, foldedResult)
2536 : llvm::APIntOps::smin(maxOrMin, foldedResult);
2538 lower ? forOp.setConstantLowerBound(maxOrMin.getSExtValue())
2539 : forOp.setConstantUpperBound(maxOrMin.getSExtValue());
2544 bool folded =
false;
2545 if (!forOp.hasConstantLowerBound())
2546 folded |= succeeded(foldLowerOrUpperBound(
true));
2549 if (!forOp.hasConstantUpperBound())
2550 folded |= succeeded(foldLowerOrUpperBound(
false));
2556 int64_t step = forOp.getStepAsInt();
2557 if (!forOp.hasConstantBounds() || step <= 0)
2558 return std::nullopt;
2559 int64_t lb = forOp.getConstantLowerBound();
2560 int64_t ub = forOp.getConstantUpperBound();
2561 return ub - lb <= 0 ? 0 : (
ub - lb + step - 1) / step;
2566 if (!llvm::hasSingleElement(*forOp.getBody()))
2568 if (forOp.getNumResults() == 0)
2571 if (tripCount == 0) {
2574 return forOp.getInits();
2577 auto yieldOp = cast<AffineYieldOp>(forOp.getBody()->getTerminator());
2578 auto iterArgs = forOp.getRegionIterArgs();
2579 bool hasValDefinedOutsideLoop =
false;
2580 bool iterArgsNotInOrder =
false;
2581 for (
unsigned i = 0, e = yieldOp->getNumOperands(); i < e; ++i) {
2582 Value val = yieldOp.getOperand(i);
2586 if (val == forOp.getInductionVar())
2588 if (iterArgIt == iterArgs.end()) {
2590 assert(forOp.isDefinedOutsideOfLoop(val) &&
2591 "must be defined outside of the loop");
2592 hasValDefinedOutsideLoop =
true;
2593 replacements.push_back(val);
2595 unsigned pos = std::distance(iterArgs.begin(), iterArgIt);
2597 iterArgsNotInOrder =
true;
2598 replacements.push_back(forOp.getInits()[pos]);
2603 if (!tripCount.has_value() &&
2604 (hasValDefinedOutsideLoop || iterArgsNotInOrder))
2608 if (tripCount.has_value() && tripCount.value() >= 2 && iterArgsNotInOrder)
2610 return llvm::to_vector_of<OpFoldResult>(replacements);
2618 auto lbMap = forOp.getLowerBoundMap();
2619 auto ubMap = forOp.getUpperBoundMap();
2620 auto prevLbMap = lbMap;
2621 auto prevUbMap = ubMap;
2634 if (lbMap == prevLbMap && ubMap == prevUbMap)
2637 if (lbMap != prevLbMap)
2638 forOp.setLowerBound(lbOperands, lbMap);
2639 if (ubMap != prevUbMap)
2640 forOp.setUpperBound(ubOperands, ubMap);
2649LogicalResult AffineForOp::fold(FoldAdaptor adaptor,
2659 results.assign(getInits().begin(), getInits().end());
2663 if (!foldResults.empty()) {
2664 results.assign(foldResults);
2673 "invalid region point");
2680void AffineForOp::getSuccessorRegions(
2685 "expected loop region");
2691 if (tripCount.has_value()) {
2695 if (tripCount == 1) {
2696 regions.push_back(RegionSuccessor(getOperation()));
2702 if (tripCount.value() > 0) {
2703 regions.push_back(RegionSuccessor(&getRegion()));
2706 if (tripCount.value() == 0) {
2707 regions.push_back(RegionSuccessor(getOperation()));
2715 regions.push_back(RegionSuccessor(&getRegion()));
2716 regions.push_back(RegionSuccessor(getOperation()));
2721 return getResults();
2722 return getRegionIterArgs();
2735 assert(map.
getNumResults() >= 1 &&
"bound map has at least one result");
2736 getLowerBoundOperandsMutable().assign(lbOperands);
2737 setLowerBoundMap(map);
2742 assert(map.
getNumResults() >= 1 &&
"bound map has at least one result");
2743 getUpperBoundOperandsMutable().assign(ubOperands);
2744 setUpperBoundMap(map);
2747bool AffineForOp::hasConstantLowerBound() {
2748 return getLowerBoundMap().isSingleConstant();
2751bool AffineForOp::hasConstantUpperBound() {
2752 return getUpperBoundMap().isSingleConstant();
2755int64_t AffineForOp::getConstantLowerBound() {
2756 return getLowerBoundMap().getSingleConstantResult();
2759int64_t AffineForOp::getConstantUpperBound() {
2760 return getUpperBoundMap().getSingleConstantResult();
2763void AffineForOp::setConstantLowerBound(
int64_t value) {
2767void AffineForOp::setConstantUpperBound(
int64_t value) {
2771AffineForOp::operand_range AffineForOp::getControlOperands() {
2776bool AffineForOp::matchingBoundOperandList() {
2777 auto lbMap = getLowerBoundMap();
2778 auto ubMap = getUpperBoundMap();
2784 for (
unsigned i = 0, e = lbMap.
getNumInputs(); i < e; i++) {
2786 if (getOperand(i) != getOperand(numOperands + i))
2794std::optional<SmallVector<Value>> AffineForOp::getLoopInductionVars() {
2795 return SmallVector<Value>{getInductionVar()};
2798std::optional<SmallVector<OpFoldResult>> AffineForOp::getLoopLowerBounds() {
2799 if (!hasConstantLowerBound())
2800 return std::nullopt;
2802 return SmallVector<OpFoldResult>{
2803 OpFoldResult(
b.getI64IntegerAttr(getConstantLowerBound()))};
2806std::optional<SmallVector<OpFoldResult>> AffineForOp::getLoopSteps() {
2808 return SmallVector<OpFoldResult>{
2809 OpFoldResult(
b.getI64IntegerAttr(getStepAsInt()))};
2812std::optional<SmallVector<OpFoldResult>> AffineForOp::getLoopUpperBounds() {
2813 if (!hasConstantUpperBound())
2816 return SmallVector<OpFoldResult>{
2817 OpFoldResult(
b.getI64IntegerAttr(getConstantUpperBound()))};
2820std::optional<APInt> AffineForOp::getStaticTripCount() {
2821 int64_t step = getStepAsInt();
2823 return std::nullopt;
2825 if (hasConstantBounds()) {
2826 int64_t lb = getConstantLowerBound();
2827 int64_t ub = getConstantUpperBound();
2828 int64_t loopSpan = ub - lb;
2831 return APInt(64, llvm::divideCeilSigned(loopSpan, step));
2834 auto lbMap = getLowerBoundMap();
2835 auto ubMap = getUpperBoundMap();
2837 return std::nullopt;
2845 AffineValueMap tripCountValueMap;
2847 &tripCountValueMap);
2850 std::optional<uint64_t> tripCount;
2851 for (
unsigned i = 0, e = tripCountValueMap.
getNumResults(); i < e; ++i) {
2853 if (
auto constExpr = llvm::dyn_cast<AffineConstantExpr>(expr)) {
2854 uint64_t value = std::max<int64_t>(constExpr.getValue(), 0);
2855 if (tripCount.has_value())
2856 tripCount = std::min(*tripCount, value);
2860 return std::nullopt;
2864 if (tripCount.has_value())
2865 return APInt(64, *tripCount);
2867 return std::nullopt;
2870FailureOr<LoopLikeOpInterface> AffineForOp::replaceWithAdditionalYields(
2872 bool replaceInitOperandUsesInLoop,
2875 OpBuilder::InsertionGuard g(rewriter);
2877 auto inits = llvm::to_vector(getInits());
2878 inits.append(newInitOperands.begin(), newInitOperands.end());
2879 AffineForOp newLoop = AffineForOp::create(
2884 newLoop->setDiscardableAttrs(getOperation()->getDiscardableAttrDictionary());
2887 auto yieldOp = cast<AffineYieldOp>(getBody()->getTerminator());
2888 ArrayRef<BlockArgument> newIterArgs =
2889 newLoop.getBody()->getArguments().take_back(newInitOperands.size());
2891 OpBuilder::InsertionGuard g(rewriter);
2893 SmallVector<Value> newYieldedValues =
2894 newYieldValuesFn(rewriter, getLoc(), newIterArgs);
2895 assert(newInitOperands.size() == newYieldedValues.size() &&
2896 "expected as many new yield values as new iter operands");
2898 yieldOp.getOperandsMutable().append(newYieldedValues);
2903 rewriter.
mergeBlocks(getBody(), newLoop.getBody(),
2904 newLoop.getBody()->getArguments().take_front(
2905 getBody()->getNumArguments()));
2907 if (replaceInitOperandUsesInLoop) {
2910 for (
auto it : llvm::zip(newInitOperands, newIterArgs)) {
2912 [&](OpOperand &use) {
2914 return newLoop->isProperAncestor(user);
2921 newLoop->getResults().take_front(getNumResults()));
2922 return cast<LoopLikeOpInterface>(newLoop.getOperation());
2950 auto ivArg = dyn_cast<BlockArgument>(val);
2951 if (!ivArg || !ivArg.getOwner() || !ivArg.getOwner()->getParent())
2952 return AffineForOp();
2954 ivArg.getOwner()->getParent()->getParentOfType<AffineForOp>())
2956 return forOp.getInductionVar() == val ? forOp : AffineForOp();
2957 return AffineForOp();
2961 auto ivArg = dyn_cast<BlockArgument>(val);
2962 if (!ivArg || !ivArg.getOwner())
2965 auto parallelOp = dyn_cast_if_present<AffineParallelOp>(containingOp);
2966 if (parallelOp && llvm::is_contained(parallelOp.getIVs(), val))
2975 ivs->reserve(forInsts.size());
2976 for (
auto forInst : forInsts)
2977 ivs->push_back(forInst.getInductionVar());
2982 ivs.reserve(affineOps.size());
2985 if (
auto forOp = dyn_cast<AffineForOp>(op))
2986 ivs.push_back(forOp.getInductionVar());
2987 else if (
auto parallelOp = dyn_cast<AffineParallelOp>(op))
2988 for (
size_t i = 0; i < parallelOp.getBody()->getNumArguments(); i++)
2989 ivs.push_back(parallelOp.getBody()->getArgument(i));
2995template <
typename BoundListTy,
typename LoopCreatorTy>
3000 LoopCreatorTy &&loopCreatorFn) {
3001 assert(lbs.size() == ubs.size() &&
"Mismatch in number of arguments");
3002 assert(lbs.size() == steps.size() &&
"Mismatch in number of arguments");
3014 ivs.reserve(lbs.size());
3015 for (
unsigned i = 0, e = lbs.size(); i < e; ++i) {
3021 if (i == e - 1 && bodyBuilderFn) {
3023 bodyBuilderFn(nestedBuilder, nestedLoc, ivs);
3025 AffineYieldOp::create(nestedBuilder, nestedLoc);
3030 auto loop = loopCreatorFn(builder, loc, lbs[i], ubs[i], steps[i], loopBody);
3039 AffineForOp::BodyBuilderFn bodyBuilderFn) {
3040 return AffineForOp::create(builder, loc, lb,
ub, step,
3048 AffineForOp::BodyBuilderFn bodyBuilderFn) {
3051 if (lbConst && ubConst)
3053 ubConst.value(), step, bodyBuilderFn);
3084 LogicalResult matchAndRewrite(AffineIfOp ifOp,
3086 if (ifOp.getElseRegion().empty() ||
3087 !llvm::hasSingleElement(*ifOp.getElseBlock()) || ifOp.getNumResults())
3100 using OpRewritePattern<AffineIfOp>::OpRewritePattern;
3102 LogicalResult matchAndRewrite(AffineIfOp op,
3103 PatternRewriter &rewriter)
const override {
3105 auto isTriviallyFalse = [](IntegerSet iSet) {
3106 return iSet.isEmptyIntegerSet();
3109 auto isTriviallyTrue = [](IntegerSet iSet) {
3110 return (iSet.getNumEqualities() == 1 && iSet.getNumInequalities() == 0 &&
3111 iSet.getConstraint(0) == 0);
3114 IntegerSet affineIfConditions = op.getIntegerSet();
3116 if (isTriviallyFalse(affineIfConditions)) {
3120 if (op.getNumResults() == 0 && !op.hasElse()) {
3126 blockToMove = op.getElseBlock();
3127 }
else if (isTriviallyTrue(affineIfConditions)) {
3128 blockToMove = op.getThenBlock();
3132 Operation *blockToMoveTerminator = blockToMove->
getTerminator();
3146 rewriter.
eraseOp(blockToMoveTerminator);
3154void AffineIfOp::getSuccessorRegions(
3162 if (getElseRegion().empty()) {
3177 return getResults();
3178 if (successor == &getThenRegion())
3179 return getThenRegion().getArguments();
3180 if (successor == &getElseRegion())
3181 return getElseRegion().getArguments();
3182 llvm_unreachable(
"invalid region successor");
3185LogicalResult AffineIfOp::verify() {
3188 auto conditionAttr = getConditionAttr();
3190 return emitOpError(
"requires an integer set attribute named 'condition'");
3193 IntegerSet condition = conditionAttr.getValue();
3195 return emitOpError(
"operand count and condition integer set dimension and "
3196 "symbol count must match");
3208 IntegerSetAttr conditionAttr;
3211 AffineIfOp::getConditionAttrStrName(),
3217 auto set = conditionAttr.getValue();
3218 if (set.getNumDims() != numDims)
3221 "dim operand count and integer set dim count must match");
3222 if (numDims + set.getNumSymbols() !=
result.operands.size())
3225 "symbol operand count and integer set symbol count must match");
3232 result.regions.reserve(2);
3239 AffineIfOp::ensureTerminator(*thenRegion, parser.
getBuilder(),
3246 AffineIfOp::ensureTerminator(*elseRegion, parser.
getBuilder(),
3258 auto conditionAttr = getConditionAttr();
3259 p <<
" " << conditionAttr;
3261 conditionAttr.getValue().getNumDims(), p);
3268 auto &elseRegion = this->getElseRegion();
3269 if (!elseRegion.
empty()) {
3280IntegerSet AffineIfOp::getIntegerSet() {
return getConditionAttr().getValue(); }
3282void AffineIfOp::setIntegerSet(
IntegerSet newSet) {
3283 setConditionAttr(IntegerSetAttr::get(newSet));
3288 (*this)->setOperands(operands);
3293 bool withElseRegion) {
3294 assert(resultTypes.empty() || withElseRegion);
3297 result.addTypes(resultTypes);
3298 result.addOperands(args);
3299 result.addAttribute(getConditionAttrStrName(), IntegerSetAttr::get(set));
3303 if (resultTypes.empty())
3304 AffineIfOp::ensureTerminator(*thenRegion, builder,
result.location);
3307 if (withElseRegion) {
3309 if (resultTypes.empty())
3310 AffineIfOp::ensureTerminator(*elseRegion, builder,
result.location);
3316 AffineIfOp::build(builder,
result, {}, set, args,
3325 bool composeAffineMin =
false) {
3332 if (llvm::none_of(operands,
3343 auto set = getIntegerSet();
3349 if (getIntegerSet() == set && llvm::equal(operands, getOperands()))
3352 setConditional(set, operands);
3358 results.
add<SimplifyDeadElse, AlwaysTrueOrFalseIf>(context);
3363 StringAttr attrName, llvm::MaybeAlign alignment) {
3365 result.addAttribute(attrName,
3375 llvm::MaybeAlign alignment) {
3376 assert(operands.size() == 1 + map.
getNumInputs() &&
"inconsistent operands");
3377 result.addOperands(operands);
3379 result.addAttribute(getMapAttrStrName(), AffineMapAttr::get(map));
3382 auto memrefType = llvm::cast<MemRefType>(operands[0].
getType());
3383 result.types.push_back(memrefType.getElementType());
3388 llvm::MaybeAlign alignment) {
3389 assert(map.
getNumInputs() == mapOperands.size() &&
"inconsistent index info");
3391 result.addOperands(mapOperands);
3392 auto memrefType = llvm::cast<MemRefType>(
memref.getType());
3393 result.addAttribute(getMapAttrStrName(), AffineMapAttr::get(map));
3396 result.types.push_back(memrefType.getElementType());
3401 llvm::MaybeAlign alignment) {
3402 auto memrefType = llvm::cast<MemRefType>(
memref.getType());
3403 int64_t rank = memrefType.getRank();
3417 AffineMapAttr mapAttr;
3422 AffineLoadOp::getMapAttrStrName(),
3432 p <<
" " << getMemRef() <<
'[';
3433 if (AffineMapAttr mapAttr = getMapAttr())
3437 if (IntegerAttr alignment = getAlignmentAttr())
3438 attrs.emplace_back(getAlignmentAttrName(), alignment);
3446template <
typename AffineMemOpTy>
3450 MemRefType memrefType,
unsigned numIndexOperands) {
3453 return op->emitOpError(
"affine map num results must equal memref rank");
3455 return op->emitOpError(
"expects as many subscripts as affine map inputs");
3457 for (
auto idx : mapOperands) {
3458 if (!idx.getType().isIndex())
3459 return op->emitOpError(
"index to load must have 'index' type");
3467LogicalResult AffineLoadOp::verify() {
3469 if (
getType() != memrefType.getElementType())
3470 return emitOpError(
"result type must match element type of memref");
3474 getNumOperands() - 1)))
3482 results.
add<SimplifyAffineOp<AffineLoadOp>>(context);
3491 auto getGlobalOp = getMemref().getDefiningOp<memref::GetGlobalOp>();
3496 getGlobalOp, getGlobalOp.getNameAttr());
3502 dyn_cast_or_null<DenseElementsAttr>(global.getConstantInitValue());
3506 if (
auto splatAttr = dyn_cast<SplatElementsAttr>(cstAttr))
3507 return splatAttr.getSplatValue<
Attribute>();
3509 if (!getAffineMap().isConstant())
3512 llvm::map_to_vector<4>(getAffineMap().getConstantResults(),
3513 [](
int64_t v) -> uint64_t {
return v; });
3514 ElementsAttr elementsAttr = cstAttr;
3515 if (!elementsAttr.isValidIndex(
indices))
3526 ValueRange mapOperands, llvm::MaybeAlign alignment) {
3527 assert(map.
getNumInputs() == mapOperands.size() &&
"inconsistent index info");
3528 result.addOperands(valueToStore);
3530 result.addOperands(mapOperands);
3531 result.getOrAddProperties<Properties>().map = AffineMapAttr::get(map);
3539 llvm::MaybeAlign alignment) {
3540 auto memrefType = llvm::cast<MemRefType>(
memref.getType());
3541 int64_t rank = memrefType.getRank();
3555 AffineMapAttr mapAttr;
3560 mapOperands, mapAttr, AffineStoreOp::getMapAttrStrName(),
3571 p <<
" " << getValueToStore();
3572 p <<
", " << getMemRef() <<
'[';
3573 if (AffineMapAttr mapAttr = getMapAttr())
3577 if (IntegerAttr alignment = getAlignmentAttr())
3578 attrs.emplace_back(getAlignmentAttrName(), alignment);
3584LogicalResult AffineStoreOp::verify() {
3587 if (getValueToStore().
getType() != memrefType.getElementType())
3589 "value to store must have the same type as memref element type");
3593 getNumOperands() - 2)))
3601 results.
add<SimplifyAffineOp<AffineStoreOp>>(context);
3604LogicalResult AffineStoreOp::fold(FoldAdaptor adaptor,
3614template <
typename T>
3617 if (op.getNumOperands() !=
3618 op.getMap().getNumDims() + op.getMap().getNumSymbols())
3619 return op.emitOpError(
3620 "operand count and affine map dimension and symbol count must match");
3622 if (op.getMap().getNumResults() == 0)
3623 return op.emitOpError(
"affine map expect at least one result");
3627template <
typename T>
3629 p <<
' ' << op.getMapAttr();
3630 auto operands = op.getOperands();
3631 unsigned numDims = op.getMap().getNumDims();
3632 p <<
'(' << operands.take_front(numDims) <<
')';
3634 if (operands.size() != numDims)
3635 p <<
'[' << operands.drop_front(numDims) <<
']';
3639template <
typename T>
3646 AffineMapAttr mapAttr;
3662template <
typename T>
3664 static_assert(llvm::is_one_of<T, AffineMinOp, AffineMaxOp>::value,
3665 "expected affine min or max op");
3671 auto foldedMap = op.getMap().partialConstantFold(operands, &results);
3673 if (foldedMap.getNumSymbols() == 1 && foldedMap.isSymbolIdentity())
3674 return op.getOperand(0);
3677 if (results.empty()) {
3679 if (foldedMap == op.getMap())
3681 op.setMapAttr(AffineMapAttr::get(foldedMap));
3682 return op.getResult();
3686 auto resultIt = std::is_same<T, AffineMinOp>::value
3687 ? llvm::min_element(results)
3688 : llvm::max_element(results);
3689 if (resultIt == results.end())
3691 return IntegerAttr::get(IndexType::get(op.getContext()), *resultIt);
3695template <
typename T>
3701 AffineMap oldMap = affineOp.getAffineMap();
3707 if (!llvm::is_contained(newExprs, expr))
3708 newExprs.push_back(expr);
3738template <
typename T>
3744 AffineMap oldMap = affineOp.getAffineMap();
3746 affineOp.getMapOperands().take_front(oldMap.
getNumDims());
3748 affineOp.getMapOperands().take_back(oldMap.
getNumSymbols());
3750 auto newDimOperands = llvm::to_vector<8>(dimOperands);
3751 auto newSymOperands = llvm::to_vector<8>(symOperands);
3759 if (
auto symExpr = dyn_cast<AffineSymbolExpr>(expr)) {
3760 Value symValue = symOperands[symExpr.getPosition()];
3762 producerOps.push_back(producerOp);
3765 }
else if (
auto dimExpr = dyn_cast<AffineDimExpr>(expr)) {
3766 Value dimValue = dimOperands[dimExpr.getPosition()];
3768 producerOps.push_back(producerOp);
3775 newExprs.push_back(expr);
3778 if (producerOps.empty())
3785 for (T producerOp : producerOps) {
3786 AffineMap producerMap = producerOp.getAffineMap();
3787 unsigned numProducerDims = producerMap.
getNumDims();
3792 producerOp.getMapOperands().take_front(numProducerDims);
3794 producerOp.getMapOperands().take_back(numProducerSyms);
3795 newDimOperands.append(dimValues.begin(), dimValues.end());
3796 newSymOperands.append(symValues.begin(), symValues.end());
3800 newExprs.push_back(expr.
shiftDims(numProducerDims, numUsedDims)
3804 numUsedDims += numProducerDims;
3805 numUsedSyms += numProducerSyms;
3811 llvm::to_vector<8>(llvm::concat<Value>(newDimOperands, newSymOperands));
3830 if (!resultExpr.isPureAffine())
3835 if (failed(flattenResult))
3848 if (llvm::is_sorted(flattenedExprs))
3853 llvm::to_vector(llvm::seq<unsigned>(0, map.
getNumResults()));
3854 llvm::sort(resultPermutation, [&](
unsigned lhs,
unsigned rhs) {
3855 return flattenedExprs[lhs] < flattenedExprs[rhs];
3858 for (
unsigned idx : resultPermutation)
3879template <
typename T>
3885 AffineMap map = affineOp.getAffineMap();
3893template <
typename T>
3899 if (affineOp.getMap().getNumResults() != 1)
3902 affineOp.getOperands());
3970ParseResult AffinePrefetchOp::parse(
OpAsmParser &parser,
3977 IntegerAttr hintInfo;
3979 StringRef readOrWrite, cacheType;
3981 AffineMapAttr mapAttr;
3985 AffinePrefetchOp::getMapAttrStrName(),
3991 AffinePrefetchOp::getLocalityHintAttrStrName(),
4001 if (readOrWrite !=
"read" && readOrWrite !=
"write")
4003 "rw specifier has to be 'read' or 'write'");
4004 result.addAttribute(AffinePrefetchOp::getIsWriteAttrStrName(),
4007 if (cacheType !=
"data" && cacheType !=
"instr")
4009 "cache type has to be 'data' or 'instr'");
4011 result.addAttribute(AffinePrefetchOp::getIsDataCacheAttrStrName(),
4018 p <<
" " << getMemref() <<
'[';
4019 AffineMapAttr mapAttr = getMapAttr();
4022 p <<
']' <<
", " << (getIsWrite() ?
"write" :
"read") <<
", " <<
"locality<"
4023 << getLocalityHint() <<
">, " << (getIsDataCache() ?
"data" :
"instr");
4028LogicalResult AffinePrefetchOp::verify() {
4029 auto mapAttr = getMapAttr();
4033 return emitOpError(
"affine.prefetch affine map num results must equal"
4036 return emitOpError(
"too few operands");
4038 if (getNumOperands() != 1)
4039 return emitOpError(
"too few operands");
4043 for (
auto idx : getMapOperands()) {
4046 "index must be a valid dimension or symbol identifier");
4054 results.
add<SimplifyAffineOp<AffinePrefetchOp>>(context);
4057LogicalResult AffinePrefetchOp::fold(FoldAdaptor adaptor,
4072 auto ubs = llvm::map_to_vector<4>(ranges, [&](
int64_t value) {
4076 build(builder,
result, resultTypes, reductions, lbs, {}, ubs,
4086 assert(llvm::all_of(lbMaps,
4088 return m.
getNumDims() == lbMaps[0].getNumDims() &&
4091 "expected all lower bounds maps to have the same number of dimensions "
4093 assert(llvm::all_of(ubMaps,
4095 return m.
getNumDims() == ubMaps[0].getNumDims() &&
4098 "expected all upper bounds maps to have the same number of dimensions "
4100 assert((lbMaps.empty() || lbMaps[0].getNumInputs() == lbArgs.size()) &&
4101 "expected lower bound maps to have as many inputs as lower bound "
4103 assert((ubMaps.empty() || ubMaps[0].getNumInputs() == ubArgs.size()) &&
4104 "expected upper bound maps to have as many inputs as upper bound "
4108 result.addTypes(resultTypes);
4112 for (arith::AtomicRMWKind reduction : reductions)
4113 reductionAttrs.push_back(
4115 result.addAttribute(getReductionsAttrStrName(),
4125 groups.reserve(groups.size() + maps.size());
4126 exprs.reserve(maps.size());
4131 return AffineMap::get(maps[0].getNumDims(), maps[0].getNumSymbols(), exprs,
4137 AffineMap lbMap = concatMapsSameInput(lbMaps, lbGroups);
4138 AffineMap ubMap = concatMapsSameInput(ubMaps, ubGroups);
4139 result.addAttribute(getLowerBoundsMapAttrStrName(),
4140 AffineMapAttr::get(lbMap));
4141 result.addAttribute(getLowerBoundsGroupsAttrStrName(),
4143 result.addAttribute(getUpperBoundsMapAttrStrName(),
4144 AffineMapAttr::get(ubMap));
4145 result.addAttribute(getUpperBoundsGroupsAttrStrName(),
4148 result.addOperands(lbArgs);
4149 result.addOperands(ubArgs);
4152 auto *bodyRegion =
result.addRegion();
4156 for (
unsigned i = 0, e = steps.size(); i < e; ++i)
4158 if (resultTypes.empty())
4159 ensureTerminator(*bodyRegion, builder,
result.location);
4163 return {&getRegion()};
4166unsigned AffineParallelOp::getNumDims() {
return getSteps().size(); }
4168AffineParallelOp::operand_range AffineParallelOp::getLowerBoundsOperands() {
4169 return getOperands().take_front(getLowerBoundsMap().getNumInputs());
4172AffineParallelOp::operand_range AffineParallelOp::getUpperBoundsOperands() {
4173 return getOperands().drop_front(getLowerBoundsMap().getNumInputs());
4176AffineMap AffineParallelOp::getLowerBoundMap(
unsigned pos) {
4177 auto values = getLowerBoundsGroups().getValues<int32_t>();
4179 for (
unsigned i = 0; i < pos; ++i)
4181 return getLowerBoundsMap().getSliceMap(start, values[pos]);
4184AffineMap AffineParallelOp::getUpperBoundMap(
unsigned pos) {
4185 auto values = getUpperBoundsGroups().getValues<int32_t>();
4187 for (
unsigned i = 0; i < pos; ++i)
4189 return getUpperBoundsMap().getSliceMap(start, values[pos]);
4193 return AffineValueMap(getLowerBoundsMap(), getLowerBoundsOperands());
4197 return AffineValueMap(getUpperBoundsMap(), getUpperBoundsOperands());
4200std::optional<SmallVector<int64_t, 8>> AffineParallelOp::getConstantRanges() {
4201 if (hasMinMaxBounds())
4202 return std::nullopt;
4210 for (
unsigned i = 0, e = rangesValueMap.
getNumResults(); i < e; ++i) {
4211 auto expr = rangesValueMap.
getResult(i);
4212 auto cst = dyn_cast<AffineConstantExpr>(expr);
4214 return std::nullopt;
4215 out.push_back(cst.getValue());
4220Block *AffineParallelOp::getBody() {
return &getRegion().
front(); }
4222OpBuilder AffineParallelOp::getBodyBuilder() {
4223 return OpBuilder(getBody(), std::prev(getBody()->end()));
4228 "operands to map must match number of inputs");
4230 auto ubOperands = getUpperBoundsOperands();
4233 newOperands.append(ubOperands.begin(), ubOperands.end());
4234 (*this)->setOperands(newOperands);
4236 setLowerBoundsMapAttr(AffineMapAttr::get(map));
4241 "operands to map must match number of inputs");
4244 newOperands.append(ubOperands.begin(), ubOperands.end());
4245 (*this)->setOperands(newOperands);
4247 setUpperBoundsMapAttr(AffineMapAttr::get(map));
4256 arith::AtomicRMWKind op) {
4258 case arith::AtomicRMWKind::addf:
4259 return isa<FloatType>(resultType);
4260 case arith::AtomicRMWKind::addi:
4261 return isa<IntegerType>(resultType);
4262 case arith::AtomicRMWKind::assign:
4264 case arith::AtomicRMWKind::mulf:
4265 return isa<FloatType>(resultType);
4266 case arith::AtomicRMWKind::muli:
4267 return isa<IntegerType>(resultType);
4268 case arith::AtomicRMWKind::maximumf:
4269 case arith::AtomicRMWKind::maxnumf:
4270 case arith::AtomicRMWKind::minimumf:
4271 case arith::AtomicRMWKind::minnumf:
4272 return isa<FloatType>(resultType);
4276 case arith::AtomicRMWKind::maxs:
4277 case arith::AtomicRMWKind::mins: {
4278 auto intType = dyn_cast<IntegerType>(resultType);
4279 return intType && !intType.isUnsigned();
4281 case arith::AtomicRMWKind::maxu:
4282 case arith::AtomicRMWKind::minu: {
4283 auto intType = dyn_cast<IntegerType>(resultType);
4284 return intType && !intType.isSigned();
4286 case arith::AtomicRMWKind::ori:
4287 case arith::AtomicRMWKind::andi:
4288 case arith::AtomicRMWKind::xori:
4289 return isa<IntegerType>(resultType);
4291 llvm_unreachable(
"Unhandled atomic rmw kind");
4294LogicalResult AffineParallelOp::verify() {
4295 auto numDims = getNumDims();
4298 getSteps().size() != numDims || getBody()->getNumArguments() != numDims) {
4299 return emitOpError() <<
"the number of region arguments ("
4300 << getBody()->getNumArguments()
4301 <<
") and the number of map groups for lower ("
4302 << getLowerBoundsGroups().getNumElements()
4303 <<
") and upper bound ("
4304 << getUpperBoundsGroups().getNumElements()
4305 <<
"), and the number of steps (" << getSteps().size()
4306 <<
") must all match";
4309 unsigned expectedNumLBResults = 0;
4310 for (APInt v : getLowerBoundsGroups()) {
4311 unsigned results = v.getZExtValue();
4313 return emitOpError()
4314 <<
"expected lower bound map to have at least one result";
4315 expectedNumLBResults += results;
4317 if (expectedNumLBResults != getLowerBoundsMap().getNumResults())
4318 return emitOpError() <<
"expected lower bounds map to have "
4319 << expectedNumLBResults <<
" results";
4320 unsigned expectedNumUBResults = 0;
4321 for (APInt v : getUpperBoundsGroups()) {
4322 unsigned results = v.getZExtValue();
4324 return emitOpError()
4325 <<
"expected upper bound map to have at least one result";
4326 expectedNumUBResults += results;
4328 if (expectedNumUBResults != getUpperBoundsMap().getNumResults())
4329 return emitOpError() <<
"expected upper bounds map to have "
4330 << expectedNumUBResults <<
" results";
4332 if (getReductions().size() != getNumResults())
4333 return emitOpError(
"a reduction must be specified for each output");
4337 for (
auto it : llvm::enumerate((getReductions()))) {
4339 auto intAttr = dyn_cast<IntegerAttr>(attr);
4340 if (!intAttr || !arith::symbolizeAtomicRMWKind(intAttr.getInt()))
4341 return emitOpError(
"invalid reduction attribute");
4342 auto kind = arith::symbolizeAtomicRMWKind(intAttr.getInt()).value();
4344 return emitOpError(
"result type cannot match reduction attribute");
4350 getLowerBoundsMap().getNumDims())))
4354 getUpperBoundsMap().getNumDims())))
4363 if (newMap ==
getAffineMap() && newOperands == operands)
4365 reset(newMap, newOperands);
4375 bool ubCanonicalized = succeeded(
ub.canonicalize());
4378 if (!lbCanonicalized && !ubCanonicalized)
4381 if (lbCanonicalized)
4383 if (ubCanonicalized)
4384 op.setUpperBounds(
ub.getOperands(),
ub.getAffineMap());
4389LogicalResult AffineParallelOp::fold(FoldAdaptor adaptor,
4390 SmallVectorImpl<OpFoldResult> &results) {
4401 StringRef keyword) {
4404 ValueRange dimOperands = operands.take_front(numDims);
4405 ValueRange symOperands = operands.drop_front(numDims);
4407 for (llvm::APInt groupSize : group) {
4411 unsigned size = groupSize.getZExtValue();
4416 p << keyword <<
'(';
4425void AffineParallelOp::print(OpAsmPrinter &p) {
4426 p <<
" (" << getBody()->getArguments() <<
") = (";
4428 getLowerBoundsOperands(),
"max");
4431 getUpperBoundsOperands(),
"min");
4433 SmallVector<int64_t, 8> steps = getSteps();
4434 bool elideSteps = llvm::all_of(steps, [](int64_t step) {
return step == 1; });
4437 llvm::interleaveComma(steps, p);
4440 if (getNumResults()) {
4442 llvm::interleaveComma(getReductions(), p, [&](
auto &attr) {
4443 arith::AtomicRMWKind sym = *arith::symbolizeAtomicRMWKind(
4444 llvm::cast<IntegerAttr>(attr).getInt());
4445 p <<
"\"" << arith::stringifyAtomicRMWKind(sym) <<
"\"";
4447 p <<
") -> (" << getResultTypes() <<
")";
4460static ParseResult deduplicateAndResolveOperands(
4461 OpAsmParser &parser,
4462 ArrayRef<SmallVector<OpAsmParser::UnresolvedOperand>> operands,
4463 SmallVectorImpl<Value> &uniqueOperands,
4464 SmallVectorImpl<AffineExpr> &replacements,
AffineExprKind kind) {
4466 "expected operands to be dim or symbol expression");
4469 for (
const auto &list : operands) {
4470 SmallVector<Value> valueOperands;
4473 for (Value operand : valueOperands) {
4474 unsigned pos = std::distance(uniqueOperands.begin(),
4475 llvm::find(uniqueOperands, operand));
4476 if (pos == uniqueOperands.size())
4477 uniqueOperands.push_back(operand);
4478 replacements.push_back(
4488enum class MinMaxKind { Min, Max };
4507static ParseResult parseAffineMapWithMinMax(OpAsmParser &parser,
4512 const llvm::StringLiteral tmpAttrStrName =
"__pseudo_bound_map";
4514 StringRef mapName = kind == MinMaxKind::Min
4515 ? AffineParallelOp::getUpperBoundsMapAttrStrName()
4516 : AffineParallelOp::getLowerBoundsMapAttrStrName();
4517 StringRef groupsName =
4518 kind == MinMaxKind::Min
4519 ? AffineParallelOp::getUpperBoundsGroupsAttrStrName()
4520 : AffineParallelOp::getLowerBoundsGroupsAttrStrName();
4526 result.addAttribute(
4527 mapName, AffineMapAttr::get(parser.getBuilder().getEmptyAffineMap()));
4528 result.addAttribute(groupsName, parser.getBuilder().getI32TensorAttr({}));
4532 SmallVector<AffineExpr> flatExprs;
4533 SmallVector<SmallVector<OpAsmParser::UnresolvedOperand>> flatDimOperands;
4534 SmallVector<SmallVector<OpAsmParser::UnresolvedOperand>> flatSymOperands;
4535 SmallVector<int32_t> numMapsPerGroup;
4536 SmallVector<OpAsmParser::UnresolvedOperand> mapOperands;
4537 auto parseOperands = [&]() {
4539 kind == MinMaxKind::Min ?
"min" :
"max"))) {
4540 mapOperands.clear();
4546 result.attributes.erase(tmpAttrStrName);
4547 llvm::append_range(flatExprs, map.getValue().getResults());
4548 auto operandsRef = llvm::ArrayRef(mapOperands);
4549 auto dimsRef = operandsRef.take_front(map.getValue().getNumDims());
4550 SmallVector<OpAsmParser::UnresolvedOperand> dims(dimsRef);
4551 auto symsRef = operandsRef.drop_front(map.getValue().getNumDims());
4552 SmallVector<OpAsmParser::UnresolvedOperand> syms(symsRef);
4553 flatDimOperands.append(map.getValue().getNumResults(), dims);
4554 flatSymOperands.append(map.getValue().getNumResults(), syms);
4555 numMapsPerGroup.push_back(map.getValue().getNumResults());
4558 flatSymOperands.emplace_back(),
4559 flatExprs.emplace_back())))
4561 numMapsPerGroup.push_back(1);
4568 unsigned totalNumDims = 0;
4569 unsigned totalNumSyms = 0;
4570 for (
unsigned i = 0, e = flatExprs.size(); i < e; ++i) {
4571 unsigned numDims = flatDimOperands[i].size();
4572 unsigned numSyms = flatSymOperands[i].size();
4573 flatExprs[i] = flatExprs[i]
4574 .shiftDims(numDims, totalNumDims)
4575 .shiftSymbols(numSyms, totalNumSyms);
4576 totalNumDims += numDims;
4577 totalNumSyms += numSyms;
4581 SmallVector<Value> dimOperands, symOperands;
4582 SmallVector<AffineExpr> dimRplacements, symRepacements;
4583 if (deduplicateAndResolveOperands(parser, flatDimOperands, dimOperands,
4585 deduplicateAndResolveOperands(parser, flatSymOperands, symOperands,
4589 result.operands.append(dimOperands.begin(), dimOperands.end());
4590 result.operands.append(symOperands.begin(), symOperands.end());
4593 auto flatMap =
AffineMap::get(totalNumDims, totalNumSyms, flatExprs,
4595 flatMap = flatMap.replaceDimsAndSymbols(
4596 dimRplacements, symRepacements, dimOperands.size(), symOperands.size());
4598 result.addAttribute(mapName, AffineMapAttr::get(flatMap));
4608ParseResult AffineParallelOp::parse(OpAsmParser &parser,
4609 OperationState &
result) {
4612 SmallVector<OpAsmParser::Argument, 4> ivs;
4615 parseAffineMapWithMinMax(parser,
result, MinMaxKind::Max) ||
4617 parseAffineMapWithMinMax(parser,
result, MinMaxKind::Min))
4620 AffineMapAttr stepsMapAttr;
4621 NamedAttrList stepsAttrs;
4622 SmallVector<OpAsmParser::UnresolvedOperand, 4> stepsMapOperands;
4624 SmallVector<int64_t, 4> steps(ivs.size(), 1);
4625 result.addAttribute(AffineParallelOp::getStepsAttrStrName(),
4629 AffineParallelOp::getStepsAttrStrName(),
4635 SmallVector<int64_t, 4> steps;
4636 auto stepsMap = stepsMapAttr.getValue();
4637 for (
const auto &
result : stepsMap.getResults()) {
4638 auto constExpr = dyn_cast<AffineConstantExpr>(
result);
4641 "steps must be constant integers");
4642 steps.push_back(constExpr.getValue());
4644 result.addAttribute(AffineParallelOp::getStepsAttrStrName(),
4650 SmallVector<Attribute, 4> reductions;
4654 auto parseAttributes = [&]() -> ParseResult {
4659 NamedAttrList attrStorage;
4664 std::optional<arith::AtomicRMWKind> reduction =
4665 arith::symbolizeAtomicRMWKind(attrVal.getValue());
4667 return parser.
emitError(loc,
"invalid reduction value: ") << attrVal;
4668 reductions.push_back(
4676 result.addAttribute(AffineParallelOp::getReductionsAttrStrName(),
4684 Region *body =
result.addRegion();
4685 for (
auto &iv : ivs)
4686 iv.type = indexType;
4692 AffineParallelOp::ensureTerminator(*body, builder,
result.location);
4696void AffineParallelOp::getSuccessorRegions(
4697 RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ions) {
4701 "expected loop region");
4705 regions.push_back(RegionSuccessor(&getRegion()));
4706 regions.push_back(RegionSuccessor(getOperation()));
4713LogicalResult AffineYieldOp::verify() {
4714 auto *parentOp = (*this)->getParentOp();
4715 auto results = parentOp->getResults();
4716 auto operands = getOperands();
4718 if (!isa<AffineParallelOp, AffineIfOp, AffineForOp>(parentOp))
4719 return emitOpError() <<
"only terminates affine.if/for/parallel regions";
4720 if (parentOp->getNumResults() != getNumOperands())
4721 return emitOpError() <<
"parent of yield must have same number of "
4722 "results as the yield operands";
4723 for (
auto it : llvm::zip(results, operands)) {
4725 return emitOpError() <<
"types mismatch between yield op and its parent";
4732AffineYieldOp::getMutableSuccessorOperands(RegionSuccessor point) {
4734 if (isa_and_nonnull<AffineParallelOp>((*this)->getParentOp()))
4735 return MutableOperandRange(getOperation(), 0, 0);
4743void AffineVectorLoadOp::build(OpBuilder &builder, OperationState &
result,
4744 VectorType resultType, AffineMap map,
4746 llvm::MaybeAlign alignment) {
4747 assert(operands.size() == 1 + map.
getNumInputs() &&
"inconsistent operands");
4748 result.addOperands(operands);
4750 result.addAttribute(getMapAttrStrName(), AffineMapAttr::get(map));
4753 result.types.push_back(resultType);
4756void AffineVectorLoadOp::build(OpBuilder &builder, OperationState &
result,
4757 VectorType resultType, Value memref,
4759 llvm::MaybeAlign alignment) {
4760 assert(map.
getNumInputs() == mapOperands.size() &&
"inconsistent index info");
4761 result.addOperands(memref);
4762 result.addOperands(mapOperands);
4763 result.addAttribute(getMapAttrStrName(), AffineMapAttr::get(map));
4766 result.types.push_back(resultType);
4769void AffineVectorLoadOp::build(OpBuilder &builder, OperationState &
result,
4770 VectorType resultType, Value memref,
4772 auto memrefType = llvm::cast<MemRefType>(memref.
getType());
4773 int64_t rank = memrefType.getRank();
4778 build(builder,
result, resultType, memref, map,
indices, alignment);
4781void AffineVectorLoadOp::getCanonicalizationPatterns(RewritePatternSet &results,
4782 MLIRContext *context) {
4783 results.
add<SimplifyAffineOp<AffineVectorLoadOp>>(context);
4786ParseResult AffineVectorLoadOp::parse(OpAsmParser &parser,
4787 OperationState &
result) {
4791 MemRefType memrefType;
4792 VectorType resultType;
4793 OpAsmParser::UnresolvedOperand memrefInfo;
4794 AffineMapAttr mapAttr;
4795 SmallVector<OpAsmParser::UnresolvedOperand, 1> mapOperands;
4799 AffineVectorLoadOp::getMapAttrStrName(),
4809void AffineVectorLoadOp::print(OpAsmPrinter &p) {
4810 p <<
" " << getMemRef() <<
'[';
4811 if (AffineMapAttr mapAttr = getMapAttr())
4814 SmallVector<NamedAttribute> attrs((*this)->getDiscardableAttrs());
4815 if (IntegerAttr alignment = getAlignmentAttr())
4816 attrs.emplace_back(getAlignmentAttrName(), alignment);
4824 VectorType vectorType) {
4826 if (memrefType.getElementType() != vectorType.getElementType())
4828 "requires memref and vector types of the same elemental type");
4832LogicalResult AffineVectorLoadOp::verify() {
4836 getNumOperands() - 1)))
4849void AffineVectorStoreOp::build(OpBuilder &builder, OperationState &
result,
4850 Value valueToStore, Value memref, AffineMap map,
4852 llvm::MaybeAlign alignment) {
4853 assert(map.
getNumInputs() == mapOperands.size() &&
"inconsistent index info");
4854 result.addOperands(valueToStore);
4855 result.addOperands(memref);
4856 result.addOperands(mapOperands);
4857 result.addAttribute(getMapAttrStrName(), AffineMapAttr::get(map));
4863void AffineVectorStoreOp::build(OpBuilder &builder, OperationState &
result,
4864 Value valueToStore, Value memref,
4866 llvm::MaybeAlign alignment) {
4867 auto memrefType = llvm::cast<MemRefType>(memref.
getType());
4868 int64_t rank = memrefType.getRank();
4873 build(builder,
result, valueToStore, memref, map,
indices, alignment);
4875void AffineVectorStoreOp::getCanonicalizationPatterns(
4876 RewritePatternSet &results, MLIRContext *context) {
4877 results.
add<SimplifyAffineOp<AffineVectorStoreOp>>(context);
4880ParseResult AffineVectorStoreOp::parse(OpAsmParser &parser,
4881 OperationState &
result) {
4884 MemRefType memrefType;
4885 VectorType resultType;
4886 OpAsmParser::UnresolvedOperand storeValueInfo;
4887 OpAsmParser::UnresolvedOperand memrefInfo;
4888 AffineMapAttr mapAttr;
4889 SmallVector<OpAsmParser::UnresolvedOperand, 1> mapOperands;
4894 AffineVectorStoreOp::getMapAttrStrName(),
4904void AffineVectorStoreOp::print(OpAsmPrinter &p) {
4905 p <<
" " << getValueToStore();
4906 p <<
", " << getMemRef() <<
'[';
4907 if (AffineMapAttr mapAttr = getMapAttr())
4910 SmallVector<NamedAttribute> attrs((*this)->getDiscardableAttrs());
4911 if (IntegerAttr alignment = getAlignmentAttr())
4912 attrs.emplace_back(getAlignmentAttrName(), alignment);
4915 p <<
" : " <<
getMemRefType() <<
", " << getValueToStore().getType();
4918LogicalResult AffineVectorStoreOp::verify() {
4922 getNumOperands() - 2)))
4935void AffineDelinearizeIndexOp::build(OpBuilder &odsBuilder,
4936 OperationState &odsState,
4938 ArrayRef<int64_t> staticBasis,
4939 bool hasOuterBound) {
4940 SmallVector<Type> returnTypes(hasOuterBound ? staticBasis.size()
4941 : staticBasis.size() + 1,
4943 build(odsBuilder, odsState, returnTypes, linearIndex, dynamicBasis,
4947void AffineDelinearizeIndexOp::build(OpBuilder &odsBuilder,
4948 OperationState &odsState,
4950 bool hasOuterBound) {
4951 if (hasOuterBound && !basis.empty() && basis.front() ==
nullptr) {
4952 hasOuterBound =
false;
4953 basis = basis.drop_front();
4955 SmallVector<Value> dynamicBasis;
4956 SmallVector<int64_t> staticBasis;
4959 build(odsBuilder, odsState, linearIndex, dynamicBasis, staticBasis,
4963void AffineDelinearizeIndexOp::build(OpBuilder &odsBuilder,
4964 OperationState &odsState,
4966 ArrayRef<OpFoldResult> basis,
4967 bool hasOuterBound) {
4968 if (hasOuterBound && !basis.empty() && basis.front() == OpFoldResult()) {
4969 hasOuterBound =
false;
4970 basis = basis.drop_front();
4972 SmallVector<Value> dynamicBasis;
4973 SmallVector<int64_t> staticBasis;
4975 build(odsBuilder, odsState, linearIndex, dynamicBasis, staticBasis,
4979void AffineDelinearizeIndexOp::build(OpBuilder &odsBuilder,
4980 OperationState &odsState,
4981 Value linearIndex, ArrayRef<int64_t> basis,
4982 bool hasOuterBound) {
4983 build(odsBuilder, odsState, linearIndex,
ValueRange{}, basis, hasOuterBound);
4986LogicalResult AffineDelinearizeIndexOp::verify() {
4987 ArrayRef<int64_t> staticBasis = getStaticBasis();
4988 if (getNumResults() != staticBasis.size() &&
4989 getNumResults() != staticBasis.size() + 1)
4990 return emitOpError(
"should return an index for each basis element and up "
4991 "to one extra index");
4993 auto dynamicMarkersCount = llvm::count_if(staticBasis, ShapedType::isDynamic);
4994 if (
static_cast<size_t>(dynamicMarkersCount) != getDynamicBasis().size())
4996 "mismatch between dynamic and static basis (kDynamic marker but no "
4997 "corresponding dynamic basis entry) -- this can only happen due to an "
4998 "incorrect fold/rewrite");
5000 if (!llvm::all_of(staticBasis, [](int64_t v) {
5001 return v > 0 || ShapedType::isDynamic(v);
5003 return emitOpError(
"no basis element may be statically non-positive");
5012static std::optional<SmallVector<int64_t>>
5016 uint64_t dynamicBasisIndex = 0;
5022 if (basis && isa<IntegerAttr>(basis)) {
5023 mutableDynamicBasis.
erase(dynamicBasisIndex);
5025 ++dynamicBasisIndex;
5030 if (dynamicBasisIndex == dynamicBasis.size())
5031 return std::nullopt;
5037 staticBasis.push_back(ShapedType::kDynamic);
5039 staticBasis.push_back(*basisVal);
5046AffineDelinearizeIndexOp::fold(FoldAdaptor adaptor,
5047 SmallVectorImpl<OpFoldResult> &
result) {
5048 std::optional<SmallVector<int64_t>> maybeStaticBasis =
5050 adaptor.getDynamicBasis());
5051 if (maybeStaticBasis) {
5052 setStaticBasis(*maybeStaticBasis);
5057 if (getNumResults() == 1) {
5058 result.push_back(getLinearIndex());
5062 if (adaptor.getLinearIndex() ==
nullptr)
5065 if (!adaptor.getDynamicBasis().empty())
5068 int64_t highPart = cast<IntegerAttr>(adaptor.getLinearIndex()).getInt();
5069 Type attrType = getLinearIndex().getType();
5071 ArrayRef<int64_t> staticBasis = getStaticBasis();
5072 if (hasOuterBound())
5073 staticBasis = staticBasis.drop_front();
5074 for (int64_t modulus : llvm::reverse(staticBasis)) {
5075 result.push_back(IntegerAttr::get(attrType, llvm::mod(highPart, modulus)));
5076 highPart = llvm::divideFloorSigned(highPart, modulus);
5078 result.push_back(IntegerAttr::get(attrType, highPart));
5083SmallVector<OpFoldResult> AffineDelinearizeIndexOp::getEffectiveBasis() {
5085 if (hasOuterBound()) {
5086 if (getStaticBasis().front() == ::mlir::ShapedType::kDynamic)
5088 getDynamicBasis().drop_front(), builder);
5090 return getMixedValues(getStaticBasis().drop_front(), getDynamicBasis(),
5094 return getMixedValues(getStaticBasis(), getDynamicBasis(), builder);
5097SmallVector<OpFoldResult> AffineDelinearizeIndexOp::getPaddedBasis() {
5098 SmallVector<OpFoldResult> ret = getMixedBasis();
5099 if (!hasOuterBound())
5100 ret.insert(ret.begin(), OpFoldResult());
5106struct DropUnitExtentBasis
5107 :
public OpRewritePattern<affine::AffineDelinearizeIndexOp> {
5110 LogicalResult matchAndRewrite(affine::AffineDelinearizeIndexOp delinearizeOp,
5111 PatternRewriter &rewriter)
const override {
5112 SmallVector<Value> replacements(delinearizeOp->getNumResults(),
nullptr);
5113 std::optional<Value> zero = std::nullopt;
5114 Location loc = delinearizeOp->getLoc();
5115 Type indexType = delinearizeOp.getLinearIndex().getType();
5116 auto getZero = [&]() -> Value {
5118 zero = arith::ConstantOp::create(rewriter, loc,
5120 return zero.value();
5125 SmallVector<OpFoldResult> newBasis;
5126 for (
auto [index, basis] :
5127 llvm::enumerate(delinearizeOp.getPaddedBasis())) {
5128 std::optional<int64_t> basisVal =
5131 replacements[index] =
getZero();
5133 newBasis.push_back(basis);
5136 if (newBasis.size() == delinearizeOp.getNumResults())
5138 "no unit basis elements");
5140 if (!newBasis.empty()) {
5142 auto newDelinearizeOp = affine::AffineDelinearizeIndexOp::create(
5143 rewriter, loc, delinearizeOp.getLinearIndex(), newBasis);
5149 replacement = newDelinearizeOp->getResult(newIndex++);
5153 rewriter.
replaceOp(delinearizeOp, replacements);
5168struct CancelDelinearizeOfLinearizeDisjointExactTail
5169 :
public OpRewritePattern<affine::AffineDelinearizeIndexOp> {
5172 LogicalResult matchAndRewrite(affine::AffineDelinearizeIndexOp delinearizeOp,
5173 PatternRewriter &rewriter)
const override {
5174 auto linearizeOp = delinearizeOp.getLinearIndex()
5175 .getDefiningOp<affine::AffineLinearizeIndexOp>();
5178 "index doesn't come from linearize");
5180 if (!linearizeOp.getDisjoint())
5183 ValueRange linearizeIns = linearizeOp.getMultiIndex();
5185 SmallVector<OpFoldResult> linearizeBasis = linearizeOp.getMixedBasis();
5186 SmallVector<OpFoldResult> delinearizeBasis = delinearizeOp.getMixedBasis();
5187 size_t numMatches = 0;
5188 for (
auto [linSize, delinSize] : llvm::zip(
5189 llvm::reverse(linearizeBasis), llvm::reverse(delinearizeBasis))) {
5190 if (linSize != delinSize)
5195 if (numMatches == 0)
5197 delinearizeOp,
"final basis element doesn't match linearize");
5200 if (numMatches == linearizeBasis.size() &&
5201 numMatches == delinearizeBasis.size() &&
5202 linearizeIns.size() == delinearizeOp.getNumResults()) {
5203 rewriter.
replaceOp(delinearizeOp, linearizeOp.getMultiIndex());
5207 Value newLinearize = affine::AffineLinearizeIndexOp::create(
5208 rewriter, linearizeOp.getLoc(), linearizeIns.drop_back(numMatches),
5209 ArrayRef<OpFoldResult>{linearizeBasis}.drop_back(numMatches),
5210 linearizeOp.getDisjoint());
5211 auto newDelinearize = affine::AffineDelinearizeIndexOp::create(
5212 rewriter, delinearizeOp.getLoc(), newLinearize,
5213 ArrayRef<OpFoldResult>{delinearizeBasis}.drop_back(numMatches),
5214 delinearizeOp.hasOuterBound());
5215 SmallVector<Value> mergedResults(newDelinearize.getResults());
5216 mergedResults.append(linearizeIns.take_back(numMatches).begin(),
5217 linearizeIns.take_back(numMatches).end());
5218 rewriter.
replaceOp(delinearizeOp, mergedResults);
5239struct SplitDelinearizeSpanningLastLinearizeArg final
5240 : OpRewritePattern<affine::AffineDelinearizeIndexOp> {
5243 LogicalResult matchAndRewrite(affine::AffineDelinearizeIndexOp delinearizeOp,
5244 PatternRewriter &rewriter)
const override {
5245 auto linearizeOp = delinearizeOp.getLinearIndex()
5246 .getDefiningOp<affine::AffineLinearizeIndexOp>();
5249 "index doesn't come from linearize");
5251 if (!linearizeOp.getDisjoint())
5253 "linearize isn't disjoint");
5258 if (linearizeOp.getStaticBasis().empty())
5260 linearizeOp,
"linearize has no basis elements (no inputs)");
5262 int64_t
target = linearizeOp.getStaticBasis().back();
5263 if (ShapedType::isDynamic(
target))
5265 linearizeOp,
"linearize ends with dynamic basis value");
5267 int64_t sizeToSplit = 1;
5268 size_t elemsToSplit = 0;
5269 ArrayRef<int64_t> basis = delinearizeOp.getStaticBasis();
5270 for (int64_t basisElem : llvm::reverse(basis)) {
5271 if (ShapedType::isDynamic(basisElem))
5273 delinearizeOp,
"dynamic basis element while scanning for split");
5274 sizeToSplit *= basisElem;
5277 if (sizeToSplit >
target)
5279 "overshot last argument size");
5280 if (sizeToSplit ==
target)
5284 if (sizeToSplit <
target)
5286 delinearizeOp,
"product of known basis elements doesn't exceed last "
5287 "linearize argument");
5289 if (elemsToSplit < 2)
5292 "need at least two elements to form the basis product");
5294 if (elemsToSplit == basis.size() && delinearizeOp.hasOuterBound())
5296 delinearizeOp,
"split would consume entire bounded basis");
5298 Value linearizeWithoutBack = affine::AffineLinearizeIndexOp::create(
5299 rewriter, linearizeOp.getLoc(), linearizeOp.getLinearIndex().getType(),
5300 linearizeOp.getMultiIndex().drop_back(), linearizeOp.getDynamicBasis(),
5301 linearizeOp.getStaticBasis().drop_back(), linearizeOp.getDisjoint());
5302 auto delinearizeWithoutSplitPart = affine::AffineDelinearizeIndexOp::create(
5303 rewriter, delinearizeOp.getLoc(), linearizeWithoutBack,
5304 delinearizeOp.getDynamicBasis(), basis.drop_back(elemsToSplit),
5305 delinearizeOp.hasOuterBound());
5306 auto delinearizeBack = affine::AffineDelinearizeIndexOp::create(
5307 rewriter, delinearizeOp.getLoc(), linearizeOp.getMultiIndex().back(),
5308 basis.take_back(elemsToSplit),
true);
5309 SmallVector<Value> results = llvm::to_vector(
5310 llvm::concat<Value>(delinearizeWithoutSplitPart.getResults(),
5311 delinearizeBack.getResults()));
5312 rewriter.
replaceOp(delinearizeOp, results);
5319void affine::AffineDelinearizeIndexOp::getCanonicalizationPatterns(
5320 RewritePatternSet &patterns, MLIRContext *context) {
5322 .
insert<CancelDelinearizeOfLinearizeDisjointExactTail,
5323 DropUnitExtentBasis, SplitDelinearizeSpanningLastLinearizeArg>(
5334 if (multiIndex.empty())
5335 return IndexType::get(ctx);
5336 return multiIndex.front().
getType();
5339void AffineLinearizeIndexOp::build(OpBuilder &odsBuilder,
5340 OperationState &odsState,
5343 if (!basis.empty() && basis.front() == Value())
5344 basis = basis.drop_front();
5345 SmallVector<Value> dynamicBasis;
5346 SmallVector<int64_t> staticBasis;
5350 build(odsBuilder, odsState, resultType, multiIndex, dynamicBasis, staticBasis,
5354void AffineLinearizeIndexOp::build(OpBuilder &odsBuilder,
5355 OperationState &odsState,
5357 ArrayRef<OpFoldResult> basis,
5359 if (!basis.empty() && basis.front() == OpFoldResult())
5360 basis = basis.drop_front();
5361 SmallVector<Value> dynamicBasis;
5362 SmallVector<int64_t> staticBasis;
5365 build(odsBuilder, odsState, resultType, multiIndex, dynamicBasis, staticBasis,
5369void AffineLinearizeIndexOp::build(OpBuilder &odsBuilder,
5370 OperationState &odsState,
5372 ArrayRef<int64_t> basis,
bool disjoint) {
5374 build(odsBuilder, odsState, resultType, multiIndex,
ValueRange{}, basis,
5378LogicalResult AffineLinearizeIndexOp::verify() {
5379 size_t numIndexes = getMultiIndex().size();
5380 size_t numBasisElems = getStaticBasis().size();
5381 if (numIndexes != numBasisElems && numIndexes != numBasisElems + 1)
5382 return emitOpError(
"should be passed a basis element for each index except "
5383 "possibly the first");
5385 auto dynamicMarkersCount =
5386 llvm::count_if(getStaticBasis(), ShapedType::isDynamic);
5387 if (
static_cast<size_t>(dynamicMarkersCount) != getDynamicBasis().size())
5389 "mismatch between dynamic and static basis (kDynamic marker but no "
5390 "corresponding dynamic basis entry) -- this can only happen due to an "
5391 "incorrect fold/rewrite");
5396OpFoldResult AffineLinearizeIndexOp::fold(FoldAdaptor adaptor) {
5397 std::optional<SmallVector<int64_t>> maybeStaticBasis =
5399 adaptor.getDynamicBasis());
5400 if (maybeStaticBasis) {
5401 setStaticBasis(*maybeStaticBasis);
5405 if (getMultiIndex().empty())
5406 return IntegerAttr::get(getResult().
getType(), 0);
5409 if (getMultiIndex().size() == 1)
5410 return getMultiIndex().front();
5415 if (llvm::any_of(adaptor.getMultiIndex(), [](Attribute a) {
5416 return !isa_and_nonnull<IntegerAttr>(a);
5420 if (!adaptor.getDynamicBasis().empty())
5425 for (
auto [length, indexAttr] :
5426 llvm::zip_first(llvm::reverse(getStaticBasis()),
5427 llvm::reverse(adaptor.getMultiIndex()))) {
5428 result =
result + cast<IntegerAttr>(indexAttr).getInt() * stride;
5429 stride = stride * length;
5432 if (!hasOuterBound())
5435 cast<IntegerAttr>(adaptor.getMultiIndex().front()).getInt() * stride;
5440SmallVector<OpFoldResult> AffineLinearizeIndexOp::getEffectiveBasis() {
5442 if (hasOuterBound()) {
5443 if (getStaticBasis().front() == ::mlir::ShapedType::kDynamic)
5445 getDynamicBasis().drop_front(), builder);
5447 return getMixedValues(getStaticBasis().drop_front(), getDynamicBasis(),
5451 return getMixedValues(getStaticBasis(), getDynamicBasis(), builder);
5454SmallVector<OpFoldResult> AffineLinearizeIndexOp::getPaddedBasis() {
5455 SmallVector<OpFoldResult> ret = getMixedBasis();
5456 if (!hasOuterBound())
5457 ret.insert(ret.begin(), OpFoldResult());
5472struct DropLinearizeUnitComponentsIfDisjointOrZero final
5473 : OpRewritePattern<affine::AffineLinearizeIndexOp> {
5476 LogicalResult matchAndRewrite(affine::AffineLinearizeIndexOp op,
5477 PatternRewriter &rewriter)
const override {
5479 size_t numIndices = multiIndex.size();
5480 SmallVector<Value> newIndices;
5481 newIndices.reserve(numIndices);
5482 SmallVector<OpFoldResult> newBasis;
5483 newBasis.reserve(numIndices);
5485 if (!op.hasOuterBound()) {
5486 newIndices.push_back(multiIndex.front());
5487 multiIndex = multiIndex.drop_front();
5490 SmallVector<OpFoldResult> basis = op.getMixedBasis();
5491 for (
auto [index, basisElem] : llvm::zip_equal(multiIndex, basis)) {
5493 if (!basisEntry || *basisEntry != 1) {
5494 newIndices.push_back(index);
5495 newBasis.push_back(basisElem);
5500 if (!op.getDisjoint() && (!indexValue || *indexValue != 0)) {
5501 newIndices.push_back(index);
5502 newBasis.push_back(basisElem);
5506 if (newIndices.size() == numIndices)
5508 "no unit basis entries to replace");
5510 if (newIndices.empty()) {
5512 op, rewriter.
getZeroAttr(op.getLinearIndex().getType()));
5516 op, newIndices, newBasis, op.getDisjoint());
5522 ArrayRef<OpFoldResult> terms) {
5523 int64_t nDynamic = 0;
5524 SmallVector<Value> dynamicPart;
5526 for (OpFoldResult term : terms) {
5533 dynamicPart.push_back(cast<Value>(term));
5537 if (
auto constant = dyn_cast<AffineConstantExpr>(
result))
5539 return AffineApplyOp::create(builder, loc,
result, dynamicPart).getResult();
5569struct CancelLinearizeOfDelinearizePortion final
5570 : OpRewritePattern<affine::AffineLinearizeIndexOp> {
5580 unsigned linStart = 0;
5581 unsigned delinStart = 0;
5582 unsigned length = 0;
5586 LogicalResult matchAndRewrite(affine::AffineLinearizeIndexOp linearizeOp,
5587 PatternRewriter &rewriter)
const override {
5588 SmallVector<Match> matches;
5590 const SmallVector<OpFoldResult> linBasis = linearizeOp.getPaddedBasis();
5591 ArrayRef<OpFoldResult> linBasisRef = linBasis;
5593 ValueRange multiIndex = linearizeOp.getMultiIndex();
5594 unsigned numLinArgs = multiIndex.size();
5595 unsigned linArgIdx = 0;
5598 llvm::SmallPtrSet<Operation *, 2> alreadyMatchedDelinearize;
5599 while (linArgIdx < numLinArgs) {
5600 auto asResult = dyn_cast<OpResult>(multiIndex[linArgIdx]);
5606 auto delinearizeOp =
5607 dyn_cast<AffineDelinearizeIndexOp>(asResult.getOwner());
5608 if (!delinearizeOp) {
5625 unsigned delinArgIdx = asResult.getResultNumber();
5626 SmallVector<OpFoldResult> delinBasis = delinearizeOp.getPaddedBasis();
5627 OpFoldResult firstDelinBound = delinBasis[delinArgIdx];
5628 OpFoldResult firstLinBound = linBasis[linArgIdx];
5629 bool boundsMatch = firstDelinBound == firstLinBound;
5630 bool bothAtFront = linArgIdx == 0 && delinArgIdx == 0;
5631 bool knownByDisjoint =
5632 linearizeOp.getDisjoint() && delinArgIdx == 0 && !firstDelinBound;
5633 if (!boundsMatch && !bothAtFront && !knownByDisjoint) {
5639 unsigned numDelinOuts = delinearizeOp.getNumResults();
5640 for (; j + linArgIdx < numLinArgs && j + delinArgIdx < numDelinOuts;
5642 if (multiIndex[linArgIdx + j] !=
5643 delinearizeOp.getResult(delinArgIdx + j))
5645 if (linBasis[linArgIdx + j] != delinBasis[delinArgIdx + j])
5651 if (j <= 1 || !alreadyMatchedDelinearize.insert(delinearizeOp).second) {
5655 matches.push_back(Match{delinearizeOp, linArgIdx, delinArgIdx, j});
5659 if (matches.empty())
5661 linearizeOp,
"no run of delinearize outputs to deal with");
5666 SmallVector<SmallVector<Value>> delinearizeReplacements;
5668 SmallVector<Value> newIndex;
5669 newIndex.reserve(numLinArgs);
5670 SmallVector<OpFoldResult> newBasis;
5671 newBasis.reserve(numLinArgs);
5672 unsigned prevMatchEnd = 0;
5673 for (Match m : matches) {
5674 unsigned gap = m.linStart - prevMatchEnd;
5675 llvm::append_range(newIndex, multiIndex.slice(prevMatchEnd, gap));
5676 llvm::append_range(newBasis, linBasisRef.slice(prevMatchEnd, gap));
5678 prevMatchEnd = m.linStart + m.length;
5680 PatternRewriter::InsertionGuard g(rewriter);
5683 ArrayRef<OpFoldResult> basisToMerge =
5684 linBasisRef.slice(m.linStart, m.length);
5687 OpFoldResult newSize =
5692 newIndex.push_back(m.delinearize.getLinearIndex());
5693 newBasis.push_back(newSize);
5695 delinearizeReplacements.push_back(SmallVector<Value>());
5699 SmallVector<Value> newDelinResults;
5700 SmallVector<OpFoldResult> newDelinBasis = m.delinearize.getPaddedBasis();
5701 newDelinBasis.erase(newDelinBasis.begin() + m.delinStart,
5702 newDelinBasis.begin() + m.delinStart + m.length);
5703 newDelinBasis.insert(newDelinBasis.begin() + m.delinStart, newSize);
5704 auto newDelinearize = AffineDelinearizeIndexOp::create(
5705 rewriter, m.delinearize.getLoc(), m.delinearize.getLinearIndex(),
5711 Value combinedElem = newDelinearize.getResult(m.delinStart);
5712 auto residualDelinearize = AffineDelinearizeIndexOp::create(
5713 rewriter, m.delinearize.getLoc(), combinedElem, basisToMerge);
5718 llvm::append_range(newDelinResults,
5719 newDelinearize.getResults().take_front(m.delinStart));
5720 llvm::append_range(newDelinResults, residualDelinearize.getResults());
5723 newDelinearize.getResults().drop_front(m.delinStart + 1));
5725 delinearizeReplacements.push_back(newDelinResults);
5726 newIndex.push_back(combinedElem);
5727 newBasis.push_back(newSize);
5729 llvm::append_range(newIndex, multiIndex.drop_front(prevMatchEnd));
5730 llvm::append_range(newBasis, linBasisRef.drop_front(prevMatchEnd));
5732 linearizeOp, newIndex, newBasis, linearizeOp.getDisjoint());
5734 for (
auto [m, newResults] :
5735 llvm::zip_equal(matches, delinearizeReplacements)) {
5736 if (newResults.empty())
5738 rewriter.
replaceOp(m.delinearize, newResults);
5749struct DropLinearizeLeadingZero final
5750 : OpRewritePattern<affine::AffineLinearizeIndexOp> {
5753 LogicalResult matchAndRewrite(affine::AffineLinearizeIndexOp op,
5754 PatternRewriter &rewriter)
const override {
5755 Value leadingIdx = op.getMultiIndex().front();
5759 if (op.getMultiIndex().size() == 1) {
5764 SmallVector<OpFoldResult> mixedBasis = op.getMixedBasis();
5765 ArrayRef<OpFoldResult> newMixedBasis = mixedBasis;
5766 if (op.hasOuterBound())
5767 newMixedBasis = newMixedBasis.drop_front();
5770 op, op.getMultiIndex().drop_front(), newMixedBasis, op.getDisjoint());
5776void affine::AffineLinearizeIndexOp::getCanonicalizationPatterns(
5777 RewritePatternSet &patterns, MLIRContext *context) {
5778 patterns.
add<CancelLinearizeOfDelinearizePortion, DropLinearizeLeadingZero,
5779 DropLinearizeUnitComponentsIfDisjointOrZero>(context);
5786#define GET_OP_CLASSES
5787#include "mlir/Dialect/Affine/IR/AffineOps.cpp.inc"
static AffineForOp buildAffineLoopFromConstants(OpBuilder &builder, Location loc, int64_t lb, int64_t ub, int64_t step, AffineForOp::BodyBuilderFn bodyBuilderFn)
Creates an affine loop from the bounds known to be constants.
static bool hasTrivialZeroTripCount(AffineForOp op)
Returns true if the affine.for has zero iterations in trivial cases.
static Type inferIndexType(MLIRContext *ctx, ValueRange multiIndex)
Infer the index type from a set of multi-index values. Returns the common type (index or vector<....
static LogicalResult verifyMemoryOpIndexing(AffineMemOpTy op, AffineMapAttr mapAttr, Operation::operand_range mapOperands, MemRefType memrefType, unsigned numIndexOperands)
Verify common indexing invariants of affine.load, affine.store, affine.vector_load and affine....
static void printAffineMinMaxOp(OpAsmPrinter &p, T op)
static bool isResultTypeMatchAtomicRMWKind(Type resultType, arith::AtomicRMWKind op)
static bool remainsLegalAfterInline(Value value, Region *src, Region *dest, const IRMapping &mapping, function_ref< bool(Value, Region *)> legalityCheck)
Checks if value known to be a legal affine dimension or symbol in src region remains legal if the ope...
static void printMinMaxBound(OpAsmPrinter &p, AffineMapAttr mapAttr, DenseIntElementsAttr group, ValueRange operands, StringRef keyword)
Prints a lower(upper) bound of an affine parallel loop with max(min) conditions in it.
static OpFoldResult foldMinMaxOp(T op, ArrayRef< Attribute > operands)
Fold an affine min or max operation with the given operands.
static bool isTopLevelValueOrAbove(Value value, Region *region)
A utility function to check if a value is defined at the top level of region or is an argument of reg...
static LogicalResult canonicalizeLoopBounds(AffineForOp forOp)
Canonicalize the bounds of the given loop.
static void simplifyExprAndOperands(AffineExpr &expr, unsigned numDims, unsigned numSymbols, ArrayRef< Value > operands)
Simplify expr while exploiting information from the values in operands.
static bool isValidAffineIndexOperand(Value value, Region *region)
static void canonicalizeMapOrSetAndOperands(MapOrSet *mapOrSet, SmallVectorImpl< Value > *operands)
static ParseResult parseBound(bool isLower, OperationState &result, OpAsmParser &p)
Parse a for operation loop bounds.
static std::optional< SmallVector< int64_t > > foldCstValueToCstAttrBasis(ArrayRef< OpFoldResult > mixedBasis, MutableOperandRange mutableDynamicBasis, ArrayRef< Attribute > dynamicBasis)
Given mixed basis of affine.delinearize_index/linearize_index replace constant SSA values with the co...
static void canonicalizePromotedSymbols(MapOrSet *mapOrSet, SmallVectorImpl< Value > *operands)
static LogicalResult verifyVectorMemoryOp(Operation *op, MemRefType memrefType, VectorType vectorType)
Verify common invariants of affine.vector_load and affine.vector_store.
static void simplifyMinOrMaxExprWithOperands(AffineMap &map, ArrayRef< Value > operands, bool isMax)
Simplify the expressions in map while making use of lower or upper bounds of its operands.
static ParseResult parseAffineMinMaxOp(OpAsmParser &parser, OperationState &result)
static LogicalResult replaceAffineDelinearizeIndexInverseExpression(AffineDelinearizeIndexOp delinOp, Value resultToReplace, AffineMap *map, SmallVectorImpl< Value > &dims, SmallVectorImpl< Value > &syms)
If this map contains of the expression x_1 + x_1 * C_1 + ... x_n * C_N + / ... (not necessarily in or...
static void composeSetAndOperands(IntegerSet &set, SmallVectorImpl< Value > &operands, bool composeAffineMin=false)
Compose any affine.apply ops feeding into operands of the integer set set by composing the maps of su...
static bool isMemRefSizeValidSymbol(AnyMemRefDefOp memrefDefOp, unsigned index, Region *region)
Returns true if the 'index' dimension of the memref defined by memrefDefOp is a statically shaped one...
static bool isNonNegativeBoundedBy(AffineExpr e, ArrayRef< Value > operands, int64_t k)
Check if e is known to be: 0 <= e < k.
static AffineForOp buildAffineLoopFromValues(OpBuilder &builder, Location loc, Value lb, Value ub, int64_t step, AffineForOp::BodyBuilderFn bodyBuilderFn)
Creates an affine loop from the bounds that may or may not be constants.
static void simplifyMapWithOperands(AffineMap &map, ArrayRef< Value > operands)
Simplify the map while exploiting information on the values in operands.
static void printDimAndSymbolList(Operation::operand_iterator begin, Operation::operand_iterator end, unsigned numDims, OpAsmPrinter &printer)
Prints dimension and symbol list.
static int64_t getLargestKnownDivisor(AffineExpr e, ArrayRef< Value > operands)
Returns the largest known divisor of e.
static void composeAffineMapAndOperands(AffineMap *map, SmallVectorImpl< Value > *operands, bool composeAffineMin=false)
Iterate over operands and fold away all those produced by an AffineApplyOp iteratively.
static void legalizeDemotedDims(MapOrSet &mapOrSet, SmallVectorImpl< Value > &operands)
A valid affine dimension may appear as a symbol in affine.apply operations.
static OpTy makeComposedMinMax(OpBuilder &b, Location loc, AffineMap map, ArrayRef< OpFoldResult > operands)
static std::optional< int64_t > getUpperBound(Value iv)
Gets the constant upper bound on an affine.for iv.
static void buildAffineLoopNestImpl(OpBuilder &builder, Location loc, BoundListTy lbs, BoundListTy ubs, ArrayRef< int64_t > steps, function_ref< void(OpBuilder &, Location, ValueRange)> bodyBuilderFn, LoopCreatorTy &&loopCreatorFn)
Builds an affine loop nest, using "loopCreatorFn" to create individual loop operations.
static LogicalResult foldLoopBounds(AffineForOp forOp)
Fold the constant bounds of a loop.
static LogicalResult replaceAffineMinBoundingBoxExpression(AffineMinOp minOp, AffineExpr dimOrSym, AffineMap *map, ValueRange dims, ValueRange syms)
Assuming dimOrSym is a quantity in the apply op map map and defined by minOp = affine_min(x_1,...
static void addAlignmentAttr(OpBuilder &builder, OperationState &result, StringAttr attrName, llvm::MaybeAlign alignment)
Adds the optional alignment attribute to result, if one is given.
static SmallVector< OpFoldResult > AffineForEmptyLoopFolder(AffineForOp forOp)
Fold the empty loop.
static LogicalResult verifyDimAndSymbolIdentifiers(OpTy &op, Operation::operand_range operands, unsigned numDims)
Utility function to verify that a set of operands are valid dimension and symbol identifiers.
static OpFoldResult makeComposedFoldedMinMax(OpBuilder &b, Location loc, AffineMap map, ArrayRef< OpFoldResult > operands)
static bool isDimOpValidSymbol(ShapedDimOpInterface dimOp, Region *region)
Returns true if the result of the dim op is a valid symbol for region.
static bool isQTimesDPlusR(AffineExpr e, ArrayRef< Value > operands, int64_t &div, AffineExpr "ientTimesDiv, AffineExpr &rem)
Check if expression e is of the form d*e_1 + e_2 where 0 <= e_2 < d.
static LogicalResult replaceDimOrSym(AffineMap *map, unsigned dimOrSymbolPosition, SmallVectorImpl< Value > &dims, SmallVectorImpl< Value > &syms, bool replaceAffineMin)
Replace all occurrences of AffineExpr at position pos in map by the defining AffineApplyOp expression...
static std::optional< int64_t > getLowerBound(Value iv)
Gets the constant lower bound on an iv.
static std::optional< uint64_t > getTrivialConstantTripCount(AffineForOp forOp)
Returns constant trip count in trivial cases.
static LogicalResult verifyAffineMinMaxOp(T op)
static void printBound(AffineMapAttr boundMap, Operation::operand_range boundOperands, const char *prefix, OpAsmPrinter &p)
static void shortenAddChainsContainingAll(AffineExpr e, const llvm::SmallDenseSet< AffineExpr, 4 > &exprsToRemove, AffineExpr newVal, DenseMap< AffineExpr, AffineExpr > &replacementsMap)
Recursively traverse e.
static void composeMultiResultAffineMap(AffineMap &map, SmallVectorImpl< Value > &operands, bool composeAffineMin=false)
Composes the given affine map with the given list of operands, pulling in the maps from any affine....
static LogicalResult canonicalizeMapExprAndTermOrder(AffineMap &map)
Canonicalize the result expression order of an affine map and return success if the order changed.
static Value getZero(OpBuilder &b, Location loc, Type elementType)
Get zero value for an element type.
static bool isLegalToInline(InlinerInterface &interface, Region *src, Region *insertRegion, bool shouldCloneInlinedRegion, IRMapping &valueMapping)
Utility to check that all of the operations within 'src' can be inlined.
static int64_t getNumElements(Type t)
Compute the total number of elements in the given type, also taking into account nested types.
*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 the output argument nBegin is set to its * replacement(set to `begin` if no invalidation happens). Since outgoing *copies could have been inserted at `end`
static Operation::operand_range getLowerBoundOperands(AffineForOp forOp)
static Operation::operand_range getUpperBoundOperands(AffineForOp forOp)
static VectorType getVectorType(Type scalarTy, const VectorizationStrategy *strategy)
Returns the vector type resulting from applying the provided vectorization strategy on the scalar typ...
RetTy walkPostOrder(AffineExpr expr)
Base type for affine expression.
AffineExpr shiftDims(unsigned numDims, unsigned shift, unsigned offset=0) const
Replace dims[offset ... numDims) by dims[offset + shift ... shift + numDims).
AffineExpr shiftSymbols(unsigned numSymbols, unsigned shift, unsigned offset=0) const
Replace symbols[offset ... numSymbols) by symbols[offset + shift ... shift + numSymbols).
AffineExpr floorDiv(uint64_t v) const
AffineExprKind getKind() const
Return the classification for this type.
int64_t getLargestKnownDivisor() const
Returns the greatest known integral divisor of this affine expression.
MLIRContext * getContext() const
AffineExpr replace(AffineExpr expr, AffineExpr replacement) const
Sparse replace method.
AffineExpr ceilDiv(uint64_t v) const
A multi-dimensional affine map Affine map's are immutable like Type's, and they are uniqued.
AffineMap getSliceMap(unsigned start, unsigned length) const
Returns the map consisting of length expressions starting from start.
MLIRContext * getContext() const
bool isFunctionOfDim(unsigned position) const
Return true if any affine expression involves AffineDimExpr position.
static AffineMap get(MLIRContext *context)
Returns a zero result affine map with no dimensions or symbols: () -> ().
AffineMap shiftDims(unsigned shift, unsigned offset=0) const
Replace dims[offset ... numDims) by dims[offset + shift ... shift + numDims).
unsigned getNumSymbols() const
unsigned getNumDims() const
ArrayRef< AffineExpr > getResults() const
bool isFunctionOfSymbol(unsigned position) const
Return true if any affine expression involves AffineSymbolExpr position.
unsigned getNumResults() const
static SmallVector< AffineMap, 4 > inferFromExprList(ArrayRef< ArrayRef< AffineExpr > > exprsList, MLIRContext *context)
Returns a vector of AffineMaps; each with as many results as exprs.size(), as many dims as the larges...
AffineMap replaceDimsAndSymbols(ArrayRef< AffineExpr > dimReplacements, ArrayRef< AffineExpr > symReplacements, unsigned numResultDims, unsigned numResultSyms) const
This method substitutes any uses of dimensions and symbols (e.g.
unsigned getNumInputs() const
AffineMap shiftSymbols(unsigned shift, unsigned offset=0) const
Replace symbols[offset ... numSymbols) by symbols[offset + shift ... shift + numSymbols).
AffineExpr getResult(unsigned idx) const
AffineMap replace(AffineExpr expr, AffineExpr replacement, unsigned numResultDims, unsigned numResultSyms) const
Sparse replace method.
static AffineMap getConstantMap(int64_t val, MLIRContext *context)
Returns a single constant result affine map.
AffineMap getSubMap(ArrayRef< unsigned > resultPos) const
Returns the map consisting of the resultPos subset.
LogicalResult constantFold(ArrayRef< Attribute > operandConstants, SmallVectorImpl< Attribute > &results, bool *hasPoison=nullptr) const
Folds the results of the application of an affine map on the provided operands to a constant if possi...
@ Paren
Parens surrounding zero or more operands.
@ OptionalSquare
Square brackets supporting zero or more ops, or nothing.
virtual ParseResult parseColonTypeList(SmallVectorImpl< Type > &result)=0
Parse a colon followed by a type list, which must have at least one type.
virtual Builder & getBuilder() const =0
Return a builder which provides useful access to MLIRContext, global objects like types and attribute...
virtual ParseResult parseCommaSeparatedList(Delimiter delimiter, function_ref< ParseResult()> parseElementFn, StringRef contextMessage=StringRef())=0
Parse a list of comma-separated items with an optional delimiter.
virtual ParseResult parseOptionalAttrDict(NamedAttrList &result)=0
Parse a named dictionary into 'result' if it is present.
virtual ParseResult parseOptionalKeyword(StringRef keyword)=0
Parse the given keyword if present.
MLIRContext * getContext() const
virtual ParseResult parseRParen()=0
Parse a ) token.
virtual InFlightDiagnostic emitError(SMLoc loc, const Twine &message={})=0
Emit a diagnostic at the specified location and return failure.
ParseResult addTypeToList(Type type, SmallVectorImpl< Type > &result)
Add the specified type to the end of the specified type list and return success.
virtual ParseResult parseOptionalRParen()=0
Parse a ) token if present.
virtual ParseResult parseLess()=0
Parse a '<' token.
virtual ParseResult parseEqual()=0
Parse a = token.
virtual ParseResult parseColonType(Type &result)=0
Parse a colon followed by a type.
virtual SMLoc getCurrentLocation()=0
Get the location of the next token and store it into the argument.
virtual SMLoc getNameLoc() const =0
Return the location of the original name token.
virtual ParseResult parseGreater()=0
Parse a '>' token.
virtual ParseResult parseLParen()=0
Parse a ( token.
virtual ParseResult parseType(Type &result)=0
Parse a type.
virtual ParseResult parseComma()=0
Parse a , token.
virtual ParseResult parseOptionalArrowTypeList(SmallVectorImpl< Type > &result)=0
Parse an optional arrow followed by a type list.
virtual ParseResult parseArrowTypeList(SmallVectorImpl< Type > &result)=0
Parse an arrow followed by a type list.
ParseResult parseKeyword(StringRef keyword)
Parse a given keyword.
virtual ParseResult parseAttribute(Attribute &result, Type type={})=0
Parse an arbitrary attribute of a given type and return it in result.
void printOptionalArrowTypeList(TypeRange &&types)
Print an optional arrow followed by a type list.
Attributes are known-constant values of operations.
This class represents an argument of a Block.
Block represents an ordered list of Operations.
Operation * getTerminator()
Get the terminator operation of this block.
BlockArgument addArgument(Type type, Location loc)
Add one value to the argument list.
BlockArgListType getArguments()
DenseI32ArrayAttr getDenseI32ArrayAttr(ArrayRef< int32_t > values)
IntegerAttr getIntegerAttr(Type type, int64_t value)
AffineMap getDimIdentityMap()
AffineMap getMultiDimIdentityMap(unsigned rank)
AffineExpr getAffineSymbolExpr(unsigned position)
AffineExpr getAffineConstantExpr(int64_t constant)
DenseIntElementsAttr getI32TensorAttr(ArrayRef< int32_t > values)
Tensor-typed DenseIntElementsAttr getters.
IntegerAttr getI64IntegerAttr(int64_t value)
IntegerType getIntegerType(unsigned width)
BoolAttr getBoolAttr(bool value)
AffineMap getEmptyAffineMap()
Returns a zero result affine map with no dimensions or symbols: () -> ().
TypedAttr getZeroAttr(Type type)
AffineMap getConstantAffineMap(int64_t val)
Returns a single constant result affine map with 0 dimensions and 0 symbols.
AffineMap getSymbolIdentityMap()
ArrayAttr getArrayAttr(ArrayRef< Attribute > value)
MLIRContext * getContext() const
ArrayAttr getI64ArrayAttr(ArrayRef< int64_t > values)
An attribute that represents a reference to a dense integer vector or tensor object.
This is a utility class for mapping one set of IR entities to another.
auto lookup(T from) const
Lookup a mapped value within the map.
An integer set representing a conjunction of one or more affine equalities and inequalities.
unsigned getNumDims() const
static IntegerSet get(unsigned dimCount, unsigned symbolCount, ArrayRef< AffineExpr > constraints, ArrayRef< bool > eqFlags)
MLIRContext * getContext() const
unsigned getNumInputs() const
ArrayRef< AffineExpr > getConstraints() const
ArrayRef< bool > getEqFlags() const
Returns the equality bits, which specify whether each of the constraints is an equality or inequality...
unsigned getNumSymbols() const
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.
This class provides a mutable adaptor for a range of operands.
void erase(unsigned subStart, unsigned subLen=1)
Erase the operands within the given sub-range.
The OpAsmParser has methods for interacting with the asm parser: parsing things from it,...
virtual ParseResult parseRegion(Region ®ion, ArrayRef< Argument > arguments={}, bool enableNameShadowing=false)=0
Parses a region.
virtual ParseResult parseArgument(Argument &result, bool allowType=false, bool allowAttrs=false)=0
Parse a single argument with the following syntax:
ParseResult parseTrailingOperandList(SmallVectorImpl< UnresolvedOperand > &result, Delimiter delimiter=Delimiter::None)
Parse zero or more trailing SSA comma-separated trailing operand references with a specified surround...
virtual ParseResult parseArgumentList(SmallVectorImpl< Argument > &result, Delimiter delimiter=Delimiter::None, bool allowType=false, bool allowAttrs=false)=0
Parse zero or more arguments with a specified surrounding delimiter.
virtual ParseResult parseAffineMapOfSSAIds(SmallVectorImpl< UnresolvedOperand > &operands, Attribute &map, StringRef attrName, NamedAttrList &attrs, Delimiter delimiter=Delimiter::Square)=0
Parses an affine map attribute where dims and symbols are SSA operands.
ParseResult parseAssignmentList(SmallVectorImpl< Argument > &lhs, SmallVectorImpl< UnresolvedOperand > &rhs)
Parse a list of assignments of the form (x1 = y1, x2 = y2, ...)
virtual ParseResult resolveOperand(const UnresolvedOperand &operand, Type type, SmallVectorImpl< Value > &result)=0
Resolve an operand to an SSA value, emitting an error on failure.
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 parseOperand(UnresolvedOperand &result, bool allowResultNumber=true)=0
Parse a single SSA value operand name along with a result number if allowResultNumber is true.
virtual ParseResult parseAffineExprOfSSAIds(SmallVectorImpl< UnresolvedOperand > &dimOperands, SmallVectorImpl< UnresolvedOperand > &symbOperands, AffineExpr &expr)=0
Parses an affine expression where dims and symbols are SSA operands.
virtual ParseResult parseOperandList(SmallVectorImpl< UnresolvedOperand > &result, Delimiter delimiter=Delimiter::None, bool allowResultNumber=true, int requiredOperandCount=-1)=0
Parse zero or more SSA comma-separated operand references with a specified surrounding delimiter,...
This is a pure-virtual base class that exposes the asmprinter hooks necessary to implement a custom p...
virtual void printOptionalAttrDict(ArrayRef< NamedAttribute > attrs, ArrayRef< StringRef > elidedAttrs={})=0
If the specified operation has attributes, print out an attribute dictionary with their values.
virtual void printAffineExprOfSSAIds(AffineExpr expr, ValueRange dimOperands, ValueRange symOperands)=0
Prints an affine expression of SSA ids with SSA id names used instead of dims and symbols.
virtual void printAffineMapOfSSAIds(AffineMapAttr mapAttr, ValueRange operands)=0
Prints an affine map of SSA ids, where SSA id names are used in place of dims/symbols.
virtual void printRegion(Region &blocks, bool printEntryBlockArgs=true, bool printBlockTerminators=true, bool printEmptyBlock=false)=0
Prints a region.
virtual void printRegionArgument(BlockArgument arg, ArrayRef< NamedAttribute > argAttrs={}, bool omitType=false)=0
Print a block argument in the usual format of: ssaName : type {attr1=42} loc("here") where location p...
virtual void printOperand(Value value)=0
Print implementations for various things an operation contains.
RAII guard to reset the insertion point of the builder when destroyed.
This class helps build Operations.
Block * createBlock(Region *parent, Region::iterator insertPt={}, TypeRange argTypes={}, ArrayRef< Location > locs={})
Add new block with 'argTypes' arguments and set the insertion point to the end of it.
void setInsertionPointToStart(Block *block)
Sets the insertion point to the start of the specified block.
void setInsertionPoint(Block *block, Block::iterator insertPoint)
Set the insertion point to the specified location.
This class represents a single result from folding an operation.
A trait of region holding operations that defines a new scope for polyhedral optimization purposes.
This class provides the API for ops that are known to be isolated from above.
This class implements the operand iterators for the Operation class.
Operation is the basic unit of execution within MLIR.
bool hasTrait()
Returns true if the operation was registered with a particular trait, e.g.
Operation * getParentOp()
Returns the closest surrounding operation that contains this operation or nullptr if this is a top-le...
OperandRange operand_range
operand_range getOperands()
Returns an iterator on the underlying Value's.
Region * getParentRegion()
Returns the region to which the instruction belongs.
operand_range::iterator operand_iterator
InFlightDiagnostic emitOpError(const Twine &message={})
Emit an error with the op name prefixed, like "'dim' op " which is convenient for verifiers.
A special type of RewriterBase that coordinates the application of a rewrite pattern on the current I...
This class represents a point being branched from in the methods of the RegionBranchOpInterface.
bool isParent() const
Returns true if branching from the parent op.
RegionBranchTerminatorOpInterface getTerminatorPredecessorOrNull() const
Returns the terminator if branching from a region.
This class represents a successor of a region.
Region * getSuccessor() const
Return the given region successor.
bool isOperation() const
Return true if the successor is an operation.
This class contains a list of basic blocks and a link to the parent operation it is attached to.
Operation * getParentOp()
Return the parent operation this region is attached to.
bool hasOneBlock()
Return true if this region has exactly one block.
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.
This class coordinates the application of a rewrite on a set of IR, providing a way for clients to tr...
virtual void eraseBlock(Block *block)
This method erases all operations in a block.
virtual void replaceOp(Operation *op, ValueRange newValues)
Replace the results of the given (original) operation with the specified list of values (replacements...
virtual void finalizeOpModification(Operation *op)
This method is used to signal the end of an in-place modification of the given operation.
virtual void eraseOp(Operation *op)
This method erases an operation that is known to have no uses.
virtual void inlineBlockBefore(Block *source, Block *dest, Block::iterator before, ValueRange argValues={})
Inline the operations of block 'source' into block 'dest' before the given position.
void mergeBlocks(Block *source, Block *dest, ValueRange argValues={})
Inline the operations of block 'source' into the end of block 'dest'.
std::enable_if_t<!std::is_convertible< CallbackT, Twine >::value, LogicalResult > notifyMatchFailure(Location loc, CallbackT &&reasonCallback)
Used to notify the listener that the IR failed to be rewritten because of a match failure,...
void modifyOpInPlace(Operation *root, CallableT &&callable)
This method is a utility wrapper around an in-place modification of an operation.
virtual void startOpModification(Operation *op)
This method is used to notify the rewriter that an in-place operation modification is about to happen...
OpTy replaceOpWithNewOp(Operation *op, Args &&...args)
Replace the results of the given (original) op with a new op that is created without verification (re...
virtual bool replaceUsesWithIf(Value from, Value to, function_ref< bool(OpOperand &)> functor, bool *allUsesReplaced=nullptr)
Find uses of from and replace them with to if the functor returns true.
This class represents a specific instance of an effect.
static DerivedEffect * get()
static DefaultResource * get()
std::vector< SmallVector< int64_t, 8 > > operandExprStack
static Operation * lookupNearestSymbolFrom(Operation *from, StringAttr symbol)
Returns the operation registered with the given symbol name within the closest parent operation of,...
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...
A variable that can be added to the constraint set as a "column".
static bool compare(const Variable &lhs, ComparisonOperator cmp, const Variable &rhs)
Return "true" if "lhs cmp rhs" was proven to hold.
This class provides an abstraction over the different types of ranges over Values.
type_range getType() const
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.
Region * getParentRegion()
Return the Region in which this Value is defined.
AffineBound represents a lower or upper bound in the for operation.
An AffineValueMap is an affine map plus its ML value operands and results for analysis purposes.
static void cartesianProductDifference(const AffineValueMap &a, const AffineValueMap &b, AffineValueMap *res)
Subtract results of 'b' from results of 'a' over their Cartesian product.
LogicalResult canonicalize()
Attempts to canonicalize the map and operands.
ArrayRef< Value > getOperands() const
AffineExpr getResult(unsigned i)
AffineMap getAffineMap() const
void reset(AffineMap map, ValueRange operands, ValueRange results={})
unsigned getNumResults() const
static void difference(const AffineValueMap &a, const AffineValueMap &b, AffineValueMap *res)
Subtract each result of 'b' from the result of 'a' at the same index; the result counts must be equal...
Operation * getOwner() const
Return the owner of this operand.
constexpr auto RecursivelySpeculatable
Speculatability
This enum is returned from the getSpeculatability method in the ConditionallySpeculatable op interfac...
constexpr auto NotSpeculatable
void buildAffineLoopNest(OpBuilder &builder, Location loc, ArrayRef< int64_t > lbs, ArrayRef< int64_t > ubs, ArrayRef< int64_t > steps, function_ref< void(OpBuilder &, Location, ValueRange)> bodyBuilderFn=nullptr)
Builds a perfect nest of affine.for loops, i.e., each loop except the innermost one contains only ano...
AffineApplyOp makeComposedAffineApply(OpBuilder &b, Location loc, AffineMap map, ArrayRef< OpFoldResult > operands, bool composeAffineMin=false)
Returns a composed AffineApplyOp by composing map and operands with other AffineApplyOps supplying th...
void extractForInductionVars(ArrayRef< AffineForOp > forInsts, SmallVectorImpl< Value > *ivs)
Extracts the induction variables from a list of AffineForOps and places them in the output argument i...
bool isValidDim(Value value)
Returns true if the given Value can be used as a dimension id in the region of the closest surroundin...
bool isAffineInductionVar(Value val)
Returns true if the provided value is the induction variable of an AffineForOp or AffineParallelOp.
SmallVector< OpFoldResult > makeComposedFoldedMultiResultAffineApply(OpBuilder &b, Location loc, AffineMap map, ArrayRef< OpFoldResult > operands, bool composeAffineMin=false)
Variant of makeComposedFoldedAffineApply suitable for multi-result maps.
OpFoldResult computeProduct(Location loc, OpBuilder &builder, ArrayRef< OpFoldResult > terms)
Return the product of terms, creating an affine.apply if any of them are non-constant values.
AffineForOp getForInductionVarOwner(Value val)
Returns the loop parent of an induction variable.
void canonicalizeMapAndOperands(AffineMap *map, SmallVectorImpl< Value > *operands)
Modifies both map and operands in-place so as to:
OpFoldResult makeComposedFoldedAffineMax(OpBuilder &b, Location loc, AffineMap map, ArrayRef< OpFoldResult > operands)
Constructs an AffineMinOp that computes a maximum across the results of applying map to operands,...
bool isAffineForInductionVar(Value val)
Returns true if the provided value is the induction variable of an AffineForOp.
OpFoldResult makeComposedFoldedAffineApply(OpBuilder &b, Location loc, AffineMap map, ArrayRef< OpFoldResult > operands, bool composeAffineMin=false)
Constructs an AffineApplyOp that applies map to operands after composing the map with the maps of any...
OpFoldResult makeComposedFoldedAffineMin(OpBuilder &b, Location loc, AffineMap map, ArrayRef< OpFoldResult > operands)
Constructs an AffineMinOp that computes a minimum across the results of applying map to operands,...
bool isTopLevelValue(Value value)
A utility function to check if a value is defined at the top level of an op with trait AffineScope or...
Region * getAffineAnalysisScope(Operation *op)
Returns the closest region enclosing op that is held by a non-affine operation; nullptr if there is n...
void fullyComposeAffineMapAndOperands(AffineMap *map, SmallVectorImpl< Value > *operands, bool composeAffineMin=false)
Given an affine map map and its input operands, this method composes into map, maps of AffineApplyOps...
void canonicalizeSetAndOperands(IntegerSet *set, SmallVectorImpl< Value > *operands)
Canonicalizes an integer set the same way canonicalizeMapAndOperands does for affine maps.
void extractInductionVars(ArrayRef< Operation * > affineOps, SmallVectorImpl< Value > &ivs)
Extracts the induction variables from a list of either AffineForOp or AffineParallelOp and places the...
bool isValidSymbol(Value value)
Returns true if the given value can be used as a symbol in the region of the closest surrounding op t...
AffineParallelOp getAffineParallelInductionVarOwner(Value val)
Returns true if the provided value is among the induction variables of an AffineParallelOp.
Region * getAffineScope(Operation *op)
Returns the closest region enclosing op that is held by an operation with trait AffineScope; nullptr ...
ParseResult parseDimAndSymbolList(OpAsmParser &parser, SmallVectorImpl< Value > &operands, unsigned &numDims)
Parses dimension and symbol list.
bool isAffineParallelInductionVar(Value val)
Returns true if val is the induction variable of an AffineParallelOp.
AffineMinOp makeComposedAffineMin(OpBuilder &b, Location loc, AffineMap map, ArrayRef< OpFoldResult > operands)
Returns an AffineMinOp obtained by composing map and operands with AffineApplyOps supplying those ope...
LogicalResult foldMemRefCast(Operation *op, Value inner=nullptr)
This is a common utility used for patterns of the form "someop(memref.cast) -> someop".
MemRefType getMemRefType(T &&t)
Convenience method to abbreviate casting getType().
Include the generated interface declarations.
AffineMap simplifyAffineMap(AffineMap map)
Simplifies an affine map by simplifying its underlying AffineExpr results.
bool matchPattern(Value value, const Pattern &pattern)
Entry point for matching a pattern over a Value.
SmallVector< OpFoldResult > getMixedValues(ArrayRef< int64_t > staticValues, ValueRange dynamicValues, MLIRContext *context)
Return a vector of OpFoldResults with the same size a staticValues, but all elements for which Shaped...
OpFoldResult getAsIndexOpFoldResult(MLIRContext *ctx, int64_t val)
Convert int64_t to integer attributes of index type and return them as OpFoldResult.
AffineMap removeDuplicateExprs(AffineMap map)
Returns a map with the same dimension and symbol count as map, but whose results are the unique affin...
std::optional< int64_t > getConstantIntValue(OpFoldResult ofr)
If ofr is a constant integer or an IntegerAttr, return the integer.
std::function< SmallVector< Value >( OpBuilder &b, Location loc, ArrayRef< BlockArgument > newBbArgs)> NewYieldValuesFn
A function that returns the additional yielded values during replaceWithAdditionalYields.
Type getType(OpFoldResult ofr)
Returns the int type of the integer in ofr.
std::optional< int64_t > getBoundForAffineExpr(AffineExpr expr, unsigned numDims, unsigned numSymbols, ArrayRef< std::optional< int64_t > > constLowerBounds, ArrayRef< std::optional< int64_t > > constUpperBounds, bool isUpper)
Get a lower or upper (depending on isUpper) bound for expr while using the constant lower and upper b...
SmallVector< int64_t > delinearize(int64_t linearIndex, ArrayRef< int64_t > strides)
Given the strides together with a linear index in the dimension space, return the vector-space offset...
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.
@ CeilDiv
RHS of ceildiv is always a constant or a symbolic expression.
@ Mod
RHS of mod is always a constant or a symbolic expression with a positive value.
@ DimId
Dimensional identifier.
@ FloorDiv
RHS of floordiv is always a constant or a symbolic expression.
@ SymbolId
Symbolic identifier.
AffineExpr getAffineBinaryOpExpr(AffineExprKind kind, AffineExpr lhs, AffineExpr rhs)
detail::constant_int_predicate_matcher m_Zero()
Matches a constant scalar / vector splat / tensor splat integer zero.
void dispatchIndexOpFoldResults(ArrayRef< OpFoldResult > ofrs, SmallVectorImpl< Value > &dynamicVec, SmallVectorImpl< int64_t > &staticVec)
Helper function to dispatch multiple OpFoldResults according to the behavior of dispatchIndexOpFoldRe...
llvm::TypeSwitch< T, ResultT > TypeSwitch
AffineExpr getAffineConstantExpr(int64_t constant, MLIRContext *context)
llvm::DenseMap< KeyT, ValueT, KeyInfoT, BucketT > DenseMap
OpFoldResult getAsOpFoldResult(Value val)
Given a value, try to extract a constant Attribute.
detail::constant_op_matcher m_Constant()
Matches a constant foldable operation.
AffineExpr getAffineDimExpr(unsigned position, MLIRContext *context)
These free functions allow clients of the API to not use classes in detail.
AffineMap foldAttributesIntoMap(Builder &b, AffineMap map, ArrayRef< OpFoldResult > operands, SmallVector< Value > &remainingValues)
Fold all attributes among the given operands into the affine map.
llvm::function_ref< Fn > function_ref
AffineExpr getAffineSymbolExpr(unsigned position, MLIRContext *context)
Canonicalize the affine map result expression order of an affine min/max operation.
LogicalResult matchAndRewrite(T affineOp, PatternRewriter &rewriter) const override
LogicalResult matchAndRewrite(T affineOp, PatternRewriter &rewriter) const override
Remove duplicated expressions in affine min/max ops.
LogicalResult matchAndRewrite(T affineOp, PatternRewriter &rewriter) const override
Merge an affine min/max op to its consumers if its consumer is also an affine min/max op.
LogicalResult matchAndRewrite(T affineOp, PatternRewriter &rewriter) const override
This is the representation of an operand reference.
This class represents a listener that may be used to hook into various actions within an OpBuilder.
OpRewritePattern is a wrapper around RewritePattern that allows for matching and rewriting against an...
OpRewritePattern(MLIRContext *context, PatternBenefit benefit=1, ArrayRef< StringRef > generatedNames={})
This represents an operation in an abstracted form, suitable for use with the builder APIs.