MLIR 24.0.0git
BufferizationOps.cpp
Go to the documentation of this file.
1//===----------------------------------------------------------------------===//
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
16#include "mlir/IR/Matchers.h"
17#include "llvm/ADT/SmallVectorExtras.h"
18#include <optional>
19
20using namespace mlir;
21using namespace mlir::bufferization;
22
23//===----------------------------------------------------------------------===//
24// Helper functions
25//===----------------------------------------------------------------------===//
26
28 OpBuilder &b, Value value, MemRefType destType,
30 auto srcType = llvm::cast<MemRefType>(value.getType());
31
32 // Element type and rank must match.
33 if (srcType.getElementType() != destType.getElementType())
34 return failure();
35 if (srcType.getRank() != destType.getRank())
36 return failure();
37
38 // In case the affine maps are different, we may need to use a copy if we go
39 // from dynamic to static offset or stride (the canonicalization cannot know
40 // at this point that it is really cast compatible).
41 auto isGuaranteedCastCompatible = [](MemRefType source, MemRefType target) {
42 int64_t sourceOffset, targetOffset;
43 SmallVector<int64_t, 4> sourceStrides, targetStrides;
44 if (failed(source.getStridesAndOffset(sourceStrides, sourceOffset)) ||
45 failed(target.getStridesAndOffset(targetStrides, targetOffset)))
46 return false;
47 auto dynamicToStatic = [](int64_t a, int64_t b) {
48 return ShapedType::isDynamic(a) && ShapedType::isStatic(b);
49 };
50 if (dynamicToStatic(sourceOffset, targetOffset))
51 return false;
52 for (auto it : zip(sourceStrides, targetStrides))
53 if (dynamicToStatic(std::get<0>(it), std::get<1>(it)))
54 return false;
55 // A cast cannot safely zero out a non-zero offset. If the source has a
56 // non-identity layout (e.g., a subview with a dynamic offset) and the
57 // destination requires identity layout (zero offset, unit strides), a cast
58 // would silently strip the offset and cause incorrect loads in the callee.
59 // Fall through to the alloc+copy path instead.
60 if (!source.getLayout().isIdentity() && target.getLayout().isIdentity())
61 return false;
62 return true;
63 };
64
65 // Note: If `areCastCompatible`, a cast is valid, but may fail at runtime. To
66 // ensure that we only generate casts that always succeed at runtime, we check
67 // a few extra conditions in `isGuaranteedCastCompatible`.
68 if (memref::CastOp::areCastCompatible(srcType, destType) &&
69 isGuaranteedCastCompatible(srcType, destType))
70 return options.castFn(b, value.getLoc(), destType, value);
71
72 auto loc = value.getLoc();
73 SmallVector<Value, 4> dynamicOperands;
74 for (int i = 0; i < destType.getRank(); ++i) {
75 if (destType.getShape()[i] != ShapedType::kDynamic)
76 continue;
77 Value size = memref::DimOp::create(b, loc, value, i);
78 dynamicOperands.push_back(size);
79 }
80
81 FailureOr<Value> copy = options.allocationFn(
82 b, loc, destType, dynamicOperands, options.bufferAlignment);
83 if (failed(copy))
84 return failure();
85 if (failed(options.memCpyFn(b, loc, value, *copy)))
86 return failure();
87 return copy;
88}
89
90/// Try to fold to_buffer(to_tensor(x)). If x's type and the result type of the
91/// to_buffer op are different, a memref.cast is needed.
93 RewriterBase &rewriter, ToBufferOp toBuffer,
95 auto bufferToTensor = toBuffer.getTensor().getDefiningOp<ToTensorOp>();
96 if (!bufferToTensor)
97 return failure();
98
99 Type srcType = bufferToTensor.getBuffer().getType();
100 Type destType = toBuffer.getType();
101
102 // Directly rewrite if the type did not change.
103 if (srcType == destType) {
104 rewriter.replaceOp(toBuffer, bufferToTensor.getBuffer());
105 return success();
106 }
107
108 if (!llvm::isa<BaseMemRefType>(srcType) ||
109 !llvm::isa<BaseMemRefType>(destType)) {
110 // Non-builtin case: the best is to try the user-provided cast.
111 auto replacement =
112 options.castFn(rewriter, bufferToTensor.getBuffer().getLoc(), destType,
113 bufferToTensor.getBuffer());
114 if (failed(replacement))
115 return failure();
116 rewriter.replaceOp(toBuffer, *replacement);
117 return success();
118 }
119
120 auto rankedSrcType = llvm::dyn_cast<MemRefType>(srcType);
121 auto rankedDestType = llvm::dyn_cast<MemRefType>(destType);
122 auto unrankedSrcType = llvm::dyn_cast<UnrankedMemRefType>(srcType);
123
124 // Ranked memref -> Ranked memref cast.
125 if (rankedSrcType && rankedDestType) {
126 FailureOr<Value> replacement = castOrReallocMemRefValue(
127 rewriter, bufferToTensor.getBuffer(), rankedDestType, options);
128 if (failed(replacement))
129 return failure();
130
131 rewriter.replaceOp(toBuffer, *replacement);
132 return success();
133 }
134
135 // Unranked memref -> Ranked memref cast: May require a copy.
136 // TODO: Not implemented at the moment.
137 if (unrankedSrcType && rankedDestType)
138 return failure();
139
140 // Unranked/ranked memref -> unranked memref cast: No copy needed if the types
141 // are cast-compatible.
142 if (!memref::CastOp::areCastCompatible(srcType, destType))
143 return failure();
144
145 rewriter.replaceOpWithNewOp<memref::CastOp>(toBuffer, destType,
146 bufferToTensor.getBuffer());
147 return success();
148}
149
151 OpBuilder &b, Location loc, Value shapedValue,
152 SmallVector<Value> &dynamicDims) {
153 auto shapedType = llvm::cast<ShapedType>(shapedValue.getType());
154 for (int64_t i = 0; i < shapedType.getRank(); ++i) {
155 if (shapedType.isDynamicDim(i)) {
156 if (llvm::isa<MemRefType>(shapedType)) {
157 dynamicDims.push_back(memref::DimOp::create(b, loc, shapedValue, i));
158 } else {
159 assert(llvm::isa<RankedTensorType>(shapedType) && "expected tensor");
160 dynamicDims.push_back(tensor::DimOp::create(b, loc, shapedValue, i));
161 }
162 }
163 }
164}
165
166//===----------------------------------------------------------------------===//
167// AllocTensorOp
168//===----------------------------------------------------------------------===//
169
170LogicalResult AllocTensorOp::verify() {
171 auto type = dyn_cast<RankedTensorType>(getType());
172 if (!type && (!getDynamicSizes().empty() || getSizeHint()))
173 return emitError("takes dynamic sizes and a size hint only for a ranked "
174 "tensor result");
175 if (getCopy() && !getDynamicSizes().empty())
176 return emitError("dynamic sizes not needed when copying a tensor");
177 if (type && !getCopy() &&
178 failed(
179 verifyDynamicDimensionCount(getOperation(), type, getDynamicSizes())))
180 return failure();
181 if (getCopy() && getCopy().getType() != getType())
182 return emitError("expected that `copy` and return type match");
183 return success();
184}
185
186void AllocTensorOp::build(OpBuilder &builder, OperationState &result,
187 RankedTensorType type, ValueRange dynamicSizes) {
188 build(builder, result, llvm::cast<TensorLikeType>(type), dynamicSizes,
189 /*copy=*/Value(),
190 /*size_hint=*/Value(),
191 /*memory_space=*/IntegerAttr());
192}
193
194void AllocTensorOp::build(OpBuilder &builder, OperationState &result,
195 RankedTensorType type, ValueRange dynamicSizes,
196 Value copy) {
197 build(builder, result, llvm::cast<TensorLikeType>(type), dynamicSizes, copy);
198}
199
200void AllocTensorOp::build(OpBuilder &builder, OperationState &result,
201 TensorType type, ValueRange dynamicSizes, Value copy,
202 IntegerAttr memorySpace) {
203 build(builder, result, llvm::cast<TensorLikeType>(type), dynamicSizes, copy,
204 /*size_hint=*/Value(), memorySpace);
205}
206
207void AllocTensorOp::build(OpBuilder &builder, OperationState &result,
208 TensorLikeType type, ValueRange dynamicSizes,
209 Value copy) {
210 build(builder, result, type, dynamicSizes, copy, /*size_hint=*/Value(),
211 /*memory_space=*/Attribute());
212}
213
214void AllocTensorOp::build(OpBuilder &builder, OperationState &result,
215 TensorLikeType type, ValueRange dynamicSizes,
216 Value copy, Value sizeHint, Attribute memorySpace) {
217 build(builder, result, Type(type), dynamicSizes, copy, sizeHint, memorySpace);
218}
219
220namespace {
221/// Change the type of the result of a `bufferization.alloc_tensor` by making
222/// the result type statically sized along dimension that in the original
223/// operation where defined as dynamic, but the size was defined using a
224/// `constant` op. For example:
225///
226/// %c5 = arith.constant 5: index
227/// %0 = bufferization.alloc_tensor(%arg0, %c5) : tensor<?x?xf32>
228///
229/// to
230///
231/// %0 = bufferization.alloc_tensor(%arg0) : tensor<?x5xf32>
232struct ReplaceStaticShapeDims : OpRewritePattern<AllocTensorOp> {
233 using OpRewritePattern<AllocTensorOp>::OpRewritePattern;
234
235 LogicalResult matchAndRewrite(AllocTensorOp op,
236 PatternRewriter &rewriter) const override {
237 // Dynamic sizes, and so this fold, belong to a ranked tensor result; any
238 // other result carries none (verifier).
239 auto type = dyn_cast<RankedTensorType>(op.getType());
240 if (!type || op.getCopy())
241 return failure();
242 SmallVector<int64_t> newShape = llvm::to_vector(type.getShape());
243 SmallVector<Value> newDynamicSizes;
244 unsigned int dynValCounter = 0;
245 for (int64_t i = 0; i < type.getRank(); ++i) {
246 if (!type.isDynamicDim(i))
247 continue;
248 Value value = op.getDynamicSizes()[dynValCounter++];
249 APInt intVal;
250 if (matchPattern(value, m_ConstantInt(&intVal))) {
251 int64_t dim = intVal.getSExtValue();
252 if (dim >= 0)
253 newShape[i] = intVal.getSExtValue();
254 else
255 newDynamicSizes.push_back(value);
256 } else {
257 newDynamicSizes.push_back(value);
258 }
259 }
260 RankedTensorType newType = RankedTensorType::get(
261 newShape, type.getElementType(), type.getEncoding());
262 if (newType == type)
263 return failure();
264 auto newOp = AllocTensorOp::create(rewriter, op.getLoc(), newType,
265 newDynamicSizes, /*copy=*/Value());
266 rewriter.replaceOpWithNewOp<tensor::CastOp>(op, type, newOp);
267 return success();
268 }
269};
270
271struct FoldDimOfAllocTensorOp : public OpRewritePattern<tensor::DimOp> {
272 using OpRewritePattern<tensor::DimOp>::OpRewritePattern;
273
274 LogicalResult matchAndRewrite(tensor::DimOp dimOp,
275 PatternRewriter &rewriter) const override {
276 std::optional<int64_t> maybeConstantIndex = dimOp.getConstantIndex();
277 auto allocTensorOp = dimOp.getSource().getDefiningOp<AllocTensorOp>();
278 if (!allocTensorOp || !maybeConstantIndex)
279 return failure();
280 // Only a ranked tensor result has dynamic sizes to forward; any other
281 // result carries none (verifier).
282 auto type = dyn_cast<RankedTensorType>(allocTensorOp.getType());
283 if (!type || *maybeConstantIndex < 0 ||
284 *maybeConstantIndex >= type.getRank())
285 return failure();
286 if (!type.isDynamicDim(*maybeConstantIndex))
287 return failure();
288 rewriter.replaceOp(
289 dimOp, allocTensorOp.getDynamicSize(rewriter, *maybeConstantIndex));
290 return success();
291 }
292};
293} // namespace
294
295void AllocTensorOp::getCanonicalizationPatterns(RewritePatternSet &results,
296 MLIRContext *ctx) {
297 results.add<FoldDimOfAllocTensorOp, ReplaceStaticShapeDims>(ctx);
298}
299
300LogicalResult AllocTensorOp::reifyResultShapes(
301 OpBuilder &builder, ReifiedRankedShapedTypeDims &reifiedReturnShapes) {
302 // The extents of a result that is not a ranked tensor are known only from
303 // its buffer.
304 auto type = dyn_cast<RankedTensorType>(getType());
305 if (!type)
306 return failure();
307 auto shapes = llvm::map_to_vector<4>(
308 llvm::seq<int64_t>(0, type.getRank()), [&](int64_t dim) -> OpFoldResult {
309 if (type.isDynamicDim(dim))
310 return getDynamicSize(builder, dim);
311 return builder.getIndexAttr(type.getDimSize(dim));
312 });
313 reifiedReturnShapes.emplace_back(std::move(shapes));
314 return success();
315}
316
317ParseResult AllocTensorOp::parse(OpAsmParser &parser, OperationState &result) {
319 if (parser.parseLParen() || parser.parseOperandList(dynamicSizesOperands) ||
320 parser.parseRParen())
321 return failure();
322 ParseResult copyKeyword = parser.parseOptionalKeyword("copy");
324 if (copyKeyword.succeeded())
325 if (parser.parseLParen() || parser.parseOperand(copyOperand) ||
326 parser.parseRParen())
327 return failure();
328 ParseResult sizeHintKeyword = parser.parseOptionalKeyword("size_hint");
329 OpAsmParser::UnresolvedOperand sizeHintOperand;
330 if (sizeHintKeyword.succeeded())
331 if (parser.parseEqual() || parser.parseOperand(sizeHintOperand))
332 return failure();
333
334 Attribute parsedProperties;
335 if (AllocTensorOp::genericParseProperties(parser, parsedProperties))
336 return failure();
337 auto propertyDictionary = dyn_cast_or_null<DictionaryAttr>(parsedProperties);
338 if (parsedProperties && !propertyDictionary)
339 return parser.emitError(parser.getNameLoc(),
340 "expected properties dictionary");
341
342 auto attrsLoc = parser.getCurrentLocation();
343 if (parser.parseOptionalAttrDict(result.attributes))
344 return failure();
345 for (StringRef attrName : AllocTensorOp::getAttributeNames()) {
346 if (result.attributes.get(attrName))
347 return parser.emitError(attrsLoc)
348 << "inherent attribute '" << attrName
349 << "' cannot be parsed from attr-dict when strict properties in "
350 "assembly format is enabled";
351 }
352 if (parser.parseColon())
353 return failure();
354
355 TensorLikeType type;
356 if (parser.parseCustomTypeWithFallback(type))
357 return failure();
358 result.addTypes(type);
359
360 Type indexType = parser.getBuilder().getIndexType();
361 if (parser.resolveOperands(dynamicSizesOperands, indexType, result.operands))
362 return failure();
363 if (copyKeyword.succeeded())
364 if (parser.resolveOperand(copyOperand, type, result.operands))
365 return failure();
366 if (sizeHintKeyword.succeeded())
367 if (parser.resolveOperand(sizeHintOperand, indexType, result.operands))
368 return failure();
369 Builder &builder = parser.getBuilder();
370 NamedAttrList properties(propertyDictionary ? propertyDictionary
371 : builder.getDictionaryAttr({}));
372 properties.set(AllocTensorOp::getOperandSegmentSizeAttr(),
373 builder.getDenseI32ArrayAttr(
374 {static_cast<int32_t>(dynamicSizesOperands.size()),
375 static_cast<int32_t>(copyKeyword.succeeded()),
376 static_cast<int32_t>(sizeHintKeyword.succeeded())}));
377 propertyDictionary = properties.getDictionary(builder.getContext());
378 auto emitError = [&]() {
379 return mlir::emitError(result.location, "invalid properties ")
380 << propertyDictionary << " for op " << result.name.getStringRef()
381 << ": ";
382 };
383 if (failed(AllocTensorOp::setPropertiesFromParsedAttr(
384 result.getOrAddProperties<Properties>(), propertyDictionary,
385 emitError)))
386 return failure();
387 return success();
388}
389
390void AllocTensorOp::print(OpAsmPrinter &p) {
391 p << "(" << getDynamicSizes() << ")";
392 if (getCopy())
393 p << " copy(" << getCopy() << ")";
394 if (getSizeHint())
395 p << " size_hint=" << getSizeHint();
396 AllocTensorOp::printProperties(getContext(), p, getProperties(),
397 /*elidedProps=*/getOperandSegmentSizeAttr());
398 p.printOptionalAttrDict((*this)->getDiscardableAttrDictionary().getValue());
399 p << " : ";
400 auto type = getResult().getType();
401 if (auto validType = llvm::dyn_cast<::mlir::TensorType>(type))
402 p.printStrippedAttrOrType(validType);
403 else
404 p << type;
405}
406
407Value AllocTensorOp::getDynamicSize(OpBuilder &b, unsigned idx) {
408 assert(isDynamicDim(idx) && "expected dynamic dim");
409 if (getCopy())
410 return tensor::DimOp::create(b, getLoc(), getCopy(), idx);
411 return getOperand(getIndexOfDynamicSize(idx));
412}
413
414//===----------------------------------------------------------------------===//
415// CloneOp
416//===----------------------------------------------------------------------===//
417
418OpFoldResult CloneOp::fold(FoldAdaptor adaptor) {
419 return succeeded(memref::foldMemRefCast(*this)) ? getResult() : Value();
420}
421
422namespace {
423
424/// Merge the clone and its source (by converting the clone to a cast) when
425/// possible.
426struct SimplifyClones : public OpRewritePattern<CloneOp> {
427 using OpRewritePattern<CloneOp>::OpRewritePattern;
428
429 LogicalResult matchAndRewrite(CloneOp cloneOp,
430 PatternRewriter &rewriter) const override {
431 if (cloneOp.use_empty()) {
432 rewriter.eraseOp(cloneOp);
433 return success();
434 }
435
436 Value source = cloneOp.getInput();
437 if (source.getType() != cloneOp.getType() &&
438 !memref::CastOp::areCastCompatible({source.getType()},
439 {cloneOp.getType()}))
440 return failure();
441
442 // Aims to find the dealloc op for the canonical source
443 // which otherwise could prevent removal of unnecessary allocs.
444 Value canonicalSource = source;
445 while (auto iface = dyn_cast_or_null<ViewLikeOpInterface>(
446 canonicalSource.getDefiningOp())) {
447 if (canonicalSource != iface.getViewDest()) {
448 break;
449 }
450 canonicalSource = iface.getViewSource();
451 }
452
453 std::optional<Operation *> maybeCloneDeallocOp =
454 memref::findDealloc(cloneOp.getOutput());
455 // Skip if either of them has > 1 deallocate operations.
456 if (!maybeCloneDeallocOp.has_value())
457 return failure();
458 std::optional<Operation *> maybeSourceDeallocOp =
459 memref::findDealloc(canonicalSource);
460 if (!maybeSourceDeallocOp.has_value())
461 return failure();
462 Operation *cloneDeallocOp = *maybeCloneDeallocOp;
463 Operation *sourceDeallocOp = *maybeSourceDeallocOp;
464
465 // If both are deallocated in the same block, their in-block lifetimes
466 // might not fully overlap, so we cannot decide which one to drop.
467 if (cloneDeallocOp && sourceDeallocOp &&
468 cloneDeallocOp->getBlock() == sourceDeallocOp->getBlock())
469 return failure();
470
471 Block *currentBlock = cloneOp->getBlock();
472 Operation *redundantDealloc = nullptr;
473 if (cloneDeallocOp && cloneDeallocOp->getBlock() == currentBlock) {
474 redundantDealloc = cloneDeallocOp;
475 } else if (sourceDeallocOp && sourceDeallocOp->getBlock() == currentBlock) {
476 redundantDealloc = sourceDeallocOp;
477 }
478
479 if (!redundantDealloc)
480 return failure();
481
482 // Safety check that there are no other deallocations inbetween
483 // cloneOp and redundantDealloc, as otherwise we might deallocate an alias
484 // of source before the uses of the clone. With alias information, we could
485 // restrict this to only fail of the dealloc's operand is an alias
486 // of the source.
487 for (Operation *pos = cloneOp->getNextNode(); pos != redundantDealloc;
488 pos = pos->getNextNode()) {
489 // Bail if we run out of operations while looking for a deallocation op.
490 if (!pos)
491 return failure();
492 auto effectInterface = dyn_cast<MemoryEffectOpInterface>(pos);
493 if (!effectInterface)
494 continue;
495 if (effectInterface.hasEffect<MemoryEffects::Free>())
496 return failure();
497 }
498
499 if (source.getType() != cloneOp.getType())
500 source = memref::CastOp::create(rewriter, cloneOp.getLoc(),
501 cloneOp.getType(), source);
502 rewriter.replaceOp(cloneOp, source);
503 rewriter.eraseOp(redundantDealloc);
504 return success();
505 }
506};
507
508} // namespace
509
510void CloneOp::getCanonicalizationPatterns(RewritePatternSet &results,
511 MLIRContext *context) {
512 results.add<SimplifyClones>(context);
513}
514
515//===----------------------------------------------------------------------===//
516// MaterializeInDestinationOp
517//===----------------------------------------------------------------------===//
518
519LogicalResult MaterializeInDestinationOp::reifyResultShapes(
520 OpBuilder &builder, ReifiedRankedShapedTypeDims &reifiedReturnShapes) {
521 if (getOperation()->getNumResults() == 1) {
522 assert(isa<TensorType>(getDest().getType()) && "expected tensor type");
523 reifiedReturnShapes.resize(1,
525 reifiedReturnShapes[0] =
526 tensor::getMixedSizes(builder, getLoc(), getDest());
527 }
528 return success();
529}
530
531Value MaterializeInDestinationOp::buildSubsetExtraction(OpBuilder &builder,
532 Location loc) {
533 if (isa<TensorType>(getDest().getType())) {
534 // The subset is the entire destination tensor.
535 return getDest();
536 }
537
538 // The "restrict" attribute is transferred from this op to the newly created
539 // to_tensor op. If this op does not the "restrict" attribute, the subset
540 // extraction cannot be built because there is no guarantee that there is no
541 // pre-existing "restrict" to_tensor op with the same/an aliasing destination.
542 if (!getRestrict())
543 return {};
544
545 // Build a bufferization.to_tensor op.
546 assert(isa<BaseMemRefType>(getDest().getType()) && "expected memref type");
547 assert(getRestrict() &&
548 "expected that ops with memrefs dest have 'restrict'");
549 setRestrict(false);
550 return ToTensorOp::create(
551 builder, loc, memref::getTensorTypeFromMemRefType(getDest().getType()),
552 getDest(),
553 /*restrict=*/true, getWritable());
554}
555
556bool MaterializeInDestinationOp::isEquivalentSubset(
557 Value candidate, function_ref<bool(Value, Value)> equivalenceFn) {
558 return equivalenceFn(getDest(), candidate);
559}
560
562MaterializeInDestinationOp::getValuesNeededToBuildSubsetExtraction() {
563 return {getDest()};
564}
565
566OpOperand &MaterializeInDestinationOp::getSourceOperand() {
567 return getOperation()->getOpOperand(0) /*source*/;
568}
569
570bool MaterializeInDestinationOp::operatesOnEquivalentSubset(
571 SubsetOpInterface subsetOp,
572 function_ref<bool(Value, Value)> equivalenceFn) {
573 return false;
574}
575
576bool MaterializeInDestinationOp::operatesOnDisjointSubset(
577 SubsetOpInterface subsetOp,
578 function_ref<bool(Value, Value)> equivalenceFn) {
579 return false;
580}
581
582LogicalResult MaterializeInDestinationOp::verify() {
583 if (!isa<TensorType, BaseMemRefType>(getDest().getType()))
584 return emitOpError("'dest' must be a tensor or a memref");
585 if (auto destType = dyn_cast<TensorType>(getDest().getType())) {
586 if (getOperation()->getNumResults() != 1)
587 return emitOpError("tensor 'dest' implies exactly one tensor result");
588 if (destType != getResult().getType())
589 return emitOpError("result and 'dest' types must match");
590 }
591 if (isa<BaseMemRefType>(getDest().getType()) &&
592 getOperation()->getNumResults() != 0)
593 return emitOpError("memref 'dest' implies zero results");
594 if (getRestrict() && !isa<BaseMemRefType>(getDest().getType()))
595 return emitOpError("'restrict' is valid only for memref destinations");
596 if (getWritable() != isa<BaseMemRefType>(getDest().getType()))
597 return emitOpError("'writable' must be specified if and only if the "
598 "destination is of memref type");
599 TensorType srcType = getSource().getType();
600 ShapedType destType = cast<ShapedType>(getDest().getType());
601 if (srcType.hasRank() != destType.hasRank())
602 return emitOpError("source/destination shapes are incompatible");
603 if (srcType.hasRank()) {
604 if (failed(verifyRanksMatch(getOperation(), srcType, destType, "source",
605 "destination")))
606 return failure();
607 for (auto [src, dest] :
608 llvm::zip(srcType.getShape(), destType.getShape())) {
609 if (src == ShapedType::kDynamic || dest == ShapedType::kDynamic) {
610 // Cannot verify dynamic dimension size. Assume that that they match at
611 // runtime.
612 continue;
613 }
614 if (src != dest)
615 return emitOpError("source/destination shapes are incompatible");
616 }
617 }
618 return success();
619}
620
621void MaterializeInDestinationOp::build(OpBuilder &builder,
622 OperationState &state, Value source,
623 Value dest) {
624 auto destTensorType = dyn_cast<TensorType>(dest.getType());
625 build(builder, state, /*result=*/destTensorType ? destTensorType : Type(),
626 source, dest);
627}
628
629MutableOperandRange MaterializeInDestinationOp::getDpsInitsMutable() {
630 return getDestMutable();
631}
632
633void MaterializeInDestinationOp::getEffects(
635 &effects) {
636 if (isa<BaseMemRefType>(getDest().getType()))
637 effects.emplace_back(MemoryEffects::Write::get(), &getDestMutable(),
639}
640
641//===----------------------------------------------------------------------===//
642// ToTensorOp
643//===----------------------------------------------------------------------===//
644
645OpFoldResult ToTensorOp::fold(FoldAdaptor) {
646 if (auto toBuffer = getBuffer().getDefiningOp<ToBufferOp>())
647 // Approximate alias analysis by conservatively folding only when no there
648 // is no interleaved operation.
649 if (toBuffer->getBlock() == this->getOperation()->getBlock() &&
650 toBuffer->getNextNode() == this->getOperation())
651 return toBuffer.getTensor();
652 return {};
653}
654
655namespace {
656struct DimOfToTensorFolder : public OpRewritePattern<tensor::DimOp> {
657 using OpRewritePattern<tensor::DimOp>::OpRewritePattern;
658
659 LogicalResult matchAndRewrite(tensor::DimOp dimOp,
660 PatternRewriter &rewriter) const override {
661 auto memrefToTensorOp = dimOp.getSource().getDefiningOp<ToTensorOp>();
662 if (!memrefToTensorOp)
663 return failure();
664
665 rewriter.replaceOpWithNewOp<memref::DimOp>(
666 dimOp, memrefToTensorOp.getBuffer(), dimOp.getIndex());
667 return success();
668 }
669};
670} // namespace
671
672void ToTensorOp::getCanonicalizationPatterns(RewritePatternSet &results,
673 MLIRContext *context) {
674 results.add<DimOfToTensorFolder>(context);
675}
676
677//===----------------------------------------------------------------------===//
678// ToBufferOp
679//===----------------------------------------------------------------------===//
680
681OpFoldResult ToBufferOp::fold(FoldAdaptor) {
682 if (auto memrefToTensor = getTensor().getDefiningOp<ToTensorOp>())
683 if (memrefToTensor.getBuffer().getType() == getType())
684 return memrefToTensor.getBuffer();
685 return {};
686}
687
688namespace {
689
690/// Replace tensor.cast + to_buffer by to_buffer + memref.cast.
691struct ToBufferOfCast : public OpRewritePattern<ToBufferOp> {
692 using OpRewritePattern<ToBufferOp>::OpRewritePattern;
693
694 LogicalResult matchAndRewrite(ToBufferOp toBuffer,
695 PatternRewriter &rewriter) const final {
696 auto tensorCastOperand =
697 toBuffer.getOperand().getDefiningOp<tensor::CastOp>();
698 if (!tensorCastOperand)
699 return failure();
700 auto srcTensorType = llvm::dyn_cast<RankedTensorType>(
701 tensorCastOperand.getOperand().getType());
702 if (!srcTensorType)
703 return failure();
704 auto currentOutputMemRefType =
705 dyn_cast<BaseMemRefType>(toBuffer.getResult().getType());
706 if (!currentOutputMemRefType)
707 return failure();
708
709 auto memrefType = currentOutputMemRefType.cloneWith(
710 srcTensorType.getShape(), srcTensorType.getElementType());
711 Value memref = ToBufferOp::create(rewriter, toBuffer.getLoc(), memrefType,
712 tensorCastOperand.getOperand(),
713 toBuffer.getReadOnly());
714 rewriter.replaceOpWithNewOp<memref::CastOp>(toBuffer, toBuffer.getType(),
715 memref);
716 return success();
717 }
718};
719
720/// Canonicalize bufferization.to_tensor + bufferization.to_buffer. Insert a
721/// cast if necessary.
722struct ToBufferToTensorFolding : public OpRewritePattern<ToBufferOp> {
723 using OpRewritePattern<ToBufferOp>::OpRewritePattern;
724
725 LogicalResult matchAndRewrite(ToBufferOp toBuffer,
726 PatternRewriter &rewriter) const final {
727 BufferizationOptions options;
728 options.bufferAlignment = 0;
729 return foldToBufferToTensorPair(rewriter, toBuffer, options);
730 }
731};
732
733/// Fold a load on a to_buffer operation into an tensor.extract on the
734/// corresponding tensor.
735struct LoadOfToBuffer : public OpRewritePattern<memref::LoadOp> {
736 using OpRewritePattern<memref::LoadOp>::OpRewritePattern;
737
738 LogicalResult matchAndRewrite(memref::LoadOp load,
739 PatternRewriter &rewriter) const override {
740 auto toBuffer = load.getMemref().getDefiningOp<ToBufferOp>();
741 if (!toBuffer || !toBuffer.getReadOnly())
742 return failure();
743
744 rewriter.replaceOpWithNewOp<tensor::ExtractOp>(load, toBuffer.getTensor(),
745 load.getIndices());
746 return success();
747 }
748};
749
750/// Fold dim of a to_buffer into the dim of the tensor.
751struct DimOfCastOp : public OpRewritePattern<memref::DimOp> {
752 using OpRewritePattern<memref::DimOp>::OpRewritePattern;
753
754 LogicalResult matchAndRewrite(memref::DimOp dimOp,
755 PatternRewriter &rewriter) const override {
756 auto castOp = dimOp.getSource().getDefiningOp<ToBufferOp>();
757 if (!castOp)
758 return failure();
759 Value newSource = castOp.getOperand();
760 rewriter.replaceOpWithNewOp<tensor::DimOp>(dimOp, newSource,
761 dimOp.getIndex());
762 return success();
763 }
764};
765
766} // namespace
767
768void ToBufferOp::getCanonicalizationPatterns(RewritePatternSet &results,
769 MLIRContext *context) {
770 results.add<DimOfCastOp, LoadOfToBuffer, ToBufferOfCast,
771 ToBufferToTensorFolding>(context);
772}
773
774std::optional<Operation *> CloneOp::buildDealloc(OpBuilder &builder,
775 Value alloc) {
776 if (!isa<BaseMemRefType>(alloc.getType()))
777 return std::nullopt;
778 return memref::DeallocOp::create(builder, alloc.getLoc(), alloc)
779 .getOperation();
780}
781
782std::optional<Value> CloneOp::buildClone(OpBuilder &builder, Value alloc) {
783 return CloneOp::create(builder, alloc.getLoc(), alloc).getResult();
784}
785
786//===----------------------------------------------------------------------===//
787// DeallocOp
788//===----------------------------------------------------------------------===//
789
790LogicalResult DeallocOp::inferReturnTypes(
791 MLIRContext *context, std::optional<::mlir::Location> location,
792 ValueRange operands, DictionaryAttr attributes, PropertyRef properties,
793 RegionRange regions, SmallVectorImpl<Type> &inferredReturnTypes) {
794 DeallocOpAdaptor adaptor(operands, attributes, properties, regions);
795 inferredReturnTypes = SmallVector<Type>(adaptor.getRetained().size(),
796 IntegerType::get(context, 1));
797 return success();
798}
799
800LogicalResult DeallocOp::verify() {
801 if (getMemrefs().size() != getConditions().size())
802 return emitOpError(
803 "must have the same number of conditions as memrefs to deallocate");
804 if (getRetained().size() != getUpdatedConditions().size())
805 return emitOpError("must have the same number of updated conditions "
806 "(results) as retained operands");
807 return success();
808}
809
810static LogicalResult updateDeallocIfChanged(DeallocOp deallocOp,
811 ValueRange memrefs,
812 ValueRange conditions,
813 PatternRewriter &rewriter) {
814 if (deallocOp.getMemrefs() == memrefs &&
815 deallocOp.getConditions() == conditions)
816 return failure();
817
818 rewriter.modifyOpInPlace(deallocOp, [&]() {
819 deallocOp.getMemrefsMutable().assign(memrefs);
820 deallocOp.getConditionsMutable().assign(conditions);
821 });
822 return success();
823}
824
825namespace {
826
827/// Remove duplicate values in the list of memrefs to be deallocated. We need to
828/// make sure the corresponding condition value is updated accordingly since
829/// their two conditions might not cover the same set of cases. In that case, we
830/// have to combine them (by computing the disjunction of them).
831/// Example:
832/// ```mlir
833/// bufferization.dealloc (%arg0, %arg0 : ...) if (%arg1, %arg2)
834/// ```
835/// is canonicalized to
836/// ```mlir
837/// %0 = arith.ori %arg1, %arg2 : i1
838/// bufferization.dealloc (%arg0 : memref<2xi32>) if (%0)
839/// ```
840struct DeallocRemoveDuplicateDeallocMemrefs
841 : public OpRewritePattern<DeallocOp> {
842 using OpRewritePattern<DeallocOp>::OpRewritePattern;
843
844 LogicalResult matchAndRewrite(DeallocOp deallocOp,
845 PatternRewriter &rewriter) const override {
846 // Unique memrefs to be deallocated.
847 DenseMap<Value, unsigned> memrefToCondition;
848 SmallVector<Value> newMemrefs, newConditions;
849 for (auto [i, memref, cond] :
850 llvm::enumerate(deallocOp.getMemrefs(), deallocOp.getConditions())) {
851 if (memrefToCondition.count(memref)) {
852 // If the dealloc conditions don't match, we need to make sure that the
853 // dealloc happens on the union of cases.
854 Value &newCond = newConditions[memrefToCondition[memref]];
855 if (newCond != cond)
856 newCond =
857 arith::OrIOp::create(rewriter, deallocOp.getLoc(), newCond, cond);
858 } else {
859 memrefToCondition.insert({memref, newConditions.size()});
860 newMemrefs.push_back(memref);
861 newConditions.push_back(cond);
862 }
863 }
864
865 // Return failure if we don't change anything such that we don't run into an
866 // infinite loop of pattern applications.
867 return updateDeallocIfChanged(deallocOp, newMemrefs, newConditions,
868 rewriter);
869 }
870};
871
872/// Remove duplicate values in the list of retained memrefs. We need to make
873/// sure the corresponding result condition value is replaced properly.
874/// Example:
875/// ```mlir
876/// %0:2 = bufferization.dealloc retain (%arg3, %arg3 : ...)
877/// ```
878/// is canonicalized to
879/// ```mlir
880/// %0 = bufferization.dealloc retain (%arg3 : memref<2xi32>)
881/// ```
882struct DeallocRemoveDuplicateRetainedMemrefs
883 : public OpRewritePattern<DeallocOp> {
884 using OpRewritePattern<DeallocOp>::OpRewritePattern;
885
886 LogicalResult matchAndRewrite(DeallocOp deallocOp,
887 PatternRewriter &rewriter) const override {
888 // Unique retained values
890 SmallVector<Value> newRetained;
891 SmallVector<unsigned> resultReplacementIdx;
892 unsigned i = 0;
893 for (auto retained : deallocOp.getRetained()) {
894 if (seen.count(retained)) {
895 resultReplacementIdx.push_back(seen[retained]);
896 continue;
897 }
898
899 seen[retained] = i;
900 newRetained.push_back(retained);
901 resultReplacementIdx.push_back(i++);
902 }
903
904 // Return failure if we don't change anything such that we don't run into an
905 // infinite loop of pattern applications.
906 if (newRetained.size() == deallocOp.getRetained().size())
907 return failure();
908
909 // We need to create a new op because the number of results is always the
910 // same as the number of condition operands.
911 auto newDeallocOp =
912 DeallocOp::create(rewriter, deallocOp.getLoc(), deallocOp.getMemrefs(),
913 deallocOp.getConditions(), newRetained);
914 SmallVector<Value> replacements(
915 llvm::map_range(resultReplacementIdx, [&](unsigned idx) {
916 return newDeallocOp.getUpdatedConditions()[idx];
917 }));
918 rewriter.replaceOp(deallocOp, replacements);
919 return success();
920 }
921};
922
923/// Erase deallocation operations where the variadic list of memrefs to
924/// deallocate is empty. Example:
925/// ```mlir
926/// %0 = bufferization.dealloc retain (%arg0: memref<2xi32>)
927/// ```
928struct EraseEmptyDealloc : public OpRewritePattern<DeallocOp> {
929 using OpRewritePattern<DeallocOp>::OpRewritePattern;
930
931 LogicalResult matchAndRewrite(DeallocOp deallocOp,
932 PatternRewriter &rewriter) const override {
933 if (deallocOp.getMemrefs().empty()) {
934 Value constFalse = arith::ConstantOp::create(rewriter, deallocOp.getLoc(),
935 rewriter.getBoolAttr(false));
936 rewriter.replaceOp(
937 deallocOp, SmallVector<Value>(deallocOp.getUpdatedConditions().size(),
938 constFalse));
939 return success();
940 }
941 return failure();
942 }
943};
944
945/// Removes memrefs from the deallocation list if their associated condition is
946/// always 'false'.
947///
948/// Example:
949/// ```
950/// bufferization.dealloc (%arg0, %arg1 : memref<2xi32>, memref<2xi32>)
951/// if (%arg2, %false)
952/// ```
953/// becomes
954/// ```
955/// bufferization.dealloc (%arg0 : memref<2xi32>) if (%arg2)
956/// ```
957struct EraseAlwaysFalseDealloc : public OpRewritePattern<DeallocOp> {
958 using OpRewritePattern<DeallocOp>::OpRewritePattern;
959
960 LogicalResult matchAndRewrite(DeallocOp deallocOp,
961 PatternRewriter &rewriter) const override {
962 SmallVector<Value> newMemrefs, newConditions;
963 for (auto [memref, cond] :
964 llvm::zip(deallocOp.getMemrefs(), deallocOp.getConditions())) {
965 if (!matchPattern(cond, m_Zero())) {
966 newMemrefs.push_back(memref);
967 newConditions.push_back(cond);
968 }
969 }
970
971 return updateDeallocIfChanged(deallocOp, newMemrefs, newConditions,
972 rewriter);
973 }
974};
975
976/// The `memref.extract_strided_metadata` is often inserted to get the base
977/// memref if the operand is not already guaranteed to be the result of a memref
978/// allocation operation. This canonicalization pattern removes this extraction
979/// operation if the operand is now produced by an allocation operation (e.g.,
980/// due to other canonicalizations simplifying the IR).
981///
982/// Example:
983/// ```mlir
984/// %alloc = memref.alloc() : memref<2xi32>
985/// %base_memref, %offset, %size, %stride = memref.extract_strided_metadata
986/// %alloc : memref<2xi32> -> memref<i32>, index, index, index
987/// bufferization.dealloc (%base_memref : memref<i32>) if (%cond)
988/// ```
989/// is canonicalized to
990/// ```mlir
991/// %alloc = memref.alloc() : memref<2xi32>
992/// bufferization.dealloc (%alloc : memref<2xi32>) if (%cond)
993/// ```
994struct SkipExtractMetadataOfAlloc : public OpRewritePattern<DeallocOp> {
995 using OpRewritePattern<DeallocOp>::OpRewritePattern;
996
997 LogicalResult matchAndRewrite(DeallocOp deallocOp,
998 PatternRewriter &rewriter) const override {
999 SmallVector<Value> newMemrefs(
1000 llvm::map_range(deallocOp.getMemrefs(), [&](Value memref) {
1001 auto extractStridedOp =
1002 memref.getDefiningOp<memref::ExtractStridedMetadataOp>();
1003 if (!extractStridedOp)
1004 return memref;
1005 Value allocMemref = extractStridedOp.getOperand();
1006 auto allocOp = allocMemref.getDefiningOp<MemoryEffectOpInterface>();
1007 if (!allocOp)
1008 return memref;
1009 if (allocOp.getEffectOnValue<MemoryEffects::Allocate>(allocMemref))
1010 return allocMemref;
1011 return memref;
1012 }));
1013
1014 return updateDeallocIfChanged(deallocOp, newMemrefs,
1015 deallocOp.getConditions(), rewriter);
1016 }
1017};
1018
1019/// Removes pairs of `bufferization.dealloc` and alloc operations if there is no
1020/// other user of the allocated value and the allocating operation can be safely
1021/// removed. If the same value is present multiple times, this pattern relies on
1022/// other canonicalization patterns to remove the duplicate first.
1023///
1024/// Example:
1025/// ```mlir
1026/// %alloc = memref.alloc() : memref<2xi32>
1027/// bufferization.dealloc (%alloc, %arg0, : ...) if (%true, %true)
1028/// ```
1029/// is canonicalized to
1030/// ```mlir
1031/// bufferization.dealloc (%arg0 : ...) if (%true)
1032/// ```
1033struct RemoveAllocDeallocPairWhenNoOtherUsers
1034 : public OpRewritePattern<DeallocOp> {
1035 using OpRewritePattern<DeallocOp>::OpRewritePattern;
1036
1037 LogicalResult matchAndRewrite(DeallocOp deallocOp,
1038 PatternRewriter &rewriter) const override {
1039 SmallVector<Value> newMemrefs, newConditions;
1040 SmallVector<Operation *> toDelete;
1041 for (auto [memref, cond] :
1042 llvm::zip(deallocOp.getMemrefs(), deallocOp.getConditions())) {
1043 if (auto allocOp = memref.getDefiningOp<MemoryEffectOpInterface>()) {
1044 // Check that it is indeed an allocate effect, that the op has no other
1045 // side effects (which would not allow us to remove the op), and that
1046 // there are no other users.
1047 if (allocOp.getEffectOnValue<MemoryEffects::Allocate>(memref) &&
1049 memref.hasOneUse()) {
1050 toDelete.push_back(allocOp);
1051 continue;
1052 }
1053 }
1054
1055 newMemrefs.push_back(memref);
1056 newConditions.push_back(cond);
1057 }
1058
1059 if (failed(updateDeallocIfChanged(deallocOp, newMemrefs, newConditions,
1060 rewriter)))
1061 return failure();
1062
1063 for (Operation *op : toDelete)
1064 rewriter.eraseOp(op);
1065
1066 return success();
1067 }
1068};
1069
1070} // anonymous namespace
1071
1072void DeallocOp::getCanonicalizationPatterns(RewritePatternSet &results,
1073 MLIRContext *context) {
1075}
1076
1078 RewritePatternSet &patterns, MLIRContext *context) {
1079 patterns.add<DeallocRemoveDuplicateDeallocMemrefs,
1080 DeallocRemoveDuplicateRetainedMemrefs, EraseEmptyDealloc,
1081 EraseAlwaysFalseDealloc, SkipExtractMetadataOfAlloc,
1082 RemoveAllocDeallocPairWhenNoOtherUsers>(context);
1083}
1084
1085//===----------------------------------------------------------------------===//
1086// TableGen'd op method definitions
1087//===----------------------------------------------------------------------===//
1088
1089#define GET_OP_CLASSES
1090#include "mlir/Dialect/Bufferization/IR/BufferizationOps.cpp.inc"
return success()
return MutableOperandRange * this
static LogicalResult updateDeallocIfChanged(DeallocOp deallocOp, ValueRange memrefs, ValueRange conditions, PatternRewriter &rewriter)
static void copy(Location loc, Value dst, Value src, Value size, OpBuilder &builder)
Copies the given number of bytes from src to dst pointers.
b
Return true if permutation is a valid permutation of the outer_dims_perm (case OuterOrInnerPerm::Oute...
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 llvm::ManagedStatic< PassManagerOptions > options
template bool mlir::hasSingleEffect< MemoryEffects::Allocate >(Operation *)
static void getDynamicSizes(RankedTensorType tp, ValueRange sizes, SmallVectorImpl< Value > &dynSizes)
Collects the dynamic dimension sizes for tp with the assumption that sizes are the dimension sizes fo...
virtual Builder & getBuilder() const =0
Return a builder which provides useful access to MLIRContext, global objects like types and attribute...
virtual ParseResult parseOptionalAttrDict(NamedAttrList &result)=0
Parse a named dictionary into 'result' if it is present.
virtual ParseResult parseOptionalKeyword(StringRef keyword)=0
Parse the given keyword if present.
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.
virtual ParseResult parseEqual()=0
Parse a = token.
virtual ParseResult parseCustomTypeWithFallback(Type &result, function_ref< ParseResult(Type &result)> parseType)=0
Parse a custom type with the provided callback, unless the next token is #, in which case the generic...
virtual SMLoc getCurrentLocation()=0
Get the location of the next token and store it into the argument.
virtual ParseResult parseColon()=0
Parse a : token.
virtual SMLoc getNameLoc() const =0
Return the location of the original name token.
virtual ParseResult parseLParen()=0
Parse a ( token.
void printStrippedAttrOrType(AttrOrType attrOrType)
Print the provided attribute in the context of an operation custom printer/parser: this will invoke d...
Attributes are known-constant values of operations.
Definition Attributes.h:25
This class is a general helper class for creating context-global objects like types,...
Definition Builders.h:51
DenseI32ArrayAttr getDenseI32ArrayAttr(ArrayRef< int32_t > values)
Definition Builders.cpp:171
BoolAttr getBoolAttr(bool value)
Definition Builders.cpp:108
MLIRContext * getContext() const
Definition Builders.h:56
IndexType getIndexType()
Definition Builders.cpp:59
DictionaryAttr getDictionaryAttr(ArrayRef< NamedAttribute > value)
Definition Builders.cpp:112
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
NamedAttrList is array of NamedAttributes that tracks whether it is sorted and does some basic work t...
The OpAsmParser has methods for interacting with the asm parser: parsing things from it,...
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 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.
This class helps build Operations.
Definition Builders.h:210
This class represents a single result from folding an operation.
This class represents an operand of an operation.
Definition Value.h:256
Block * getBlock()
Returns the operation block that contains this operation.
Definition Operation.h:230
A special type of RewriterBase that coordinates the application of a rewrite pattern on the current I...
Type-safe wrapper around a void* for passing properties, including the properties structs of operatio...
This class provides an abstraction over the different types of ranges over Regions.
Definition Region.h:363
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 replaceOp(Operation *op, ValueRange newValues)
Replace the results of the given (original) operation with the specified list of values (replacements...
virtual void eraseOp(Operation *op)
This method erases an operation that is known to have no uses.
void modifyOpInPlace(Operation *root, CallableT &&callable)
This method is a utility wrapper around an in-place modification of an operation.
OpTy replaceOpWithNewOp(Operation *op, Args &&...args)
Replace the results of the given (original) op with a new op that is created without verification (re...
This class represents a specific instance of an effect.
Tensor types represent multi-dimensional arrays, and have two variants: RankedTensorType and Unranked...
ArrayRef< int64_t > getShape() const
Returns the shape of this tensor type.
bool hasRank() const
Returns if this type is ranked, i.e. it has a known number of dimensions.
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
This class provides an abstraction over the different types of ranges over Values.
Definition ValueRange.h:392
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
Type getType() const
Return the type of this value.
Definition Value.h:105
Location getLoc() const
Return the location of this value.
Definition Value.cpp:24
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
Definition Value.cpp:18
void populateDeallocOpCanonicalizationPatterns(RewritePatternSet &patterns, MLIRContext *context)
Add the canonicalization patterns for bufferization.dealloc to the given pattern set to make them ava...
FailureOr< Value > castOrReallocMemRefValue(OpBuilder &b, Value value, MemRefType type, const BufferizationOptions &options)
Try to cast the given ranked MemRef-typed value to the given ranked MemRef type.
LogicalResult foldToBufferToTensorPair(RewriterBase &rewriter, ToBufferOp toBuffer, const BufferizationOptions &options)
Try to fold to_buffer(to_tensor(x)).
void populateDynamicDimSizes(OpBuilder &b, Location loc, Value shapedValue, SmallVector< Value > &dynamicDims)
Populate dynamicDims with tensor::DimOp / memref::DimOp results for all dynamic dimensions of the giv...
Type getTensorTypeFromMemRefType(Type type)
Return an unranked/ranked tensor type for the given unranked/ranked memref type.
Definition MemRefOps.cpp:63
std::optional< Operation * > findDealloc(Value allocValue)
Finds a single dealloc operation for the given allocated value.
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
SmallVector< OpFoldResult > getMixedSizes(OpBuilder &builder, Location loc, Value value)
Return the dimensions of the given tensor value.
Definition TensorOps.cpp:92
Include the generated interface declarations.
bool matchPattern(Value value, const Pattern &pattern)
Entry point for matching a pattern over a Value.
Definition Matchers.h:490
detail::constant_int_value_binder m_ConstantInt(IntegerAttr::ValueType *bind_value)
Matches a constant holding a scalar/vector/tensor integer (splat) and writes the integer value to bin...
Definition Matchers.h:527
LogicalResult verifyDynamicDimensionCount(Operation *op, ShapedType type, ValueRange dynamicSizes)
Verify that the number of dynamic size operands matches the number of dynamic dimensions in the shape...
Type getType(OpFoldResult ofr)
Returns the int type of the integer in ofr.
Definition Utils.cpp:311
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.
SmallVector< SmallVector< OpFoldResult > > ReifiedRankedShapedTypeDims
detail::constant_int_predicate_matcher m_Zero()
Matches a constant scalar / vector splat / tensor splat integer zero.
Definition Matchers.h:442
LogicalResult verifyRanksMatch(Operation *op, ShapedType lhs, ShapedType rhs, StringRef lhsName, StringRef rhsName)
Verify that two shaped types have matching ranks.
llvm::DenseMap< KeyT, ValueT, KeyInfoT, BucketT > DenseMap
Definition LLVM.h:123
llvm::function_ref< Fn > function_ref
Definition LLVM.h:155
This is the representation of an operand reference.
OpRewritePattern is a wrapper around RewritePattern that allows for matching and rewriting against an...
This represents an operation in an abstracted form, suitable for use with the builder APIs.