29 auto srcType = llvm::cast<MemRefType>(value.
getType());
32 if (srcType.getElementType() != destType.getElementType())
34 if (srcType.getMemorySpace() != destType.getMemorySpace())
36 if (srcType.getRank() != destType.getRank())
42 auto isGuaranteedCastCompatible = [](MemRefType source, MemRefType target) {
43 int64_t sourceOffset, targetOffset;
48 auto dynamicToStatic = [](int64_t a, int64_t b) {
49 return ShapedType::isDynamic(a) && !ShapedType::isDynamic(b);
51 if (dynamicToStatic(sourceOffset, targetOffset))
53 for (
auto it : zip(sourceStrides, targetStrides))
54 if (dynamicToStatic(std::get<0>(it), std::get<1>(it)))
62 if (memref::CastOp::areCastCompatible(srcType, destType) &&
63 isGuaranteedCastCompatible(srcType, destType)) {
70 for (
int i = 0; i < destType.getRank(); ++i) {
71 if (destType.getShape()[i] != ShapedType::kDynamic)
73 Value size = b.
create<memref::DimOp>(loc, value, i);
74 dynamicOperands.push_back(size);
77 FailureOr<Value>
copy =
78 options.createAlloc(b, loc, destType, dynamicOperands);
81 if (failed(
options.createMemCpy(b, loc, value, *
copy)))
91 auto memrefToTensor = toMemref.getTensor().getDefiningOp<ToTensorOp>();
95 Type srcType = memrefToTensor.getMemref().getType();
96 Type destType = toMemref.getType();
99 if (srcType == destType) {
100 rewriter.
replaceOp(toMemref, memrefToTensor.getMemref());
104 auto rankedSrcType = llvm::dyn_cast<MemRefType>(srcType);
105 auto rankedDestType = llvm::dyn_cast<MemRefType>(destType);
106 auto unrankedSrcType = llvm::dyn_cast<UnrankedMemRefType>(srcType);
109 if (rankedSrcType && rankedDestType) {
111 rewriter, memrefToTensor.getMemref(), rankedDestType,
options);
112 if (failed(replacement))
115 rewriter.
replaceOp(toMemref, *replacement);
121 if (unrankedSrcType && rankedDestType)
126 assert(memref::CastOp::areCastCompatible(srcType, destType) &&
127 "expected that types are cast compatible");
129 memrefToTensor.getMemref());
136 auto shapedType = llvm::cast<ShapedType>(shapedValue.
getType());
137 for (int64_t i = 0; i < shapedType.getRank(); ++i) {
138 if (shapedType.isDynamicDim(i)) {
139 if (llvm::isa<MemRefType>(shapedType)) {
140 dynamicDims.push_back(b.
create<memref::DimOp>(loc, shapedValue, i));
142 assert(llvm::isa<RankedTensorType>(shapedType) &&
"expected tensor");
143 dynamicDims.push_back(b.
create<tensor::DimOp>(loc, shapedValue, i));
153 LogicalResult AllocTensorOp::bufferize(
RewriterBase &rewriter,
159 if (getOperation()->getUses().empty()) {
160 rewriter.
eraseOp(getOperation());
168 if (failed(maybeCopyBuffer))
170 copyBuffer = *maybeCopyBuffer;
175 if (failed(allocType))
179 assert(dynamicDims.empty() &&
"expected either `copy` or `dynamicDims`");
182 FailureOr<Value> alloc =
options.createAlloc(
183 rewriter, loc, llvm::cast<MemRefType>(*allocType), dynamicDims);
189 if (failed(
options.createMemCpy(rewriter, loc, copyBuffer, *alloc)))
199 bool AllocTensorOp::resultBufferizesToMemoryWrite(
OpResult opResult,
202 return static_cast<bool>(getCopy());
205 bool AllocTensorOp::bufferizesToMemoryRead(
OpOperand &opOperand,
208 "expected copy operand");
212 bool AllocTensorOp::bufferizesToMemoryWrite(
OpOperand &opOperand,
215 "expected copy operand");
225 FailureOr<BaseMemRefType>
228 assert(value == getResult() &&
"invalid value");
232 if (getMemorySpace().has_value()) {
233 memorySpace = *getMemorySpace();
234 }
else if (getCopy()) {
235 auto copyBufferType =
237 if (failed(copyBufferType))
239 memorySpace = copyBufferType->getMemorySpace();
243 return getOperation()->emitError(
"could not infer memory space");
251 return emitError(
"dynamic sizes not needed when copying a tensor");
252 if (!getCopy() &&
getType().getNumDynamicDims() !=
255 <<
getType().getNumDynamicDims() <<
" dynamic sizes";
257 return emitError(
"expected that `copy` and return type match");
262 RankedTensorType type,
ValueRange dynamicSizes) {
263 build(builder, result, type, dynamicSizes,
Value(),
269 RankedTensorType type,
ValueRange dynamicSizes,
271 build(builder, result, type, dynamicSizes,
copy,
Value(),
277 IntegerAttr memorySpace) {
278 build(builder, result, type, dynamicSizes,
copy,
Value(),
297 LogicalResult matchAndRewrite(AllocTensorOp op,
303 unsigned int dynValCounter = 0;
304 for (int64_t i = 0; i < op.getType().getRank(); ++i) {
305 if (!op.isDynamicDim(i))
307 Value value = op.getDynamicSizes()[dynValCounter++];
310 int64_t dim = intVal.getSExtValue();
312 newShape[i] = intVal.getSExtValue();
314 newDynamicSizes.push_back(value);
316 newDynamicSizes.push_back(value);
320 newShape, op.getType().getElementType(), op.getType().getEncoding());
321 if (newType == op.getType())
323 auto newOp = rewriter.
create<AllocTensorOp>(
333 LogicalResult matchAndRewrite(tensor::DimOp dimOp,
335 std::optional<int64_t> maybeConstantIndex = dimOp.getConstantIndex();
336 auto allocTensorOp = dimOp.getSource().getDefiningOp<AllocTensorOp>();
337 if (!allocTensorOp || !maybeConstantIndex)
339 if (*maybeConstantIndex < 0 ||
340 *maybeConstantIndex >= allocTensorOp.getType().getRank())
342 if (!allocTensorOp.getType().isDynamicDim(*maybeConstantIndex))
345 dimOp, allocTensorOp.getDynamicSize(rewriter, *maybeConstantIndex));
353 results.
add<FoldDimOfAllocTensorOp, ReplaceStaticShapeDims>(ctx);
358 auto shapes = llvm::to_vector<4>(
359 llvm::map_range(llvm::seq<int64_t>(0,
getType().getRank()),
361 if (isDynamicDim(dim))
362 return getDynamicSize(builder, dim);
365 reifiedReturnShapes.emplace_back(std::move(shapes));
376 if (copyKeyword.succeeded())
382 if (sizeHintKeyword.succeeded())
396 if (copyKeyword.succeeded())
399 if (sizeHintKeyword.succeeded())
402 result.
addAttribute(AllocTensorOp::getOperandSegmentSizeAttr(),
404 {static_cast<int32_t>(dynamicSizesOperands.size()),
405 static_cast<int32_t>(copyKeyword.succeeded()),
406 static_cast<int32_t>(sizeHintKeyword.succeeded())}));
413 p <<
" copy(" << getCopy() <<
")";
415 p <<
" size_hint=" << getSizeHint();
417 AllocTensorOp::getOperandSegmentSizeAttr()});
419 auto type = getResult().getType();
420 if (
auto validType = llvm::dyn_cast<::mlir::TensorType>(type))
427 assert(isDynamicDim(idx) &&
"expected dynamic dim");
429 return b.
create<tensor::DimOp>(getLoc(), getCopy(), idx);
430 return getOperand(getIndexOfDynamicSize(idx));
448 LogicalResult matchAndRewrite(CloneOp cloneOp,
450 if (cloneOp.use_empty()) {
455 Value source = cloneOp.getInput();
456 if (source.
getType() != cloneOp.getType() &&
457 !memref::CastOp::areCastCompatible({source.getType()},
458 {cloneOp.getType()}))
463 Value canonicalSource = source;
464 while (
auto iface = dyn_cast_or_null<ViewLikeOpInterface>(
466 canonicalSource = iface.getViewSource();
468 std::optional<Operation *> maybeCloneDeallocOp =
471 if (!maybeCloneDeallocOp.has_value())
473 std::optional<Operation *> maybeSourceDeallocOp =
475 if (!maybeSourceDeallocOp.has_value())
477 Operation *cloneDeallocOp = *maybeCloneDeallocOp;
478 Operation *sourceDeallocOp = *maybeSourceDeallocOp;
482 if (cloneDeallocOp && sourceDeallocOp &&
486 Block *currentBlock = cloneOp->getBlock();
488 if (cloneDeallocOp && cloneDeallocOp->
getBlock() == currentBlock) {
489 redundantDealloc = cloneDeallocOp;
490 }
else if (sourceDeallocOp && sourceDeallocOp->
getBlock() == currentBlock) {
491 redundantDealloc = sourceDeallocOp;
494 if (!redundantDealloc)
502 for (
Operation *pos = cloneOp->getNextNode(); pos != redundantDealloc;
503 pos = pos->getNextNode()) {
507 auto effectInterface = dyn_cast<MemoryEffectOpInterface>(pos);
508 if (!effectInterface)
514 if (source.
getType() != cloneOp.getType())
515 source = rewriter.
create<memref::CastOp>(cloneOp.getLoc(),
516 cloneOp.getType(), source);
518 rewriter.
eraseOp(redundantDealloc);
527 results.
add<SimplifyClones>(context);
534 LogicalResult DeallocTensorOp::bufferize(
RewriterBase &rewriter,
539 rewriter.
create<memref::DeallocOp>(getLoc(), *buffer);
540 rewriter.
eraseOp(getOperation());
548 bool MaterializeInDestinationOp::bufferizesToMemoryRead(
550 return opOperand == getSourceMutable();
553 bool MaterializeInDestinationOp::bufferizesToMemoryWrite(
555 if (opOperand == getDestMutable()) {
556 assert(isa<TensorType>(getDest().
getType()) &&
"expected tensor type");
562 bool MaterializeInDestinationOp::mustBufferizeInPlace(
571 MaterializeInDestinationOp::getAliasingValues(
OpOperand &opOperand,
573 if (opOperand == getDestMutable()) {
574 assert(isa<TensorType>(getDest().
getType()) &&
"expected tensor type");
581 MaterializeInDestinationOp::bufferize(
RewriterBase &rewriter,
583 bool tensorDest = isa<TensorType>(getDest().
getType());
587 if (failed(maybeBuffer))
589 buffer = *maybeBuffer;
591 assert(isa<BaseMemRefType>(getDest().
getType()) &&
"expected memref type");
595 if (failed(srcBuffer))
597 if (failed(
options.createMemCpy(rewriter, getLoc(), *srcBuffer, buffer)))
604 bool MaterializeInDestinationOp::bufferizesToElementwiseAccess(
613 if (getOperation()->getNumResults() == 1) {
614 assert(isa<TensorType>(getDest().
getType()) &&
"expected tensor type");
615 reifiedReturnShapes.resize(1,
617 reifiedReturnShapes[0] =
623 Value MaterializeInDestinationOp::buildSubsetExtraction(
OpBuilder &builder,
625 if (isa<TensorType>(getDest().
getType())) {
638 assert(isa<BaseMemRefType>(getDest().
getType()) &&
"expected memref type");
639 assert(getRestrict() &&
640 "expected that ops with memrefs dest have 'restrict'");
642 return builder.
create<ToTensorOp>(loc, getDest(),
true,
646 bool MaterializeInDestinationOp::isEquivalentSubset(
648 return equivalenceFn(getDest(), candidate);
652 MaterializeInDestinationOp::getValuesNeededToBuildSubsetExtraction() {
656 OpOperand &MaterializeInDestinationOp::getSourceOperand() {
657 return getOperation()->getOpOperand(0) ;
660 bool MaterializeInDestinationOp::operatesOnEquivalentSubset(
661 SubsetOpInterface subsetOp,
666 bool MaterializeInDestinationOp::operatesOnDisjointSubset(
667 SubsetOpInterface subsetOp,
673 if (!isa<TensorType, BaseMemRefType>(getDest().
getType()))
674 return emitOpError(
"'dest' must be a tensor or a memref");
675 if (
auto destType = dyn_cast<TensorType>(getDest().
getType())) {
676 if (getOperation()->getNumResults() != 1)
677 return emitOpError(
"tensor 'dest' implies exactly one tensor result");
678 if (destType != getResult().
getType())
679 return emitOpError(
"result and 'dest' types must match");
681 if (isa<BaseMemRefType>(getDest().
getType()) &&
682 getOperation()->getNumResults() != 0)
683 return emitOpError(
"memref 'dest' implies zero results");
684 if (getRestrict() && !isa<BaseMemRefType>(getDest().
getType()))
685 return emitOpError(
"'restrict' is valid only for memref destinations");
686 if (getWritable() != isa<BaseMemRefType>(getDest().
getType()))
687 return emitOpError(
"'writable' must be specified if and only if the "
688 "destination is of memref type");
690 ShapedType destType = cast<ShapedType>(getDest().
getType());
691 if (srcType.
hasRank() != destType.hasRank())
692 return emitOpError(
"source/destination shapes are incompatible");
694 if (srcType.getRank() != destType.getRank())
695 return emitOpError(
"rank mismatch between source and destination shape");
696 for (
auto [src, dest] :
697 llvm::zip(srcType.
getShape(), destType.getShape())) {
698 if (src == ShapedType::kDynamic || dest == ShapedType::kDynamic) {
704 return emitOpError(
"source/destination shapes are incompatible");
710 void MaterializeInDestinationOp::build(
OpBuilder &builder,
713 auto destTensorType = dyn_cast<TensorType>(dest.
getType());
714 build(builder, state, destTensorType ? destTensorType :
Type(),
718 bool MaterializeInDestinationOp::isWritable(
Value value,
720 return isa<TensorType>(getDest().
getType()) ? true : getWritable();
724 return getDestMutable();
727 void MaterializeInDestinationOp::getEffects(
730 if (isa<BaseMemRefType>(getDest().
getType()))
740 return getWritable();
744 if (
auto toMemref = getMemref().getDefiningOp<ToMemrefOp>())
747 if (toMemref->getBlock() == this->getOperation()->getBlock() &&
748 toMemref->getNextNode() == this->getOperation())
749 return toMemref.getTensor();
757 LogicalResult matchAndRewrite(tensor::DimOp dimOp,
759 auto memrefToTensorOp = dimOp.getSource().getDefiningOp<ToTensorOp>();
760 if (!memrefToTensorOp)
764 dimOp, memrefToTensorOp.getMemref(), dimOp.getIndex());
772 results.
add<DimOfToTensorFolder>(context);
780 if (
auto memrefToTensor = getTensor().getDefiningOp<ToTensorOp>())
781 if (memrefToTensor.getMemref().getType() ==
getType())
782 return memrefToTensor.getMemref();
792 LogicalResult matchAndRewrite(ToMemrefOp toMemref,
794 auto tensorCastOperand =
795 toMemref.getOperand().getDefiningOp<tensor::CastOp>();
796 if (!tensorCastOperand)
798 auto srcTensorType = llvm::dyn_cast<RankedTensorType>(
799 tensorCastOperand.getOperand().getType());
803 srcTensorType.getElementType());
804 Value memref = rewriter.
create<ToMemrefOp>(toMemref.getLoc(), memrefType,
805 tensorCastOperand.getOperand());
817 LogicalResult matchAndRewrite(ToMemrefOp toMemref,
830 LogicalResult matchAndRewrite(memref::LoadOp load,
832 auto toMemref = load.getMemref().getDefiningOp<ToMemrefOp>();
846 LogicalResult matchAndRewrite(memref::DimOp dimOp,
848 auto castOp = dimOp.getSource().getDefiningOp<ToMemrefOp>();
851 Value newSource = castOp.getOperand();
862 results.
add<DimOfCastOp, LoadOfToMemref, ToMemrefOfCast,
863 ToMemrefToTensorFolding>(context);
866 LogicalResult ToMemrefOp::bufferize(
RewriterBase &rewriter,
875 std::optional<Operation *> CloneOp::buildDealloc(
OpBuilder &builder,
877 return builder.
create<memref::DeallocOp>(alloc.
getLoc(), alloc)
881 std::optional<Value> CloneOp::buildClone(
OpBuilder &builder,
Value alloc) {
882 return builder.
create<CloneOp>(alloc.
getLoc(), alloc).getResult();
889 LogicalResult DeallocOp::inferReturnTypes(
890 MLIRContext *context, std::optional<::mlir::Location> location,
893 DeallocOpAdaptor adaptor(operands, attributes, properties, regions);
900 if (getMemrefs().size() != getConditions().size())
902 "must have the same number of conditions as memrefs to deallocate");
903 if (getRetained().size() != getUpdatedConditions().size())
904 return emitOpError(
"must have the same number of updated conditions "
905 "(results) as retained operands");
913 if (deallocOp.getMemrefs() == memrefs &&
914 deallocOp.getConditions() == conditions)
918 deallocOp.getMemrefsMutable().assign(memrefs);
919 deallocOp.getConditionsMutable().assign(conditions);
939 struct DeallocRemoveDuplicateDeallocMemrefs
943 LogicalResult matchAndRewrite(DeallocOp deallocOp,
948 for (
auto [i, memref, cond] :
950 if (memrefToCondition.count(memref)) {
953 Value &newCond = newConditions[memrefToCondition[memref]];
956 rewriter.
create<arith::OrIOp>(deallocOp.getLoc(), newCond, cond);
958 memrefToCondition.insert({memref, newConditions.size()});
959 newMemrefs.push_back(memref);
960 newConditions.push_back(cond);
981 struct DeallocRemoveDuplicateRetainedMemrefs
985 LogicalResult matchAndRewrite(DeallocOp deallocOp,
992 for (
auto retained : deallocOp.getRetained()) {
993 if (seen.count(retained)) {
994 resultReplacementIdx.push_back(seen[retained]);
999 newRetained.push_back(retained);
1000 resultReplacementIdx.push_back(i++);
1005 if (newRetained.size() == deallocOp.getRetained().size())
1011 rewriter.
create<DeallocOp>(deallocOp.getLoc(), deallocOp.getMemrefs(),
1012 deallocOp.getConditions(), newRetained);
1014 llvm::map_range(resultReplacementIdx, [&](
unsigned idx) {
1015 return newDeallocOp.getUpdatedConditions()[idx];
1017 rewriter.
replaceOp(deallocOp, replacements);
1030 LogicalResult matchAndRewrite(DeallocOp deallocOp,
1032 if (deallocOp.getMemrefs().empty()) {
1033 Value constFalse = rewriter.
create<arith::ConstantOp>(
1059 LogicalResult matchAndRewrite(DeallocOp deallocOp,
1062 for (
auto [memref, cond] :
1063 llvm::zip(deallocOp.getMemrefs(), deallocOp.getConditions())) {
1065 newMemrefs.push_back(memref);
1066 newConditions.push_back(cond);
1096 LogicalResult matchAndRewrite(DeallocOp deallocOp,
1099 llvm::map_range(deallocOp.getMemrefs(), [&](
Value memref) {
1100 auto extractStridedOp =
1101 memref.getDefiningOp<memref::ExtractStridedMetadataOp>();
1102 if (!extractStridedOp)
1104 Value allocMemref = extractStridedOp.getOperand();
1105 auto allocOp = allocMemref.getDefiningOp<MemoryEffectOpInterface>();
1108 if (allocOp.getEffectOnValue<MemoryEffects::Allocate>(allocMemref))
1114 deallocOp.getConditions(), rewriter);
1132 struct RemoveAllocDeallocPairWhenNoOtherUsers
1136 LogicalResult matchAndRewrite(DeallocOp deallocOp,
1140 for (
auto [memref, cond] :
1141 llvm::zip(deallocOp.getMemrefs(), deallocOp.getConditions())) {
1142 if (
auto allocOp = memref.
getDefiningOp<MemoryEffectOpInterface>()) {
1147 hasSingleEffect<MemoryEffects::Allocate>(allocOp, memref) &&
1149 toDelete.push_back(allocOp);
1154 newMemrefs.push_back(memref);
1155 newConditions.push_back(cond);
1178 patterns.
add<DeallocRemoveDuplicateDeallocMemrefs,
1179 DeallocRemoveDuplicateRetainedMemrefs, EraseEmptyDealloc,
1180 EraseAlwaysFalseDealloc, SkipExtractMetadataOfAlloc,
1181 RemoveAllocDeallocPairWhenNoOtherUsers>(context);
1188 #define GET_OP_CLASSES
1189 #include "mlir/Dialect/Bufferization/IR/BufferizationOps.cpp.inc"
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.
static llvm::ManagedStatic< PassManagerOptions > options
static void print(spirv::VerCapExtAttr triple, DialectAsmPrinter &printer)
static RankedTensorType getBufferType(const SparseTensorType &stt, bool needTmpCOO)
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...
Base class for generic analysis states.
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 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 ParseResult parseColon()=0
Parse a : 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.
Block represents an ordered list of Operations.
IntegerAttr getIndexAttr(int64_t value)
DenseI32ArrayAttr getDenseI32ArrayAttr(ArrayRef< int32_t > values)
BoolAttr getBoolAttr(bool value)
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
MLIRContext is the top-level object for a collection of MLIR operations.
This class provides a mutable adaptor for a range of operands.
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.
RAII guard to reset the insertion point of the builder when destroyed.
This class helps build Operations.
Operation * create(const OperationState &state)
Creates an operation given the fields represented as an OperationState.
This class represents a single result from folding an operation.
This class represents an operand of an operation.
unsigned getOperandNumber()
Return which operand this is in the OpOperand list of the Operation.
This is a value defined by a result of an operation.
Simple wrapper around a void* in order to express generically how to pass in op properties through AP...
Operation is the basic unit of execution within MLIR.
Location getLoc()
The source location the operation was defined or derived from.
Block * getBlock()
Returns the operation block that contains this operation.
A special type of RewriterBase that coordinates the application of a rewrite pattern on the current I...
This class provides an abstraction over the different types of ranges over Regions.
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.
static DerivedEffect * get()
Returns a unique instance for the derived effect class.
static DefaultResource * get()
Returns a unique instance for the given effect class.
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...
This class provides an abstraction over the different types of ranges over Values.
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Type getType() const
Return the type of this value.
bool hasOneUse() const
Returns true if this value has exactly one use.
Location getLoc() const
Return the location of this value.
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
void populateDeallocOpCanonicalizationPatterns(RewritePatternSet &patterns, MLIRContext *context)
Add the canonicalization patterns for bufferization.dealloc to the given pattern set to make them ava...
void replaceOpWithBufferizedValues(RewriterBase &rewriter, Operation *op, ValueRange values)
Replace an op with replacement values.
BaseMemRefType getMemRefTypeWithStaticIdentityLayout(TensorType tensorType, Attribute memorySpace=nullptr)
Return a MemRef type with a static identity layout (i.e., no layout map).
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 foldToMemrefToTensorPair(RewriterBase &rewriter, ToMemrefOp toMemref, const BufferizationOptions &options)
Try to fold to_memref(to_tensor(x)).
FailureOr< BaseMemRefType > getBufferType(Value value, const BufferizationOptions &options)
Return the buffer type for a given Value (tensor) after bufferization without bufferizing any IR.
FailureOr< Value > getBuffer(RewriterBase &rewriter, Value value, const BufferizationOptions &options)
Lookup the buffer for the given value.
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...
constexpr void enumerate(std::tuple< Tys... > &tuple, CallbackT &&callback)
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".
QueryRef parse(llvm::StringRef line, const QuerySession &qs)
SmallVector< OpFoldResult > getMixedSizes(OpBuilder &builder, Location loc, Value value)
Return the dimensions of the given tensor value.
Include the generated interface declarations.
bool matchPattern(Value value, const Pattern &pattern)
Entry point for matching a pattern over a Value.
detail::constant_int_value_binder m_ConstantInt(IntegerAttr::ValueType *bind_value)
Matches a constant holding a scalar/vector/tensor integer (splat) and writes the integer value to bin...
LogicalResult reifyResultShapes(OpBuilder &b, Operation *op, ReifiedRankedShapedTypeDims &reifiedReturnShapes)
Reify the shape of the result of an operation (typically in terms of the shape of its operands).
Type getType(OpFoldResult ofr)
Returns the int type of the integer in ofr.
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.
LogicalResult getStridesAndOffset(MemRefType t, SmallVectorImpl< int64_t > &strides, int64_t &offset)
Returns the strides of the MemRef if the layout map is in strided form.
detail::constant_int_predicate_matcher m_Zero()
Matches a constant scalar / vector splat / tensor splat integer zero.
auto get(MLIRContext *context, Ts &&...params)
Helper method that injects context only if needed, this helps unify some of the attribute constructio...
LogicalResult verify(Operation *op, bool verifyRecursively=true)
Perform (potentially expensive) checks of invariants, used to detect compiler bugs,...
The following effect indicates that the operation allocates from some resource.
The following effect indicates that the operation frees some resource that has been allocated.
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.
SmallVector< Value, 4 > operands
void addAttribute(StringRef name, Attribute attr)
Add an attribute with the specified name.
void addTypes(ArrayRef< Type > newTypes)
Options for BufferizableOpInterface-based bufferization.