MLIR 24.0.0git
AffineOps.cpp
Go to the documentation of this file.
1//===- AffineOps.cpp - MLIR Affine Operations -----------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
14#include "mlir/IR/AffineExpr.h"
16#include "mlir/IR/IRMapping.h"
17#include "mlir/IR/IntegerSet.h"
18#include "mlir/IR/Matchers.h"
21#include "mlir/IR/Value.h"
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"
32#include <numeric>
33#include <optional>
34
35using namespace mlir;
36using namespace mlir::affine;
37
38using llvm::divideCeilSigned;
39using llvm::divideFloorSigned;
40using llvm::mod;
41
42#define DEBUG_TYPE "affine-ops"
43
44#include "mlir/Dialect/Affine/IR/AffineOpsDialect.cpp.inc"
45
46/// A utility function to check if a value is defined at the top level of
47/// `region` or is an argument of `region`. A value of index type defined at the
48/// top level of a `AffineScope` region is always a valid symbol for all
49/// uses in that region.
51 if (auto arg = dyn_cast<BlockArgument>(value))
52 return arg.getParentRegion() == region;
53 return value.getDefiningOp()->getParentRegion() == region;
54}
55
56/// Checks if `value` known to be a legal affine dimension or symbol in `src`
57/// region remains legal if the operation that uses it is inlined into `dest`
58/// with the given value mapping. `legalityCheck` is either `isValidDim` or
59/// `isValidSymbol`, depending on the value being required to remain a valid
60/// dimension or symbol.
61static bool
63 const IRMapping &mapping,
64 function_ref<bool(Value, Region *)> legalityCheck) {
65 // If the value is a valid dimension for any other reason than being
66 // a top-level value, it will remain valid: constants get inlined
67 // with the function, transitive affine applies also get inlined and
68 // will be checked themselves, etc.
69 if (!isTopLevelValue(value, src))
70 return true;
71
72 // If it's a top-level value because it's a block operand, i.e. a
73 // function argument, check whether the value replacing it after
74 // inlining is a valid dimension in the new region.
75 if (llvm::isa<BlockArgument>(value))
76 return legalityCheck(mapping.lookup(value), dest);
77
78 // If it's a top-level value because it's defined in the region,
79 // it can only be inlined if the defining op is a constant or a
80 // `dim`, which can appear anywhere and be valid, since the defining
81 // op won't be top-level anymore after inlining.
82 Attribute operandCst;
83 bool isDimLikeOp = isa<ShapedDimOpInterface>(value.getDefiningOp());
84 return matchPattern(value.getDefiningOp(), m_Constant(&operandCst)) ||
85 isDimLikeOp;
86}
87
88/// Checks if all values known to be legal affine dimensions or symbols in `src`
89/// remain so if their respective users are inlined into `dest`.
90static bool
92 const IRMapping &mapping,
93 function_ref<bool(Value, Region *)> legalityCheck) {
94 return llvm::all_of(values, [&](Value v) {
95 return remainsLegalAfterInline(v, src, dest, mapping, legalityCheck);
96 });
97}
98
99/// Checks if an affine read or write operation remains legal after inlining
100/// from `src` to `dest`.
101template <typename OpTy>
102static bool remainsLegalAfterInline(OpTy op, Region *src, Region *dest,
103 const IRMapping &mapping) {
104 static_assert(llvm::is_one_of<OpTy, AffineReadOpInterface,
105 AffineWriteOpInterface>::value,
106 "only ops with affine read/write interface are supported");
107
108 AffineMap map = op.getAffineMap();
109 ValueRange dimOperands = op.getMapOperands().take_front(map.getNumDims());
110 ValueRange symbolOperands =
111 op.getMapOperands().take_back(map.getNumSymbols());
113 dimOperands, src, dest, mapping,
114 static_cast<bool (*)(Value, Region *)>(isValidDim)))
115 return false;
117 symbolOperands, src, dest, mapping,
118 static_cast<bool (*)(Value, Region *)>(isValidSymbol)))
119 return false;
120 return true;
121}
122
123/// Checks if an affine apply operation remains legal after inlining from `src`
124/// to `dest`.
125// Use "unused attribute" marker to silence clang-tidy warning stemming from
126// the inability to see through "llvm::TypeSwitch".
127template <>
128[[maybe_unused]] bool remainsLegalAfterInline(AffineApplyOp op, Region *src,
129 Region *dest,
130 const IRMapping &mapping) {
131 // If it's a valid dimension, we need to check that it remains so.
132 if (isValidDim(op.getResult(), src))
134 op.getMapOperands(), src, dest, mapping,
135 static_cast<bool (*)(Value, Region *)>(isValidDim));
136
137 // Otherwise it must be a valid symbol, check that it remains so.
139 op.getMapOperands(), src, dest, mapping,
140 static_cast<bool (*)(Value, Region *)>(isValidSymbol));
141}
142
143//===----------------------------------------------------------------------===//
144// AffineDialect Interfaces
145//===----------------------------------------------------------------------===//
146
147namespace {
148/// This class defines the interface for handling inlining with affine
149/// operations.
150struct AffineInlinerInterface : public DialectInlinerInterface {
151 using DialectInlinerInterface::DialectInlinerInterface;
152
153 //===--------------------------------------------------------------------===//
154 // Analysis Hooks
155 //===--------------------------------------------------------------------===//
156
157 /// Returns true if the given region 'src' can be inlined into the region
158 /// 'dest' that is attached to an operation registered to the current dialect.
159 /// 'wouldBeCloned' is set if the region is cloned into its new location
160 /// rather than moved, indicating there may be other users.
161 bool isLegalToInline(Region *dest, Region *src, bool wouldBeCloned,
162 IRMapping &valueMapping) const final {
163 // We can inline into affine loops and conditionals if this doesn't break
164 // affine value categorization rules.
165 Operation *destOp = dest->getParentOp();
166 if (!isa<AffineParallelOp, AffineForOp, AffineIfOp>(destOp))
167 return false;
168
169 // Multi-block regions cannot be inlined into affine constructs, all of
170 // which require single-block regions.
171 if (!src->hasOneBlock())
172 return false;
173
174 // Side-effecting operations that the affine dialect cannot understand
175 // should not be inlined.
176 Block &srcBlock = src->front();
177 for (Operation &op : srcBlock) {
178 // Ops with no side effects are fine,
179 if (auto iface = dyn_cast<MemoryEffectOpInterface>(op)) {
180 if (iface.hasNoEffect())
181 continue;
182 }
183
184 // Assuming the inlined region is valid, we only need to check if the
185 // inlining would change it.
186 bool remainsValid =
187 llvm::TypeSwitch<Operation *, bool>(&op)
188 .Case<AffineApplyOp, AffineReadOpInterface,
189 AffineWriteOpInterface>([&](auto op) {
190 return remainsLegalAfterInline(op, src, dest, valueMapping);
191 })
192 .Default([](Operation *) {
193 // Conservatively disallow inlining ops we cannot reason about.
194 return false;
195 });
196
197 if (!remainsValid)
198 return false;
199 }
200
201 return true;
202 }
203
204 /// Returns true if the given operation 'op', that is registered to this
205 /// dialect, can be inlined into the given region, false otherwise.
206 bool isLegalToInline(Operation *op, Region *region, bool wouldBeCloned,
207 IRMapping &valueMapping) const final {
208 // Always allow inlining affine operations into a region that is marked as
209 // affine scope, or into affine loops and conditionals. There are some edge
210 // cases when inlining *into* affine structures, but that is handled in the
211 // other 'isLegalToInline' hook above.
212 Operation *parentOp = region->getParentOp();
213 return parentOp->hasTrait<OpTrait::AffineScope>() ||
214 isa<AffineForOp, AffineParallelOp, AffineIfOp>(parentOp);
215 }
216
217 /// Affine regions should be analyzed recursively.
218 bool shouldAnalyzeRecursively(Operation *op) const final { return true; }
219};
220} // namespace
221
222//===----------------------------------------------------------------------===//
223// AffineDialect
224//===----------------------------------------------------------------------===//
225
226void AffineDialect::initialize() {
227 addInterfaces<AffineInlinerInterface>();
228 declarePromisedInterfaces<ValueBoundsOpInterface, AffineApplyOp, AffineMaxOp,
229 AffineMinOp>();
230}
231
232/// Materialize a single constant operation from a given attribute value with
233/// the desired resultant type.
234Operation *AffineDialect::materializeConstant(OpBuilder &builder,
235 Attribute value, Type type,
236 Location loc) {
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);
240}
241
242/// A utility function to check if a value is defined at the top level of an
243/// op with trait `AffineScope`. If the value is defined in an unlinked region,
244/// conservatively assume it is not top-level. A value of index type defined at
245/// the top level is always a valid symbol.
247 if (auto arg = dyn_cast<BlockArgument>(value)) {
248 // The block owning the argument may be unlinked, e.g. when the surrounding
249 // region has not yet been attached to an Op, at which point the parent Op
250 // is null.
251 Operation *parentOp = arg.getOwner()->getParentOp();
252 return parentOp && parentOp->hasTrait<OpTrait::AffineScope>();
253 }
254 // The defining Op may live in an unlinked block so its parent Op may be null.
255 Operation *parentOp = value.getDefiningOp()->getParentOp();
256 return parentOp && parentOp->hasTrait<OpTrait::AffineScope>();
257}
258
259/// Returns the closest region enclosing `op` that is held by an operation with
260/// trait `AffineScope`; `nullptr` if there is no such region.
262 auto *curOp = op;
263 while (auto *parentOp = curOp->getParentOp()) {
264 if (parentOp->hasTrait<OpTrait::AffineScope>())
265 return curOp->getParentRegion();
266 curOp = parentOp;
267 }
268 return nullptr;
269}
270
272 Operation *curOp = op;
273 while (auto *parentOp = curOp->getParentOp()) {
274 if (!isa<AffineForOp, AffineIfOp, AffineParallelOp>(parentOp))
275 return curOp->getParentRegion();
276 curOp = parentOp;
277 }
278 return nullptr;
279}
280
281// A Value can be used as a dimension id iff it meets one of the following
282// conditions:
283// *) It is valid as a symbol.
284// *) It is an induction variable.
285// *) It is the result of affine apply operation with dimension id arguments.
287 // The value must be an index type.
288 if (!value.getType().isIndex())
289 return false;
290
291 if (auto *defOp = value.getDefiningOp())
292 return isValidDim(value, getAffineScope(defOp));
293
294 // This value has to be a block argument for an op that has the
295 // `AffineScope` trait or an induction var of an affine.for or
296 // affine.parallel.
297 if (isAffineInductionVar(value))
298 return true;
299 auto *parentOp = llvm::cast<BlockArgument>(value).getOwner()->getParentOp();
300 return parentOp && parentOp->hasTrait<OpTrait::AffineScope>();
301}
302
303// Value can be used as a dimension id iff it meets one of the following
304// conditions:
305// *) It is valid as a symbol.
306// *) It is an induction variable.
307// *) It is the result of an affine apply operation with dimension id operands.
308// *) It is the result of a more specialized index transformation (ex.
309// delinearize_index or linearize_index) with dimension id operands.
311 // The value must be an index type.
312 if (!value.getType().isIndex())
313 return false;
314
315 // All valid symbols are okay.
316 if (isValidSymbol(value, region))
317 return true;
318
319 auto *op = value.getDefiningOp();
320 if (!op) {
321 // This value has to be an induction var for an affine.for or an
322 // affine.parallel.
323 return isAffineInductionVar(value);
324 }
325
326 // Affine apply operation is ok if all of its operands are ok.
327 if (auto applyOp = dyn_cast<AffineApplyOp>(op))
328 return applyOp.isValidDim(region);
329 // delinearize_index and linearize_index are special forms of apply
330 // and so are valid dimensions if all their arguments are valid dimensions.
331 if (isa<AffineDelinearizeIndexOp, AffineLinearizeIndexOp>(op))
332 return llvm::all_of(op->getOperands(),
333 [&](Value arg) { return ::isValidDim(arg, region); });
334 // The dim op is okay if its operand memref/tensor is defined at the top
335 // level.
336 if (auto dimOp = dyn_cast<ShapedDimOpInterface>(op))
337 return isTopLevelValue(dimOp.getShapedValue());
338 return false;
339}
340
341/// Returns true if the 'index' dimension of the `memref` defined by
342/// `memrefDefOp` is a statically shaped one or defined using a valid symbol
343/// for `region`.
344template <typename AnyMemRefDefOp>
345static bool isMemRefSizeValidSymbol(AnyMemRefDefOp memrefDefOp, unsigned index,
346 Region *region) {
347 MemRefType memRefType = memrefDefOp.getType();
348
349 // Dimension index is out of bounds.
350 if (index >= memRefType.getRank()) {
351 return false;
352 }
353
354 // Statically shaped.
355 if (!memRefType.isDynamicDim(index))
356 return true;
357 // Get the position of the dimension among dynamic dimensions;
358 unsigned dynamicDimPos = memRefType.getDynamicDimIndex(index);
359 return isValidSymbol(*(memrefDefOp.getDynamicSizes().begin() + dynamicDimPos),
360 region);
361}
362
363/// Returns true if the result of the dim op is a valid symbol for `region`.
364static bool isDimOpValidSymbol(ShapedDimOpInterface dimOp, Region *region) {
365 // The dim op is okay if its source is defined at the top level.
366 if (isTopLevelValue(dimOp.getShapedValue()))
367 return true;
368
369 // Conservatively handle remaining BlockArguments as non-valid symbols.
370 // E.g. scf.for iterArgs.
371 if (llvm::isa<BlockArgument>(dimOp.getShapedValue()))
372 return false;
373
374 // The dim op is also okay if its operand memref is a view/subview whose
375 // corresponding size is a valid symbol.
376 std::optional<int64_t> index = getConstantIntValue(dimOp.getDimension());
377
378 // Be conservative if we can't understand the dimension.
379 if (!index.has_value())
380 return false;
381
382 // Skip over all memref.cast ops (if any).
383 Operation *op = dimOp.getShapedValue().getDefiningOp();
384 while (auto castOp = dyn_cast<memref::CastOp>(op)) {
385 // Bail on unranked memrefs.
386 if (isa<UnrankedMemRefType>(castOp.getSource().getType()))
387 return false;
388 op = castOp.getSource().getDefiningOp();
389 if (!op)
390 return false;
391 }
392
393 int64_t i = index.value();
395 .Case<memref::ViewOp, memref::SubViewOp, memref::AllocOp>(
396 [&](auto op) { return isMemRefSizeValidSymbol(op, i, region); })
397 .Default([](Operation *) { return false; });
398}
399
400// A value can be used as a symbol (at all its use sites) iff it meets one of
401// the following conditions:
402// *) It is a constant.
403// *) Its defining op or block arg appearance is immediately enclosed by an op
404// with `AffineScope` trait.
405// *) It is the result of an affine.apply operation with symbol operands.
406// *) It is a result of the dim op on a memref whose corresponding size is a
407// valid symbol.
409 if (!value)
410 return false;
411
412 // The value must be an index type.
413 if (!value.getType().isIndex())
414 return false;
415
416 // Check that the value is a top level value.
417 if (isTopLevelValue(value))
418 return true;
419
420 if (auto *defOp = value.getDefiningOp())
421 return isValidSymbol(value, getAffineScope(defOp));
422
423 return false;
424}
425
426/// A utility function to check if a value is defined at the top level of
427/// `region` or is an argument of `region` or is defined above the region.
428static bool isTopLevelValueOrAbove(Value value, Region *region) {
429 Region *parentRegion = value.getParentRegion();
430 do {
431 if (parentRegion == region)
432 return true;
433 Operation *regionOp = region->getParentOp();
434 if (regionOp->hasTrait<OpTrait::IsIsolatedFromAbove>())
435 break;
436 region = region->getParentOp()->getParentRegion();
437 } while (region);
438 return false;
439}
440
441/// A value can be used as a symbol for `region` iff it meets one of the
442/// following conditions:
443/// *) It is a constant.
444/// *) It is a result of a `Pure` operation whose operands are valid symbolic
445/// *) identifiers.
446/// *) It is a result of the dim op on a memref whose corresponding size is
447/// a valid symbol.
448/// *) It is defined at the top level of 'region' or is its argument.
449/// *) It dominates `region`'s parent op.
450/// If `region` is null, conservatively assume the symbol definition scope does
451/// not exist and only accept the values that would be symbols regardless of
452/// the surrounding region structure, i.e. the first three cases above.
454 // The value must be an index type.
455 if (!value.getType().isIndex())
456 return false;
457
458 // A top-level value is a valid symbol.
459 if (region && isTopLevelValueOrAbove(value, region))
460 return true;
461
462 auto *defOp = value.getDefiningOp();
463 if (!defOp)
464 return false;
465
466 // Constant operation is ok.
467 Attribute operandCst;
468 if (matchPattern(defOp, m_Constant(&operandCst)))
469 return true;
470
471 // `Pure` operation that whose operands are valid symbolic identifiers.
472 if (isPure(defOp) && llvm::all_of(defOp->getOperands(), [&](Value operand) {
473 return affine::isValidSymbol(operand, region);
474 })) {
475 return true;
476 }
477
478 // Dim op results could be valid symbols at any level.
479 if (auto dimOp = dyn_cast<ShapedDimOpInterface>(defOp))
480 return isDimOpValidSymbol(dimOp, region);
481
482 return false;
483}
484
485// Returns true if 'value' is a valid index to an affine operation (e.g.
486// affine.load, affine.store, affine.dma_start, affine.dma_wait) where
487// `region` provides the polyhedral symbol scope. Returns false otherwise.
488static bool isValidAffineIndexOperand(Value value, Region *region) {
489 return isValidDim(value, region) || isValidSymbol(value, region);
490}
491
492/// Prints dimension and symbol list.
495 unsigned numDims, OpAsmPrinter &printer) {
496 OperandRange operands(begin, end);
497 printer << '(' << operands.take_front(numDims) << ')';
498 if (operands.size() > numDims)
499 printer << '[' << operands.drop_front(numDims) << ']';
500}
501
502/// Parses dimension and symbol list and returns true if parsing failed.
504 OpAsmParser &parser, SmallVectorImpl<Value> &operands, unsigned &numDims) {
507 return failure();
508 // Store number of dimensions for validation by caller.
509 numDims = opInfos.size();
510
511 // Parse the optional symbol operands.
512 auto indexTy = parser.getBuilder().getIndexType();
513 return failure(parser.parseOperandList(
515 parser.resolveOperands(opInfos, indexTy, operands));
516}
517
518/// Utility function to verify that a set of operands are valid dimension and
519/// symbol identifiers. The operands should be laid out such that the dimension
520/// operands are before the symbol operands. This function returns failure if
521/// there was an invalid operand. An operation is provided to emit any necessary
522/// errors.
523template <typename OpTy>
524static LogicalResult
526 unsigned numDims) {
527 unsigned opIt = 0;
528 for (auto operand : operands) {
529 if (opIt++ < numDims) {
530 if (!isValidDim(operand, getAffineScope(op)))
531 return op.emitOpError("operand cannot be used as a dimension id");
532 } else if (!isValidSymbol(operand, getAffineScope(op))) {
533 return op.emitOpError("operand cannot be used as a symbol");
534 }
535 }
536 return success();
537}
538
539//===----------------------------------------------------------------------===//
540// AffineApplyOp
541//===----------------------------------------------------------------------===//
542
543AffineValueMap AffineApplyOp::getAffineValueMap() {
544 return AffineValueMap(getAffineMap(), getOperands(), getResult());
545}
546
547ParseResult AffineApplyOp::parse(OpAsmParser &parser, OperationState &result) {
548 auto &builder = parser.getBuilder();
549 auto indexTy = builder.getIndexType();
550
551 AffineMapAttr mapAttr;
552 unsigned numDims;
553 if (parser.parseAttribute(mapAttr, "map", result.attributes) ||
554 parseDimAndSymbolList(parser, result.operands, numDims) ||
555 parser.parseOptionalAttrDict(result.attributes))
556 return failure();
557 auto map = mapAttr.getValue();
558
559 if (map.getNumDims() != numDims ||
560 numDims + map.getNumSymbols() != result.operands.size()) {
561 return parser.emitError(parser.getNameLoc(),
562 "dimension or symbol index mismatch");
563 }
564
565 result.types.append(map.getNumResults(), indexTy);
566 return success();
567}
568
569void AffineApplyOp::print(OpAsmPrinter &p) {
570 p << " " << getMapAttr();
571 printDimAndSymbolList(operand_begin(), operand_end(),
572 getAffineMap().getNumDims(), p);
573 p.printOptionalAttrDict((*this)->getDiscardableAttrDictionary().getValue());
574}
575
576LogicalResult AffineApplyOp::verify() {
577 // Check input and output dimensions match.
578 AffineMap affineMap = getMap();
579
580 // Verify that operand count matches affine map dimension and symbol count.
581 if (getNumOperands() != affineMap.getNumDims() + affineMap.getNumSymbols())
582 return emitOpError(
583 "operand count and affine map dimension and symbol count must match");
584
585 // Verify that the map only produces one result.
586 if (affineMap.getNumResults() != 1)
587 return emitOpError("mapping must produce one value");
588
589 // Do not allow valid dims to be used in symbol positions. We do allow
590 // affine.apply to use operands for values that may neither qualify as affine
591 // dims or affine symbols due to usage outside of affine ops, analyses, etc.
592 Region *region = getAffineScope(*this);
593 for (Value operand : getMapOperands().drop_front(affineMap.getNumDims())) {
594 if (::isValidDim(operand, region) && !::isValidSymbol(operand, region))
595 return emitError("dimensional operand cannot be used as a symbol");
596 }
597
598 return success();
599}
600
601// The result of the affine apply operation can be used as a dimension id if all
602// its operands are valid dimension ids.
603bool AffineApplyOp::isValidDim() {
604 return llvm::all_of(getOperands(),
605 [](Value op) { return affine::isValidDim(op); });
606}
607
608// The result of the affine apply operation can be used as a dimension id if all
609// its operands are valid dimension ids with the parent operation of `region`
610// defining the polyhedral scope for symbols.
611bool AffineApplyOp::isValidDim(Region *region) {
612 return llvm::all_of(getOperands(),
613 [&](Value op) { return ::isValidDim(op, region); });
614}
615
616// The result of the affine apply operation can be used as a symbol if all its
617// operands are symbols.
618bool AffineApplyOp::isValidSymbol() {
619 return llvm::all_of(getOperands(),
620 [](Value op) { return affine::isValidSymbol(op); });
621}
622
623// The result of the affine apply operation can be used as a symbol in `region`
624// if all its operands are symbols in `region`.
625bool AffineApplyOp::isValidSymbol(Region *region) {
626 return llvm::all_of(getOperands(), [&](Value operand) {
627 return affine::isValidSymbol(operand, region);
628 });
629}
630
631OpFoldResult AffineApplyOp::fold(FoldAdaptor adaptor) {
632 auto map = getAffineMap();
633
634 // Fold dims and symbols to existing values.
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());
640
641 // Otherwise, default to folding the map.
643 bool hasPoison = false;
644 auto foldResult =
645 map.constantFold(adaptor.getMapOperands(), result, &hasPoison);
646 if (hasPoison)
647 return ub::PoisonAttr::get(getContext());
648 if (failed(foldResult))
649 return {};
650 return result[0];
651}
652
653/// Returns the largest known divisor of `e`. Exploits information from the
654/// values in `operands`.
656 // This method isn't aware of `operands`.
658
659 // We now make use of operands for the case `e` is a dim expression.
660 // TODO: More powerful simplification would have to modify
661 // getLargestKnownDivisor to take `operands` and exploit that information as
662 // well for dim/sym expressions, but in that case, getLargestKnownDivisor
663 // can't be part of the IR library but of the `Analysis` library. The IR
664 // library can only really depend on simple O(1) checks.
665 auto dimExpr = dyn_cast<AffineDimExpr>(e);
666 // If it's not a dim expr, `div` is the best we have.
667 if (!dimExpr)
668 return div;
669
670 // We simply exploit information from loop IVs.
671 // We don't need to use mlir::getLargestKnownDivisorOfValue since the other
672 // desired simplifications are expected to be part of other
673 // canonicalizations. Also, mlir::getLargestKnownDivisorOfValue is part of the
674 // LoopAnalysis library.
675 Value operand = operands[dimExpr.getPosition()];
676 int64_t operandDivisor = 1;
677 // TODO: With the right accessors, this can be extended to
678 // LoopLikeOpInterface.
679 if (AffineForOp forOp = getForInductionVarOwner(operand)) {
680 if (forOp.hasConstantLowerBound() && forOp.getConstantLowerBound() == 0) {
681 operandDivisor = forOp.getStepAsInt();
682 } else {
683 uint64_t lbLargestKnownDivisor =
684 forOp.getLowerBoundMap().getLargestKnownDivisorOfMapExprs();
685 operandDivisor = std::gcd(lbLargestKnownDivisor, forOp.getStepAsInt());
686 }
687 }
688 return operandDivisor;
689}
690
691/// Check if `e` is known to be: 0 <= `e` < `k`. Handles the simple cases of `e`
692/// being an affine dim expression or a constant.
694 int64_t k) {
695 if (auto constExpr = dyn_cast<AffineConstantExpr>(e)) {
696 int64_t constVal = constExpr.getValue();
697 return constVal >= 0 && constVal < k;
698 }
699 auto dimExpr = dyn_cast<AffineDimExpr>(e);
700 if (!dimExpr)
701 return false;
702 Value operand = operands[dimExpr.getPosition()];
703 // TODO: With the right accessors, this can be extended to
704 // LoopLikeOpInterface.
705 if (AffineForOp forOp = getForInductionVarOwner(operand)) {
706 if (forOp.hasConstantLowerBound() && forOp.getConstantLowerBound() >= 0 &&
707 forOp.hasConstantUpperBound() && forOp.getConstantUpperBound() <= k) {
708 return true;
709 }
710 }
711
712 // We don't consider other cases like `operand` being defined by a constant or
713 // an affine.apply op since such cases will already be handled by other
714 // patterns and propagation of loop IVs or constant would happen.
715 return false;
716}
717
718/// Check if expression `e` is of the form d*e_1 + e_2 where 0 <= e_2 < d.
719/// Set `div` to `d`, `quotientTimesDiv` to e_1 and `rem` to e_2 if the
720/// expression is in that form.
722 AffineExpr &quotientTimesDiv, AffineExpr &rem) {
723 auto bin = dyn_cast<AffineBinaryOpExpr>(e);
724 if (!bin || bin.getKind() != AffineExprKind::Add)
725 return false;
726
727 AffineExpr llhs = bin.getLHS();
728 AffineExpr rlhs = bin.getRHS();
729 div = getLargestKnownDivisor(llhs, operands);
730 if (isNonNegativeBoundedBy(rlhs, operands, div)) {
731 quotientTimesDiv = llhs;
732 rem = rlhs;
733 return true;
734 }
735 div = getLargestKnownDivisor(rlhs, operands);
736 if (isNonNegativeBoundedBy(llhs, operands, div)) {
737 quotientTimesDiv = rlhs;
738 rem = llhs;
739 return true;
740 }
741 return false;
742}
743
744/// Gets the constant lower bound on an `iv`.
745static std::optional<int64_t> getLowerBound(Value iv) {
746 AffineForOp forOp = getForInductionVarOwner(iv);
747 if (forOp && forOp.hasConstantLowerBound())
748 return forOp.getConstantLowerBound();
749 return std::nullopt;
750}
751
752/// Gets the constant upper bound on an affine.for `iv`.
753static std::optional<int64_t> getUpperBound(Value iv) {
754 AffineForOp forOp = getForInductionVarOwner(iv);
755 if (!forOp || !forOp.hasConstantUpperBound())
756 return std::nullopt;
757
758 // If its lower bound is also known, we can get a more precise bound
759 // whenever the step is not one.
760 if (forOp.hasConstantLowerBound()) {
761 return forOp.getConstantUpperBound() - 1 -
762 (forOp.getConstantUpperBound() - forOp.getConstantLowerBound() - 1) %
763 forOp.getStepAsInt();
764 }
765 return forOp.getConstantUpperBound() - 1;
766}
767
768/// Determine a constant upper bound for `expr` if one exists while exploiting
769/// values in `operands`. Note that the upper bound is an inclusive one. `expr`
770/// is guaranteed to be less than or equal to it.
771static std::optional<int64_t> getUpperBound(AffineExpr expr, unsigned numDims,
772 unsigned numSymbols,
773 ArrayRef<Value> operands) {
774 if (auto constExpr = dyn_cast<AffineConstantExpr>(expr))
775 return constExpr.getValue();
776
777 // Get the constant lower or upper bounds on the operands.
778 SmallVector<std::optional<int64_t>> constLowerBounds, constUpperBounds;
779 constLowerBounds.reserve(operands.size());
780 constUpperBounds.reserve(operands.size());
781 for (Value operand : operands) {
782 constLowerBounds.push_back(getLowerBound(operand));
783 constUpperBounds.push_back(getUpperBound(operand));
784 }
785
786 return getBoundForAffineExpr(expr, numDims, numSymbols, constLowerBounds,
787 constUpperBounds,
788 /*isUpper=*/true);
789}
790
791/// Determine a constant lower bound for `expr` if one exists while exploiting
792/// values in `operands`. Note that the upper bound is an inclusive one. `expr`
793/// is guaranteed to be less than or equal to it.
794static std::optional<int64_t> getLowerBound(AffineExpr expr, unsigned numDims,
795 unsigned numSymbols,
796 ArrayRef<Value> operands) {
797 if (auto constExpr = dyn_cast<AffineConstantExpr>(expr))
798 return constExpr.getValue();
799
800 // Get the constant lower or upper bounds on the operands.
801 SmallVector<std::optional<int64_t>> constLowerBounds, constUpperBounds;
802 constLowerBounds.reserve(operands.size());
803 constUpperBounds.reserve(operands.size());
804 for (Value operand : operands) {
805 constLowerBounds.push_back(getLowerBound(operand));
806 constUpperBounds.push_back(getUpperBound(operand));
807 }
808
809 return getBoundForAffineExpr(expr, numDims, numSymbols, constLowerBounds,
810 constUpperBounds,
811 /*isUpper=*/false);
812}
813
814/// Simplify `expr` while exploiting information from the values in `operands`.
815static void simplifyExprAndOperands(AffineExpr &expr, unsigned numDims,
816 unsigned numSymbols,
817 ArrayRef<Value> operands) {
818 // We do this only for certain floordiv/mod expressions.
819 auto binExpr = dyn_cast<AffineBinaryOpExpr>(expr);
820 if (!binExpr)
821 return;
822
823 // Simplify the child expressions first.
824 AffineExpr lhs = binExpr.getLHS();
825 AffineExpr rhs = binExpr.getRHS();
826 simplifyExprAndOperands(lhs, numDims, numSymbols, operands);
827 simplifyExprAndOperands(rhs, numDims, numSymbols, operands);
828 expr = getAffineBinaryOpExpr(binExpr.getKind(), lhs, rhs);
829
830 binExpr = dyn_cast<AffineBinaryOpExpr>(expr);
831 if (!binExpr || (expr.getKind() != AffineExprKind::FloorDiv &&
833 expr.getKind() != AffineExprKind::Mod)) {
834 return;
835 }
836
837 // The `lhs` and `rhs` may be different post construction of simplified expr.
838 lhs = binExpr.getLHS();
839 rhs = binExpr.getRHS();
840 auto rhsConst = dyn_cast<AffineConstantExpr>(rhs);
841 if (!rhsConst)
842 return;
843
844 int64_t rhsConstVal = rhsConst.getValue();
845 // Undefined exprsessions aren't touched; IR can still be valid with them.
846 if (rhsConstVal <= 0)
847 return;
848
849 // Exploit constant lower/upper bounds to simplify a floordiv or mod.
850 MLIRContext *context = expr.getContext();
851 std::optional<int64_t> lhsLbConst =
852 getLowerBound(lhs, numDims, numSymbols, operands);
853 std::optional<int64_t> lhsUbConst =
854 getUpperBound(lhs, numDims, numSymbols, operands);
855 if (lhsLbConst && lhsUbConst) {
856 int64_t lhsLbConstVal = *lhsLbConst;
857 int64_t lhsUbConstVal = *lhsUbConst;
858 // lhs floordiv c is a single value lhs is bounded in a range `c` that has
859 // the same quotient.
860 if (binExpr.getKind() == AffineExprKind::FloorDiv &&
861 divideFloorSigned(lhsLbConstVal, rhsConstVal) ==
862 divideFloorSigned(lhsUbConstVal, rhsConstVal)) {
864 divideFloorSigned(lhsLbConstVal, rhsConstVal), context);
865 return;
866 }
867 // lhs ceildiv c is a single value if the entire range has the same ceil
868 // quotient.
869 if (binExpr.getKind() == AffineExprKind::CeilDiv &&
870 divideCeilSigned(lhsLbConstVal, rhsConstVal) ==
871 divideCeilSigned(lhsUbConstVal, rhsConstVal)) {
872 expr = getAffineConstantExpr(divideCeilSigned(lhsLbConstVal, rhsConstVal),
873 context);
874 return;
875 }
876 // lhs mod c is lhs if the entire range has quotient 0 w.r.t the rhs.
877 if (binExpr.getKind() == AffineExprKind::Mod && lhsLbConstVal >= 0 &&
878 lhsLbConstVal < rhsConstVal && lhsUbConstVal < rhsConstVal) {
879 expr = lhs;
880 return;
881 }
882 }
883
884 // Simplify expressions of the form e = (e_1 + e_2) floordiv c or (e_1 + e_2)
885 // mod c, where e_1 is a multiple of `k` and 0 <= e_2 < k. In such cases, if
886 // `c` % `k` == 0, (e_1 + e_2) floordiv c can be simplified to e_1 floordiv c.
887 // And when k % c == 0, (e_1 + e_2) mod c can be simplified to e_2 mod c.
888 AffineExpr quotientTimesDiv, rem;
889 int64_t divisor;
890 if (isQTimesDPlusR(lhs, operands, divisor, quotientTimesDiv, rem)) {
891 if (rhsConstVal % divisor == 0 &&
892 binExpr.getKind() == AffineExprKind::FloorDiv) {
893 expr = quotientTimesDiv.floorDiv(rhsConst);
894 } else if (divisor % rhsConstVal == 0 &&
895 binExpr.getKind() == AffineExprKind::Mod) {
896 expr = rem % rhsConst;
897 }
898 return;
899 }
900
901 // Handle the simple case when the LHS expression can be either upper
902 // bounded or is a known multiple of RHS constant.
903 // lhs floordiv c -> 0 if 0 <= lhs < c,
904 // lhs mod c -> 0 if lhs % c = 0.
905 if ((isNonNegativeBoundedBy(lhs, operands, rhsConstVal) &&
906 binExpr.getKind() == AffineExprKind::FloorDiv) ||
907 (getLargestKnownDivisor(lhs, operands) % rhsConstVal == 0 &&
908 binExpr.getKind() == AffineExprKind::Mod)) {
909 expr = getAffineConstantExpr(0, expr.getContext());
910 }
911}
912
913/// Simplify the expressions in `map` while making use of lower or upper bounds
914/// of its operands. If `isMax` is true, the map is to be treated as a max of
915/// its result expressions, and min otherwise. Eg: min (d0, d1) -> (8, 4 * d0 +
916/// d1) can be simplified to (8) if the operands are respectively lower bounded
917/// by 2 and 0 (the second expression can't be lower than 8).
919 ArrayRef<Value> operands,
920 bool isMax) {
921 // Can't simplify.
922 if (operands.empty())
923 return;
924
925 // Get the upper or lower bound on an affine.for op IV using its range.
926 // Get the constant lower or upper bounds on the operands.
927 SmallVector<std::optional<int64_t>> constLowerBounds, constUpperBounds;
928 constLowerBounds.reserve(operands.size());
929 constUpperBounds.reserve(operands.size());
930 for (Value operand : operands) {
931 constLowerBounds.push_back(getLowerBound(operand));
932 constUpperBounds.push_back(getUpperBound(operand));
933 }
934
935 // We will compute the lower and upper bounds on each of the expressions
936 // Then, we will check (depending on max or min) as to whether a specific
937 // bound is redundant by checking if its highest (in case of max) and its
938 // lowest (in the case of min) value is already lower than (or higher than)
939 // the lower bound (or upper bound in the case of min) of another bound.
940 SmallVector<std::optional<int64_t>, 4> lowerBounds, upperBounds;
941 lowerBounds.reserve(map.getNumResults());
942 upperBounds.reserve(map.getNumResults());
943 for (AffineExpr e : map.getResults()) {
944 if (auto constExpr = dyn_cast<AffineConstantExpr>(e)) {
945 lowerBounds.push_back(constExpr.getValue());
946 upperBounds.push_back(constExpr.getValue());
947 } else {
948 lowerBounds.push_back(
950 constLowerBounds, constUpperBounds,
951 /*isUpper=*/false));
952 upperBounds.push_back(
954 constLowerBounds, constUpperBounds,
955 /*isUpper=*/true));
956 }
957 }
958
959 // Collect expressions that are not redundant.
960 SmallVector<AffineExpr, 4> irredundantExprs;
961 for (auto exprEn : llvm::enumerate(map.getResults())) {
962 AffineExpr e = exprEn.value();
963 unsigned i = exprEn.index();
964 // Some expressions can be turned into constants.
965 if (lowerBounds[i] && upperBounds[i] && *lowerBounds[i] == *upperBounds[i])
966 e = getAffineConstantExpr(*lowerBounds[i], e.getContext());
967
968 // Check if the expression is redundant.
969 if (isMax) {
970 if (!upperBounds[i]) {
971 irredundantExprs.push_back(e);
972 continue;
973 }
974 // If there exists another expression such that its lower bound is greater
975 // than this expression's upper bound, it's redundant.
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)
980 return false;
981 if (*otherLowerBound > *upperBounds[i])
982 return true;
983 if (*otherLowerBound < *upperBounds[i])
984 return false;
985 // Equality case. When both expressions are considered redundant, we
986 // don't want to get both of them. We keep the one that appears
987 // first.
988 if (upperBounds[pos] && lowerBounds[i] &&
989 lowerBounds[i] == upperBounds[i] &&
990 otherLowerBound == *upperBounds[pos] && i < pos)
991 return false;
992 return true;
993 }))
994 irredundantExprs.push_back(e);
995 } else {
996 if (!lowerBounds[i]) {
997 irredundantExprs.push_back(e);
998 continue;
999 }
1000 // Likewise for the `min` case. Use the complement of the condition above.
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)
1005 return false;
1006 if (*otherUpperBound < *lowerBounds[i])
1007 return true;
1008 if (*otherUpperBound > *lowerBounds[i])
1009 return false;
1010 if (lowerBounds[pos] && upperBounds[i] &&
1011 lowerBounds[i] == upperBounds[i] &&
1012 otherUpperBound == lowerBounds[pos] && i < pos)
1013 return false;
1014 return true;
1015 }))
1016 irredundantExprs.push_back(e);
1017 }
1018 }
1019
1020 // Create the map without the redundant expressions.
1021 map = AffineMap::get(map.getNumDims(), map.getNumSymbols(), irredundantExprs,
1022 map.getContext());
1023}
1024
1025/// Simplify the map while exploiting information on the values in `operands`.
1026// Use "unused attribute" marker to silence warning stemming from the inability
1027// to see through the template expansion.
1028[[maybe_unused]] static void simplifyMapWithOperands(AffineMap &map,
1029 ArrayRef<Value> operands) {
1030 assert(map.getNumInputs() == operands.size() && "invalid operands for map");
1031 SmallVector<AffineExpr> newResults;
1032 newResults.reserve(map.getNumResults());
1033 for (AffineExpr expr : map.getResults()) {
1035 operands);
1036 newResults.push_back(expr);
1037 }
1038 map = AffineMap::get(map.getNumDims(), map.getNumSymbols(), newResults,
1039 map.getContext());
1040}
1041
1042/// Assuming `dimOrSym` is a quantity in the apply op map `map` and defined by
1043/// `minOp = affine_min(x_1, ..., x_n)`. This function checks that:
1044/// `0 < affine_min(x_1, ..., x_n)` and proceeds with replacing the patterns:
1045/// ```
1046/// dimOrSym.ceildiv(x_k)
1047/// (dimOrSym + x_k - 1).floordiv(x_k)
1048/// ```
1049/// by `1` for all `k` in `1, ..., n`. This is possible because `x / x_k <= 1`.
1050///
1051///
1052/// Warning: ValueBoundsConstraintSet::computeConstantBound is needed to check
1053/// `minOp` is positive.
1054static LogicalResult replaceAffineMinBoundingBoxExpression(AffineMinOp minOp,
1055 AffineExpr dimOrSym,
1056 AffineMap *map,
1057 ValueRange dims,
1058 ValueRange syms) {
1059 LDBG() << "replaceAffineMinBoundingBoxExpression: `" << minOp << "`";
1060 AffineMap affineMinMap = minOp.getAffineMap();
1061
1062 // Check the value is positive.
1063 for (unsigned i = 0, e = affineMinMap.getNumResults(); i < e; ++i) {
1064 // Compare each expression in the minimum against 0.
1066 getAsIndexOpFoldResult(minOp.getContext(), 0),
1069 minOp.getOperands())))
1070 return failure();
1071 }
1072
1073 /// Convert affine symbols and dimensions in minOp to symbols or dimensions in
1074 /// the apply op affine map.
1075 DenseMap<AffineExpr, AffineExpr> dimSymConversionTable;
1076 SmallVector<unsigned> unmappedDims, unmappedSyms;
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);
1081 continue;
1082 }
1083 dimSymConversionTable[getAffineDimExpr(i, minOp.getContext())] =
1084 getAffineDimExpr(it.getIndex(), minOp.getContext());
1085 }
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);
1090 continue;
1091 }
1092 dimSymConversionTable[getAffineSymbolExpr(i, minOp.getContext())] =
1093 getAffineSymbolExpr(it.getIndex(), minOp.getContext());
1094 }
1095
1096 // Create the replacement map.
1098 AffineExpr c1 = getAffineConstantExpr(1, minOp.getContext());
1099 for (AffineExpr expr : affineMinMap.getResults()) {
1100 // If we cannot express the result in terms of the apply map symbols and
1101 // sims then continue.
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); }))
1106 continue;
1107
1108 AffineExpr convertedExpr = expr.replace(dimSymConversionTable);
1109
1110 // dimOrSym.ceilDiv(expr) -> 1
1111 repl[dimOrSym.ceilDiv(convertedExpr)] = c1;
1112 // (dimOrSym + expr - 1).floorDiv(expr) -> 1
1113 repl[(dimOrSym + convertedExpr - 1).floorDiv(convertedExpr)] = c1;
1114 }
1115 AffineMap initialMap = *map;
1116 *map = initialMap.replace(repl, initialMap.getNumDims(),
1117 initialMap.getNumSymbols());
1118 return success(*map != initialMap);
1119}
1120
1121/// Recursively traverse `e`. If `e` or one of its sub-expressions has the form
1122/// e1 + e2 + ... + eK, where the e_i are a super(multi)set of `exprsToRemove`,
1123/// place a map between e and `newVal` + sum({e1, e2, .. eK} - exprsToRemove)
1124/// into `replacementsMap`. If no entries were added to `replacementsMap`,
1125/// nothing was found.
1127 AffineExpr e, const llvm::SmallDenseSet<AffineExpr, 4> &exprsToRemove,
1128 AffineExpr newVal, DenseMap<AffineExpr, AffineExpr> &replacementsMap) {
1129 auto binOp = dyn_cast<AffineBinaryOpExpr>(e);
1130 if (!binOp)
1131 return;
1132 AffineExpr lhs = binOp.getLHS();
1133 AffineExpr rhs = binOp.getRHS();
1134 if (binOp.getKind() != AffineExprKind::Add) {
1135 shortenAddChainsContainingAll(lhs, exprsToRemove, newVal, replacementsMap);
1136 shortenAddChainsContainingAll(rhs, exprsToRemove, newVal, replacementsMap);
1137 return;
1138 }
1139 SmallVector<AffineExpr> toPreserve;
1140 llvm::SmallDenseSet<AffineExpr, 4> ourTracker(exprsToRemove);
1141 AffineExpr thisTerm = rhs;
1142 AffineExpr nextTerm = lhs;
1143
1144 while (thisTerm) {
1145 if (!ourTracker.erase(thisTerm)) {
1146 toPreserve.push_back(thisTerm);
1147 shortenAddChainsContainingAll(thisTerm, exprsToRemove, newVal,
1148 replacementsMap);
1149 }
1150 auto nextBinOp = dyn_cast_if_present<AffineBinaryOpExpr>(nextTerm);
1151 if (!nextBinOp || nextBinOp.getKind() != AffineExprKind::Add) {
1152 thisTerm = nextTerm;
1153 nextTerm = AffineExpr();
1154 } else {
1155 thisTerm = nextBinOp.getRHS();
1156 nextTerm = nextBinOp.getLHS();
1157 }
1158 }
1159 if (!ourTracker.empty())
1160 return;
1161 // We reverse the terms to be preserved here in order to preserve
1162 // associativity between them.
1163 AffineExpr newExpr = newVal;
1164 for (AffineExpr preserved : llvm::reverse(toPreserve))
1165 newExpr = newExpr + preserved;
1166 replacementsMap.insert({e, newExpr});
1167}
1168
1169/// If this map contains of the expression `x_1 + x_1 * C_1 + ... x_n * C_N +
1170/// ...` (not necessarily in order) where the set of the `x_i` is the set of
1171/// outputs of an `affine.delinearize_index` whos inverse is that expression,
1172/// replace that expression with the input of that delinearize_index op.
1173///
1174/// `unitDimInput` is the input that was detected as the potential start to this
1175/// replacement chain - if it isn't the rightmost result of the delinearization,
1176/// this method fails. (This is intended to ensure we don't have redundant scans
1177/// over the same expression).
1178///
1179/// While this currently only handles delinearizations with a constant basis,
1180/// that isn't a fundamental limitation.
1181///
1182/// This is a utility function for `replaceDimOrSym` below.
1184 AffineDelinearizeIndexOp delinOp, Value resultToReplace, AffineMap *map,
1186 if (!delinOp.getDynamicBasis().empty())
1187 return failure();
1188 if (resultToReplace != delinOp.getMultiIndex().back())
1189 return failure();
1190
1191 MLIRContext *ctx = delinOp.getContext();
1192 SmallVector<AffineExpr> resToExpr(delinOp.getNumResults(), AffineExpr());
1193 for (auto [pos, dim] : llvm::enumerate(dims)) {
1194 auto asResult = dyn_cast_if_present<OpResult>(dim);
1195 if (!asResult)
1196 continue;
1197 if (asResult.getOwner() == delinOp.getOperation())
1198 resToExpr[asResult.getResultNumber()] = getAffineDimExpr(pos, ctx);
1199 }
1200 for (auto [pos, sym] : llvm::enumerate(syms)) {
1201 auto asResult = dyn_cast_if_present<OpResult>(sym);
1202 if (!asResult)
1203 continue;
1204 if (asResult.getOwner() == delinOp.getOperation())
1205 resToExpr[asResult.getResultNumber()] = getAffineSymbolExpr(pos, ctx);
1206 }
1207 if (llvm::is_contained(resToExpr, AffineExpr()))
1208 return failure();
1209
1210 bool isDimReplacement = llvm::all_of(resToExpr, llvm::IsaPred<AffineDimExpr>);
1211 int64_t stride = 1;
1212 llvm::SmallDenseSet<AffineExpr, 4> expectedExprs;
1213 // This isn't zip_equal since sometimes the delinearize basis is missing a
1214 // size for the first result.
1215 for (auto [binding, size] : llvm::zip(
1216 llvm::reverse(resToExpr), llvm::reverse(delinOp.getStaticBasis()))) {
1217 expectedExprs.insert(binding * getAffineConstantExpr(stride, ctx));
1218 stride *= size;
1219 }
1220 if (resToExpr.size() != delinOp.getStaticBasis().size())
1221 expectedExprs.insert(resToExpr[0] * stride);
1222
1224 AffineExpr delinInExpr = isDimReplacement
1225 ? getAffineDimExpr(dims.size(), ctx)
1226 : getAffineSymbolExpr(syms.size(), ctx);
1227
1228 for (AffineExpr e : map->getResults())
1229 shortenAddChainsContainingAll(e, expectedExprs, delinInExpr, replacements);
1230 if (replacements.empty())
1231 return failure();
1232
1233 AffineMap origMap = *map;
1234 if (isDimReplacement)
1235 dims.push_back(delinOp.getLinearIndex());
1236 else
1237 syms.push_back(delinOp.getLinearIndex());
1238 *map = origMap.replace(replacements, dims.size(), syms.size());
1239
1240 // Blank out dead dimensions and symbols
1241 for (AffineExpr e : resToExpr) {
1242 if (auto d = dyn_cast<AffineDimExpr>(e)) {
1243 unsigned pos = d.getPosition();
1244 if (!map->isFunctionOfDim(pos))
1245 dims[pos] = nullptr;
1246 }
1247 if (auto s = dyn_cast<AffineSymbolExpr>(e)) {
1248 unsigned pos = s.getPosition();
1249 if (!map->isFunctionOfSymbol(pos))
1250 syms[pos] = nullptr;
1251 }
1252 }
1253 return success();
1254}
1255
1256/// Replace all occurrences of AffineExpr at position `pos` in `map` by the
1257/// defining AffineApplyOp expression and operands.
1258/// When `dimOrSymbolPosition < dims.size()`, AffineDimExpr@[pos] is replaced.
1259/// When `dimOrSymbolPosition >= dims.size()`,
1260/// AffineSymbolExpr@[pos - dims.size()] is replaced.
1261/// Mutate `map`,`dims` and `syms` in place as follows:
1262/// 1. `dims` and `syms` are only appended to.
1263/// 2. `map` dim and symbols are gradually shifted to higher positions.
1264/// 3. Old `dim` and `sym` entries are replaced by nullptr
1265/// This avoids the need for any bookkeeping.
1266/// If `replaceAffineMin` is set to true, additionally triggers more expensive
1267/// replacements involving affine_min operations.
1268static LogicalResult replaceDimOrSym(AffineMap *map,
1269 unsigned dimOrSymbolPosition,
1272 bool replaceAffineMin) {
1273 MLIRContext *ctx = map->getContext();
1274 bool isDimReplacement = (dimOrSymbolPosition < dims.size());
1275 unsigned pos = isDimReplacement ? dimOrSymbolPosition
1276 : dimOrSymbolPosition - dims.size();
1277 Value &v = isDimReplacement ? dims[pos] : syms[pos];
1278 if (!v)
1279 return failure();
1280
1281 if (auto minOp = v.getDefiningOp<AffineMinOp>(); minOp && replaceAffineMin) {
1282 AffineExpr dimOrSym = isDimReplacement ? getAffineDimExpr(pos, ctx)
1283 : getAffineSymbolExpr(pos, ctx);
1284 return replaceAffineMinBoundingBoxExpression(minOp, dimOrSym, map, dims,
1285 syms);
1286 }
1287
1288 if (auto delinOp = v.getDefiningOp<affine::AffineDelinearizeIndexOp>()) {
1289 return replaceAffineDelinearizeIndexInverseExpression(delinOp, v, map, dims,
1290 syms);
1291 }
1292
1293 auto affineApply = v.getDefiningOp<AffineApplyOp>();
1294 if (!affineApply)
1295 return failure();
1296
1297 // At this point we will perform a replacement of `v`, set the entry in `dim`
1298 // or `sym` to nullptr immediately.
1299 v = nullptr;
1300
1301 // Compute the map, dims and symbols coming from the AffineApplyOp.
1302 AffineMap composeMap = affineApply.getAffineMap();
1303 assert(composeMap.getNumResults() == 1 && "affine.apply with >1 results");
1304 SmallVector<Value> composeOperands(affineApply.getMapOperands().begin(),
1305 affineApply.getMapOperands().end());
1306 // Canonicalize the map to promote dims to symbols when possible. This is to
1307 // avoid generating invalid maps.
1308 canonicalizeMapAndOperands(&composeMap, &composeOperands);
1309 AffineExpr replacementExpr =
1310 composeMap.shiftDims(dims.size()).shiftSymbols(syms.size()).getResult(0);
1311 ValueRange composeDims =
1312 ArrayRef<Value>(composeOperands).take_front(composeMap.getNumDims());
1313 ValueRange composeSyms =
1314 ArrayRef<Value>(composeOperands).take_back(composeMap.getNumSymbols());
1315 AffineExpr toReplace = isDimReplacement ? getAffineDimExpr(pos, ctx)
1316 : getAffineSymbolExpr(pos, ctx);
1317
1318 // Append the dims and symbols where relevant and perform the replacement.
1319 dims.append(composeDims.begin(), composeDims.end());
1320 syms.append(composeSyms.begin(), composeSyms.end());
1321 *map = map->replace(toReplace, replacementExpr, dims.size(), syms.size());
1322
1323 return success();
1324}
1325
1326/// Iterate over `operands` and fold away all those produced by an AffineApplyOp
1327/// iteratively. Perform canonicalization of map and operands as well as
1328/// AffineMap simplification. `map` and `operands` are mutated in place.
1330 SmallVectorImpl<Value> *operands,
1331 bool composeAffineMin = false) {
1332 if (map->getNumResults() == 0) {
1333 canonicalizeMapAndOperands(map, operands);
1334 *map = simplifyAffineMap(*map);
1335 return;
1336 }
1337
1338 MLIRContext *ctx = map->getContext();
1339 SmallVector<Value, 4> dims(operands->begin(),
1340 operands->begin() + map->getNumDims());
1341 SmallVector<Value, 4> syms(operands->begin() + map->getNumDims(),
1342 operands->end());
1343
1344 // Iterate over dims and symbols coming from AffineApplyOp and replace until
1345 // exhaustion. This iteratively mutates `map`, `dims` and `syms`. Both `dims`
1346 // and `syms` can only increase by construction.
1347 // The implementation uses a `while` loop to support the case of symbols
1348 // that may be constructed from dims ;this may be overkill.
1349 while (true) {
1350 bool changed = false;
1351 for (unsigned pos = 0; pos != dims.size() + syms.size(); ++pos)
1352 if ((changed |=
1353 succeeded(replaceDimOrSym(map, pos, dims, syms, composeAffineMin))))
1354 break;
1355 if (!changed)
1356 break;
1357 }
1358
1359 // Clear operands so we can fill them anew.
1360 operands->clear();
1361
1362 // At this point we may have introduced null operands, prune them out before
1363 // canonicalizing map and operands.
1364 unsigned nDims = 0, nSyms = 0;
1365 SmallVector<AffineExpr, 4> dimReplacements, symReplacements;
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();
1373 if (!v) {
1374 assert(isDim ? !map->isFunctionOfDim(en.index())
1375 : !map->isFunctionOfSymbol(en.index()) &&
1376 "map is function of unexpected expr@pos");
1377 repls.push_back(getAffineConstantExpr(0, ctx));
1378 continue;
1379 }
1380 repls.push_back(isDim ? getAffineDimExpr(nDims++, ctx)
1381 : getAffineSymbolExpr(nSyms++, ctx));
1382 operands->push_back(v);
1383 }
1384 }
1385 *map = map->replaceDimsAndSymbols(dimReplacements, symReplacements, nDims,
1386 nSyms);
1387
1388 // Canonicalize and simplify before returning.
1389 canonicalizeMapAndOperands(map, operands);
1390 *map = simplifyAffineMap(*map);
1391}
1392
1394 AffineMap *map, SmallVectorImpl<Value> *operands, bool composeAffineMin) {
1395 while (llvm::any_of(*operands, [](Value v) {
1396 return isa_and_nonnull<AffineApplyOp>(v.getDefiningOp());
1397 })) {
1398 composeAffineMapAndOperands(map, operands, composeAffineMin);
1399 }
1400 // Additional trailing step for AffineMinOps in case no chains of AffineApply.
1401 if (composeAffineMin && llvm::any_of(*operands, [](Value v) {
1402 return isa_and_nonnull<AffineMinOp>(v.getDefiningOp());
1403 })) {
1404 composeAffineMapAndOperands(map, operands, composeAffineMin);
1405 }
1406}
1407
1408AffineApplyOp
1410 ArrayRef<OpFoldResult> operands,
1411 bool composeAffineMin) {
1412 SmallVector<Value> valueOperands;
1413 map = foldAttributesIntoMap(b, map, operands, valueOperands);
1414 composeAffineMapAndOperands(&map, &valueOperands, composeAffineMin);
1415 assert(map);
1416 return AffineApplyOp::create(b, loc, map, valueOperands);
1417}
1418
1419AffineApplyOp
1421 ArrayRef<OpFoldResult> operands,
1422 bool composeAffineMin) {
1424 b, loc,
1426 .front(),
1427 operands, composeAffineMin);
1428}
1429
1430/// Composes the given affine map with the given list of operands, pulling in
1431/// the maps from any affine.apply operations that supply the operands.
1433 SmallVectorImpl<Value> &operands,
1434 bool composeAffineMin = false) {
1435 // Compose and canonicalize each expression in the map individually because
1436 // composition only applies to single-result maps, collecting potentially
1437 // duplicate operands in a single list with shifted dimensions and symbols.
1438 SmallVector<Value> dims, symbols;
1440 for (unsigned i : llvm::seq<unsigned>(0, map.getNumResults())) {
1441 SmallVector<Value> submapOperands(operands.begin(), operands.end());
1442 AffineMap submap = map.getSubMap({i});
1443 fullyComposeAffineMapAndOperands(&submap, &submapOperands,
1444 composeAffineMin);
1445 canonicalizeMapAndOperands(&submap, &submapOperands);
1446 unsigned numNewDims = submap.getNumDims();
1447 submap = submap.shiftDims(dims.size()).shiftSymbols(symbols.size());
1448 llvm::append_range(dims,
1449 ArrayRef<Value>(submapOperands).take_front(numNewDims));
1450 llvm::append_range(symbols,
1451 ArrayRef<Value>(submapOperands).drop_front(numNewDims));
1452 exprs.push_back(submap.getResult(0));
1453 }
1454
1455 // Canonicalize the map created from composed expressions to deduplicate the
1456 // dimension and symbol operands.
1457 operands = llvm::to_vector(llvm::concat<Value>(dims, symbols));
1458 map = AffineMap::get(dims.size(), symbols.size(), exprs, map.getContext());
1459 canonicalizeMapAndOperands(&map, &operands);
1460}
1461
1464 bool composeAffineMin) {
1465 assert(map.getNumResults() == 1 && "building affine.apply with !=1 result");
1466
1467 // Create new builder without a listener, so that no notification is
1468 // triggered if the op is folded.
1469 // TODO: OpBuilder::createOrFold should return OpFoldResults, then this
1470 // workaround is no longer needed.
1471 OpBuilder newBuilder(b.getContext());
1472 newBuilder.setInsertionPoint(b.getInsertionBlock(), b.getInsertionPoint());
1473
1474 // Create op.
1475 AffineApplyOp applyOp =
1476 makeComposedAffineApply(newBuilder, loc, map, operands, composeAffineMin);
1477
1478 // Get constant operands.
1479 SmallVector<Attribute> constOperands(applyOp->getNumOperands());
1480 for (unsigned i = 0, e = constOperands.size(); i != e; ++i)
1481 matchPattern(applyOp->getOperand(i), m_Constant(&constOperands[i]));
1482
1483 // Try to fold the operation.
1484 SmallVector<OpFoldResult> foldResults;
1485 if (failed(applyOp->fold(constOperands, foldResults)) ||
1486 foldResults.empty()) {
1487 if (OpBuilder::Listener *listener = b.getListener())
1488 listener->notifyOperationInserted(applyOp, /*previous=*/{});
1489 return applyOp.getResult();
1490 }
1491
1492 applyOp->erase();
1493 return llvm::getSingleElement(foldResults);
1494}
1495
1497 OpBuilder &b, Location loc, AffineExpr expr,
1498 ArrayRef<OpFoldResult> operands, bool composeAffineMin) {
1500 b, loc,
1502 .front(),
1503 operands, composeAffineMin);
1504}
1505
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);
1514 });
1515}
1516
1517template <typename OpTy>
1519 ArrayRef<OpFoldResult> operands) {
1520 SmallVector<Value> valueOperands;
1521 map = foldAttributesIntoMap(b, map, operands, valueOperands);
1522 composeMultiResultAffineMap(map, valueOperands);
1523 return OpTy::create(b, loc, b.getIndexType(), map, valueOperands);
1524}
1525
1526AffineMinOp
1531
1532template <typename OpTy>
1534 AffineMap map,
1535 ArrayRef<OpFoldResult> operands) {
1536 // Create new builder without a listener, so that no notification is
1537 // triggered if the op is folded.
1538 // TODO: OpBuilder::createOrFold should return OpFoldResults, then this
1539 // workaround is no longer needed.
1540 OpBuilder newBuilder(b.getContext());
1541 newBuilder.setInsertionPoint(b.getInsertionBlock(), b.getInsertionPoint());
1542
1543 // Create op.
1544 auto minMaxOp = makeComposedMinMax<OpTy>(newBuilder, loc, map, operands);
1545
1546 // Get constant operands.
1547 SmallVector<Attribute> constOperands(minMaxOp->getNumOperands());
1548 for (unsigned i = 0, e = constOperands.size(); i != e; ++i)
1549 matchPattern(minMaxOp->getOperand(i), m_Constant(&constOperands[i]));
1550
1551 // Try to fold the operation.
1552 SmallVector<OpFoldResult> foldResults;
1553 if (failed(minMaxOp->fold(constOperands, foldResults)) ||
1554 foldResults.empty()) {
1555 if (OpBuilder::Listener *listener = b.getListener())
1556 listener->notifyOperationInserted(minMaxOp, /*previous=*/{});
1557 return minMaxOp.getResult();
1558 }
1559
1560 minMaxOp->erase();
1561 return llvm::getSingleElement(foldResults);
1562}
1563
1570
1577
1578// A symbol may appear as a dim in affine.apply operations. This function
1579// canonicalizes dims that are valid symbols into actual symbols.
1580template <class MapOrSet>
1581static void canonicalizePromotedSymbols(MapOrSet *mapOrSet,
1582 SmallVectorImpl<Value> *operands) {
1583 if (!mapOrSet || operands->empty())
1584 return;
1585
1586 assert(mapOrSet->getNumInputs() == operands->size() &&
1587 "map/set inputs must match number of operands");
1588
1589 auto *context = mapOrSet->getContext();
1590 SmallVector<Value, 8> resultOperands;
1591 resultOperands.reserve(operands->size());
1592 SmallVector<Value, 8> remappedSymbols;
1593 remappedSymbols.reserve(operands->size());
1594 unsigned nextDim = 0;
1595 unsigned nextSym = 0;
1596 unsigned oldNumSyms = mapOrSet->getNumSymbols();
1597 SmallVector<AffineExpr, 8> dimRemapping(mapOrSet->getNumDims());
1598 for (unsigned i = 0, e = mapOrSet->getNumInputs(); i != e; ++i) {
1599 if (i < mapOrSet->getNumDims()) {
1600 if (isValidSymbol((*operands)[i])) {
1601 // This is a valid symbol that appears as a dim, canonicalize it.
1602 dimRemapping[i] = getAffineSymbolExpr(oldNumSyms + nextSym++, context);
1603 remappedSymbols.push_back((*operands)[i]);
1604 } else {
1605 dimRemapping[i] = getAffineDimExpr(nextDim++, context);
1606 resultOperands.push_back((*operands)[i]);
1607 }
1608 } else {
1609 resultOperands.push_back((*operands)[i]);
1610 }
1611 }
1612
1613 resultOperands.append(remappedSymbols.begin(), remappedSymbols.end());
1614 *operands = std::move(resultOperands);
1615 *mapOrSet = mapOrSet->replaceDimsAndSymbols(
1616 dimRemapping, /*symReplacements=*/{}, nextDim, oldNumSyms + nextSym);
1617
1618 assert(mapOrSet->getNumInputs() == operands->size() &&
1619 "map/set inputs must match number of operands");
1620}
1621
1622/// A valid affine dimension may appear as a symbol in affine.apply operations.
1623/// Given an application of `operands` to an affine map or integer set
1624/// `mapOrSet`, this function canonicalizes symbols of `mapOrSet` that are valid
1625/// dims, but not valid symbols into actual dims. Without such a legalization,
1626/// the affine.apply will be invalid. This method is the exact inverse of
1627/// canonicalizePromotedSymbols.
1628template <class MapOrSet>
1629static void legalizeDemotedDims(MapOrSet &mapOrSet,
1630 SmallVectorImpl<Value> &operands) {
1631 if (!mapOrSet || operands.empty())
1632 return;
1633
1634 unsigned numOperands = operands.size();
1635
1636 assert(mapOrSet.getNumInputs() == numOperands &&
1637 "map/set inputs must match number of operands");
1638
1639 auto *context = mapOrSet.getContext();
1640 SmallVector<Value, 8> resultOperands;
1641 resultOperands.reserve(numOperands);
1642 SmallVector<Value, 8> remappedDims;
1643 remappedDims.reserve(numOperands);
1644 SmallVector<Value, 8> symOperands;
1645 symOperands.reserve(mapOrSet.getNumSymbols());
1646 unsigned nextSym = 0;
1647 unsigned nextDim = 0;
1648 unsigned oldNumDims = mapOrSet.getNumDims();
1649 SmallVector<AffineExpr, 8> symRemapping(mapOrSet.getNumSymbols());
1650 resultOperands.assign(operands.begin(), operands.begin() + oldNumDims);
1651 for (unsigned i = oldNumDims, e = mapOrSet.getNumInputs(); i != e; ++i) {
1652 if (operands[i] && isValidDim(operands[i]) && !isValidSymbol(operands[i])) {
1653 // This is a valid dim that appears as a symbol, legalize it.
1654 symRemapping[i - oldNumDims] =
1655 getAffineDimExpr(oldNumDims + nextDim++, context);
1656 remappedDims.push_back(operands[i]);
1657 } else {
1658 symRemapping[i - oldNumDims] = getAffineSymbolExpr(nextSym++, context);
1659 symOperands.push_back(operands[i]);
1660 }
1661 }
1662
1663 append_range(resultOperands, remappedDims);
1664 append_range(resultOperands, symOperands);
1665 operands = std::move(resultOperands);
1666 mapOrSet = mapOrSet.replaceDimsAndSymbols(
1667 /*dimReplacements=*/{}, symRemapping, oldNumDims + nextDim, nextSym);
1668
1669 assert(mapOrSet.getNumInputs() == operands.size() &&
1670 "map/set inputs must match number of operands");
1671}
1672
1673// Works for either an affine map or an integer set.
1674template <class MapOrSet>
1675static void canonicalizeMapOrSetAndOperands(MapOrSet *mapOrSet,
1676 SmallVectorImpl<Value> *operands) {
1677 static_assert(llvm::is_one_of<MapOrSet, AffineMap, IntegerSet>::value,
1678 "Argument must be either of AffineMap or IntegerSet type");
1679
1680 if (!mapOrSet || operands->empty())
1681 return;
1682
1683 assert(mapOrSet->getNumInputs() == operands->size() &&
1684 "map/set inputs must match number of operands");
1685
1686 canonicalizePromotedSymbols<MapOrSet>(mapOrSet, operands);
1687 legalizeDemotedDims<MapOrSet>(*mapOrSet, *operands);
1688
1689 // Check to see what dims are used.
1690 llvm::SmallBitVector usedDims(mapOrSet->getNumDims());
1691 llvm::SmallBitVector usedSyms(mapOrSet->getNumSymbols());
1692 mapOrSet->walkExprs([&](AffineExpr expr) {
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;
1697 });
1698
1699 auto *context = mapOrSet->getContext();
1700
1701 SmallVector<Value, 8> resultOperands;
1702 resultOperands.reserve(operands->size());
1703
1704 llvm::SmallDenseMap<Value, AffineExpr, 8> seenDims;
1705 SmallVector<AffineExpr, 8> dimRemapping(mapOrSet->getNumDims());
1706 unsigned nextDim = 0;
1707 for (unsigned i = 0, e = mapOrSet->getNumDims(); i != e; ++i) {
1708 if (usedDims[i]) {
1709 // Remap dim positions for duplicate operands.
1710 auto it = seenDims.find((*operands)[i]);
1711 if (it == seenDims.end()) {
1712 dimRemapping[i] = getAffineDimExpr(nextDim++, context);
1713 resultOperands.push_back((*operands)[i]);
1714 seenDims.insert(std::make_pair((*operands)[i], dimRemapping[i]));
1715 } else {
1716 dimRemapping[i] = it->second;
1717 }
1718 }
1719 }
1720 llvm::SmallDenseMap<Value, AffineExpr, 8> seenSymbols;
1721 SmallVector<AffineExpr, 8> symRemapping(mapOrSet->getNumSymbols());
1722 unsigned nextSym = 0;
1723 for (unsigned i = 0, e = mapOrSet->getNumSymbols(); i != e; ++i) {
1724 if (!usedSyms[i])
1725 continue;
1726 // Handle constant operands (only needed for symbolic operands since
1727 // constant operands in dimensional positions would have already been
1728 // promoted to symbolic positions above).
1729 IntegerAttr operandCst;
1730 if (matchPattern((*operands)[i + mapOrSet->getNumDims()],
1731 m_Constant(&operandCst))) {
1732 symRemapping[i] =
1733 getAffineConstantExpr(operandCst.getValue().getSExtValue(), context);
1734 continue;
1735 }
1736 // Remap symbol positions for duplicate operands.
1737 auto it = seenSymbols.find((*operands)[i + mapOrSet->getNumDims()]);
1738 if (it == seenSymbols.end()) {
1739 symRemapping[i] = getAffineSymbolExpr(nextSym++, context);
1740 resultOperands.push_back((*operands)[i + mapOrSet->getNumDims()]);
1741 seenSymbols.insert(std::make_pair((*operands)[i + mapOrSet->getNumDims()],
1742 symRemapping[i]));
1743 } else {
1744 symRemapping[i] = it->second;
1745 }
1746 }
1747 *mapOrSet = mapOrSet->replaceDimsAndSymbols(dimRemapping, symRemapping,
1748 nextDim, nextSym);
1749 *operands = std::move(resultOperands);
1750}
1751
1756
1761
1762namespace {
1763/// Simplify AffineApply, AffineLoad, and AffineStore operations by composing
1764/// maps that supply results into them.
1765///
1766template <typename AffineOpTy>
1767struct SimplifyAffineOp : public OpRewritePattern<AffineOpTy> {
1768 using OpRewritePattern<AffineOpTy>::OpRewritePattern;
1769
1770 /// Replace the affine op with another instance of it with the supplied
1771 /// map and mapOperands.
1772 void replaceAffineOp(PatternRewriter &rewriter, AffineOpTy affineOp,
1773 AffineMap map, ArrayRef<Value> mapOperands) const;
1774
1775 LogicalResult matchAndRewrite(AffineOpTy affineOp,
1776 PatternRewriter &rewriter) const override {
1777 static_assert(
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 "
1782 "expected");
1783 auto map = affineOp.getAffineMap();
1784 AffineMap oldMap = map;
1785 auto oldOperands = affineOp.getMapOperands();
1786 SmallVector<Value, 8> resultOperands(oldOperands);
1787 composeAffineMapAndOperands(&map, &resultOperands);
1788 canonicalizeMapAndOperands(&map, &resultOperands);
1789 simplifyMapWithOperands(map, resultOperands);
1790 if (map == oldMap && std::equal(oldOperands.begin(), oldOperands.end(),
1791 resultOperands.begin()))
1792 return failure();
1793
1794 replaceAffineOp(rewriter, affineOp, map, resultOperands);
1795 return success();
1796 }
1797};
1798
1799// Specialize the template to account for the different build signatures for
1800// affine load, store, and apply ops.
1801template <>
1802void SimplifyAffineOp<AffineLoadOp>::replaceAffineOp(
1803 PatternRewriter &rewriter, AffineLoadOp load, AffineMap map,
1804 ArrayRef<Value> mapOperands) const {
1805 rewriter.replaceOpWithNewOp<AffineLoadOp>(load, load.getMemRef(), map,
1806 mapOperands, load.getMaybeAlign());
1807}
1808template <>
1809void SimplifyAffineOp<AffinePrefetchOp>::replaceAffineOp(
1810 PatternRewriter &rewriter, AffinePrefetchOp prefetch, AffineMap map,
1811 ArrayRef<Value> mapOperands) const {
1812 rewriter.replaceOpWithNewOp<AffinePrefetchOp>(
1813 prefetch, prefetch.getMemref(), map, mapOperands, prefetch.getIsWrite(),
1814 prefetch.getLocalityHint(), prefetch.getIsDataCache());
1815}
1816template <>
1817void SimplifyAffineOp<AffineStoreOp>::replaceAffineOp(
1818 PatternRewriter &rewriter, AffineStoreOp store, AffineMap map,
1819 ArrayRef<Value> mapOperands) const {
1820 rewriter.replaceOpWithNewOp<AffineStoreOp>(
1821 store, store.getValueToStore(), store.getMemRef(), map, mapOperands,
1822 store.getMaybeAlign());
1823}
1824template <>
1825void SimplifyAffineOp<AffineVectorLoadOp>::replaceAffineOp(
1826 PatternRewriter &rewriter, AffineVectorLoadOp vectorload, AffineMap map,
1827 ArrayRef<Value> mapOperands) const {
1828 rewriter.replaceOpWithNewOp<AffineVectorLoadOp>(
1829 vectorload, vectorload.getVectorType(), vectorload.getMemRef(), map,
1830 mapOperands, vectorload.getMaybeAlign());
1831}
1832template <>
1833void SimplifyAffineOp<AffineVectorStoreOp>::replaceAffineOp(
1834 PatternRewriter &rewriter, AffineVectorStoreOp vectorstore, AffineMap map,
1835 ArrayRef<Value> mapOperands) const {
1836 rewriter.replaceOpWithNewOp<AffineVectorStoreOp>(
1837 vectorstore, vectorstore.getValueToStore(), vectorstore.getMemRef(), map,
1838 mapOperands, vectorstore.getMaybeAlign());
1839}
1840
1841// Generic version for ops that don't have extra operands.
1842template <typename AffineOpTy>
1843void SimplifyAffineOp<AffineOpTy>::replaceAffineOp(
1844 PatternRewriter &rewriter, AffineOpTy op, AffineMap map,
1845 ArrayRef<Value> mapOperands) const {
1846 rewriter.replaceOpWithNewOp<AffineOpTy>(op, map, mapOperands);
1847}
1848} // namespace
1849
1850void AffineApplyOp::getCanonicalizationPatterns(RewritePatternSet &results,
1851 MLIRContext *context) {
1852 results.add<SimplifyAffineOp<AffineApplyOp>>(context);
1853}
1854
1855//===----------------------------------------------------------------------===//
1856// AffineDmaStartOp
1857//===----------------------------------------------------------------------===//
1858
1859// TODO: Check that map operands are loop IVs or symbols.
1860void AffineDmaStartOp::build(OpBuilder &builder, OperationState &result,
1861 Value srcMemRef, AffineMap srcMap,
1862 ValueRange srcIndices, Value destMemRef,
1863 AffineMap dstMap, ValueRange destIndices,
1864 Value tagMemRef, AffineMap tagMap,
1865 ValueRange tagIndices, Value numElements,
1866 Value stride, Value elementsPerStride) {
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);
1877 if (stride) {
1878 result.addOperands({stride, elementsPerStride});
1879 }
1880}
1881
1882void AffineDmaStartOp::print(OpAsmPrinter &p) {
1883 p << " " << getSrcMemRef() << '[';
1884 p.printAffineMapOfSSAIds(getSrcMapAttr(), getSrcIndices());
1885 p << "], " << getDstMemRef() << '[';
1886 p.printAffineMapOfSSAIds(getDstMapAttr(), getDstIndices());
1887 p << "], " << getTagMemRef() << '[';
1888 p.printAffineMapOfSSAIds(getTagMapAttr(), getTagIndices());
1889 p << "], " << getNumElements();
1890 if (isStrided()) {
1891 p << ", " << getStride();
1892 p << ", " << getNumElementsPerStride();
1893 }
1894 p << " : " << getSrcMemRefType() << ", " << getDstMemRefType() << ", "
1895 << getTagMemRefType();
1896}
1897
1898// Parse AffineDmaStartOp.
1899// Ex:
1900// affine.dma_start %src[%i, %j], %dst[%k, %l], %tag[%index], %size,
1901// %stride, %num_elt_per_stride
1902// : memref<3076 x f32, 0>, memref<1024 x f32, 2>, memref<1 x i32>
1903//
1904ParseResult AffineDmaStartOp::parse(OpAsmParser &parser,
1906 OpAsmParser::UnresolvedOperand srcMemRefInfo;
1907 AffineMapAttr srcMapAttr;
1909 OpAsmParser::UnresolvedOperand dstMemRefInfo;
1910 AffineMapAttr dstMapAttr;
1912 OpAsmParser::UnresolvedOperand tagMemRefInfo;
1913 AffineMapAttr tagMapAttr;
1915 OpAsmParser::UnresolvedOperand numElementsInfo;
1917
1919 auto indexType = parser.getBuilder().getIndexType();
1920
1921 // Parse and resolve the following list of operands:
1922 // *) dst memref followed by its affine maps operands (in square brackets).
1923 // *) src memref followed by its affine map operands (in square brackets).
1924 // *) tag memref followed by its affine map operands (in square brackets).
1925 // *) number of elements transferred by DMA operation.
1926 if (parser.parseOperand(srcMemRefInfo) ||
1927 parser.parseAffineMapOfSSAIds(srcMapOperands, srcMapAttr,
1928 getSrcMapAttrStrName(),
1929 result.attributes) ||
1930 parser.parseComma() || parser.parseOperand(dstMemRefInfo) ||
1931 parser.parseAffineMapOfSSAIds(dstMapOperands, dstMapAttr,
1932 getDstMapAttrStrName(),
1933 result.attributes) ||
1934 parser.parseComma() || parser.parseOperand(tagMemRefInfo) ||
1935 parser.parseAffineMapOfSSAIds(tagMapOperands, tagMapAttr,
1936 getTagMapAttrStrName(),
1937 result.attributes) ||
1938 parser.parseComma() || parser.parseOperand(numElementsInfo))
1939 return failure();
1940
1941 // Parse optional stride and elements per stride.
1942 if (parser.parseTrailingOperandList(strideInfo))
1943 return failure();
1944
1945 if (!strideInfo.empty() && strideInfo.size() != 2) {
1946 return parser.emitError(parser.getNameLoc(),
1947 "expected two stride related operands");
1948 }
1949 bool isStrided = strideInfo.size() == 2;
1950
1951 if (parser.parseColonTypeList(types))
1952 return failure();
1953
1954 if (types.size() != 3)
1955 return parser.emitError(parser.getNameLoc(), "expected three types");
1956
1957 if (parser.resolveOperand(srcMemRefInfo, types[0], result.operands) ||
1958 parser.resolveOperands(srcMapOperands, indexType, result.operands) ||
1959 parser.resolveOperand(dstMemRefInfo, types[1], result.operands) ||
1960 parser.resolveOperands(dstMapOperands, indexType, result.operands) ||
1961 parser.resolveOperand(tagMemRefInfo, types[2], result.operands) ||
1962 parser.resolveOperands(tagMapOperands, indexType, result.operands) ||
1963 parser.resolveOperand(numElementsInfo, indexType, result.operands))
1964 return failure();
1965
1966 if (isStrided) {
1967 if (parser.resolveOperands(strideInfo, indexType, result.operands))
1968 return failure();
1969 }
1970
1971 // Check that src/dst/tag operand counts match their map.numInputs.
1972 if (srcMapOperands.size() != srcMapAttr.getValue().getNumInputs() ||
1973 dstMapOperands.size() != dstMapAttr.getValue().getNumInputs() ||
1974 tagMapOperands.size() != tagMapAttr.getValue().getNumInputs())
1975 return parser.emitError(parser.getNameLoc(),
1976 "memref operand count not equal to map.numInputs");
1977 return success();
1978}
1979
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");
1987
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");
1994 }
1995
1996 Region *scope = getAffineScope(*this);
1997 for (auto idx : getSrcIndices()) {
1998 if (!idx.getType().isIndex())
1999 return emitOpError("src index to dma_start must have 'index' type");
2000 if (!isValidAffineIndexOperand(idx, scope))
2001 return emitOpError(
2002 "src index must be a valid dimension or symbol identifier");
2003 }
2004 for (auto idx : getDstIndices()) {
2005 if (!idx.getType().isIndex())
2006 return emitOpError("dst index to dma_start must have 'index' type");
2007 if (!isValidAffineIndexOperand(idx, scope))
2008 return emitOpError(
2009 "dst index must be a valid dimension or symbol identifier");
2010 }
2011 for (auto idx : getTagIndices()) {
2012 if (!idx.getType().isIndex())
2013 return emitOpError("tag index to dma_start must have 'index' type");
2014 if (!isValidAffineIndexOperand(idx, scope))
2015 return emitOpError(
2016 "tag index must be a valid dimension or symbol identifier");
2017 }
2018 return success();
2019}
2020
2021LogicalResult AffineDmaStartOp::fold(FoldAdaptor adaptor,
2023 /// dma_start(memrefcast) -> dma_start
2024 return memref::foldMemRefCast(*this);
2025}
2026
2027void AffineDmaStartOp::getEffects(
2029 &effects) {
2030 effects.emplace_back(MemoryEffects::Read::get(), &getSrcMemRefMutable(),
2032 effects.emplace_back(MemoryEffects::Write::get(), &getDstMemRefMutable(),
2034 effects.emplace_back(MemoryEffects::Read::get(), &getTagMemRefMutable(),
2036}
2037
2038//===----------------------------------------------------------------------===//
2039// AffineDmaWaitOp
2040//===----------------------------------------------------------------------===//
2041
2042// TODO: Check that map operands are loop IVs or symbols.
2043void AffineDmaWaitOp::build(OpBuilder &builder, OperationState &result,
2044 Value tagMemRef, AffineMap tagMap,
2045 ValueRange tagIndices, Value numElements) {
2046 result.addOperands(tagMemRef);
2047 result.addAttribute(getTagMapAttrStrName(), AffineMapAttr::get(tagMap));
2048 result.addOperands(tagIndices);
2049 result.addOperands(numElements);
2050}
2051
2052void AffineDmaWaitOp::print(OpAsmPrinter &p) {
2053 p << " " << getTagMemRef() << '[';
2054 SmallVector<Value, 2> operands(getTagIndices());
2055 p.printAffineMapOfSSAIds(getTagMapAttr(), operands);
2056 p << "], ";
2058 p << " : " << getTagMemRef().getType();
2059}
2060
2061// Parse AffineDmaWaitOp.
2062// Eg:
2063// affine.dma_wait %tag[%index], %num_elements
2064// : memref<1 x i32, (d0) -> (d0), 4>
2065//
2066ParseResult AffineDmaWaitOp::parse(OpAsmParser &parser,
2068 OpAsmParser::UnresolvedOperand tagMemRefInfo;
2069 AffineMapAttr tagMapAttr;
2071 Type type;
2072 auto indexType = parser.getBuilder().getIndexType();
2073 OpAsmParser::UnresolvedOperand numElementsInfo;
2074
2075 // Parse tag memref, its map operands, and dma size.
2076 if (parser.parseOperand(tagMemRefInfo) ||
2077 parser.parseAffineMapOfSSAIds(tagMapOperands, tagMapAttr,
2078 getTagMapAttrStrName(),
2079 result.attributes) ||
2080 parser.parseComma() || parser.parseOperand(numElementsInfo) ||
2081 parser.parseColonType(type) ||
2082 parser.resolveOperand(tagMemRefInfo, type, result.operands) ||
2083 parser.resolveOperands(tagMapOperands, indexType, result.operands) ||
2084 parser.resolveOperand(numElementsInfo, indexType, result.operands))
2085 return failure();
2086
2087 if (!llvm::isa<MemRefType>(type))
2088 return parser.emitError(parser.getNameLoc(),
2089 "expected tag to be of memref type");
2090
2091 if (tagMapOperands.size() != tagMapAttr.getValue().getNumInputs())
2092 return parser.emitError(parser.getNameLoc(),
2093 "tag memref operand count != to map.numInputs");
2094 return success();
2095}
2096
2097LogicalResult AffineDmaWaitOp::verify() {
2098 if (!llvm::isa<MemRefType>(getOperand(0).getType()))
2099 return emitOpError("expected DMA tag to be of memref type");
2100 Region *scope = getAffineScope(*this);
2101 for (auto idx : getTagIndices()) {
2102 if (!idx.getType().isIndex())
2103 return emitOpError("index to dma_wait must have 'index' type");
2104 if (!isValidAffineIndexOperand(idx, scope))
2105 return emitOpError(
2106 "index must be a valid dimension or symbol identifier");
2107 }
2108 return success();
2109}
2110
2111LogicalResult AffineDmaWaitOp::fold(FoldAdaptor adaptor,
2113 /// dma_wait(memrefcast) -> dma_wait
2114 return memref::foldMemRefCast(*this);
2115}
2116
2117void AffineDmaWaitOp::getEffects(
2119 &effects) {
2120 effects.emplace_back(MemoryEffects::Read::get(), &getTagMemRefMutable(),
2122}
2123
2124//===----------------------------------------------------------------------===//
2125// AffineForOp
2126//===----------------------------------------------------------------------===//
2127
2128/// 'bodyBuilder' is used to build the body of affine.for. If iterArgs and
2129/// bodyBuilder are empty/null, we include default terminator op.
2130void AffineForOp::build(OpBuilder &builder, OperationState &result,
2131 ValueRange lbOperands, AffineMap lbMap,
2132 ValueRange ubOperands, AffineMap ubMap, int64_t step,
2133 ValueRange iterArgs, BodyBuilderFn bodyBuilder) {
2134 assert(((!lbMap && lbOperands.empty()) ||
2135 lbOperands.size() == lbMap.getNumInputs()) &&
2136 "lower bound operand count does not match the affine map");
2137 assert(((!ubMap && ubOperands.empty()) ||
2138 ubOperands.size() == ubMap.getNumInputs()) &&
2139 "upper bound operand count does not match the affine map");
2140 assert(step > 0 && "step has to be a positive integer constant");
2141
2142 OpBuilder::InsertionGuard guard(builder);
2143
2144 // Set variadic segment sizes.
2145 result.addAttribute(
2146 getOperandSegmentSizeAttr(),
2147 builder.getDenseI32ArrayAttr({static_cast<int32_t>(lbOperands.size()),
2148 static_cast<int32_t>(ubOperands.size()),
2149 static_cast<int32_t>(iterArgs.size())}));
2150
2151 for (Value val : iterArgs)
2152 result.addTypes(val.getType());
2153
2154 // Add an attribute for the step.
2155 result.addAttribute(getStepAttrName(result.name),
2156 builder.getIntegerAttr(builder.getIndexType(), step));
2157
2158 // Add the lower bound.
2159 result.addAttribute(getLowerBoundMapAttrName(result.name),
2160 AffineMapAttr::get(lbMap));
2161 result.addOperands(lbOperands);
2162
2163 // Add the upper bound.
2164 result.addAttribute(getUpperBoundMapAttrName(result.name),
2165 AffineMapAttr::get(ubMap));
2166 result.addOperands(ubOperands);
2167
2168 result.addOperands(iterArgs);
2169 // Create a region and a block for the body. The argument of the region is
2170 // the loop induction variable.
2171 Region *bodyRegion = result.addRegion();
2172 Block *bodyBlock = builder.createBlock(bodyRegion);
2173 Value inductionVar =
2174 bodyBlock->addArgument(builder.getIndexType(), result.location);
2175 for (Value val : iterArgs)
2176 bodyBlock->addArgument(val.getType(), val.getLoc());
2177
2178 // Create the default terminator if the builder is not provided and if the
2179 // iteration arguments are not provided. Otherwise, leave this to the caller
2180 // because we don't know which values to return from the loop.
2181 if (iterArgs.empty() && !bodyBuilder) {
2182 ensureTerminator(*bodyRegion, builder, result.location);
2183 } else if (bodyBuilder) {
2184 OpBuilder::InsertionGuard guard(builder);
2185 builder.setInsertionPointToStart(bodyBlock);
2186 bodyBuilder(builder, result.location, inductionVar,
2187 bodyBlock->getArguments().drop_front());
2188 }
2189}
2190
2191void AffineForOp::build(OpBuilder &builder, OperationState &result, int64_t lb,
2192 int64_t ub, int64_t step, ValueRange iterArgs,
2193 BodyBuilderFn bodyBuilder) {
2194 auto lbMap = AffineMap::getConstantMap(lb, builder.getContext());
2195 auto ubMap = AffineMap::getConstantMap(ub, builder.getContext());
2196 return build(builder, result, {}, lbMap, {}, ubMap, step, iterArgs,
2197 bodyBuilder);
2198}
2199
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");
2205
2206 return success();
2207}
2208
2209LogicalResult AffineForOp::verifyRegions() {
2210 // Step must be a strictly positive integer.
2211 if (getStepAsInt() <= 0)
2212 return emitOpError("expected step to be a positive integer, got ")
2213 << getStepAsInt();
2214
2215 // Verify that the bound operands are valid dimension/symbols.
2216 /// Lower bound.
2217 if (getLowerBoundMap().getNumInputs() > 0)
2219 getLowerBoundMap().getNumDims())))
2220 return failure();
2221 /// Upper bound.
2222 if (getUpperBoundMap().getNumInputs() > 0)
2224 getUpperBoundMap().getNumDims())))
2225 return failure();
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");
2230
2231 unsigned opNumResults = getNumResults();
2232 if (opNumResults == 0)
2233 return success();
2234
2235 // If ForOp defines values, check that the number and types of the defined
2236 // values match ForOp initial iter operands and backedge basic block
2237 // arguments.
2238 if (getNumIterOperands() != opNumResults)
2239 return emitOpError(
2240 "mismatch between the number of loop-carried values and results");
2241 if (getNumRegionIterArgs() != opNumResults)
2242 return emitOpError(
2243 "mismatch between the number of basic block args and results");
2244
2245 return success();
2246}
2247
2248/// Parse a for operation loop bounds.
2249static ParseResult parseBound(bool isLower, OperationState &result,
2250 OpAsmParser &p) {
2251 // 'min' / 'max' prefixes are generally syntactic sugar, but are required if
2252 // the map has multiple results.
2253 bool failedToParsedMinMax =
2254 failed(p.parseOptionalKeyword(isLower ? "max" : "min"));
2255
2256 auto &builder = p.getBuilder();
2257 auto boundAttrStrName =
2258 isLower ? AffineForOp::getLowerBoundMapAttrName(result.name)
2259 : AffineForOp::getUpperBoundMapAttrName(result.name);
2260
2261 // Parse ssa-id as identity map.
2263 if (p.parseOperandList(boundOpInfos))
2264 return failure();
2265
2266 if (!boundOpInfos.empty()) {
2267 // Check that only one operand was parsed.
2268 if (boundOpInfos.size() > 1)
2269 return p.emitError(p.getNameLoc(),
2270 "expected only one loop bound operand");
2271
2272 // TODO: improve error message when SSA value is not of index type.
2273 // Currently it is 'use of value ... expects different type than prior uses'
2274 if (p.resolveOperand(boundOpInfos.front(), builder.getIndexType(),
2275 result.operands))
2276 return failure();
2277
2278 // Create an identity map using symbol id. This representation is optimized
2279 // for storage. Analysis passes may expand it into a multi-dimensional map
2280 // if desired.
2281 AffineMap map = builder.getSymbolIdentityMap();
2282 result.addAttribute(boundAttrStrName, AffineMapAttr::get(map));
2283 return success();
2284 }
2285
2286 // Get the attribute location.
2287 SMLoc attrLoc = p.getCurrentLocation();
2288
2289 Attribute boundAttr;
2290 if (p.parseAttribute(boundAttr, builder.getIndexType(), boundAttrStrName,
2291 result.attributes))
2292 return failure();
2293
2294 // Parse full form - affine map followed by dim and symbol list.
2295 if (auto affineMapAttr = dyn_cast<AffineMapAttr>(boundAttr)) {
2296 unsigned currentNumOperands = result.operands.size();
2297 unsigned numDims;
2298 if (parseDimAndSymbolList(p, result.operands, numDims))
2299 return failure();
2300
2301 auto map = affineMapAttr.getValue();
2302 if (map.getNumDims() != numDims)
2303 return p.emitError(
2304 p.getNameLoc(),
2305 "dim operand count and affine map dim count must match");
2306
2307 unsigned numDimAndSymbolOperands =
2308 result.operands.size() - currentNumOperands;
2309 if (numDims + map.getNumSymbols() != numDimAndSymbolOperands)
2310 return p.emitError(
2311 p.getNameLoc(),
2312 "symbol operand count and affine map symbol count must match");
2313
2314 // If the map has multiple results, make sure that we parsed the min/max
2315 // prefix.
2316 if (map.getNumResults() > 1 && failedToParsedMinMax) {
2317 if (isLower) {
2318 return p.emitError(attrLoc, "lower loop bound affine map with "
2319 "multiple results requires 'max' prefix");
2320 }
2321 return p.emitError(attrLoc, "upper loop bound affine map with multiple "
2322 "results requires 'min' prefix");
2323 }
2324 return success();
2325 }
2326
2327 // Parse custom assembly form.
2328 if (auto integerAttr = dyn_cast<IntegerAttr>(boundAttr)) {
2329 result.attributes.pop_back();
2330 result.addAttribute(
2331 boundAttrStrName,
2332 AffineMapAttr::get(builder.getConstantAffineMap(integerAttr.getInt())));
2333 return success();
2334 }
2335
2336 return p.emitError(
2337 p.getNameLoc(),
2338 "expected valid affine map representation for loop bounds");
2339}
2340
2341ParseResult AffineForOp::parse(OpAsmParser &parser, OperationState &result) {
2342 auto &builder = parser.getBuilder();
2343 OpAsmParser::Argument inductionVariable;
2344 inductionVariable.type = builder.getIndexType();
2345 // Parse the induction variable followed by '='.
2346 if (parser.parseArgument(inductionVariable) || parser.parseEqual())
2347 return failure();
2348
2349 // Parse loop bounds.
2350 int64_t numOperands = result.operands.size();
2351 if (parseBound(/*isLower=*/true, result, parser))
2352 return failure();
2353 int64_t numLbOperands = result.operands.size() - numOperands;
2354 if (parser.parseKeyword("to", " between bounds"))
2355 return failure();
2356 numOperands = result.operands.size();
2357 if (parseBound(/*isLower=*/false, result, parser))
2358 return failure();
2359 int64_t numUbOperands = result.operands.size() - numOperands;
2360
2361 // Parse the optional loop step, we default to 1 if one is not present.
2362 if (parser.parseOptionalKeyword("step")) {
2363 result.addAttribute(
2364 getStepAttrName(result.name),
2365 builder.getIntegerAttr(builder.getIndexType(), /*value=*/1));
2366 } else {
2367 SMLoc stepLoc = parser.getCurrentLocation();
2368 IntegerAttr stepAttr;
2369 if (parser.parseAttribute(stepAttr, builder.getIndexType(),
2370 getStepAttrName(result.name).data(),
2371 result.attributes))
2372 return failure();
2373
2374 if (!stepAttr.getValue().isStrictlyPositive())
2375 return parser.emitError(
2376 stepLoc,
2377 "expected step to be representable as a positive signed integer");
2378 }
2379
2380 // Parse the optional initial iteration arguments.
2381 SmallVector<OpAsmParser::Argument, 4> regionArgs;
2382 SmallVector<OpAsmParser::UnresolvedOperand, 4> operands;
2383
2384 // Induction variable.
2385 regionArgs.push_back(inductionVariable);
2386
2387 if (succeeded(parser.parseOptionalKeyword("iter_args"))) {
2388 // Parse assignment list and results type list.
2389 if (parser.parseAssignmentList(regionArgs, operands) ||
2390 parser.parseArrowTypeList(result.types))
2391 return failure();
2392 // Resolve input operands.
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;
2397 if (parser.resolveOperand(std::get<1>(argOperandType), type,
2398 result.operands))
2399 return failure();
2400 }
2401 }
2402
2403 result.addAttribute(
2404 getOperandSegmentSizeAttr(),
2405 builder.getDenseI32ArrayAttr({static_cast<int32_t>(numLbOperands),
2406 static_cast<int32_t>(numUbOperands),
2407 static_cast<int32_t>(operands.size())}));
2408
2409 // Parse the body region.
2410 Region *body = result.addRegion();
2411 if (regionArgs.size() != result.types.size() + 1)
2412 return parser.emitError(
2413 parser.getNameLoc(),
2414 "mismatch between the number of loop-carried values and results");
2415 if (parser.parseRegion(*body, regionArgs))
2416 return failure();
2417
2418 AffineForOp::ensureTerminator(*body, builder, result.location);
2419
2420 // Parse the optional attribute list.
2421 return parser.parseOptionalAttrDict(result.attributes);
2422}
2423
2424static void printBound(AffineMapAttr boundMap,
2425 Operation::operand_range boundOperands,
2426 const char *prefix, OpAsmPrinter &p) {
2427 AffineMap map = boundMap.getValue();
2428
2429 // Check if this bound should be printed using custom assembly form.
2430 // The decision to restrict printing custom assembly form to trivial cases
2431 // comes from the will to roundtrip MLIR binary -> text -> binary in a
2432 // lossless way.
2433 // Therefore, custom assembly form parsing and printing is only supported for
2434 // zero-operand constant maps and single symbol operand identity maps.
2435 if (map.getNumResults() == 1) {
2436 AffineExpr expr = map.getResult(0);
2437
2438 // Print constant bound.
2439 if (map.getNumDims() == 0 && map.getNumSymbols() == 0) {
2440 if (auto constExpr = dyn_cast<AffineConstantExpr>(expr)) {
2441 p << constExpr.getValue();
2442 return;
2443 }
2444 }
2445
2446 // Print bound that consists of a single SSA symbol if the map is over a
2447 // single symbol.
2448 if (map.getNumDims() == 0 && map.getNumSymbols() == 1) {
2449 if (isa<AffineSymbolExpr>(expr)) {
2450 p.printOperand(*boundOperands.begin());
2451 return;
2452 }
2453 }
2454 } else {
2455 // Map has multiple results. Print 'min' or 'max' prefix.
2456 p << prefix << ' ';
2457 }
2458
2459 // Print the map and its operands.
2460 p << boundMap;
2461 printDimAndSymbolList(boundOperands.begin(), boundOperands.end(),
2462 map.getNumDims(), p);
2463}
2464
2465unsigned AffineForOp::getNumIterOperands() {
2466 AffineMap lbMap = getLowerBoundMapAttr().getValue();
2467 AffineMap ubMap = getUpperBoundMapAttr().getValue();
2468
2469 return getNumOperands() - lbMap.getNumInputs() - ubMap.getNumInputs();
2470}
2471
2472std::optional<MutableArrayRef<OpOperand>>
2473AffineForOp::getYieldedValuesMutable() {
2474 return cast<AffineYieldOp>(getBody()->getTerminator()).getOperandsMutable();
2475}
2476
2477void AffineForOp::print(OpAsmPrinter &p) {
2478 p << ' ';
2479 p.printRegionArgument(getBody()->getArgument(0), /*argAttrs=*/{},
2480 /*omitType=*/true);
2481 p << " = ";
2482 printBound(getLowerBoundMapAttr(), getLowerBoundOperands(), "max", p);
2483 p << " to ";
2484 printBound(getUpperBoundMapAttr(), getUpperBoundOperands(), "min", p);
2485
2486 if (getStepAsInt() != 1)
2487 p << " step " << getStepAsInt();
2488
2489 bool printBlockTerminators = false;
2490 if (getNumIterOperands() > 0) {
2491 p << " iter_args(";
2492 auto regionArgs = getRegionIterArgs();
2493 auto operands = getInits();
2494
2495 llvm::interleaveComma(llvm::zip(regionArgs, operands), p, [&](auto it) {
2496 p << std::get<0>(it) << " = " << std::get<1>(it);
2497 });
2498 p << ") -> (" << getResultTypes() << ")";
2499 printBlockTerminators = true;
2500 }
2501
2502 p << ' ';
2503 p.printRegion(getRegion(), /*printEntryBlockArgs=*/false,
2504 printBlockTerminators);
2505 p.printOptionalAttrDict((*this)->getDiscardableAttrDictionary().getValue());
2506}
2507
2508/// Fold the constant bounds of a loop.
2509static LogicalResult foldLoopBounds(AffineForOp forOp) {
2510 auto foldLowerOrUpperBound = [&forOp](bool lower) {
2511 // Check to see if each of the operands is the result of a constant. If
2512 // so, get the value. If not, ignore it.
2513 SmallVector<Attribute, 8> operandConstants;
2514 auto boundOperands =
2515 lower ? forOp.getLowerBoundOperands() : forOp.getUpperBoundOperands();
2516 for (auto operand : boundOperands) {
2517 Attribute operandCst;
2518 matchPattern(operand, m_Constant(&operandCst));
2519 operandConstants.push_back(operandCst);
2520 }
2521
2522 AffineMap boundMap =
2523 lower ? forOp.getLowerBoundMap() : forOp.getUpperBoundMap();
2524 assert(boundMap.getNumResults() >= 1 &&
2525 "bound maps should have at least one result");
2526 SmallVector<Attribute, 4> foldedResults;
2527 if (failed(boundMap.constantFold(operandConstants, foldedResults)))
2528 return failure();
2529
2530 // Compute the max or min as applicable over the results.
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);
2537 }
2538 lower ? forOp.setConstantLowerBound(maxOrMin.getSExtValue())
2539 : forOp.setConstantUpperBound(maxOrMin.getSExtValue());
2540 return success();
2541 };
2542
2543 // Try to fold the lower bound.
2544 bool folded = false;
2545 if (!forOp.hasConstantLowerBound())
2546 folded |= succeeded(foldLowerOrUpperBound(/*lower=*/true));
2547
2548 // Try to fold the upper bound.
2549 if (!forOp.hasConstantUpperBound())
2550 folded |= succeeded(foldLowerOrUpperBound(/*lower=*/false));
2551 return success(folded);
2552}
2553
2554/// Returns constant trip count in trivial cases.
2555static std::optional<uint64_t> getTrivialConstantTripCount(AffineForOp forOp) {
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;
2562}
2563
2564/// Fold the empty loop.
2566 if (!llvm::hasSingleElement(*forOp.getBody()))
2567 return {};
2568 if (forOp.getNumResults() == 0)
2569 return {};
2570 std::optional<uint64_t> tripCount = getTrivialConstantTripCount(forOp);
2571 if (tripCount == 0) {
2572 // The initial values of the iteration arguments would be the op's
2573 // results.
2574 return forOp.getInits();
2575 }
2576 SmallVector<Value, 4> replacements;
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);
2583 BlockArgument *iterArgIt = llvm::find(iterArgs, val);
2584 // TODO: It should be possible to perform a replacement by computing the
2585 // last value of the IV based on the bounds and the step.
2586 if (val == forOp.getInductionVar())
2587 return {};
2588 if (iterArgIt == iterArgs.end()) {
2589 // `val` is defined outside of the loop.
2590 assert(forOp.isDefinedOutsideOfLoop(val) &&
2591 "must be defined outside of the loop");
2592 hasValDefinedOutsideLoop = true;
2593 replacements.push_back(val);
2594 } else {
2595 unsigned pos = std::distance(iterArgs.begin(), iterArgIt);
2596 if (pos != i)
2597 iterArgsNotInOrder = true;
2598 replacements.push_back(forOp.getInits()[pos]);
2599 }
2600 }
2601 // Bail out when the trip count is unknown and the loop returns any value
2602 // defined outside of the loop or any iterArg out of order.
2603 if (!tripCount.has_value() &&
2604 (hasValDefinedOutsideLoop || iterArgsNotInOrder))
2605 return {};
2606 // Bail out when the loop iterates more than once and it returns any iterArg
2607 // out of order.
2608 if (tripCount.has_value() && tripCount.value() >= 2 && iterArgsNotInOrder)
2609 return {};
2610 return llvm::to_vector_of<OpFoldResult>(replacements);
2611}
2612
2613/// Canonicalize the bounds of the given loop.
2614static LogicalResult canonicalizeLoopBounds(AffineForOp forOp) {
2615 SmallVector<Value, 4> lbOperands(forOp.getLowerBoundOperands());
2616 SmallVector<Value, 4> ubOperands(forOp.getUpperBoundOperands());
2617
2618 auto lbMap = forOp.getLowerBoundMap();
2619 auto ubMap = forOp.getUpperBoundMap();
2620 auto prevLbMap = lbMap;
2621 auto prevUbMap = ubMap;
2622
2623 composeAffineMapAndOperands(&lbMap, &lbOperands);
2624 canonicalizeMapAndOperands(&lbMap, &lbOperands);
2625 simplifyMinOrMaxExprWithOperands(lbMap, lbOperands, /*isMax=*/true);
2626 simplifyMinOrMaxExprWithOperands(ubMap, ubOperands, /*isMax=*/false);
2627 lbMap = removeDuplicateExprs(lbMap);
2628
2629 composeAffineMapAndOperands(&ubMap, &ubOperands);
2630 canonicalizeMapAndOperands(&ubMap, &ubOperands);
2631 ubMap = removeDuplicateExprs(ubMap);
2632
2633 // Any canonicalization change always leads to updated map(s).
2634 if (lbMap == prevLbMap && ubMap == prevUbMap)
2635 return failure();
2636
2637 if (lbMap != prevLbMap)
2638 forOp.setLowerBound(lbOperands, lbMap);
2639 if (ubMap != prevUbMap)
2640 forOp.setUpperBound(ubOperands, ubMap);
2641 return success();
2642}
2643
2644/// Returns true if the affine.for has zero iterations in trivial cases.
2645static bool hasTrivialZeroTripCount(AffineForOp op) {
2646 return getTrivialConstantTripCount(op) == 0;
2647}
2648
2649LogicalResult AffineForOp::fold(FoldAdaptor adaptor,
2651 bool folded = succeeded(foldLoopBounds(*this));
2652 folded |= succeeded(canonicalizeLoopBounds(*this));
2653 if (hasTrivialZeroTripCount(*this) && getNumResults() != 0) {
2654 // The initial values of the loop-carried variables (iter_args) are the
2655 // results of the op. But this must be avoided for an affine.for op that
2656 // does not return any results. Since ops that do not return results cannot
2657 // be folded away, we would enter an infinite loop of folds on the same
2658 // affine.for op.
2659 results.assign(getInits().begin(), getInits().end());
2660 folded = true;
2661 }
2662 SmallVector<OpFoldResult> foldResults = AffineForEmptyLoopFolder(*this);
2663 if (!foldResults.empty()) {
2664 results.assign(foldResults);
2665 folded = true;
2666 }
2667 return success(folded);
2668}
2669
2670OperandRange AffineForOp::getEntrySuccessorOperands(RegionSuccessor successor) {
2671 assert(
2672 (successor.isOperation() || successor.getSuccessor() == &getRegion()) &&
2673 "invalid region point");
2674
2675 // The initial operands map to the loop arguments after the induction
2676 // variable or are forwarded to the results when the trip count is zero.
2677 return getInits();
2678}
2679
2680void AffineForOp::getSuccessorRegions(
2682 assert((point.isParent() ||
2683 point.getTerminatorPredecessorOrNull()->getParentRegion() ==
2684 &getRegion()) &&
2685 "expected loop region");
2686 // The loop may typically branch back to its body or to the parent operation.
2687 // If the predecessor is the parent op and the trip count is known to be at
2688 // least one, branch into the body using the iterator arguments. And in cases
2689 // we know the trip count is zero, it can only branch back to its parent.
2690 std::optional<uint64_t> tripCount = getTrivialConstantTripCount(*this);
2691 if (tripCount.has_value()) {
2692 if (!point.isParent()) {
2693 // From the loop body, if the trip count is one, we can only branch back
2694 // to the parent.
2695 if (tripCount == 1) {
2696 regions.push_back(RegionSuccessor(getOperation()));
2697 return;
2698 }
2699 if (tripCount == 0)
2700 return;
2701 } else {
2702 if (tripCount.value() > 0) {
2703 regions.push_back(RegionSuccessor(&getRegion()));
2704 return;
2705 }
2706 if (tripCount.value() == 0) {
2707 regions.push_back(RegionSuccessor(getOperation()));
2708 return;
2709 }
2710 }
2711 }
2712
2713 // In all other cases, the loop may branch back to itself or the parent
2714 // operation.
2715 regions.push_back(RegionSuccessor(&getRegion()));
2716 regions.push_back(RegionSuccessor(getOperation()));
2717}
2718
2719ValueRange AffineForOp::getSuccessorInputs(RegionSuccessor successor) {
2720 if (successor.isOperation())
2721 return getResults();
2722 return getRegionIterArgs();
2723}
2724
2725AffineBound AffineForOp::getLowerBound() {
2726 return AffineBound(*this, getLowerBoundOperands(), getLowerBoundMap());
2727}
2728
2729AffineBound AffineForOp::getUpperBound() {
2730 return AffineBound(*this, getUpperBoundOperands(), getUpperBoundMap());
2731}
2732
2733void AffineForOp::setLowerBound(ValueRange lbOperands, AffineMap map) {
2734 assert(lbOperands.size() == map.getNumInputs());
2735 assert(map.getNumResults() >= 1 && "bound map has at least one result");
2736 getLowerBoundOperandsMutable().assign(lbOperands);
2737 setLowerBoundMap(map);
2738}
2739
2740void AffineForOp::setUpperBound(ValueRange ubOperands, AffineMap map) {
2741 assert(ubOperands.size() == map.getNumInputs());
2742 assert(map.getNumResults() >= 1 && "bound map has at least one result");
2743 getUpperBoundOperandsMutable().assign(ubOperands);
2744 setUpperBoundMap(map);
2745}
2746
2747bool AffineForOp::hasConstantLowerBound() {
2748 return getLowerBoundMap().isSingleConstant();
2749}
2750
2751bool AffineForOp::hasConstantUpperBound() {
2752 return getUpperBoundMap().isSingleConstant();
2753}
2754
2755int64_t AffineForOp::getConstantLowerBound() {
2756 return getLowerBoundMap().getSingleConstantResult();
2757}
2758
2759int64_t AffineForOp::getConstantUpperBound() {
2760 return getUpperBoundMap().getSingleConstantResult();
2761}
2762
2763void AffineForOp::setConstantLowerBound(int64_t value) {
2764 setLowerBound({}, AffineMap::getConstantMap(value, getContext()));
2765}
2766
2767void AffineForOp::setConstantUpperBound(int64_t value) {
2768 setUpperBound({}, AffineMap::getConstantMap(value, getContext()));
2769}
2770
2771AffineForOp::operand_range AffineForOp::getControlOperands() {
2772 return {operand_begin(), operand_begin() + getLowerBoundOperands().size() +
2773 getUpperBoundOperands().size()};
2774}
2775
2776bool AffineForOp::matchingBoundOperandList() {
2777 auto lbMap = getLowerBoundMap();
2778 auto ubMap = getUpperBoundMap();
2779 if (lbMap.getNumDims() != ubMap.getNumDims() ||
2780 lbMap.getNumSymbols() != ubMap.getNumSymbols())
2781 return false;
2782
2783 unsigned numOperands = lbMap.getNumInputs();
2784 for (unsigned i = 0, e = lbMap.getNumInputs(); i < e; i++) {
2785 // Compare Value 's.
2786 if (getOperand(i) != getOperand(numOperands + i))
2787 return false;
2788 }
2789 return true;
2790}
2791
2792SmallVector<Region *> AffineForOp::getLoopRegions() { return {&getRegion()}; }
2793
2794std::optional<SmallVector<Value>> AffineForOp::getLoopInductionVars() {
2795 return SmallVector<Value>{getInductionVar()};
2796}
2797
2798std::optional<SmallVector<OpFoldResult>> AffineForOp::getLoopLowerBounds() {
2799 if (!hasConstantLowerBound())
2800 return std::nullopt;
2801 OpBuilder b(getContext());
2802 return SmallVector<OpFoldResult>{
2803 OpFoldResult(b.getI64IntegerAttr(getConstantLowerBound()))};
2804}
2805
2806std::optional<SmallVector<OpFoldResult>> AffineForOp::getLoopSteps() {
2807 OpBuilder b(getContext());
2808 return SmallVector<OpFoldResult>{
2809 OpFoldResult(b.getI64IntegerAttr(getStepAsInt()))};
2810}
2811
2812std::optional<SmallVector<OpFoldResult>> AffineForOp::getLoopUpperBounds() {
2813 if (!hasConstantUpperBound())
2814 return {};
2815 OpBuilder b(getContext());
2816 return SmallVector<OpFoldResult>{
2817 OpFoldResult(b.getI64IntegerAttr(getConstantUpperBound()))};
2818}
2819
2820std::optional<APInt> AffineForOp::getStaticTripCount() {
2821 int64_t step = getStepAsInt();
2822 if (step <= 0)
2823 return std::nullopt;
2824
2825 if (hasConstantBounds()) {
2826 int64_t lb = getConstantLowerBound();
2827 int64_t ub = getConstantUpperBound();
2828 int64_t loopSpan = ub - lb;
2829 if (loopSpan < 0)
2830 loopSpan = 0;
2831 return APInt(64, llvm::divideCeilSigned(loopSpan, step));
2832 }
2833
2834 auto lbMap = getLowerBoundMap();
2835 auto ubMap = getUpperBoundMap();
2836 if (lbMap.getNumResults() != 1)
2837 return std::nullopt;
2838
2839 // Difference of each upper bound expression from the single lower bound
2840 // expression (divided by the step) provides the expressions for the trip
2841 // count map.
2842 AffineValueMap ubValueMap(ubMap, getUpperBoundOperands());
2843 AffineValueMap lbValueMap(lbMap, getLowerBoundOperands());
2844
2845 AffineValueMap tripCountValueMap;
2846 AffineValueMap::cartesianProductDifference(ubValueMap, lbValueMap,
2847 &tripCountValueMap);
2848
2849 // Take the min if all trip counts are constant.
2850 std::optional<uint64_t> tripCount;
2851 for (unsigned i = 0, e = tripCountValueMap.getNumResults(); i < e; ++i) {
2852 AffineExpr expr = tripCountValueMap.getResult(i).ceilDiv(step);
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);
2857 else
2858 tripCount = value;
2859 } else {
2860 return std::nullopt;
2861 }
2862 }
2863
2864 if (tripCount.has_value())
2865 return APInt(64, *tripCount);
2866
2867 return std::nullopt;
2868}
2869
2870FailureOr<LoopLikeOpInterface> AffineForOp::replaceWithAdditionalYields(
2871 RewriterBase &rewriter, ValueRange newInitOperands,
2872 bool replaceInitOperandUsesInLoop,
2873 const NewYieldValuesFn &newYieldValuesFn) {
2874 // Create a new loop before the existing one, with the extra operands.
2875 OpBuilder::InsertionGuard g(rewriter);
2876 rewriter.setInsertionPoint(getOperation());
2877 auto inits = llvm::to_vector(getInits());
2878 inits.append(newInitOperands.begin(), newInitOperands.end());
2879 AffineForOp newLoop = AffineForOp::create(
2880 rewriter, getLoc(), getLowerBoundOperands(), getLowerBoundMap(),
2881 getUpperBoundOperands(), getUpperBoundMap(), getStepAsInt(), inits);
2882 // Existing operands, results, and region arguments retain their positions;
2883 // only new loop-carried values are appended.
2884 newLoop->setDiscardableAttrs(getOperation()->getDiscardableAttrDictionary());
2885
2886 // Generate the new yield values and append them to the scf.yield operation.
2887 auto yieldOp = cast<AffineYieldOp>(getBody()->getTerminator());
2888 ArrayRef<BlockArgument> newIterArgs =
2889 newLoop.getBody()->getArguments().take_back(newInitOperands.size());
2890 {
2891 OpBuilder::InsertionGuard g(rewriter);
2892 rewriter.setInsertionPoint(yieldOp);
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");
2897 rewriter.modifyOpInPlace(yieldOp, [&]() {
2898 yieldOp.getOperandsMutable().append(newYieldedValues);
2899 });
2900 }
2901
2902 // Move the loop body to the new op.
2903 rewriter.mergeBlocks(getBody(), newLoop.getBody(),
2904 newLoop.getBody()->getArguments().take_front(
2905 getBody()->getNumArguments()));
2906
2907 if (replaceInitOperandUsesInLoop) {
2908 // Replace all uses of `newInitOperands` with the corresponding basic block
2909 // arguments.
2910 for (auto it : llvm::zip(newInitOperands, newIterArgs)) {
2911 rewriter.replaceUsesWithIf(std::get<0>(it), std::get<1>(it),
2912 [&](OpOperand &use) {
2913 Operation *user = use.getOwner();
2914 return newLoop->isProperAncestor(user);
2915 });
2916 }
2917 }
2918
2919 // Replace the old loop.
2920 rewriter.replaceOp(getOperation(),
2921 newLoop->getResults().take_front(getNumResults()));
2922 return cast<LoopLikeOpInterface>(newLoop.getOperation());
2923}
2924
2925Speculation::Speculatability AffineForOp::getSpeculatability() {
2926 // `affine.for (I = Start; I < End; I += 1)` terminates for all values of
2927 // Start and End.
2928 //
2929 // For Step != 1, the loop may not terminate. We can add more smarts here if
2930 // needed.
2931 return getStepAsInt() == 1 ? Speculation::RecursivelySpeculatable
2933}
2934
2935/// Returns true if the provided value is the induction variable of a
2936/// AffineForOp.
2938 return getForInductionVarOwner(val) != AffineForOp();
2939}
2940
2944
2948
2950 auto ivArg = dyn_cast<BlockArgument>(val);
2951 if (!ivArg || !ivArg.getOwner() || !ivArg.getOwner()->getParent())
2952 return AffineForOp();
2953 if (auto forOp =
2954 ivArg.getOwner()->getParent()->getParentOfType<AffineForOp>())
2955 // Check to make sure `val` is the induction variable, not an iter_arg.
2956 return forOp.getInductionVar() == val ? forOp : AffineForOp();
2957 return AffineForOp();
2958}
2959
2961 auto ivArg = dyn_cast<BlockArgument>(val);
2962 if (!ivArg || !ivArg.getOwner())
2963 return nullptr;
2964 Operation *containingOp = ivArg.getOwner()->getParentOp();
2965 auto parallelOp = dyn_cast_if_present<AffineParallelOp>(containingOp);
2966 if (parallelOp && llvm::is_contained(parallelOp.getIVs(), val))
2967 return parallelOp;
2968 return nullptr;
2969}
2970
2971/// Extracts the induction variables from a list of AffineForOps and returns
2972/// them.
2975 ivs->reserve(forInsts.size());
2976 for (auto forInst : forInsts)
2977 ivs->push_back(forInst.getInductionVar());
2978}
2979
2982 ivs.reserve(affineOps.size());
2983 for (Operation *op : affineOps) {
2984 // Add constraints from forOp's bounds.
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));
2990 }
2991}
2992
2993/// Builds an affine loop nest, using "loopCreatorFn" to create individual loop
2994/// operations.
2995template <typename BoundListTy, typename LoopCreatorTy>
2997 OpBuilder &builder, Location loc, BoundListTy lbs, BoundListTy ubs,
2998 ArrayRef<int64_t> steps,
2999 function_ref<void(OpBuilder &, Location, ValueRange)> bodyBuilderFn,
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");
3003
3004 // If there are no loops to be constructed, construct the body anyway.
3005 OpBuilder::InsertionGuard guard(builder);
3006 if (lbs.empty()) {
3007 if (bodyBuilderFn)
3008 bodyBuilderFn(builder, loc, ValueRange());
3009 return;
3010 }
3011
3012 // Create the loops iteratively and store the induction variables.
3014 ivs.reserve(lbs.size());
3015 for (unsigned i = 0, e = lbs.size(); i < e; ++i) {
3016 // Callback for creating the loop body, always creates the terminator.
3017 auto loopBody = [&](OpBuilder &nestedBuilder, Location nestedLoc, Value iv,
3018 ValueRange iterArgs) {
3019 ivs.push_back(iv);
3020 // In the innermost loop, call the body builder.
3021 if (i == e - 1 && bodyBuilderFn) {
3022 OpBuilder::InsertionGuard nestedGuard(nestedBuilder);
3023 bodyBuilderFn(nestedBuilder, nestedLoc, ivs);
3024 }
3025 AffineYieldOp::create(nestedBuilder, nestedLoc);
3026 };
3027
3028 // Delegate actual loop creation to the callback in order to dispatch
3029 // between constant- and variable-bound loops.
3030 auto loop = loopCreatorFn(builder, loc, lbs[i], ubs[i], steps[i], loopBody);
3031 builder.setInsertionPointToStart(loop.getBody());
3032 }
3033}
3034
3035/// Creates an affine loop from the bounds known to be constants.
3036static AffineForOp
3038 int64_t ub, int64_t step,
3039 AffineForOp::BodyBuilderFn bodyBuilderFn) {
3040 return AffineForOp::create(builder, loc, lb, ub, step,
3041 /*iterArgs=*/ValueRange(), bodyBuilderFn);
3042}
3043
3044/// Creates an affine loop from the bounds that may or may not be constants.
3045static AffineForOp
3047 int64_t step,
3048 AffineForOp::BodyBuilderFn bodyBuilderFn) {
3049 std::optional<int64_t> lbConst = getConstantIntValue(lb);
3050 std::optional<int64_t> ubConst = getConstantIntValue(ub);
3051 if (lbConst && ubConst)
3052 return buildAffineLoopFromConstants(builder, loc, lbConst.value(),
3053 ubConst.value(), step, bodyBuilderFn);
3054 return AffineForOp::create(builder, loc, lb, builder.getDimIdentityMap(), ub,
3055 builder.getDimIdentityMap(), step,
3056 /*iterArgs=*/ValueRange(), bodyBuilderFn);
3057}
3058
3060 OpBuilder &builder, Location loc, ArrayRef<int64_t> lbs,
3062 function_ref<void(OpBuilder &, Location, ValueRange)> bodyBuilderFn) {
3063 buildAffineLoopNestImpl(builder, loc, lbs, ubs, steps, bodyBuilderFn,
3065}
3066
3068 OpBuilder &builder, Location loc, ValueRange lbs, ValueRange ubs,
3069 ArrayRef<int64_t> steps,
3070 function_ref<void(OpBuilder &, Location, ValueRange)> bodyBuilderFn) {
3071 buildAffineLoopNestImpl(builder, loc, lbs, ubs, steps, bodyBuilderFn,
3073}
3074
3075//===----------------------------------------------------------------------===//
3076// AffineIfOp
3077//===----------------------------------------------------------------------===//
3078
3079namespace {
3080/// Remove else blocks that have nothing other than a zero value yield.
3081struct SimplifyDeadElse : public OpRewritePattern<AffineIfOp> {
3082 using OpRewritePattern<AffineIfOp>::OpRewritePattern;
3083
3084 LogicalResult matchAndRewrite(AffineIfOp ifOp,
3085 PatternRewriter &rewriter) const override {
3086 if (ifOp.getElseRegion().empty() ||
3087 !llvm::hasSingleElement(*ifOp.getElseBlock()) || ifOp.getNumResults())
3088 return failure();
3089
3090 rewriter.startOpModification(ifOp);
3091 rewriter.eraseBlock(ifOp.getElseBlock());
3092 rewriter.finalizeOpModification(ifOp);
3093 return success();
3094 }
3095};
3096
3097/// Removes affine.if cond if the condition is always true or false in certain
3098/// trivial cases. Promotes the then/else block in the parent operation block.
3099struct AlwaysTrueOrFalseIf : public OpRewritePattern<AffineIfOp> {
3100 using OpRewritePattern<AffineIfOp>::OpRewritePattern;
3101
3102 LogicalResult matchAndRewrite(AffineIfOp op,
3103 PatternRewriter &rewriter) const override {
3104
3105 auto isTriviallyFalse = [](IntegerSet iSet) {
3106 return iSet.isEmptyIntegerSet();
3107 };
3108
3109 auto isTriviallyTrue = [](IntegerSet iSet) {
3110 return (iSet.getNumEqualities() == 1 && iSet.getNumInequalities() == 0 &&
3111 iSet.getConstraint(0) == 0);
3112 };
3113
3114 IntegerSet affineIfConditions = op.getIntegerSet();
3115 Block *blockToMove;
3116 if (isTriviallyFalse(affineIfConditions)) {
3117 // The absence, or equivalently, the emptiness of the else region need not
3118 // be checked when affine.if is returning results because if an affine.if
3119 // operation is returning results, it always has a non-empty else region.
3120 if (op.getNumResults() == 0 && !op.hasElse()) {
3121 // If the else region is absent, or equivalently, empty, remove the
3122 // affine.if operation (which is not returning any results).
3123 rewriter.eraseOp(op);
3124 return success();
3125 }
3126 blockToMove = op.getElseBlock();
3127 } else if (isTriviallyTrue(affineIfConditions)) {
3128 blockToMove = op.getThenBlock();
3129 } else {
3130 return failure();
3131 }
3132 Operation *blockToMoveTerminator = blockToMove->getTerminator();
3133 // Promote the "blockToMove" block to the parent operation block between the
3134 // prologue and epilogue of "op".
3135 rewriter.inlineBlockBefore(blockToMove, op);
3136 // Replace the "op" operation with the operands of the
3137 // "blockToMoveTerminator" operation. Note that "blockToMoveTerminator" is
3138 // the affine.yield operation present in the "blockToMove" block. It has no
3139 // operands when affine.if is not returning results and therefore, in that
3140 // case, replaceOp just erases "op". When affine.if is not returning
3141 // results, the affine.yield operation can be omitted. It gets inserted
3142 // implicitly.
3143 rewriter.replaceOp(op, blockToMoveTerminator->getOperands());
3144 // Erase the "blockToMoveTerminator" operation since it is now in the parent
3145 // operation block, which already has its own terminator.
3146 rewriter.eraseOp(blockToMoveTerminator);
3147 return success();
3148 }
3149};
3150} // namespace
3151
3152/// AffineIfOp has two regions -- `then` and `else`. The flow of data should be
3153/// as follows: AffineIfOp -> `then`/`else` -> AffineIfOp
3154void AffineIfOp::getSuccessorRegions(
3156 // If the predecessor is an AffineIfOp, then branching into both `then` and
3157 // `else` region is valid.
3158 if (point.isParent()) {
3159 regions.reserve(2);
3160 regions.push_back(RegionSuccessor(&getThenRegion()));
3161 // If the "else" region is empty, branch bach into parent.
3162 if (getElseRegion().empty()) {
3163 regions.push_back(RegionSuccessor(getOperation()));
3164 } else {
3165 regions.push_back(RegionSuccessor(&getElseRegion()));
3166 }
3167 return;
3168 }
3169
3170 // If the predecessor is the `else`/`then` region, then branching into parent
3171 // op is valid.
3172 regions.push_back(RegionSuccessor(getOperation()));
3173}
3174
3175ValueRange AffineIfOp::getSuccessorInputs(RegionSuccessor successor) {
3176 if (successor.isOperation())
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");
3183}
3184
3185LogicalResult AffineIfOp::verify() {
3186 // Verify that we have a condition attribute.
3187 // FIXME: This should be specified in the arguments list in ODS.
3188 auto conditionAttr = getConditionAttr();
3189 if (!conditionAttr)
3190 return emitOpError("requires an integer set attribute named 'condition'");
3191
3192 // Verify that there are enough operands for the condition.
3193 IntegerSet condition = conditionAttr.getValue();
3194 if (getNumOperands() != condition.getNumInputs())
3195 return emitOpError("operand count and condition integer set dimension and "
3196 "symbol count must match");
3197
3198 // Verify that the operands are valid dimension/symbols.
3199 if (failed(verifyDimAndSymbolIdentifiers(*this, getOperands(),
3200 condition.getNumDims())))
3201 return failure();
3202
3203 return success();
3204}
3205
3206ParseResult AffineIfOp::parse(OpAsmParser &parser, OperationState &result) {
3207 // Parse the condition attribute set.
3208 IntegerSetAttr conditionAttr;
3209 unsigned numDims;
3210 if (parser.parseAttribute(conditionAttr,
3211 AffineIfOp::getConditionAttrStrName(),
3212 result.attributes) ||
3213 parseDimAndSymbolList(parser, result.operands, numDims))
3214 return failure();
3215
3216 // Verify the condition operands.
3217 auto set = conditionAttr.getValue();
3218 if (set.getNumDims() != numDims)
3219 return parser.emitError(
3220 parser.getNameLoc(),
3221 "dim operand count and integer set dim count must match");
3222 if (numDims + set.getNumSymbols() != result.operands.size())
3223 return parser.emitError(
3224 parser.getNameLoc(),
3225 "symbol operand count and integer set symbol count must match");
3226
3227 if (parser.parseOptionalArrowTypeList(result.types))
3228 return failure();
3229
3230 // Create the regions for 'then' and 'else'. The latter must be created even
3231 // if it remains empty for the validity of the operation.
3232 result.regions.reserve(2);
3233 Region *thenRegion = result.addRegion();
3234 Region *elseRegion = result.addRegion();
3235
3236 // Parse the 'then' region.
3237 if (parser.parseRegion(*thenRegion, {}, {}))
3238 return failure();
3239 AffineIfOp::ensureTerminator(*thenRegion, parser.getBuilder(),
3240 result.location);
3241
3242 // If we find an 'else' keyword then parse the 'else' region.
3243 if (!parser.parseOptionalKeyword("else")) {
3244 if (parser.parseRegion(*elseRegion, {}, {}))
3245 return failure();
3246 AffineIfOp::ensureTerminator(*elseRegion, parser.getBuilder(),
3247 result.location);
3248 }
3249
3250 // Parse the optional attribute list.
3251 if (parser.parseOptionalAttrDict(result.attributes))
3252 return failure();
3253
3254 return success();
3255}
3256
3257void AffineIfOp::print(OpAsmPrinter &p) {
3258 auto conditionAttr = getConditionAttr();
3259 p << " " << conditionAttr;
3260 printDimAndSymbolList(operand_begin(), operand_end(),
3261 conditionAttr.getValue().getNumDims(), p);
3262 p.printOptionalArrowTypeList(getResultTypes());
3263 p << ' ';
3264 p.printRegion(getThenRegion(), /*printEntryBlockArgs=*/false,
3265 /*printBlockTerminators=*/getNumResults());
3266
3267 // Print the 'else' regions if it has any blocks.
3268 auto &elseRegion = this->getElseRegion();
3269 if (!elseRegion.empty()) {
3270 p << " else ";
3271 p.printRegion(elseRegion,
3272 /*printEntryBlockArgs=*/false,
3273 /*printBlockTerminators=*/getNumResults());
3274 }
3275
3276 // Print the attribute list.
3277 p.printOptionalAttrDict((*this)->getDiscardableAttrDictionary().getValue());
3278}
3279
3280IntegerSet AffineIfOp::getIntegerSet() { return getConditionAttr().getValue(); }
3281
3282void AffineIfOp::setIntegerSet(IntegerSet newSet) {
3283 setConditionAttr(IntegerSetAttr::get(newSet));
3284}
3285
3286void AffineIfOp::setConditional(IntegerSet set, ValueRange operands) {
3287 setIntegerSet(set);
3288 (*this)->setOperands(operands);
3289}
3290
3291void AffineIfOp::build(OpBuilder &builder, OperationState &result,
3292 TypeRange resultTypes, IntegerSet set, ValueRange args,
3293 bool withElseRegion) {
3294 assert(resultTypes.empty() || withElseRegion);
3295 OpBuilder::InsertionGuard guard(builder);
3296
3297 result.addTypes(resultTypes);
3298 result.addOperands(args);
3299 result.addAttribute(getConditionAttrStrName(), IntegerSetAttr::get(set));
3300
3301 Region *thenRegion = result.addRegion();
3302 builder.createBlock(thenRegion);
3303 if (resultTypes.empty())
3304 AffineIfOp::ensureTerminator(*thenRegion, builder, result.location);
3305
3306 Region *elseRegion = result.addRegion();
3307 if (withElseRegion) {
3308 builder.createBlock(elseRegion);
3309 if (resultTypes.empty())
3310 AffineIfOp::ensureTerminator(*elseRegion, builder, result.location);
3311 }
3312}
3313
3314void AffineIfOp::build(OpBuilder &builder, OperationState &result,
3315 IntegerSet set, ValueRange args, bool withElseRegion) {
3316 AffineIfOp::build(builder, result, /*resultTypes=*/{}, set, args,
3317 withElseRegion);
3318}
3319
3320/// Compose any affine.apply ops feeding into `operands` of the integer set
3321/// `set` by composing the maps of such affine.apply ops with the integer
3322/// set constraints.
3324 SmallVectorImpl<Value> &operands,
3325 bool composeAffineMin = false) {
3326 // We will simply reuse the API of the map composition by viewing the LHSs of
3327 // the equalities and inequalities of `set` as the affine exprs of an affine
3328 // map. Convert to equivalent map, compose, and convert back to set.
3329 auto map = AffineMap::get(set.getNumDims(), set.getNumSymbols(),
3330 set.getConstraints(), set.getContext());
3331 // Check if any composition is possible.
3332 if (llvm::none_of(operands,
3333 [](Value v) { return v.getDefiningOp<AffineApplyOp>(); }))
3334 return;
3335
3336 composeAffineMapAndOperands(&map, &operands, composeAffineMin);
3337 set = IntegerSet::get(map.getNumDims(), map.getNumSymbols(), map.getResults(),
3338 set.getEqFlags());
3339}
3340
3341/// Canonicalize an affine if op's conditional (integer set + operands).
3342LogicalResult AffineIfOp::fold(FoldAdaptor, SmallVectorImpl<OpFoldResult> &) {
3343 auto set = getIntegerSet();
3344 SmallVector<Value, 4> operands(getOperands());
3345 composeSetAndOperands(set, operands);
3346 canonicalizeSetAndOperands(&set, &operands);
3347
3348 // Check if the canonicalization or composition led to any change.
3349 if (getIntegerSet() == set && llvm::equal(operands, getOperands()))
3350 return failure();
3351
3352 setConditional(set, operands);
3353 return success();
3354}
3355
3356void AffineIfOp::getCanonicalizationPatterns(RewritePatternSet &results,
3357 MLIRContext *context) {
3358 results.add<SimplifyDeadElse, AlwaysTrueOrFalseIf>(context);
3359}
3360
3361/// Adds the optional `alignment` attribute to `result`, if one is given.
3363 StringAttr attrName, llvm::MaybeAlign alignment) {
3364 if (alignment)
3365 result.addAttribute(attrName,
3366 builder.getI64IntegerAttr(alignment->value()));
3367}
3368
3369//===----------------------------------------------------------------------===//
3370// AffineLoadOp
3371//===----------------------------------------------------------------------===//
3372
3373void AffineLoadOp::build(OpBuilder &builder, OperationState &result,
3374 AffineMap map, ValueRange operands,
3375 llvm::MaybeAlign alignment) {
3376 assert(operands.size() == 1 + map.getNumInputs() && "inconsistent operands");
3377 result.addOperands(operands);
3378 if (map)
3379 result.addAttribute(getMapAttrStrName(), AffineMapAttr::get(map));
3380 addAlignmentAttr(builder, result, getAlignmentAttrName(result.name),
3381 alignment);
3382 auto memrefType = llvm::cast<MemRefType>(operands[0].getType());
3383 result.types.push_back(memrefType.getElementType());
3384}
3385
3386void AffineLoadOp::build(OpBuilder &builder, OperationState &result,
3387 Value memref, AffineMap map, ValueRange mapOperands,
3388 llvm::MaybeAlign alignment) {
3389 assert(map.getNumInputs() == mapOperands.size() && "inconsistent index info");
3390 result.addOperands(memref);
3391 result.addOperands(mapOperands);
3392 auto memrefType = llvm::cast<MemRefType>(memref.getType());
3393 result.addAttribute(getMapAttrStrName(), AffineMapAttr::get(map));
3394 addAlignmentAttr(builder, result, getAlignmentAttrName(result.name),
3395 alignment);
3396 result.types.push_back(memrefType.getElementType());
3397}
3398
3399void AffineLoadOp::build(OpBuilder &builder, OperationState &result,
3401 llvm::MaybeAlign alignment) {
3402 auto memrefType = llvm::cast<MemRefType>(memref.getType());
3403 int64_t rank = memrefType.getRank();
3404 // Create identity map for memrefs with at least one dimension or () -> ()
3405 // for zero-dimensional memrefs.
3406 auto map =
3407 rank ? builder.getMultiDimIdentityMap(rank) : builder.getEmptyAffineMap();
3408 build(builder, result, memref, map, indices, alignment);
3409}
3410
3411ParseResult AffineLoadOp::parse(OpAsmParser &parser, OperationState &result) {
3412 auto &builder = parser.getBuilder();
3413 auto indexTy = builder.getIndexType();
3414
3415 MemRefType type;
3417 AffineMapAttr mapAttr;
3419 return failure(
3420 parser.parseOperand(memrefInfo) ||
3421 parser.parseAffineMapOfSSAIds(mapOperands, mapAttr,
3422 AffineLoadOp::getMapAttrStrName(),
3423 result.attributes) ||
3424 parser.parseOptionalAttrDict(result.attributes) ||
3425 parser.parseColonType(type) ||
3426 parser.resolveOperand(memrefInfo, type, result.operands) ||
3427 parser.resolveOperands(mapOperands, indexTy, result.operands) ||
3428 parser.addTypeToList(type.getElementType(), result.types));
3429}
3430
3431void AffineLoadOp::print(OpAsmPrinter &p) {
3432 p << " " << getMemRef() << '[';
3433 if (AffineMapAttr mapAttr = getMapAttr())
3434 p.printAffineMapOfSSAIds(mapAttr, getMapOperands());
3435 p << ']';
3436 SmallVector<NamedAttribute> attrs((*this)->getDiscardableAttrs());
3437 if (IntegerAttr alignment = getAlignmentAttr())
3438 attrs.emplace_back(getAlignmentAttrName(), alignment);
3439 llvm::sort(attrs);
3440 p.printOptionalAttrDict(attrs);
3441 p << " : " << getMemRefType();
3442}
3443
3444/// Verify common indexing invariants of affine.load, affine.store,
3445/// affine.vector_load and affine.vector_store.
3446template <typename AffineMemOpTy>
3447static LogicalResult
3448verifyMemoryOpIndexing(AffineMemOpTy op, AffineMapAttr mapAttr,
3449 Operation::operand_range mapOperands,
3450 MemRefType memrefType, unsigned numIndexOperands) {
3451 AffineMap map = mapAttr.getValue();
3452 if (map.getNumResults() != memrefType.getRank())
3453 return op->emitOpError("affine map num results must equal memref rank");
3454 if (map.getNumInputs() != numIndexOperands)
3455 return op->emitOpError("expects as many subscripts as affine map inputs");
3456
3457 for (auto idx : mapOperands) {
3458 if (!idx.getType().isIndex())
3459 return op->emitOpError("index to load must have 'index' type");
3460 }
3461 if (failed(verifyDimAndSymbolIdentifiers(op, mapOperands, map.getNumDims())))
3462 return failure();
3463
3464 return success();
3465}
3466
3467LogicalResult AffineLoadOp::verify() {
3468 auto memrefType = getMemRefType();
3469 if (getType() != memrefType.getElementType())
3470 return emitOpError("result type must match element type of memref");
3471
3472 if (failed(verifyMemoryOpIndexing(*this, getMapAttr(), getMapOperands(),
3473 memrefType,
3474 /*numIndexOperands=*/getNumOperands() - 1)))
3475 return failure();
3476
3477 return success();
3478}
3479
3480void AffineLoadOp::getCanonicalizationPatterns(RewritePatternSet &results,
3481 MLIRContext *context) {
3482 results.add<SimplifyAffineOp<AffineLoadOp>>(context);
3483}
3484
3485OpFoldResult AffineLoadOp::fold(FoldAdaptor adaptor) {
3486 /// load(memrefcast) -> load
3487 if (succeeded(memref::foldMemRefCast(*this)))
3488 return getResult();
3489
3490 // Fold load from a global constant memref.
3491 auto getGlobalOp = getMemref().getDefiningOp<memref::GetGlobalOp>();
3492 if (!getGlobalOp)
3493 return {};
3494 // Get to the memref.global defining the symbol.
3496 getGlobalOp, getGlobalOp.getNameAttr());
3497 if (!global)
3498 return {};
3499
3500 // Check if the global memref is a constant.
3501 auto cstAttr =
3502 dyn_cast_or_null<DenseElementsAttr>(global.getConstantInitValue());
3503 if (!cstAttr)
3504 return {};
3505 // If it's a splat constant, we can fold irrespective of indices.
3506 if (auto splatAttr = dyn_cast<SplatElementsAttr>(cstAttr))
3507 return splatAttr.getSplatValue<Attribute>();
3508 // Otherwise, we can fold only if we know the indices.
3509 if (!getAffineMap().isConstant())
3510 return {};
3511 auto indices =
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))
3516 return {};
3517 return elementsAttr.getValues<Attribute>()[indices];
3518}
3519
3520//===----------------------------------------------------------------------===//
3521// AffineStoreOp
3522//===----------------------------------------------------------------------===//
3523
3524void AffineStoreOp::build(OpBuilder &builder, OperationState &result,
3525 Value valueToStore, Value memref, AffineMap map,
3526 ValueRange mapOperands, llvm::MaybeAlign alignment) {
3527 assert(map.getNumInputs() == mapOperands.size() && "inconsistent index info");
3528 result.addOperands(valueToStore);
3529 result.addOperands(memref);
3530 result.addOperands(mapOperands);
3531 result.getOrAddProperties<Properties>().map = AffineMapAttr::get(map);
3532 addAlignmentAttr(builder, result, getAlignmentAttrName(result.name),
3533 alignment);
3534}
3535
3536// Use identity map.
3537void AffineStoreOp::build(OpBuilder &builder, OperationState &result,
3538 Value valueToStore, Value memref, ValueRange indices,
3539 llvm::MaybeAlign alignment) {
3540 auto memrefType = llvm::cast<MemRefType>(memref.getType());
3541 int64_t rank = memrefType.getRank();
3542 // Create identity map for memrefs with at least one dimension or () -> ()
3543 // for zero-dimensional memrefs.
3544 auto map =
3545 rank ? builder.getMultiDimIdentityMap(rank) : builder.getEmptyAffineMap();
3546 build(builder, result, valueToStore, memref, map, indices, alignment);
3547}
3548
3549ParseResult AffineStoreOp::parse(OpAsmParser &parser, OperationState &result) {
3550 auto indexTy = parser.getBuilder().getIndexType();
3551
3552 MemRefType type;
3553 OpAsmParser::UnresolvedOperand storeValueInfo;
3555 AffineMapAttr mapAttr;
3557 return failure(parser.parseOperand(storeValueInfo) || parser.parseComma() ||
3558 parser.parseOperand(memrefInfo) ||
3560 mapOperands, mapAttr, AffineStoreOp::getMapAttrStrName(),
3561 result.attributes) ||
3562 parser.parseOptionalAttrDict(result.attributes) ||
3563 parser.parseColonType(type) ||
3564 parser.resolveOperand(storeValueInfo, type.getElementType(),
3565 result.operands) ||
3566 parser.resolveOperand(memrefInfo, type, result.operands) ||
3567 parser.resolveOperands(mapOperands, indexTy, result.operands));
3568}
3569
3570void AffineStoreOp::print(OpAsmPrinter &p) {
3571 p << " " << getValueToStore();
3572 p << ", " << getMemRef() << '[';
3573 if (AffineMapAttr mapAttr = getMapAttr())
3574 p.printAffineMapOfSSAIds(mapAttr, getMapOperands());
3575 p << ']';
3576 SmallVector<NamedAttribute> attrs((*this)->getDiscardableAttrs());
3577 if (IntegerAttr alignment = getAlignmentAttr())
3578 attrs.emplace_back(getAlignmentAttrName(), alignment);
3579 llvm::sort(attrs);
3580 p.printOptionalAttrDict(attrs);
3581 p << " : " << getMemRefType();
3582}
3583
3584LogicalResult AffineStoreOp::verify() {
3585 // The value to store must have the same type as memref element type.
3586 auto memrefType = getMemRefType();
3587 if (getValueToStore().getType() != memrefType.getElementType())
3588 return emitOpError(
3589 "value to store must have the same type as memref element type");
3590
3591 if (failed(verifyMemoryOpIndexing(*this, getMapAttr(), getMapOperands(),
3592 memrefType,
3593 /*numIndexOperands=*/getNumOperands() - 2)))
3594 return failure();
3595
3596 return success();
3597}
3598
3599void AffineStoreOp::getCanonicalizationPatterns(RewritePatternSet &results,
3600 MLIRContext *context) {
3601 results.add<SimplifyAffineOp<AffineStoreOp>>(context);
3602}
3603
3604LogicalResult AffineStoreOp::fold(FoldAdaptor adaptor,
3606 /// store(memrefcast) -> store
3607 return memref::foldMemRefCast(*this, getValueToStore());
3608}
3609
3610//===----------------------------------------------------------------------===//
3611// AffineMinMaxOpBase
3612//===----------------------------------------------------------------------===//
3613
3614template <typename T>
3615static LogicalResult verifyAffineMinMaxOp(T op) {
3616 // Verify that operand count matches affine map dimension and symbol count.
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");
3621
3622 if (op.getMap().getNumResults() == 0)
3623 return op.emitOpError("affine map expect at least one result");
3624 return success();
3625}
3626
3627template <typename T>
3628static void printAffineMinMaxOp(OpAsmPrinter &p, T op) {
3629 p << ' ' << op.getMapAttr();
3630 auto operands = op.getOperands();
3631 unsigned numDims = op.getMap().getNumDims();
3632 p << '(' << operands.take_front(numDims) << ')';
3633
3634 if (operands.size() != numDims)
3635 p << '[' << operands.drop_front(numDims) << ']';
3636 p.printOptionalAttrDict(op->getDiscardableAttrDictionary().getValue());
3637}
3638
3639template <typename T>
3640static ParseResult parseAffineMinMaxOp(OpAsmParser &parser,
3642 auto &builder = parser.getBuilder();
3643 auto indexType = builder.getIndexType();
3646 AffineMapAttr mapAttr;
3647 return failure(
3648 parser.parseAttribute(mapAttr, T::getMapAttrStrName(),
3649 result.attributes) ||
3651 parser.parseOperandList(symInfos,
3653 parser.parseOptionalAttrDict(result.attributes) ||
3654 parser.resolveOperands(dimInfos, indexType, result.operands) ||
3655 parser.resolveOperands(symInfos, indexType, result.operands) ||
3656 parser.addTypeToList(indexType, result.types));
3657}
3658
3659/// Fold an affine min or max operation with the given operands. The operand
3660/// list may contain nulls, which are interpreted as the operand not being a
3661/// constant.
3662template <typename T>
3664 static_assert(llvm::is_one_of<T, AffineMinOp, AffineMaxOp>::value,
3665 "expected affine min or max op");
3666
3667 // Fold the affine map.
3668 // TODO: Fold more cases:
3669 // min(some_affine, some_affine + constant, ...), etc.
3671 auto foldedMap = op.getMap().partialConstantFold(operands, &results);
3672
3673 if (foldedMap.getNumSymbols() == 1 && foldedMap.isSymbolIdentity())
3674 return op.getOperand(0);
3675
3676 // If some of the map results are not constant, try changing the map in-place.
3677 if (results.empty()) {
3678 // If the map is the same, report that folding did not happen.
3679 if (foldedMap == op.getMap())
3680 return {};
3681 op.setMapAttr(AffineMapAttr::get(foldedMap));
3682 return op.getResult();
3683 }
3684
3685 // Otherwise, completely fold the op into a constant.
3686 auto resultIt = std::is_same<T, AffineMinOp>::value
3687 ? llvm::min_element(results)
3688 : llvm::max_element(results);
3689 if (resultIt == results.end())
3690 return {};
3691 return IntegerAttr::get(IndexType::get(op.getContext()), *resultIt);
3692}
3693
3694/// Remove duplicated expressions in affine min/max ops.
3695template <typename T>
3698
3699 LogicalResult matchAndRewrite(T affineOp,
3700 PatternRewriter &rewriter) const override {
3701 AffineMap oldMap = affineOp.getAffineMap();
3702
3704 for (AffineExpr expr : oldMap.getResults()) {
3705 // This is a linear scan over newExprs, but it should be fine given that
3706 // we typically just have a few expressions per op.
3707 if (!llvm::is_contained(newExprs, expr))
3708 newExprs.push_back(expr);
3709 }
3710
3711 if (newExprs.size() == oldMap.getNumResults())
3712 return failure();
3713
3714 auto newMap = AffineMap::get(oldMap.getNumDims(), oldMap.getNumSymbols(),
3715 newExprs, rewriter.getContext());
3716 rewriter.replaceOpWithNewOp<T>(affineOp, newMap, affineOp.getMapOperands());
3717
3718 return success();
3719 }
3720};
3721
3722/// Merge an affine min/max op to its consumers if its consumer is also an
3723/// affine min/max op.
3724///
3725/// This pattern requires the producer affine min/max op is bound to a
3726/// dimension/symbol that is used as a standalone expression in the consumer
3727/// affine op's map.
3728///
3729/// For example, a pattern like the following:
3730///
3731/// %0 = affine.min affine_map<()[s0] -> (s0 + 16, s0 * 8)> ()[%sym1]
3732/// %1 = affine.min affine_map<(d0)[s0] -> (s0 + 4, d0)> (%0)[%sym2]
3733///
3734/// Can be turned into:
3735///
3736/// %1 = affine.min affine_map<
3737/// ()[s0, s1] -> (s0 + 4, s1 + 16, s1 * 8)> ()[%sym2, %sym1]
3738template <typename T>
3741
3742 LogicalResult matchAndRewrite(T affineOp,
3743 PatternRewriter &rewriter) const override {
3744 AffineMap oldMap = affineOp.getAffineMap();
3745 ValueRange dimOperands =
3746 affineOp.getMapOperands().take_front(oldMap.getNumDims());
3747 ValueRange symOperands =
3748 affineOp.getMapOperands().take_back(oldMap.getNumSymbols());
3749
3750 auto newDimOperands = llvm::to_vector<8>(dimOperands);
3751 auto newSymOperands = llvm::to_vector<8>(symOperands);
3753 SmallVector<T, 4> producerOps;
3754
3755 // Go over each expression to see whether it's a single dimension/symbol
3756 // with the corresponding operand which is the result of another affine
3757 // min/max op. If So it can be merged into this affine op.
3758 for (AffineExpr expr : oldMap.getResults()) {
3759 if (auto symExpr = dyn_cast<AffineSymbolExpr>(expr)) {
3760 Value symValue = symOperands[symExpr.getPosition()];
3761 if (auto producerOp = symValue.getDefiningOp<T>()) {
3762 producerOps.push_back(producerOp);
3763 continue;
3764 }
3765 } else if (auto dimExpr = dyn_cast<AffineDimExpr>(expr)) {
3766 Value dimValue = dimOperands[dimExpr.getPosition()];
3767 if (auto producerOp = dimValue.getDefiningOp<T>()) {
3768 producerOps.push_back(producerOp);
3769 continue;
3770 }
3771 }
3772 // For the above cases we will remove the expression by merging the
3773 // producer affine min/max's affine expressions. Otherwise we need to
3774 // keep the existing expression.
3775 newExprs.push_back(expr);
3776 }
3777
3778 if (producerOps.empty())
3779 return failure();
3780
3781 unsigned numUsedDims = oldMap.getNumDims();
3782 unsigned numUsedSyms = oldMap.getNumSymbols();
3783
3784 // Now go over all producer affine ops and merge their expressions.
3785 for (T producerOp : producerOps) {
3786 AffineMap producerMap = producerOp.getAffineMap();
3787 unsigned numProducerDims = producerMap.getNumDims();
3788 unsigned numProducerSyms = producerMap.getNumSymbols();
3789
3790 // Collect all dimension/symbol values.
3791 ValueRange dimValues =
3792 producerOp.getMapOperands().take_front(numProducerDims);
3793 ValueRange symValues =
3794 producerOp.getMapOperands().take_back(numProducerSyms);
3795 newDimOperands.append(dimValues.begin(), dimValues.end());
3796 newSymOperands.append(symValues.begin(), symValues.end());
3797
3798 // For expressions we need to shift to avoid overlap.
3799 for (AffineExpr expr : producerMap.getResults()) {
3800 newExprs.push_back(expr.shiftDims(numProducerDims, numUsedDims)
3801 .shiftSymbols(numProducerSyms, numUsedSyms));
3802 }
3803
3804 numUsedDims += numProducerDims;
3805 numUsedSyms += numProducerSyms;
3806 }
3807
3808 auto newMap = AffineMap::get(numUsedDims, numUsedSyms, newExprs,
3809 rewriter.getContext());
3810 auto newOperands =
3811 llvm::to_vector<8>(llvm::concat<Value>(newDimOperands, newSymOperands));
3812 rewriter.replaceOpWithNewOp<T>(affineOp, newMap, newOperands);
3813
3814 return success();
3815 }
3816};
3817
3818/// Canonicalize the result expression order of an affine map and return success
3819/// if the order changed.
3820///
3821/// The function flattens the map's affine expressions to coefficient arrays and
3822/// sorts them in lexicographic order. A coefficient array contains a multiplier
3823/// for every dimension/symbol and a constant term. The canonicalization fails
3824/// if a result expression is not pure or if the flattening requires local
3825/// variables that, unlike dimensions and symbols, have no global order.
3826static LogicalResult canonicalizeMapExprAndTermOrder(AffineMap &map) {
3827 SmallVector<SmallVector<int64_t>> flattenedExprs;
3828 for (const AffineExpr &resultExpr : map.getResults()) {
3829 // Fail if the expression is not pure.
3830 if (!resultExpr.isPureAffine())
3831 return failure();
3832
3833 SimpleAffineExprFlattener flattener(map.getNumDims(), map.getNumSymbols());
3834 auto flattenResult = flattener.walkPostOrder(resultExpr);
3835 if (failed(flattenResult))
3836 return failure();
3837
3838 // Fail if the flattened expression has local variables.
3839 if (flattener.operandExprStack.back().size() !=
3840 map.getNumDims() + map.getNumSymbols() + 1)
3841 return failure();
3842
3843 flattenedExprs.emplace_back(flattener.operandExprStack.back().begin(),
3844 flattener.operandExprStack.back().end());
3845 }
3846
3847 // Fail if sorting is not necessary.
3848 if (llvm::is_sorted(flattenedExprs))
3849 return failure();
3850
3851 // Reorder the result expressions according to their flattened form.
3852 SmallVector<unsigned> resultPermutation =
3853 llvm::to_vector(llvm::seq<unsigned>(0, map.getNumResults()));
3854 llvm::sort(resultPermutation, [&](unsigned lhs, unsigned rhs) {
3855 return flattenedExprs[lhs] < flattenedExprs[rhs];
3856 });
3857 SmallVector<AffineExpr> newExprs;
3858 for (unsigned idx : resultPermutation)
3859 newExprs.push_back(map.getResult(idx));
3860
3861 map = AffineMap::get(map.getNumDims(), map.getNumSymbols(), newExprs,
3862 map.getContext());
3863 return success();
3864}
3865
3866/// Canonicalize the affine map result expression order of an affine min/max
3867/// operation.
3868///
3869/// The pattern calls `canonicalizeMapExprAndTermOrder` to order the result
3870/// expressions and replaces the operation if the order changed.
3871///
3872/// For example, the following operation:
3873///
3874/// %0 = affine.min affine_map<(d0, d1) -> (d0 + d1, d1 + 16, 32)> (%i0, %i1)
3875///
3876/// Turns into:
3877///
3878/// %0 = affine.min affine_map<(d0, d1) -> (32, d1 + 16, d0 + d1)> (%i0, %i1)
3879template <typename T>
3882
3883 LogicalResult matchAndRewrite(T affineOp,
3884 PatternRewriter &rewriter) const override {
3885 AffineMap map = affineOp.getAffineMap();
3886 if (failed(canonicalizeMapExprAndTermOrder(map)))
3887 return failure();
3888 rewriter.replaceOpWithNewOp<T>(affineOp, map, affineOp.getMapOperands());
3889 return success();
3890 }
3891};
3892
3893template <typename T>
3896
3897 LogicalResult matchAndRewrite(T affineOp,
3898 PatternRewriter &rewriter) const override {
3899 if (affineOp.getMap().getNumResults() != 1)
3900 return failure();
3901 rewriter.replaceOpWithNewOp<AffineApplyOp>(affineOp, affineOp.getMap(),
3902 affineOp.getOperands());
3903 return success();
3904 }
3905};
3906
3907//===----------------------------------------------------------------------===//
3908// AffineMinOp
3909//===----------------------------------------------------------------------===//
3910//
3911// %0 = affine.min (d0) -> (1000, d0 + 512) (%i0)
3912//
3913
3914OpFoldResult AffineMinOp::fold(FoldAdaptor adaptor) {
3915 return foldMinMaxOp(*this, adaptor.getOperands());
3916}
3917
3918void AffineMinOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
3919 MLIRContext *context) {
3922 MergeAffineMinMaxOp<AffineMinOp>, SimplifyAffineOp<AffineMinOp>,
3924 context);
3925}
3926
3927LogicalResult AffineMinOp::verify() { return verifyAffineMinMaxOp(*this); }
3928
3929ParseResult AffineMinOp::parse(OpAsmParser &parser, OperationState &result) {
3931}
3932
3933void AffineMinOp::print(OpAsmPrinter &p) { printAffineMinMaxOp(p, *this); }
3934
3935//===----------------------------------------------------------------------===//
3936// AffineMaxOp
3937//===----------------------------------------------------------------------===//
3938//
3939// %0 = affine.max (d0) -> (1000, d0 + 512) (%i0)
3940//
3941
3942OpFoldResult AffineMaxOp::fold(FoldAdaptor adaptor) {
3943 return foldMinMaxOp(*this, adaptor.getOperands());
3944}
3945
3946void AffineMaxOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
3947 MLIRContext *context) {
3950 MergeAffineMinMaxOp<AffineMaxOp>, SimplifyAffineOp<AffineMaxOp>,
3952 context);
3953}
3954
3955LogicalResult AffineMaxOp::verify() { return verifyAffineMinMaxOp(*this); }
3956
3957ParseResult AffineMaxOp::parse(OpAsmParser &parser, OperationState &result) {
3959}
3960
3961void AffineMaxOp::print(OpAsmPrinter &p) { printAffineMinMaxOp(p, *this); }
3962
3963//===----------------------------------------------------------------------===//
3964// AffinePrefetchOp
3965//===----------------------------------------------------------------------===//
3966
3967//
3968// affine.prefetch %0[%i, %j + 5], read, locality<3>, data : memref<400x400xi32>
3969//
3970ParseResult AffinePrefetchOp::parse(OpAsmParser &parser,
3972 auto &builder = parser.getBuilder();
3973 auto indexTy = builder.getIndexType();
3974
3975 MemRefType type;
3977 IntegerAttr hintInfo;
3978 auto i32Type = parser.getBuilder().getIntegerType(32);
3979 StringRef readOrWrite, cacheType;
3980
3981 AffineMapAttr mapAttr;
3983 if (parser.parseOperand(memrefInfo) ||
3984 parser.parseAffineMapOfSSAIds(mapOperands, mapAttr,
3985 AffinePrefetchOp::getMapAttrStrName(),
3986 result.attributes) ||
3987 parser.parseComma() || parser.parseKeyword(&readOrWrite) ||
3988 parser.parseComma() || parser.parseKeyword("locality") ||
3989 parser.parseLess() ||
3990 parser.parseAttribute(hintInfo, i32Type,
3991 AffinePrefetchOp::getLocalityHintAttrStrName(),
3992 result.attributes) ||
3993 parser.parseGreater() || parser.parseComma() ||
3994 parser.parseKeyword(&cacheType) ||
3995 parser.parseOptionalAttrDict(result.attributes) ||
3996 parser.parseColonType(type) ||
3997 parser.resolveOperand(memrefInfo, type, result.operands) ||
3998 parser.resolveOperands(mapOperands, indexTy, result.operands))
3999 return failure();
4000
4001 if (readOrWrite != "read" && readOrWrite != "write")
4002 return parser.emitError(parser.getNameLoc(),
4003 "rw specifier has to be 'read' or 'write'");
4004 result.addAttribute(AffinePrefetchOp::getIsWriteAttrStrName(),
4005 parser.getBuilder().getBoolAttr(readOrWrite == "write"));
4006
4007 if (cacheType != "data" && cacheType != "instr")
4008 return parser.emitError(parser.getNameLoc(),
4009 "cache type has to be 'data' or 'instr'");
4010
4011 result.addAttribute(AffinePrefetchOp::getIsDataCacheAttrStrName(),
4012 parser.getBuilder().getBoolAttr(cacheType == "data"));
4013
4014 return success();
4015}
4016
4017void AffinePrefetchOp::print(OpAsmPrinter &p) {
4018 p << " " << getMemref() << '[';
4019 AffineMapAttr mapAttr = getMapAttr();
4020 if (mapAttr)
4021 p.printAffineMapOfSSAIds(mapAttr, getMapOperands());
4022 p << ']' << ", " << (getIsWrite() ? "write" : "read") << ", " << "locality<"
4023 << getLocalityHint() << ">, " << (getIsDataCache() ? "data" : "instr");
4024 p.printOptionalAttrDict((*this)->getDiscardableAttrDictionary().getValue());
4025 p << " : " << getMemRefType();
4026}
4027
4028LogicalResult AffinePrefetchOp::verify() {
4029 auto mapAttr = getMapAttr();
4030 if (mapAttr) {
4031 AffineMap map = mapAttr.getValue();
4032 if (map.getNumResults() != getMemRefType().getRank())
4033 return emitOpError("affine.prefetch affine map num results must equal"
4034 " memref rank");
4035 if (map.getNumInputs() + 1 != getNumOperands())
4036 return emitOpError("too few operands");
4037 } else {
4038 if (getNumOperands() != 1)
4039 return emitOpError("too few operands");
4040 }
4041
4042 Region *scope = getAffineScope(*this);
4043 for (auto idx : getMapOperands()) {
4044 if (!isValidAffineIndexOperand(idx, scope))
4045 return emitOpError(
4046 "index must be a valid dimension or symbol identifier");
4047 }
4048 return success();
4049}
4050
4051void AffinePrefetchOp::getCanonicalizationPatterns(RewritePatternSet &results,
4052 MLIRContext *context) {
4053 // prefetch(memrefcast) -> prefetch
4054 results.add<SimplifyAffineOp<AffinePrefetchOp>>(context);
4055}
4056
4057LogicalResult AffinePrefetchOp::fold(FoldAdaptor adaptor,
4059 /// prefetch(memrefcast) -> prefetch
4060 return memref::foldMemRefCast(*this);
4061}
4062
4063//===----------------------------------------------------------------------===//
4064// AffineParallelOp
4065//===----------------------------------------------------------------------===//
4066
4067void AffineParallelOp::build(OpBuilder &builder, OperationState &result,
4068 TypeRange resultTypes,
4070 ArrayRef<int64_t> ranges) {
4071 SmallVector<AffineMap> lbs(ranges.size(), builder.getConstantAffineMap(0));
4072 auto ubs = llvm::map_to_vector<4>(ranges, [&](int64_t value) {
4073 return builder.getConstantAffineMap(value);
4074 });
4075 SmallVector<int64_t> steps(ranges.size(), 1);
4076 build(builder, result, resultTypes, reductions, lbs, /*lbArgs=*/{}, ubs,
4077 /*ubArgs=*/{}, steps);
4078}
4079
4080void AffineParallelOp::build(OpBuilder &builder, OperationState &result,
4081 TypeRange resultTypes,
4083 ArrayRef<AffineMap> lbMaps, ValueRange lbArgs,
4084 ArrayRef<AffineMap> ubMaps, ValueRange ubArgs,
4085 ArrayRef<int64_t> steps) {
4086 assert(llvm::all_of(lbMaps,
4087 [lbMaps](AffineMap m) {
4088 return m.getNumDims() == lbMaps[0].getNumDims() &&
4089 m.getNumSymbols() == lbMaps[0].getNumSymbols();
4090 }) &&
4091 "expected all lower bounds maps to have the same number of dimensions "
4092 "and symbols");
4093 assert(llvm::all_of(ubMaps,
4094 [ubMaps](AffineMap m) {
4095 return m.getNumDims() == ubMaps[0].getNumDims() &&
4096 m.getNumSymbols() == ubMaps[0].getNumSymbols();
4097 }) &&
4098 "expected all upper bounds maps to have the same number of dimensions "
4099 "and symbols");
4100 assert((lbMaps.empty() || lbMaps[0].getNumInputs() == lbArgs.size()) &&
4101 "expected lower bound maps to have as many inputs as lower bound "
4102 "operands");
4103 assert((ubMaps.empty() || ubMaps[0].getNumInputs() == ubArgs.size()) &&
4104 "expected upper bound maps to have as many inputs as upper bound "
4105 "operands");
4106
4107 OpBuilder::InsertionGuard guard(builder);
4108 result.addTypes(resultTypes);
4109
4110 // Convert the reductions to integer attributes.
4111 SmallVector<Attribute, 4> reductionAttrs;
4112 for (arith::AtomicRMWKind reduction : reductions)
4113 reductionAttrs.push_back(
4114 builder.getI64IntegerAttr(static_cast<int64_t>(reduction)));
4115 result.addAttribute(getReductionsAttrStrName(),
4116 builder.getArrayAttr(reductionAttrs));
4117
4118 // Concatenates maps defined in the same input space (same dimensions and
4119 // symbols), assumes there is at least one map.
4120 auto concatMapsSameInput = [&builder](ArrayRef<AffineMap> maps,
4121 SmallVectorImpl<int32_t> &groups) {
4122 if (maps.empty())
4123 return AffineMap::get(builder.getContext());
4125 groups.reserve(groups.size() + maps.size());
4126 exprs.reserve(maps.size());
4127 for (AffineMap m : maps) {
4128 llvm::append_range(exprs, m.getResults());
4129 groups.push_back(m.getNumResults());
4130 }
4131 return AffineMap::get(maps[0].getNumDims(), maps[0].getNumSymbols(), exprs,
4132 maps[0].getContext());
4133 };
4134
4135 // Set up the bounds.
4136 SmallVector<int32_t> lbGroups, ubGroups;
4137 AffineMap lbMap = concatMapsSameInput(lbMaps, lbGroups);
4138 AffineMap ubMap = concatMapsSameInput(ubMaps, ubGroups);
4139 result.addAttribute(getLowerBoundsMapAttrStrName(),
4140 AffineMapAttr::get(lbMap));
4141 result.addAttribute(getLowerBoundsGroupsAttrStrName(),
4142 builder.getI32TensorAttr(lbGroups));
4143 result.addAttribute(getUpperBoundsMapAttrStrName(),
4144 AffineMapAttr::get(ubMap));
4145 result.addAttribute(getUpperBoundsGroupsAttrStrName(),
4146 builder.getI32TensorAttr(ubGroups));
4147 result.addAttribute(getStepsAttrStrName(), builder.getI64ArrayAttr(steps));
4148 result.addOperands(lbArgs);
4149 result.addOperands(ubArgs);
4150
4151 // Create a region and a block for the body.
4152 auto *bodyRegion = result.addRegion();
4153 Block *body = builder.createBlock(bodyRegion);
4154
4155 // Add all the block arguments.
4156 for (unsigned i = 0, e = steps.size(); i < e; ++i)
4157 body->addArgument(IndexType::get(builder.getContext()), result.location);
4158 if (resultTypes.empty())
4159 ensureTerminator(*bodyRegion, builder, result.location);
4160}
4161
4162SmallVector<Region *> AffineParallelOp::getLoopRegions() {
4163 return {&getRegion()};
4164}
4165
4166unsigned AffineParallelOp::getNumDims() { return getSteps().size(); }
4167
4168AffineParallelOp::operand_range AffineParallelOp::getLowerBoundsOperands() {
4169 return getOperands().take_front(getLowerBoundsMap().getNumInputs());
4170}
4171
4172AffineParallelOp::operand_range AffineParallelOp::getUpperBoundsOperands() {
4173 return getOperands().drop_front(getLowerBoundsMap().getNumInputs());
4174}
4175
4176AffineMap AffineParallelOp::getLowerBoundMap(unsigned pos) {
4177 auto values = getLowerBoundsGroups().getValues<int32_t>();
4178 unsigned start = 0;
4179 for (unsigned i = 0; i < pos; ++i)
4180 start += values[i];
4181 return getLowerBoundsMap().getSliceMap(start, values[pos]);
4182}
4183
4184AffineMap AffineParallelOp::getUpperBoundMap(unsigned pos) {
4185 auto values = getUpperBoundsGroups().getValues<int32_t>();
4186 unsigned start = 0;
4187 for (unsigned i = 0; i < pos; ++i)
4188 start += values[i];
4189 return getUpperBoundsMap().getSliceMap(start, values[pos]);
4190}
4191
4192AffineValueMap AffineParallelOp::getLowerBoundsValueMap() {
4193 return AffineValueMap(getLowerBoundsMap(), getLowerBoundsOperands());
4194}
4195
4196AffineValueMap AffineParallelOp::getUpperBoundsValueMap() {
4197 return AffineValueMap(getUpperBoundsMap(), getUpperBoundsOperands());
4198}
4199
4200std::optional<SmallVector<int64_t, 8>> AffineParallelOp::getConstantRanges() {
4201 if (hasMinMaxBounds())
4202 return std::nullopt;
4203
4204 // Try to convert all the ranges to constant expressions.
4206 AffineValueMap rangesValueMap;
4207 AffineValueMap::difference(getUpperBoundsValueMap(), getLowerBoundsValueMap(),
4208 &rangesValueMap);
4209 out.reserve(rangesValueMap.getNumResults());
4210 for (unsigned i = 0, e = rangesValueMap.getNumResults(); i < e; ++i) {
4211 auto expr = rangesValueMap.getResult(i);
4212 auto cst = dyn_cast<AffineConstantExpr>(expr);
4213 if (!cst)
4214 return std::nullopt;
4215 out.push_back(cst.getValue());
4216 }
4217 return out;
4218}
4219
4220Block *AffineParallelOp::getBody() { return &getRegion().front(); }
4221
4222OpBuilder AffineParallelOp::getBodyBuilder() {
4223 return OpBuilder(getBody(), std::prev(getBody()->end()));
4224}
4225
4226void AffineParallelOp::setLowerBounds(ValueRange lbOperands, AffineMap map) {
4227 assert(lbOperands.size() == map.getNumInputs() &&
4228 "operands to map must match number of inputs");
4229
4230 auto ubOperands = getUpperBoundsOperands();
4231
4232 SmallVector<Value, 4> newOperands(lbOperands);
4233 newOperands.append(ubOperands.begin(), ubOperands.end());
4234 (*this)->setOperands(newOperands);
4235
4236 setLowerBoundsMapAttr(AffineMapAttr::get(map));
4237}
4238
4239void AffineParallelOp::setUpperBounds(ValueRange ubOperands, AffineMap map) {
4240 assert(ubOperands.size() == map.getNumInputs() &&
4241 "operands to map must match number of inputs");
4242
4243 SmallVector<Value, 4> newOperands(getLowerBoundsOperands());
4244 newOperands.append(ubOperands.begin(), ubOperands.end());
4245 (*this)->setOperands(newOperands);
4246
4247 setUpperBoundsMapAttr(AffineMapAttr::get(map));
4248}
4249
4250void AffineParallelOp::setSteps(ArrayRef<int64_t> newSteps) {
4251 setStepsAttr(getBodyBuilder().getI64ArrayAttr(newSteps));
4252}
4253
4254// check whether resultType match op or not in affine.parallel
4256 arith::AtomicRMWKind op) {
4257 switch (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:
4263 return true;
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);
4273 // The kind carries the signedness of the comparison; the integer is
4274 // signless (what arith's maxsi/minsi/maxui/minui, which the reduction
4275 // lowers to, operate on) or of that signedness.
4276 case arith::AtomicRMWKind::maxs:
4277 case arith::AtomicRMWKind::mins: {
4278 auto intType = dyn_cast<IntegerType>(resultType);
4279 return intType && !intType.isUnsigned();
4280 }
4281 case arith::AtomicRMWKind::maxu:
4282 case arith::AtomicRMWKind::minu: {
4283 auto intType = dyn_cast<IntegerType>(resultType);
4284 return intType && !intType.isSigned();
4285 }
4286 case arith::AtomicRMWKind::ori:
4287 case arith::AtomicRMWKind::andi:
4288 case arith::AtomicRMWKind::xori:
4289 return isa<IntegerType>(resultType);
4290 }
4291 llvm_unreachable("Unhandled atomic rmw kind");
4292}
4293
4294LogicalResult AffineParallelOp::verify() {
4295 auto numDims = getNumDims();
4296 if (getLowerBoundsGroups().getNumElements() != numDims ||
4297 getUpperBoundsGroups().getNumElements() != numDims ||
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";
4307 }
4308
4309 unsigned expectedNumLBResults = 0;
4310 for (APInt v : getLowerBoundsGroups()) {
4311 unsigned results = v.getZExtValue();
4312 if (results == 0)
4313 return emitOpError()
4314 << "expected lower bound map to have at least one result";
4315 expectedNumLBResults += results;
4316 }
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();
4323 if (results == 0)
4324 return emitOpError()
4325 << "expected upper bound map to have at least one result";
4326 expectedNumUBResults += results;
4327 }
4328 if (expectedNumUBResults != getUpperBoundsMap().getNumResults())
4329 return emitOpError() << "expected upper bounds map to have "
4330 << expectedNumUBResults << " results";
4331
4332 if (getReductions().size() != getNumResults())
4333 return emitOpError("a reduction must be specified for each output");
4334
4335 // Verify reduction ops are all valid and each result type matches reduction
4336 // ops
4337 for (auto it : llvm::enumerate((getReductions()))) {
4338 Attribute attr = it.value();
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();
4343 if (!isResultTypeMatchAtomicRMWKind(getResult(it.index()).getType(), kind))
4344 return emitOpError("result type cannot match reduction attribute");
4345 }
4346
4347 // Verify that the bound operands are valid dimension/symbols.
4348 /// Lower bounds.
4349 if (failed(verifyDimAndSymbolIdentifiers(*this, getLowerBoundsOperands(),
4350 getLowerBoundsMap().getNumDims())))
4351 return failure();
4352 /// Upper bounds.
4353 if (failed(verifyDimAndSymbolIdentifiers(*this, getUpperBoundsOperands(),
4354 getUpperBoundsMap().getNumDims())))
4355 return failure();
4356 return success();
4357}
4358
4360 SmallVector<Value, 4> newOperands{operands};
4361 auto newMap = getAffineMap();
4362 composeAffineMapAndOperands(&newMap, &newOperands);
4363 if (newMap == getAffineMap() && newOperands == operands)
4364 return failure();
4365 reset(newMap, newOperands);
4366 return success();
4367}
4368
4369/// Canonicalize the bounds of the given loop.
4370static LogicalResult canonicalizeLoopBounds(AffineParallelOp op) {
4371 AffineValueMap lb = op.getLowerBoundsValueMap();
4372 bool lbCanonicalized = succeeded(lb.canonicalize());
4373
4374 AffineValueMap ub = op.getUpperBoundsValueMap();
4375 bool ubCanonicalized = succeeded(ub.canonicalize());
4376
4377 // Any canonicalization change always leads to updated map(s).
4378 if (!lbCanonicalized && !ubCanonicalized)
4379 return failure();
4380
4381 if (lbCanonicalized)
4382 op.setLowerBounds(lb.getOperands(), lb.getAffineMap());
4383 if (ubCanonicalized)
4384 op.setUpperBounds(ub.getOperands(), ub.getAffineMap());
4385
4386 return success();
4387}
4388
4389LogicalResult AffineParallelOp::fold(FoldAdaptor adaptor,
4390 SmallVectorImpl<OpFoldResult> &results) {
4391 return canonicalizeLoopBounds(*this);
4392}
4393
4394/// Prints a lower(upper) bound of an affine parallel loop with max(min)
4395/// conditions in it. `mapAttr` is a flat list of affine expressions and `group`
4396/// identifies which of the those expressions form max/min groups. `operands`
4397/// are the SSA values of dimensions and symbols and `keyword` is either "min"
4398/// or "max".
4399static void printMinMaxBound(OpAsmPrinter &p, AffineMapAttr mapAttr,
4400 DenseIntElementsAttr group, ValueRange operands,
4401 StringRef keyword) {
4402 AffineMap map = mapAttr.getValue();
4403 unsigned numDims = map.getNumDims();
4404 ValueRange dimOperands = operands.take_front(numDims);
4405 ValueRange symOperands = operands.drop_front(numDims);
4406 unsigned start = 0;
4407 for (llvm::APInt groupSize : group) {
4408 if (start != 0)
4409 p << ", ";
4410
4411 unsigned size = groupSize.getZExtValue();
4412 if (size == 1) {
4413 p.printAffineExprOfSSAIds(map.getResult(start), dimOperands, symOperands);
4414 ++start;
4415 } else {
4416 p << keyword << '(';
4417 AffineMap submap = map.getSliceMap(start, size);
4418 p.printAffineMapOfSSAIds(AffineMapAttr::get(submap), operands);
4419 p << ')';
4420 start += size;
4421 }
4422 }
4423}
4424
4425void AffineParallelOp::print(OpAsmPrinter &p) {
4426 p << " (" << getBody()->getArguments() << ") = (";
4427 printMinMaxBound(p, getLowerBoundsMapAttr(), getLowerBoundsGroupsAttr(),
4428 getLowerBoundsOperands(), "max");
4429 p << ") to (";
4430 printMinMaxBound(p, getUpperBoundsMapAttr(), getUpperBoundsGroupsAttr(),
4431 getUpperBoundsOperands(), "min");
4432 p << ')';
4433 SmallVector<int64_t, 8> steps = getSteps();
4434 bool elideSteps = llvm::all_of(steps, [](int64_t step) { return step == 1; });
4435 if (!elideSteps) {
4436 p << " step (";
4437 llvm::interleaveComma(steps, p);
4438 p << ')';
4439 }
4440 if (getNumResults()) {
4441 p << " reduce (";
4442 llvm::interleaveComma(getReductions(), p, [&](auto &attr) {
4443 arith::AtomicRMWKind sym = *arith::symbolizeAtomicRMWKind(
4444 llvm::cast<IntegerAttr>(attr).getInt());
4445 p << "\"" << arith::stringifyAtomicRMWKind(sym) << "\"";
4446 });
4447 p << ") -> (" << getResultTypes() << ")";
4448 }
4449
4450 p << ' ';
4451 p.printRegion(getRegion(), /*printEntryBlockArgs=*/false,
4452 /*printBlockTerminators=*/getNumResults());
4453 p.printOptionalAttrDict((*this)->getDiscardableAttrDictionary().getValue());
4454}
4455
4456/// Given a list of lists of parsed operands, populates `uniqueOperands` with
4457/// unique operands. Also populates `replacements with affine expressions of
4458/// `kind` that can be used to update affine maps previously accepting a
4459/// `operands` to accept `uniqueOperands` instead.
4460static ParseResult deduplicateAndResolveOperands(
4461 OpAsmParser &parser,
4462 ArrayRef<SmallVector<OpAsmParser::UnresolvedOperand>> operands,
4463 SmallVectorImpl<Value> &uniqueOperands,
4464 SmallVectorImpl<AffineExpr> &replacements, AffineExprKind kind) {
4465 assert((kind == AffineExprKind::DimId || kind == AffineExprKind::SymbolId) &&
4466 "expected operands to be dim or symbol expression");
4467
4468 Type indexType = parser.getBuilder().getIndexType();
4469 for (const auto &list : operands) {
4470 SmallVector<Value> valueOperands;
4471 if (parser.resolveOperands(list, indexType, valueOperands))
4472 return failure();
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(
4479 kind == AffineExprKind::DimId
4480 ? getAffineDimExpr(pos, parser.getContext())
4481 : getAffineSymbolExpr(pos, parser.getContext()));
4482 }
4483 }
4484 return success();
4485}
4486
4487namespace {
4488enum class MinMaxKind { Min, Max };
4489} // namespace
4490
4491/// Parses an affine map that can contain a min/max for groups of its results,
4492/// e.g., max(expr-1, expr-2), expr-3, max(expr-4, expr-5, expr-6). Populates
4493/// `result` attributes with the map (flat list of expressions) and the grouping
4494/// (list of integers that specify how many expressions to put into each
4495/// min/max) attributes. Deduplicates repeated operands.
4496///
4497/// parallel-bound ::= `(` parallel-group-list `)`
4498/// parallel-group-list ::= parallel-group (`,` parallel-group-list)?
4499/// parallel-group ::= simple-group | min-max-group
4500/// simple-group ::= expr-of-ssa-ids
4501/// min-max-group ::= ( `min` | `max` ) `(` expr-of-ssa-ids-list `)`
4502/// expr-of-ssa-ids-list ::= expr-of-ssa-ids (`,` expr-of-ssa-id-list)?
4503///
4504/// Examples:
4505/// (%0, min(%1 + %2, %3), %4, min(%5 floordiv 32, %6))
4506/// (%0, max(%1 - 2 * %2))
4507static ParseResult parseAffineMapWithMinMax(OpAsmParser &parser,
4508 OperationState &result,
4509 MinMaxKind kind) {
4510 // Using `const` not `constexpr` below to workaround a MSVC optimizer bug,
4511 // see: https://reviews.llvm.org/D134227#3821753
4512 const llvm::StringLiteral tmpAttrStrName = "__pseudo_bound_map";
4513
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();
4521
4522 if (failed(parser.parseLParen()))
4523 return failure();
4524
4525 if (succeeded(parser.parseOptionalRParen())) {
4526 result.addAttribute(
4527 mapName, AffineMapAttr::get(parser.getBuilder().getEmptyAffineMap()));
4528 result.addAttribute(groupsName, parser.getBuilder().getI32TensorAttr({}));
4529 return success();
4530 }
4531
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 = [&]() {
4538 if (succeeded(parser.parseOptionalKeyword(
4539 kind == MinMaxKind::Min ? "min" : "max"))) {
4540 mapOperands.clear();
4541 AffineMapAttr map;
4542 if (failed(parser.parseAffineMapOfSSAIds(mapOperands, map, tmpAttrStrName,
4543 result.attributes,
4545 return failure();
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());
4556 } else {
4557 if (failed(parser.parseAffineExprOfSSAIds(flatDimOperands.emplace_back(),
4558 flatSymOperands.emplace_back(),
4559 flatExprs.emplace_back())))
4560 return failure();
4561 numMapsPerGroup.push_back(1);
4562 }
4563 return success();
4564 };
4565 if (parser.parseCommaSeparatedList(parseOperands) || parser.parseRParen())
4566 return failure();
4567
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;
4578 }
4579
4580 // Deduplicate map operands.
4581 SmallVector<Value> dimOperands, symOperands;
4582 SmallVector<AffineExpr> dimRplacements, symRepacements;
4583 if (deduplicateAndResolveOperands(parser, flatDimOperands, dimOperands,
4584 dimRplacements, AffineExprKind::DimId) ||
4585 deduplicateAndResolveOperands(parser, flatSymOperands, symOperands,
4586 symRepacements, AffineExprKind::SymbolId))
4587 return failure();
4588
4589 result.operands.append(dimOperands.begin(), dimOperands.end());
4590 result.operands.append(symOperands.begin(), symOperands.end());
4591
4592 Builder &builder = parser.getBuilder();
4593 auto flatMap = AffineMap::get(totalNumDims, totalNumSyms, flatExprs,
4594 parser.getContext());
4595 flatMap = flatMap.replaceDimsAndSymbols(
4596 dimRplacements, symRepacements, dimOperands.size(), symOperands.size());
4597
4598 result.addAttribute(mapName, AffineMapAttr::get(flatMap));
4599 result.addAttribute(groupsName, builder.getI32TensorAttr(numMapsPerGroup));
4600 return success();
4601}
4602
4603//
4604// operation ::= `affine.parallel` `(` ssa-ids `)` `=` parallel-bound
4605// `to` parallel-bound steps? region attr-dict?
4606// steps ::= `steps` `(` integer-literals `)`
4607//
4608ParseResult AffineParallelOp::parse(OpAsmParser &parser,
4609 OperationState &result) {
4610 auto &builder = parser.getBuilder();
4611 auto indexType = builder.getIndexType();
4612 SmallVector<OpAsmParser::Argument, 4> ivs;
4614 parser.parseEqual() ||
4615 parseAffineMapWithMinMax(parser, result, MinMaxKind::Max) ||
4616 parser.parseKeyword("to") ||
4617 parseAffineMapWithMinMax(parser, result, MinMaxKind::Min))
4618 return failure();
4619
4620 AffineMapAttr stepsMapAttr;
4621 NamedAttrList stepsAttrs;
4622 SmallVector<OpAsmParser::UnresolvedOperand, 4> stepsMapOperands;
4623 if (failed(parser.parseOptionalKeyword("step"))) {
4624 SmallVector<int64_t, 4> steps(ivs.size(), 1);
4625 result.addAttribute(AffineParallelOp::getStepsAttrStrName(),
4626 builder.getI64ArrayAttr(steps));
4627 } else {
4628 if (parser.parseAffineMapOfSSAIds(stepsMapOperands, stepsMapAttr,
4629 AffineParallelOp::getStepsAttrStrName(),
4630 stepsAttrs,
4632 return failure();
4633
4634 // Convert steps from an AffineMap into an I64ArrayAttr.
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);
4639 if (!constExpr)
4640 return parser.emitError(parser.getNameLoc(),
4641 "steps must be constant integers");
4642 steps.push_back(constExpr.getValue());
4643 }
4644 result.addAttribute(AffineParallelOp::getStepsAttrStrName(),
4645 builder.getI64ArrayAttr(steps));
4646 }
4647
4648 // Parse optional clause of the form: `reduce ("addf", "maxf")`, where the
4649 // quoted strings are a member of the enum AtomicRMWKind.
4650 SmallVector<Attribute, 4> reductions;
4651 if (succeeded(parser.parseOptionalKeyword("reduce"))) {
4652 if (parser.parseLParen())
4653 return failure();
4654 auto parseAttributes = [&]() -> ParseResult {
4655 // Parse a single quoted string via the attribute parsing, and then
4656 // verify it is a member of the enum and convert to it's integer
4657 // representation.
4658 StringAttr attrVal;
4659 NamedAttrList attrStorage;
4660 auto loc = parser.getCurrentLocation();
4661 if (parser.parseAttribute(attrVal, builder.getNoneType(), "reduce",
4662 attrStorage))
4663 return failure();
4664 std::optional<arith::AtomicRMWKind> reduction =
4665 arith::symbolizeAtomicRMWKind(attrVal.getValue());
4666 if (!reduction)
4667 return parser.emitError(loc, "invalid reduction value: ") << attrVal;
4668 reductions.push_back(
4669 builder.getI64IntegerAttr(static_cast<int64_t>(reduction.value())));
4670 // While we keep getting commas, keep parsing.
4671 return success();
4672 };
4673 if (parser.parseCommaSeparatedList(parseAttributes) || parser.parseRParen())
4674 return failure();
4675 }
4676 result.addAttribute(AffineParallelOp::getReductionsAttrStrName(),
4677 builder.getArrayAttr(reductions));
4678
4679 // Parse return types of reductions (if any)
4680 if (parser.parseOptionalArrowTypeList(result.types))
4681 return failure();
4682
4683 // Now parse the body.
4684 Region *body = result.addRegion();
4685 for (auto &iv : ivs)
4686 iv.type = indexType;
4687 if (parser.parseRegion(*body, ivs) ||
4688 parser.parseOptionalAttrDict(result.attributes))
4689 return failure();
4690
4691 // Add a terminator if none was parsed.
4692 AffineParallelOp::ensureTerminator(*body, builder, result.location);
4693 return success();
4694}
4695
4696void AffineParallelOp::getSuccessorRegions(
4697 RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> &regions) {
4698 assert((point.isParent() ||
4699 point.getTerminatorPredecessorOrNull()->getParentRegion() ==
4700 &getRegion()) &&
4701 "expected loop region");
4702 // Both the operation itself and the region may be branching into the body or
4703 // back into the operation itself. It is possible for the loop to not enter
4704 // the body.
4705 regions.push_back(RegionSuccessor(&getRegion()));
4706 regions.push_back(RegionSuccessor(getOperation()));
4707}
4708
4709//===----------------------------------------------------------------------===//
4710// AffineYieldOp
4711//===----------------------------------------------------------------------===//
4712
4713LogicalResult AffineYieldOp::verify() {
4714 auto *parentOp = (*this)->getParentOp();
4715 auto results = parentOp->getResults();
4716 auto operands = getOperands();
4717
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)) {
4724 if (std::get<0>(it).getType() != std::get<1>(it).getType())
4725 return emitOpError() << "types mismatch between yield op and its parent";
4726 }
4727
4728 return success();
4729}
4730
4731MutableOperandRange
4732AffineYieldOp::getMutableSuccessorOperands(RegionSuccessor point) {
4733 // Reductions in affine.parallel are not directly forwarded SSA values.
4734 if (isa_and_nonnull<AffineParallelOp>((*this)->getParentOp()))
4735 return MutableOperandRange(getOperation(), /*start=*/0, /*length=*/0);
4736 return MutableOperandRange(*this);
4737}
4738
4739//===----------------------------------------------------------------------===//
4740// AffineVectorLoadOp
4741//===----------------------------------------------------------------------===//
4742
4743void AffineVectorLoadOp::build(OpBuilder &builder, OperationState &result,
4744 VectorType resultType, AffineMap map,
4745 ValueRange operands,
4746 llvm::MaybeAlign alignment) {
4747 assert(operands.size() == 1 + map.getNumInputs() && "inconsistent operands");
4748 result.addOperands(operands);
4749 if (map)
4750 result.addAttribute(getMapAttrStrName(), AffineMapAttr::get(map));
4751 addAlignmentAttr(builder, result, getAlignmentAttrName(result.name),
4752 alignment);
4753 result.types.push_back(resultType);
4754}
4755
4756void AffineVectorLoadOp::build(OpBuilder &builder, OperationState &result,
4757 VectorType resultType, Value memref,
4758 AffineMap map, ValueRange mapOperands,
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));
4764 addAlignmentAttr(builder, result, getAlignmentAttrName(result.name),
4765 alignment);
4766 result.types.push_back(resultType);
4767}
4768
4769void AffineVectorLoadOp::build(OpBuilder &builder, OperationState &result,
4770 VectorType resultType, Value memref,
4771 ValueRange indices, llvm::MaybeAlign alignment) {
4772 auto memrefType = llvm::cast<MemRefType>(memref.getType());
4773 int64_t rank = memrefType.getRank();
4774 // Create identity map for memrefs with at least one dimension or () -> ()
4775 // for zero-dimensional memrefs.
4776 auto map =
4777 rank ? builder.getMultiDimIdentityMap(rank) : builder.getEmptyAffineMap();
4778 build(builder, result, resultType, memref, map, indices, alignment);
4779}
4780
4781void AffineVectorLoadOp::getCanonicalizationPatterns(RewritePatternSet &results,
4782 MLIRContext *context) {
4783 results.add<SimplifyAffineOp<AffineVectorLoadOp>>(context);
4784}
4785
4786ParseResult AffineVectorLoadOp::parse(OpAsmParser &parser,
4787 OperationState &result) {
4788 auto &builder = parser.getBuilder();
4789 auto indexTy = builder.getIndexType();
4790
4791 MemRefType memrefType;
4792 VectorType resultType;
4793 OpAsmParser::UnresolvedOperand memrefInfo;
4794 AffineMapAttr mapAttr;
4795 SmallVector<OpAsmParser::UnresolvedOperand, 1> mapOperands;
4796 return failure(
4797 parser.parseOperand(memrefInfo) ||
4798 parser.parseAffineMapOfSSAIds(mapOperands, mapAttr,
4799 AffineVectorLoadOp::getMapAttrStrName(),
4800 result.attributes) ||
4801 parser.parseOptionalAttrDict(result.attributes) ||
4802 parser.parseColonType(memrefType) || parser.parseComma() ||
4803 parser.parseType(resultType) ||
4804 parser.resolveOperand(memrefInfo, memrefType, result.operands) ||
4805 parser.resolveOperands(mapOperands, indexTy, result.operands) ||
4806 parser.addTypeToList(resultType, result.types));
4807}
4808
4809void AffineVectorLoadOp::print(OpAsmPrinter &p) {
4810 p << " " << getMemRef() << '[';
4811 if (AffineMapAttr mapAttr = getMapAttr())
4812 p.printAffineMapOfSSAIds(mapAttr, getMapOperands());
4813 p << ']';
4814 SmallVector<NamedAttribute> attrs((*this)->getDiscardableAttrs());
4815 if (IntegerAttr alignment = getAlignmentAttr())
4816 attrs.emplace_back(getAlignmentAttrName(), alignment);
4817 llvm::sort(attrs);
4818 p.printOptionalAttrDict(attrs);
4819 p << " : " << getMemRefType() << ", " << getType();
4820}
4821
4822/// Verify common invariants of affine.vector_load and affine.vector_store.
4823static LogicalResult verifyVectorMemoryOp(Operation *op, MemRefType memrefType,
4824 VectorType vectorType) {
4825 // Check that memref and vector element types match.
4826 if (memrefType.getElementType() != vectorType.getElementType())
4827 return op->emitOpError(
4828 "requires memref and vector types of the same elemental type");
4829 return success();
4830}
4831
4832LogicalResult AffineVectorLoadOp::verify() {
4833 MemRefType memrefType = getMemRefType();
4834 if (failed(verifyMemoryOpIndexing(*this, getMapAttr(), getMapOperands(),
4835 memrefType,
4836 /*numIndexOperands=*/getNumOperands() - 1)))
4837 return failure();
4838
4839 if (failed(verifyVectorMemoryOp(getOperation(), memrefType, getVectorType())))
4840 return failure();
4841
4842 return success();
4843}
4844
4845//===----------------------------------------------------------------------===//
4846// AffineVectorStoreOp
4847//===----------------------------------------------------------------------===//
4848
4849void AffineVectorStoreOp::build(OpBuilder &builder, OperationState &result,
4850 Value valueToStore, Value memref, AffineMap map,
4851 ValueRange mapOperands,
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));
4858 addAlignmentAttr(builder, result, getAlignmentAttrName(result.name),
4859 alignment);
4860}
4861
4862// Use identity 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();
4869 // Create identity map for memrefs with at least one dimension or () -> ()
4870 // for zero-dimensional memrefs.
4871 auto map =
4872 rank ? builder.getMultiDimIdentityMap(rank) : builder.getEmptyAffineMap();
4873 build(builder, result, valueToStore, memref, map, indices, alignment);
4874}
4875void AffineVectorStoreOp::getCanonicalizationPatterns(
4876 RewritePatternSet &results, MLIRContext *context) {
4877 results.add<SimplifyAffineOp<AffineVectorStoreOp>>(context);
4878}
4879
4880ParseResult AffineVectorStoreOp::parse(OpAsmParser &parser,
4881 OperationState &result) {
4882 auto indexTy = parser.getBuilder().getIndexType();
4883
4884 MemRefType memrefType;
4885 VectorType resultType;
4886 OpAsmParser::UnresolvedOperand storeValueInfo;
4887 OpAsmParser::UnresolvedOperand memrefInfo;
4888 AffineMapAttr mapAttr;
4889 SmallVector<OpAsmParser::UnresolvedOperand, 1> mapOperands;
4890 return failure(
4891 parser.parseOperand(storeValueInfo) || parser.parseComma() ||
4892 parser.parseOperand(memrefInfo) ||
4893 parser.parseAffineMapOfSSAIds(mapOperands, mapAttr,
4894 AffineVectorStoreOp::getMapAttrStrName(),
4895 result.attributes) ||
4896 parser.parseOptionalAttrDict(result.attributes) ||
4897 parser.parseColonType(memrefType) || parser.parseComma() ||
4898 parser.parseType(resultType) ||
4899 parser.resolveOperand(storeValueInfo, resultType, result.operands) ||
4900 parser.resolveOperand(memrefInfo, memrefType, result.operands) ||
4901 parser.resolveOperands(mapOperands, indexTy, result.operands));
4902}
4903
4904void AffineVectorStoreOp::print(OpAsmPrinter &p) {
4905 p << " " << getValueToStore();
4906 p << ", " << getMemRef() << '[';
4907 if (AffineMapAttr mapAttr = getMapAttr())
4908 p.printAffineMapOfSSAIds(mapAttr, getMapOperands());
4909 p << ']';
4910 SmallVector<NamedAttribute> attrs((*this)->getDiscardableAttrs());
4911 if (IntegerAttr alignment = getAlignmentAttr())
4912 attrs.emplace_back(getAlignmentAttrName(), alignment);
4913 llvm::sort(attrs);
4914 p.printOptionalAttrDict(attrs);
4915 p << " : " << getMemRefType() << ", " << getValueToStore().getType();
4916}
4917
4918LogicalResult AffineVectorStoreOp::verify() {
4919 MemRefType memrefType = getMemRefType();
4920 if (failed(verifyMemoryOpIndexing(*this, getMapAttr(), getMapOperands(),
4921 memrefType,
4922 /*numIndexOperands=*/getNumOperands() - 2)))
4923 return failure();
4924
4925 if (failed(verifyVectorMemoryOp(*this, memrefType, getVectorType())))
4926 return failure();
4927
4928 return success();
4929}
4930
4931//===----------------------------------------------------------------------===//
4932// DelinearizeIndexOp
4933//===----------------------------------------------------------------------===//
4934
4935void AffineDelinearizeIndexOp::build(OpBuilder &odsBuilder,
4936 OperationState &odsState,
4937 Value linearIndex, ValueRange dynamicBasis,
4938 ArrayRef<int64_t> staticBasis,
4939 bool hasOuterBound) {
4940 SmallVector<Type> returnTypes(hasOuterBound ? staticBasis.size()
4941 : staticBasis.size() + 1,
4942 linearIndex.getType());
4943 build(odsBuilder, odsState, returnTypes, linearIndex, dynamicBasis,
4944 staticBasis);
4945}
4946
4947void AffineDelinearizeIndexOp::build(OpBuilder &odsBuilder,
4948 OperationState &odsState,
4949 Value linearIndex, ValueRange basis,
4950 bool hasOuterBound) {
4951 if (hasOuterBound && !basis.empty() && basis.front() == nullptr) {
4952 hasOuterBound = false;
4953 basis = basis.drop_front();
4954 }
4955 SmallVector<Value> dynamicBasis;
4956 SmallVector<int64_t> staticBasis;
4957 dispatchIndexOpFoldResults(getAsOpFoldResult(basis), dynamicBasis,
4958 staticBasis);
4959 build(odsBuilder, odsState, linearIndex, dynamicBasis, staticBasis,
4960 hasOuterBound);
4961}
4962
4963void AffineDelinearizeIndexOp::build(OpBuilder &odsBuilder,
4964 OperationState &odsState,
4965 Value linearIndex,
4966 ArrayRef<OpFoldResult> basis,
4967 bool hasOuterBound) {
4968 if (hasOuterBound && !basis.empty() && basis.front() == OpFoldResult()) {
4969 hasOuterBound = false;
4970 basis = basis.drop_front();
4971 }
4972 SmallVector<Value> dynamicBasis;
4973 SmallVector<int64_t> staticBasis;
4974 dispatchIndexOpFoldResults(basis, dynamicBasis, staticBasis);
4975 build(odsBuilder, odsState, linearIndex, dynamicBasis, staticBasis,
4976 hasOuterBound);
4977}
4978
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);
4984}
4985
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");
4992
4993 auto dynamicMarkersCount = llvm::count_if(staticBasis, ShapedType::isDynamic);
4994 if (static_cast<size_t>(dynamicMarkersCount) != getDynamicBasis().size())
4995 return emitOpError(
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");
4999
5000 if (!llvm::all_of(staticBasis, [](int64_t v) {
5001 return v > 0 || ShapedType::isDynamic(v);
5002 }))
5003 return emitOpError("no basis element may be statically non-positive");
5004
5005 return success();
5006}
5007
5008/// Given mixed basis of affine.delinearize_index/linearize_index replace
5009/// constant SSA values with the constant integer value and return the new
5010/// static basis. In case no such candidate for replacement exists, this utility
5011/// returns std::nullopt.
5012static std::optional<SmallVector<int64_t>>
5014 MutableOperandRange mutableDynamicBasis,
5015 ArrayRef<Attribute> dynamicBasis) {
5016 uint64_t dynamicBasisIndex = 0;
5017 for (Attribute basis : dynamicBasis) {
5018 // Skip poison values: they don't have a concrete integer value, so erasing
5019 // them from the dynamic operands would create an inconsistency between
5020 // the static basis (which would still hold kDynamic) and the dynamic
5021 // operand list (which would be one element shorter).
5022 if (basis && isa<IntegerAttr>(basis)) {
5023 mutableDynamicBasis.erase(dynamicBasisIndex);
5024 } else {
5025 ++dynamicBasisIndex;
5026 }
5027 }
5028
5029 // No constant SSA value exists.
5030 if (dynamicBasisIndex == dynamicBasis.size())
5031 return std::nullopt;
5032
5033 SmallVector<int64_t> staticBasis;
5034 for (OpFoldResult basis : mixedBasis) {
5035 std::optional<int64_t> basisVal = getConstantIntValue(basis);
5036 if (!basisVal)
5037 staticBasis.push_back(ShapedType::kDynamic);
5038 else
5039 staticBasis.push_back(*basisVal);
5040 }
5041
5042 return staticBasis;
5043}
5044
5045LogicalResult
5046AffineDelinearizeIndexOp::fold(FoldAdaptor adaptor,
5047 SmallVectorImpl<OpFoldResult> &result) {
5048 std::optional<SmallVector<int64_t>> maybeStaticBasis =
5049 foldCstValueToCstAttrBasis(getMixedBasis(), getDynamicBasisMutable(),
5050 adaptor.getDynamicBasis());
5051 if (maybeStaticBasis) {
5052 setStaticBasis(*maybeStaticBasis);
5053 return success();
5054 }
5055 // If we won't be doing any division or modulo (no basis or the one basis
5056 // element is purely advisory), simply return the input value.
5057 if (getNumResults() == 1) {
5058 result.push_back(getLinearIndex());
5059 return success();
5060 }
5061
5062 if (adaptor.getLinearIndex() == nullptr)
5063 return failure();
5064
5065 if (!adaptor.getDynamicBasis().empty())
5066 return failure();
5067
5068 int64_t highPart = cast<IntegerAttr>(adaptor.getLinearIndex()).getInt();
5069 Type attrType = getLinearIndex().getType();
5070
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);
5077 }
5078 result.push_back(IntegerAttr::get(attrType, highPart));
5079 std::reverse(result.begin(), result.end());
5080 return success();
5081}
5082
5083SmallVector<OpFoldResult> AffineDelinearizeIndexOp::getEffectiveBasis() {
5084 OpBuilder builder(getContext());
5085 if (hasOuterBound()) {
5086 if (getStaticBasis().front() == ::mlir::ShapedType::kDynamic)
5087 return getMixedValues(getStaticBasis().drop_front(),
5088 getDynamicBasis().drop_front(), builder);
5089
5090 return getMixedValues(getStaticBasis().drop_front(), getDynamicBasis(),
5091 builder);
5092 }
5093
5094 return getMixedValues(getStaticBasis(), getDynamicBasis(), builder);
5095}
5096
5097SmallVector<OpFoldResult> AffineDelinearizeIndexOp::getPaddedBasis() {
5098 SmallVector<OpFoldResult> ret = getMixedBasis();
5099 if (!hasOuterBound())
5100 ret.insert(ret.begin(), OpFoldResult());
5101 return ret;
5102}
5103
5104namespace {
5105// Drops delinearization indices that correspond to unit-extent basis
5106struct DropUnitExtentBasis
5107 : public OpRewritePattern<affine::AffineDelinearizeIndexOp> {
5108 using Base::Base;
5109
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 {
5117 if (!zero)
5118 zero = arith::ConstantOp::create(rewriter, loc,
5119 rewriter.getZeroAttr(indexType));
5120 return zero.value();
5121 };
5122
5123 // Replace all indices corresponding to unit-extent basis with 0.
5124 // Remaining basis can be used to get a new `affine.delinearize_index` op.
5125 SmallVector<OpFoldResult> newBasis;
5126 for (auto [index, basis] :
5127 llvm::enumerate(delinearizeOp.getPaddedBasis())) {
5128 std::optional<int64_t> basisVal =
5129 basis ? getConstantIntValue(basis) : std::nullopt;
5130 if (basisVal == 1)
5131 replacements[index] = getZero();
5132 else
5133 newBasis.push_back(basis);
5134 }
5135
5136 if (newBasis.size() == delinearizeOp.getNumResults())
5137 return rewriter.notifyMatchFailure(delinearizeOp,
5138 "no unit basis elements");
5139
5140 if (!newBasis.empty()) {
5141 // Will drop the leading nullptr from `basis` if there was no outer bound.
5142 auto newDelinearizeOp = affine::AffineDelinearizeIndexOp::create(
5143 rewriter, loc, delinearizeOp.getLinearIndex(), newBasis);
5144 int newIndex = 0;
5145 // Map back the new delinearized indices to the values they replace.
5146 for (auto &replacement : replacements) {
5147 if (replacement)
5148 continue;
5149 replacement = newDelinearizeOp->getResult(newIndex++);
5150 }
5151 }
5152
5153 rewriter.replaceOp(delinearizeOp, replacements);
5154 return success();
5155 }
5156};
5157
5158/// If a `affine.delinearize_index`'s input is a `affine.linearize_index
5159/// disjoint` and the two operations end with the same basis elements,
5160/// cancel those parts of the operations out because they are inverses
5161/// of each other.
5162///
5163/// If the operations have the same basis, cancel them entirely.
5164///
5165/// The `disjoint` flag is needed on the `affine.linearize_index` because
5166/// otherwise, there is no guarantee that the inputs to the linearization are
5167/// in-bounds the way the outputs of the delinearization would be.
5168struct CancelDelinearizeOfLinearizeDisjointExactTail
5169 : public OpRewritePattern<affine::AffineDelinearizeIndexOp> {
5170 using Base::Base;
5171
5172 LogicalResult matchAndRewrite(affine::AffineDelinearizeIndexOp delinearizeOp,
5173 PatternRewriter &rewriter) const override {
5174 auto linearizeOp = delinearizeOp.getLinearIndex()
5175 .getDefiningOp<affine::AffineLinearizeIndexOp>();
5176 if (!linearizeOp)
5177 return rewriter.notifyMatchFailure(delinearizeOp,
5178 "index doesn't come from linearize");
5179
5180 if (!linearizeOp.getDisjoint())
5181 return rewriter.notifyMatchFailure(linearizeOp, "not disjoint");
5182
5183 ValueRange linearizeIns = linearizeOp.getMultiIndex();
5184 // Note: we use the full basis so we don't lose outer bounds later.
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)
5191 break;
5192 ++numMatches;
5193 }
5194
5195 if (numMatches == 0)
5196 return rewriter.notifyMatchFailure(
5197 delinearizeOp, "final basis element doesn't match linearize");
5198
5199 // The easy case: everything lines up and the basis match sup completely.
5200 if (numMatches == linearizeBasis.size() &&
5201 numMatches == delinearizeBasis.size() &&
5202 linearizeIns.size() == delinearizeOp.getNumResults()) {
5203 rewriter.replaceOp(delinearizeOp, linearizeOp.getMultiIndex());
5204 return success();
5205 }
5206
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);
5219 return success();
5220 }
5221};
5222
5223/// If the input to a delinearization is a disjoint linearization, and the
5224/// last k > 1 components of the delinearization basis multiply to the
5225/// last component of the linearization basis, break the linearization and
5226/// delinearization into two parts, peeling off the last input to linearization.
5227/// The split does not apply when it would consume an entire outer-bounded
5228/// delinearization basis because earlier linearization inputs still contribute
5229/// to the first delinearized result.
5230///
5231/// For example:
5232/// %0 = affine.linearize_index [%z, %y, %x] by (3, 2, 32) : index
5233/// %1:4 = affine.delinearize_index %0 by (2, 3, 8, 4) : index, ...
5234/// becomes
5235/// %0 = affine.linearize_index [%z, %y] by (3, 2) : index
5236/// %1:2 = affine.delinearize_index %0 by (2, 3) : index
5237/// %2:2 = affine.delinearize_index %x by (8, 4) : index
5238/// where the original %1:4 is replaced by %1:2 ++ %2:2
5239struct SplitDelinearizeSpanningLastLinearizeArg final
5240 : OpRewritePattern<affine::AffineDelinearizeIndexOp> {
5241 using Base::Base;
5242
5243 LogicalResult matchAndRewrite(affine::AffineDelinearizeIndexOp delinearizeOp,
5244 PatternRewriter &rewriter) const override {
5245 auto linearizeOp = delinearizeOp.getLinearIndex()
5246 .getDefiningOp<affine::AffineLinearizeIndexOp>();
5247 if (!linearizeOp)
5248 return rewriter.notifyMatchFailure(delinearizeOp,
5249 "index doesn't come from linearize");
5250
5251 if (!linearizeOp.getDisjoint())
5252 return rewriter.notifyMatchFailure(linearizeOp,
5253 "linearize isn't disjoint");
5254
5255 // A linearize with no inputs has an empty basis and folds to a constant
5256 // zero; there is nothing to split, and reading its last basis element
5257 // below would be out of bounds.
5258 if (linearizeOp.getStaticBasis().empty())
5259 return rewriter.notifyMatchFailure(
5260 linearizeOp, "linearize has no basis elements (no inputs)");
5261
5262 int64_t target = linearizeOp.getStaticBasis().back();
5263 if (ShapedType::isDynamic(target))
5264 return rewriter.notifyMatchFailure(
5265 linearizeOp, "linearize ends with dynamic basis value");
5266
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))
5272 return rewriter.notifyMatchFailure(
5273 delinearizeOp, "dynamic basis element while scanning for split");
5274 sizeToSplit *= basisElem;
5275 elemsToSplit += 1;
5276
5277 if (sizeToSplit > target)
5278 return rewriter.notifyMatchFailure(delinearizeOp,
5279 "overshot last argument size");
5280 if (sizeToSplit == target)
5281 break;
5282 }
5283
5284 if (sizeToSplit < target)
5285 return rewriter.notifyMatchFailure(
5286 delinearizeOp, "product of known basis elements doesn't exceed last "
5287 "linearize argument");
5288
5289 if (elemsToSplit < 2)
5290 return rewriter.notifyMatchFailure(
5291 delinearizeOp,
5292 "need at least two elements to form the basis product");
5293
5294 if (elemsToSplit == basis.size() && delinearizeOp.hasOuterBound())
5295 return rewriter.notifyMatchFailure(
5296 delinearizeOp, "split would consume entire bounded basis");
5297
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), /*hasOuterBound=*/true);
5309 SmallVector<Value> results = llvm::to_vector(
5310 llvm::concat<Value>(delinearizeWithoutSplitPart.getResults(),
5311 delinearizeBack.getResults()));
5312 rewriter.replaceOp(delinearizeOp, results);
5313
5314 return success();
5315 }
5316};
5317} // namespace
5318
5319void affine::AffineDelinearizeIndexOp::getCanonicalizationPatterns(
5320 RewritePatternSet &patterns, MLIRContext *context) {
5321 patterns
5322 .insert<CancelDelinearizeOfLinearizeDisjointExactTail,
5323 DropUnitExtentBasis, SplitDelinearizeSpanningLastLinearizeArg>(
5324 context);
5325}
5326
5327//===----------------------------------------------------------------------===//
5328// LinearizeIndexOp
5329//===----------------------------------------------------------------------===//
5330
5331/// Infer the index type from a set of multi-index values. Returns the common
5332/// type (index or vector<...xindex>), or IndexType if the set is empty.
5333static Type inferIndexType(MLIRContext *ctx, ValueRange multiIndex) {
5334 if (multiIndex.empty())
5335 return IndexType::get(ctx);
5336 return multiIndex.front().getType();
5337}
5338
5339void AffineLinearizeIndexOp::build(OpBuilder &odsBuilder,
5340 OperationState &odsState,
5341 ValueRange multiIndex, ValueRange basis,
5342 bool disjoint) {
5343 if (!basis.empty() && basis.front() == Value())
5344 basis = basis.drop_front();
5345 SmallVector<Value> dynamicBasis;
5346 SmallVector<int64_t> staticBasis;
5347 dispatchIndexOpFoldResults(getAsOpFoldResult(basis), dynamicBasis,
5348 staticBasis);
5349 Type resultType = inferIndexType(odsBuilder.getContext(), multiIndex);
5350 build(odsBuilder, odsState, resultType, multiIndex, dynamicBasis, staticBasis,
5351 disjoint);
5352}
5353
5354void AffineLinearizeIndexOp::build(OpBuilder &odsBuilder,
5355 OperationState &odsState,
5356 ValueRange multiIndex,
5357 ArrayRef<OpFoldResult> basis,
5358 bool disjoint) {
5359 if (!basis.empty() && basis.front() == OpFoldResult())
5360 basis = basis.drop_front();
5361 SmallVector<Value> dynamicBasis;
5362 SmallVector<int64_t> staticBasis;
5363 dispatchIndexOpFoldResults(basis, dynamicBasis, staticBasis);
5364 Type resultType = inferIndexType(odsBuilder.getContext(), multiIndex);
5365 build(odsBuilder, odsState, resultType, multiIndex, dynamicBasis, staticBasis,
5366 disjoint);
5367}
5368
5369void AffineLinearizeIndexOp::build(OpBuilder &odsBuilder,
5370 OperationState &odsState,
5371 ValueRange multiIndex,
5372 ArrayRef<int64_t> basis, bool disjoint) {
5373 Type resultType = inferIndexType(odsBuilder.getContext(), multiIndex);
5374 build(odsBuilder, odsState, resultType, multiIndex, ValueRange{}, basis,
5375 disjoint);
5376}
5377
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");
5384
5385 auto dynamicMarkersCount =
5386 llvm::count_if(getStaticBasis(), ShapedType::isDynamic);
5387 if (static_cast<size_t>(dynamicMarkersCount) != getDynamicBasis().size())
5388 return emitOpError(
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");
5392
5393 return success();
5394}
5395
5396OpFoldResult AffineLinearizeIndexOp::fold(FoldAdaptor adaptor) {
5397 std::optional<SmallVector<int64_t>> maybeStaticBasis =
5398 foldCstValueToCstAttrBasis(getMixedBasis(), getDynamicBasisMutable(),
5399 adaptor.getDynamicBasis());
5400 if (maybeStaticBasis) {
5401 setStaticBasis(*maybeStaticBasis);
5402 return getResult();
5403 }
5404 // No indices linearizes to zero.
5405 if (getMultiIndex().empty())
5406 return IntegerAttr::get(getResult().getType(), 0);
5407
5408 // One single index linearizes to itself.
5409 if (getMultiIndex().size() == 1)
5410 return getMultiIndex().front();
5411
5412 // Return nullptr if any multi-index attribute has not been folded to a
5413 // concrete integer (e.g. it is still a runtime value or has folded to a
5414 // non-integer attribute such as #ub.poison).
5415 if (llvm::any_of(adaptor.getMultiIndex(), [](Attribute a) {
5416 return !isa_and_nonnull<IntegerAttr>(a);
5417 }))
5418 return nullptr;
5419
5420 if (!adaptor.getDynamicBasis().empty())
5421 return nullptr;
5422
5423 int64_t result = 0;
5424 int64_t stride = 1;
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;
5430 }
5431 // Handle the index element with no basis element.
5432 if (!hasOuterBound())
5433 result =
5434 result +
5435 cast<IntegerAttr>(adaptor.getMultiIndex().front()).getInt() * stride;
5436
5437 return IntegerAttr::get(getResult().getType(), result);
5438}
5439
5440SmallVector<OpFoldResult> AffineLinearizeIndexOp::getEffectiveBasis() {
5441 OpBuilder builder(getContext());
5442 if (hasOuterBound()) {
5443 if (getStaticBasis().front() == ::mlir::ShapedType::kDynamic)
5444 return getMixedValues(getStaticBasis().drop_front(),
5445 getDynamicBasis().drop_front(), builder);
5446
5447 return getMixedValues(getStaticBasis().drop_front(), getDynamicBasis(),
5448 builder);
5449 }
5450
5451 return getMixedValues(getStaticBasis(), getDynamicBasis(), builder);
5452}
5453
5454SmallVector<OpFoldResult> AffineLinearizeIndexOp::getPaddedBasis() {
5455 SmallVector<OpFoldResult> ret = getMixedBasis();
5456 if (!hasOuterBound())
5457 ret.insert(ret.begin(), OpFoldResult());
5458 return ret;
5459}
5460
5461namespace {
5462/// Rewrite `affine.linearize_index disjoint [%...a, %x, %...b] by (%...c, 1,
5463/// %...d)` to `affine.linearize_index disjoint [%...a, %...b] by (%...c,
5464/// %...d)`.
5465
5466/// Note that `disjoint` is required here, because, without it, we could have
5467/// `affine.linearize_index [%...a, %c64, %...b] by (%...c, 1, %...d)`
5468/// is a valid operation where the `%c64` cannot be trivially dropped.
5469///
5470/// Alternatively, if `%x` in the above is a known constant 0, remove it even if
5471/// the operation isn't asserted to be `disjoint`.
5472struct DropLinearizeUnitComponentsIfDisjointOrZero final
5473 : OpRewritePattern<affine::AffineLinearizeIndexOp> {
5474 using Base::Base;
5475
5476 LogicalResult matchAndRewrite(affine::AffineLinearizeIndexOp op,
5477 PatternRewriter &rewriter) const override {
5478 ValueRange multiIndex = op.getMultiIndex();
5479 size_t numIndices = multiIndex.size();
5480 SmallVector<Value> newIndices;
5481 newIndices.reserve(numIndices);
5482 SmallVector<OpFoldResult> newBasis;
5483 newBasis.reserve(numIndices);
5484
5485 if (!op.hasOuterBound()) {
5486 newIndices.push_back(multiIndex.front());
5487 multiIndex = multiIndex.drop_front();
5488 }
5489
5490 SmallVector<OpFoldResult> basis = op.getMixedBasis();
5491 for (auto [index, basisElem] : llvm::zip_equal(multiIndex, basis)) {
5492 std::optional<int64_t> basisEntry = getConstantIntValue(basisElem);
5493 if (!basisEntry || *basisEntry != 1) {
5494 newIndices.push_back(index);
5495 newBasis.push_back(basisElem);
5496 continue;
5497 }
5498
5499 std::optional<int64_t> indexValue = getConstantIntValue(index);
5500 if (!op.getDisjoint() && (!indexValue || *indexValue != 0)) {
5501 newIndices.push_back(index);
5502 newBasis.push_back(basisElem);
5503 continue;
5504 }
5505 }
5506 if (newIndices.size() == numIndices)
5507 return rewriter.notifyMatchFailure(op,
5508 "no unit basis entries to replace");
5509
5510 if (newIndices.empty()) {
5511 rewriter.replaceOpWithNewOp<arith::ConstantOp>(
5512 op, rewriter.getZeroAttr(op.getLinearIndex().getType()));
5513 return success();
5514 }
5515 rewriter.replaceOpWithNewOp<affine::AffineLinearizeIndexOp>(
5516 op, newIndices, newBasis, op.getDisjoint());
5517 return success();
5518 }
5519};
5520
5521OpFoldResult computeProduct(Location loc, OpBuilder &builder,
5522 ArrayRef<OpFoldResult> terms) {
5523 int64_t nDynamic = 0;
5524 SmallVector<Value> dynamicPart;
5525 AffineExpr result = builder.getAffineConstantExpr(1);
5526 for (OpFoldResult term : terms) {
5527 if (!term)
5528 return term;
5529 std::optional<int64_t> maybeConst = getConstantIntValue(term);
5530 if (maybeConst) {
5531 result = result * builder.getAffineConstantExpr(*maybeConst);
5532 } else {
5533 dynamicPart.push_back(cast<Value>(term));
5534 result = result * builder.getAffineSymbolExpr(nDynamic++);
5535 }
5536 }
5537 if (auto constant = dyn_cast<AffineConstantExpr>(result))
5538 return getAsIndexOpFoldResult(builder.getContext(), constant.getValue());
5539 return AffineApplyOp::create(builder, loc, result, dynamicPart).getResult();
5540}
5541
5542/// If conseceutive outputs of a delinearize_index are linearized with the same
5543/// bounds, canonicalize away the redundant arithmetic.
5544///
5545/// That is, if we have
5546/// ```
5547/// %s:N = affine.delinearize_index %x into (...a, B1, B2, ... BK, ...b)
5548/// %t = affine.linearize_index [...c, %s#I, %s#(I + 1), ... %s#(I+K-1), ...d]
5549/// by (...e, B1, B2, ..., BK, ...f)
5550/// ```
5551///
5552/// We can rewrite this to
5553/// ```
5554/// B = B1 * B2 ... BK
5555/// %sMerged:(N-K+1) affine.delinearize_index %x into (...a, B, ...b)
5556/// %t = affine.linearize_index [...c, %s#I, ...d] by (...e, B, ...f)
5557/// ```
5558/// where we replace all results of %s unaffected by the change with results
5559/// from %sMerged.
5560///
5561/// As a special case, if all results of the delinearize are merged in this way
5562/// we can replace those usages with %x, thus cancelling the delinearization
5563/// entirely, as in
5564/// ```
5565/// %s:3 = affine.delinearize_index %x into (2, 4, 8)
5566/// %t = affine.linearize_index [%s#0, %s#1, %s#2, %c0] by (2, 4, 8, 16)
5567/// ```
5568/// becoming `%t = affine.linearize_index [%x, %c0] by (64, 16)`
5569struct CancelLinearizeOfDelinearizePortion final
5570 : OpRewritePattern<affine::AffineLinearizeIndexOp> {
5571 using Base::Base;
5572
5573private:
5574 // Struct representing a case where the cancellation pattern
5575 // applies. A `Match` means that `length` inputs to the linearize operation
5576 // starting at `linStart` can be cancelled with `length` outputs of
5577 // `delinearize`, starting from `delinStart`.
5578 struct Match {
5579 AffineDelinearizeIndexOp delinearize;
5580 unsigned linStart = 0;
5581 unsigned delinStart = 0;
5582 unsigned length = 0;
5583 };
5584
5585public:
5586 LogicalResult matchAndRewrite(affine::AffineLinearizeIndexOp linearizeOp,
5587 PatternRewriter &rewriter) const override {
5588 SmallVector<Match> matches;
5589
5590 const SmallVector<OpFoldResult> linBasis = linearizeOp.getPaddedBasis();
5591 ArrayRef<OpFoldResult> linBasisRef = linBasis;
5592
5593 ValueRange multiIndex = linearizeOp.getMultiIndex();
5594 unsigned numLinArgs = multiIndex.size();
5595 unsigned linArgIdx = 0;
5596 // We only want to replace one run from the same delinearize op per
5597 // pattern invocation lest we run into invalidation issues.
5598 llvm::SmallPtrSet<Operation *, 2> alreadyMatchedDelinearize;
5599 while (linArgIdx < numLinArgs) {
5600 auto asResult = dyn_cast<OpResult>(multiIndex[linArgIdx]);
5601 if (!asResult) {
5602 linArgIdx++;
5603 continue;
5604 }
5605
5606 auto delinearizeOp =
5607 dyn_cast<AffineDelinearizeIndexOp>(asResult.getOwner());
5608 if (!delinearizeOp) {
5609 linArgIdx++;
5610 continue;
5611 }
5612
5613 /// Result 0 of the delinearize and argument 0 of the linearize can
5614 /// leave their maximum value unspecified. However, even if this happens
5615 /// we can still sometimes start the match process. Specifically, if
5616 /// - The argument we're matching is result 0 and argument 0 (so the
5617 /// bounds don't matter). For example,
5618 ///
5619 /// %0:2 = affine.delinearize_index %x into (8) : index, index
5620 /// %1 = affine.linearize_index [%s#0, %s#1, ...] (8, ...)
5621 /// allows cancellation
5622 /// - The delinearization doesn't specify a bound, but the linearization
5623 /// is `disjoint`, which asserts that the bound on the linearization is
5624 /// correct.
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) {
5634 linArgIdx++;
5635 continue;
5636 }
5637
5638 unsigned j = 1;
5639 unsigned numDelinOuts = delinearizeOp.getNumResults();
5640 for (; j + linArgIdx < numLinArgs && j + delinArgIdx < numDelinOuts;
5641 ++j) {
5642 if (multiIndex[linArgIdx + j] !=
5643 delinearizeOp.getResult(delinArgIdx + j))
5644 break;
5645 if (linBasis[linArgIdx + j] != delinBasis[delinArgIdx + j])
5646 break;
5647 }
5648 // If there're multiple matches against the same delinearize_index,
5649 // only rewrite the first one we find to prevent invalidations. The next
5650 // ones will be taken care of by subsequent pattern invocations.
5651 if (j <= 1 || !alreadyMatchedDelinearize.insert(delinearizeOp).second) {
5652 linArgIdx++;
5653 continue;
5654 }
5655 matches.push_back(Match{delinearizeOp, linArgIdx, delinArgIdx, j});
5656 linArgIdx += j;
5657 }
5658
5659 if (matches.empty())
5660 return rewriter.notifyMatchFailure(
5661 linearizeOp, "no run of delinearize outputs to deal with");
5662
5663 // Record all the delinearize replacements so we can do them after creating
5664 // the new linearization operation, since the new operation might use
5665 // outputs of something we're replacing.
5666 SmallVector<SmallVector<Value>> delinearizeReplacements;
5667
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));
5677 // Update here so we don't forget this during early continues
5678 prevMatchEnd = m.linStart + m.length;
5679
5680 PatternRewriter::InsertionGuard g(rewriter);
5681 rewriter.setInsertionPoint(m.delinearize);
5682
5683 ArrayRef<OpFoldResult> basisToMerge =
5684 linBasisRef.slice(m.linStart, m.length);
5685 // We use the slice from the linearize's basis above because of the
5686 // "bounds inferred from `disjoint`" case above.
5687 OpFoldResult newSize =
5688 computeProduct(linearizeOp.getLoc(), rewriter, basisToMerge);
5689
5690 // Trivial case where we can just skip past the delinearize all together
5691 if (m.length == m.delinearize.getNumResults()) {
5692 newIndex.push_back(m.delinearize.getLinearIndex());
5693 newBasis.push_back(newSize);
5694 // Pad out set of replacements so we don't do anything with this one.
5695 delinearizeReplacements.push_back(SmallVector<Value>());
5696 continue;
5697 }
5698
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(),
5706 newDelinBasis);
5707
5708 // Since there may be other uses of the indices we just merged together,
5709 // create a residual affine.delinearize_index that delinearizes the
5710 // merged output into its component parts.
5711 Value combinedElem = newDelinearize.getResult(m.delinStart);
5712 auto residualDelinearize = AffineDelinearizeIndexOp::create(
5713 rewriter, m.delinearize.getLoc(), combinedElem, basisToMerge);
5714
5715 // Swap all the uses of the unaffected delinearize outputs to the new
5716 // delinearization so that the old code can be removed if this
5717 // linearize_index is the only user of the merged results.
5718 llvm::append_range(newDelinResults,
5719 newDelinearize.getResults().take_front(m.delinStart));
5720 llvm::append_range(newDelinResults, residualDelinearize.getResults());
5721 llvm::append_range(
5722 newDelinResults,
5723 newDelinearize.getResults().drop_front(m.delinStart + 1));
5724
5725 delinearizeReplacements.push_back(newDelinResults);
5726 newIndex.push_back(combinedElem);
5727 newBasis.push_back(newSize);
5728 }
5729 llvm::append_range(newIndex, multiIndex.drop_front(prevMatchEnd));
5730 llvm::append_range(newBasis, linBasisRef.drop_front(prevMatchEnd));
5731 rewriter.replaceOpWithNewOp<AffineLinearizeIndexOp>(
5732 linearizeOp, newIndex, newBasis, linearizeOp.getDisjoint());
5733
5734 for (auto [m, newResults] :
5735 llvm::zip_equal(matches, delinearizeReplacements)) {
5736 if (newResults.empty())
5737 continue;
5738 rewriter.replaceOp(m.delinearize, newResults);
5739 }
5740
5741 return success();
5742 }
5743};
5744
5745/// Strip leading zero from affine.linearize_index.
5746///
5747/// `affine.linearize_index [%c0, ...a] by (%x, ...b)` can be rewritten
5748/// to `affine.linearize_index [...a] by (...b)` in all cases.
5749struct DropLinearizeLeadingZero final
5750 : OpRewritePattern<affine::AffineLinearizeIndexOp> {
5751 using Base::Base;
5752
5753 LogicalResult matchAndRewrite(affine::AffineLinearizeIndexOp op,
5754 PatternRewriter &rewriter) const override {
5755 Value leadingIdx = op.getMultiIndex().front();
5756 if (!matchPattern(leadingIdx, m_Zero()))
5757 return failure();
5758
5759 if (op.getMultiIndex().size() == 1) {
5760 rewriter.replaceOp(op, leadingIdx);
5761 return success();
5762 }
5763
5764 SmallVector<OpFoldResult> mixedBasis = op.getMixedBasis();
5765 ArrayRef<OpFoldResult> newMixedBasis = mixedBasis;
5766 if (op.hasOuterBound())
5767 newMixedBasis = newMixedBasis.drop_front();
5768
5769 rewriter.replaceOpWithNewOp<affine::AffineLinearizeIndexOp>(
5770 op, op.getMultiIndex().drop_front(), newMixedBasis, op.getDisjoint());
5771 return success();
5772 }
5773};
5774} // namespace
5775
5776void affine::AffineLinearizeIndexOp::getCanonicalizationPatterns(
5777 RewritePatternSet &patterns, MLIRContext *context) {
5778 patterns.add<CancelLinearizeOfDelinearizePortion, DropLinearizeLeadingZero,
5779 DropLinearizeUnitComponentsIfDisjointOrZero>(context);
5780}
5781
5782//===----------------------------------------------------------------------===//
5783// TableGen'd op method definitions
5784//===----------------------------------------------------------------------===//
5785
5786#define GET_OP_CLASSES
5787#include "mlir/Dialect/Affine/IR/AffineOps.cpp.inc"
return success()
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...
Definition AffineOps.cpp:62
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 &quotientTimesDiv, 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.
b
Return true if permutation is a valid permutation of the outer_dims_perm (case OuterOrInnerPerm::Oute...
b getI64ArrayAttr(paddingDimensions)
b getContext())
auto load
*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)
Definition SCFToGPU.cpp:75
static Operation::operand_range getUpperBoundOperands(AffineForOp forOp)
Definition SCFToGPU.cpp:80
static VectorType getVectorType(Type scalarTy, const VectorizationStrategy *strategy)
Returns the vector type resulting from applying the provided vectorization strategy on the scalar typ...
#define div(a, b)
#define rem(a, b)
RetTy walkPostOrder(AffineExpr expr)
Base type for affine expression.
Definition AffineExpr.h:68
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.
Definition AffineMap.h:46
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.
Definition AffineMap.h:223
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).
Definition AffineMap.h:269
unsigned getNumSymbols() const
unsigned getNumDims() const
ArrayRef< AffineExpr > getResults() const
bool isFunctionOfSymbol(unsigned position) const
Return true if any affine expression involves AffineSymbolExpr position.
Definition AffineMap.h:230
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).
Definition AffineMap.h:282
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.
Definition Attributes.h:25
This class represents an argument of a Block.
Definition Value.h:308
Block represents an ordered list of Operations.
Definition Block.h:34
Operation & front()
Definition Block.h:178
Operation * getTerminator()
Get the terminator operation of this block.
Definition Block.cpp:249
BlockArgument addArgument(Type type, Location loc)
Add one value to the argument list.
Definition Block.cpp:158
BlockArgListType getArguments()
Definition Block.h:112
DenseI32ArrayAttr getDenseI32ArrayAttr(ArrayRef< int32_t > values)
Definition Builders.cpp:171
IntegerAttr getIntegerAttr(Type type, int64_t value)
Definition Builders.cpp:237
AffineMap getDimIdentityMap()
Definition Builders.cpp:392
AffineMap getMultiDimIdentityMap(unsigned rank)
Definition Builders.cpp:396
AffineExpr getAffineSymbolExpr(unsigned position)
Definition Builders.cpp:377
AffineExpr getAffineConstantExpr(int64_t constant)
Definition Builders.cpp:381
DenseIntElementsAttr getI32TensorAttr(ArrayRef< int32_t > values)
Tensor-typed DenseIntElementsAttr getters.
Definition Builders.cpp:187
IntegerAttr getI64IntegerAttr(int64_t value)
Definition Builders.cpp:120
IntegerType getIntegerType(unsigned width)
Definition Builders.cpp:75
NoneType getNoneType()
Definition Builders.cpp:96
BoolAttr getBoolAttr(bool value)
Definition Builders.cpp:108
AffineMap getEmptyAffineMap()
Returns a zero result affine map with no dimensions or symbols: () -> ().
Definition Builders.cpp:385
TypedAttr getZeroAttr(Type type)
Definition Builders.cpp:333
AffineMap getConstantAffineMap(int64_t val)
Returns a single constant result affine map with 0 dimensions and 0 symbols.
Definition Builders.cpp:387
AffineMap getSymbolIdentityMap()
Definition Builders.cpp:405
ArrayAttr getArrayAttr(ArrayRef< Attribute > value)
Definition Builders.cpp:275
MLIRContext * getContext() const
Definition Builders.h:56
ArrayAttr getI64ArrayAttr(ArrayRef< int64_t > values)
Definition Builders.cpp:290
IndexType getIndexType()
Definition Builders.cpp:59
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.
Definition IRMapping.h:26
auto lookup(T from) const
Lookup a mapped value within the map.
Definition IRMapping.h:72
An integer set representing a conjunction of one or more affine equalities and inequalities.
Definition IntegerSet.h:44
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...
Definition Location.h:76
MLIRContext is the top-level object for a collection of MLIR operations.
Definition MLIRContext.h:71
This class provides a mutable adaptor for a range of operands.
Definition ValueRange.h:119
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 &region, 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.
Definition Builders.h:351
This class helps build Operations.
Definition Builders.h:210
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.
Definition Builders.cpp:439
void setInsertionPointToStart(Block *block)
Sets the insertion point to the start of the specified block.
Definition Builders.h:434
void setInsertionPoint(Block *block, Block::iterator insertPoint)
Set the insertion point to the specified location.
Definition Builders.h:401
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.
Definition ValueRange.h:44
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
bool hasTrait()
Returns true if the operation was registered with a particular trait, e.g.
Definition Operation.h:803
Operation * getParentOp()
Returns the closest surrounding operation that contains this operation or nullptr if this is a top-le...
Definition Operation.h:251
OperandRange operand_range
Definition Operation.h:398
operand_range getOperands()
Returns an iterator on the underlying Value's.
Definition Operation.h:405
Region * getParentRegion()
Returns the region to which the instruction belongs.
Definition Operation.h:247
operand_range::iterator operand_iterator
Definition Operation.h:399
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.
Definition Region.h:26
Block & front()
Definition Region.h:65
bool empty()
Definition Region.h:60
Operation * getParentOp()
Return the parent operation this region is attached to.
Definition Region.h:198
bool hasOneBlock()
Return true if this region has exactly one block.
Definition Region.h:68
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.
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.
Definition TypeRange.h:40
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
bool isIndex() const
Definition Types.cpp:56
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.
Definition ValueRange.h:392
type_range getType() const
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
Type getType() const
Return the type of this value.
Definition Value.h:105
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
Definition Value.cpp:18
Region * getParentRegion()
Return the Region in which this Value is defined.
Definition Value.cpp:39
AffineBound represents a lower or upper bound in the for operation.
Definition AffineOps.h:216
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)
void reset(AffineMap map, ValueRange operands, ValueRange results={})
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.
Definition UseDefLists.h:38
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".
Definition MemRefOps.cpp:48
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:886
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.
Definition Matchers.h:490
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.
Definition Utils.cpp:311
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.
AffineExprKind
Definition AffineExpr.h:40
@ CeilDiv
RHS of ceildiv is always a constant or a symbolic expression.
Definition AffineExpr.h:50
@ Mod
RHS of mod is always a constant or a symbolic expression with a positive value.
Definition AffineExpr.h:46
@ DimId
Dimensional identifier.
Definition AffineExpr.h:59
@ FloorDiv
RHS of floordiv is always a constant or a symbolic expression.
Definition AffineExpr.h:48
@ SymbolId
Symbolic identifier.
Definition AffineExpr.h:61
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.
Definition Matchers.h:442
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
Definition LLVM.h:147
AffineExpr getAffineConstantExpr(int64_t constant, MLIRContext *context)
llvm::DenseMap< KeyT, ValueT, KeyInfoT, BucketT > DenseMap
Definition LLVM.h:123
OpFoldResult getAsOpFoldResult(Value val)
Given a value, try to extract a constant Attribute.
detail::constant_op_matcher m_Constant()
Matches a constant foldable operation.
Definition Matchers.h:369
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
Definition LLVM.h:155
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.
Definition Builders.h:288
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.