MLIR 22.0.0git
Pattern.h
Go to the documentation of this file.
1//===- Pattern.h - Pattern for conversion to the LLVM dialect ---*- C++ -*-===//
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
9#ifndef MLIR_CONVERSION_LLVMCOMMON_PATTERN_H
10#define MLIR_CONVERSION_LLVMCOMMON_PATTERN_H
11
16
17namespace mlir {
18class CallOpInterface;
19
20namespace LLVM {
21namespace detail {
22/// Replaces the given operation "op" with a new operation of type "targetOp"
23/// and given operands.
24LogicalResult oneToOneRewrite(Operation *op, StringRef targetOp,
25 ValueRange operands,
26 ArrayRef<NamedAttribute> targetAttrs,
27 Attribute propertiesAttr,
28 const LLVMTypeConverter &typeConverter,
29 ConversionPatternRewriter &rewriter);
30
31/// Replaces the given operation "op" with a call to an LLVM intrinsic with the
32/// specified name "intrinsic" and operands.
33///
34/// The rewrite performs a simple one-to-one matching between the op and LLVM
35/// intrinsic. For example:
36///
37/// ```mlir
38/// %res = intr.op %val : vector<16xf32>
39/// ```
40///
41/// can be converted to
42///
43/// ```mlir
44/// %res = llvm.call_intrinsic "intrinsic"(%val)
45/// ```
46///
47/// The provided operands must be LLVM-compatible.
48///
49/// Upholds a convention that multi-result operations get converted into an
50/// operation returning the LLVM IR structure type, in which case individual
51/// values are first extracted before replacing the original results.
52LogicalResult intrinsicRewrite(Operation *op, StringRef intrinsic,
53 ValueRange operands,
54 const LLVMTypeConverter &typeConverter,
55 RewriterBase &rewriter);
56
57/// Return "true" if the given type is an unsupported floating point type.
58/// In case of a vector type, return "true" if the element type is an
59/// unsupported floating point type.
60bool isUnsupportedFloatingPointType(const TypeConverter &typeConverter,
61 Type type);
62/// Return "true" if the given op has any unsupported floating point
63/// types (either operands or results).
65 const TypeConverter &typeConverter);
66} // namespace detail
67
68/// Decomposes a `src` value into a set of values of type `dstType` through
69/// series of bitcasts and vector ops. Src and dst types are expected to be int
70/// or float types or vector types of them.
72 Type dstType);
73
74/// Composes a set of `src` values into a single value of type `dstType` through
75/// series of bitcasts and vector ops. Inversely to `decomposeValue`, this
76/// function is used to combine multiple values into a single value.
78 Type dstType);
79
80/// Performs the index computation to get to the element at `indices` of the
81/// memory pointed to by `memRefDesc`, using the layout map of `type`.
82/// The indices are linearized as:
83/// `base_offset + index_0 * stride_0 + ... + index_n * stride_n`.
85 OpBuilder &builder, Location loc, const LLVMTypeConverter &converter,
86 MemRefType type, Value memRefDesc, ValueRange indices,
87 LLVM::GEPNoWrapFlags noWrapFlags = LLVM::GEPNoWrapFlags::none);
88} // namespace LLVM
89
90/// Base class for operation conversions targeting the LLVM IR dialect. It
91/// provides the conversion patterns with access to the LLVMTypeConverter and
92/// the LowerToLLVMOptions. The class captures the LLVMTypeConverter and the
93/// LowerToLLVMOptions by reference meaning the references have to remain alive
94/// during the entire pattern lifetime.
96public:
97 ConvertToLLVMPattern(StringRef rootOpName, MLIRContext *context,
98 const LLVMTypeConverter &typeConverter,
99 PatternBenefit benefit = 1);
100
101protected:
102 /// See `ConversionPattern::ConversionPattern` for information on the other
103 /// available constructors.
104 using ConversionPattern::ConversionPattern;
105
106 /// Returns the LLVM dialect.
107 LLVM::LLVMDialect &getDialect() const;
108
109 const LLVMTypeConverter *getTypeConverter() const;
110
111 /// Gets the MLIR type wrapping the LLVM integer type whose bit width is
112 /// defined by the used type converter.
113 Type getIndexType() const;
114
115 /// Gets the MLIR type wrapping the LLVM integer type whose bit width
116 /// corresponds to that of a LLVM pointer type.
117 Type getIntPtrType(unsigned addressSpace = 0) const;
118
119 /// Gets the MLIR type wrapping the LLVM void type.
120 Type getVoidType() const;
121
122 /// Get the MLIR type wrapping the LLVM i8* type.
123 [[deprecated("Use getPtrType() instead!")]]
124 Type getVoidPtrType() const;
125
126 /// Get the MLIR type wrapping the LLVM ptr type.
127 Type getPtrType(unsigned addressSpace = 0) const;
128
129 /// Create a constant Op producing a value of `resultType` from an index-typed
130 /// integer attribute.
131 static Value createIndexAttrConstant(OpBuilder &builder, Location loc,
132 Type resultType, int64_t value);
133
134 /// Convenience wrapper for the corresponding helper utility.
135 /// This is a strided getElementPtr variant with linearized subscripts.
137 ConversionPatternRewriter &rewriter, Location loc, MemRefType type,
138 Value memRefDesc, ValueRange indices,
139 LLVM::GEPNoWrapFlags noWrapFlags = LLVM::GEPNoWrapFlags::none) const;
140
141 /// Returns if the given memref type is convertible to LLVM and has an
142 /// identity layout map.
143 bool isConvertibleAndHasIdentityMaps(MemRefType type) const;
144
145 /// Returns the type of a pointer to an element of the memref.
146 Type getElementPtrType(MemRefType type) const;
147
148 /// Computes sizes, strides and buffer size of `memRefType` with identity
149 /// layout. Emits constant ops for the static sizes of `memRefType`, and uses
150 /// `dynamicSizes` for the others. Emits instructions to compute strides and
151 /// buffer size from these sizes.
152 ///
153 /// For example, memref<4x?xf32> with `sizeInBytes = true` emits:
154 /// `sizes[0]` = llvm.mlir.constant(4 : index) : i64
155 /// `sizes[1]` = `dynamicSizes[0]`
156 /// `strides[1]` = llvm.mlir.constant(1 : index) : i64
157 /// `strides[0]` = `sizes[0]`
158 /// %size = llvm.mul `sizes[0]`, `sizes[1]` : i64
159 /// %nullptr = llvm.mlir.zero : !llvm.ptr
160 /// %gep = llvm.getelementptr %nullptr[%size]
161 /// : (!llvm.ptr, i64) -> !llvm.ptr, f32
162 /// `sizeBytes` = llvm.ptrtoint %gep : !llvm.ptr to i64
163 ///
164 /// If `sizeInBytes = false`, memref<4x?xf32> emits:
165 /// `sizes[0]` = llvm.mlir.constant(4 : index) : i64
166 /// `sizes[1]` = `dynamicSizes[0]`
167 /// `strides[1]` = llvm.mlir.constant(1 : index) : i64
168 /// `strides[0]` = `sizes[0]`
169 /// %size = llvm.mul `sizes[0]`, `sizes[1]` : i64
170 void getMemRefDescriptorSizes(Location loc, MemRefType memRefType,
171 ValueRange dynamicSizes,
172 ConversionPatternRewriter &rewriter,
174 SmallVectorImpl<Value> &strides, Value &size,
175 bool sizeInBytes = true) const;
176
177 /// Computes the size of type in bytes.
179 ConversionPatternRewriter &rewriter) const;
180
181 /// Computes total number of elements for the given MemRef and dynamicSizes.
182 Value getNumElements(Location loc, MemRefType memRefType,
183 ValueRange dynamicSizes,
184 ConversionPatternRewriter &rewriter) const;
185
186 /// Creates and populates a canonical memref descriptor struct.
188 createMemRefDescriptor(Location loc, MemRefType memRefType,
189 Value allocatedPtr, Value alignedPtr,
190 ArrayRef<Value> sizes, ArrayRef<Value> strides,
191 ConversionPatternRewriter &rewriter) const;
192
193 /// Copies the given unranked memory descriptor to heap-allocated memory (if
194 /// toDynamic is true) or to stack-allocated memory (otherwise) and returns
195 /// the new descriptor. Also frees the previously used memory (that is assumed
196 /// to be heap-allocated) if toDynamic is false. Returns a "null" SSA value
197 /// on failure.
199 UnrankedMemRefType memRefType, Value operand,
200 bool toDynamic) const;
201
202 /// Copies the memory descriptor for any operands that were unranked
203 /// descriptors originally to heap-allocated memory (if toDynamic is true) or
204 /// to stack-allocated memory (otherwise). The vector of descriptors is
205 /// updated in place. Also frees the previously used memory (that is assumed
206 /// to be heap-allocated) if toDynamic is false.
207 LogicalResult copyUnrankedDescriptors(OpBuilder &builder, Location loc,
208 TypeRange origTypes,
209 SmallVectorImpl<Value> &operands,
210 bool toDynamic) const;
211};
212
213/// Utility class for operation conversions targeting the LLVM dialect that
214/// match exactly one source operation.
215template <typename SourceOp, bool FailOnUnsupportedFP = false>
217public:
218 using OpAdaptor = typename SourceOp::Adaptor;
220 typename SourceOp::template GenericAdaptor<ArrayRef<ValueRange>>;
221
222 explicit ConvertOpToLLVMPattern(const LLVMTypeConverter &typeConverter,
223 PatternBenefit benefit = 1)
224 : ConvertToLLVMPattern(SourceOp::getOperationName(),
225 &typeConverter.getContext(), typeConverter,
226 benefit) {}
227
228 /// Wrappers around the RewritePattern methods that pass the derived op type.
229 LogicalResult
231 ConversionPatternRewriter &rewriter) const final {
232 // Bail on unsupported floating point types. (These are type-converted to
233 // integer types.)
234 if (FailOnUnsupportedFP && LLVM::detail::opHasUnsupportedFloatingPointTypes(
235 op, *this->typeConverter)) {
236 return rewriter.notifyMatchFailure(op, "unsupported floating point type");
237 }
238 auto sourceOp = cast<SourceOp>(op);
239 return matchAndRewrite(sourceOp, OpAdaptor(operands, sourceOp), rewriter);
240 }
241 LogicalResult
243 ConversionPatternRewriter &rewriter) const final {
244 // Bail on unsupported floating point types. (These are type-converted to
245 // integer types.)
246 if (FailOnUnsupportedFP && LLVM::detail::opHasUnsupportedFloatingPointTypes(
247 op, *this->typeConverter)) {
248 return rewriter.notifyMatchFailure(op, "unsupported floating point type");
249 }
250 auto sourceOp = cast<SourceOp>(op);
251 return matchAndRewrite(sourceOp, OneToNOpAdaptor(operands, sourceOp),
252 rewriter);
253 }
254
255 /// Methods that operate on the SourceOp type. One of these must be
256 /// overridden by the derived pattern class.
257 virtual LogicalResult
258 matchAndRewrite(SourceOp op, OpAdaptor adaptor,
259 ConversionPatternRewriter &rewriter) const {
260 llvm_unreachable("matchAndRewrite is not implemented");
261 }
262 virtual LogicalResult
263 matchAndRewrite(SourceOp op, OneToNOpAdaptor adaptor,
264 ConversionPatternRewriter &rewriter) const {
265 return dispatchTo1To1(*this, op, adaptor, rewriter);
266 }
267
268private:
269 using ConvertToLLVMPattern::matchAndRewrite;
270};
271
272/// Utility class for operation conversions targeting the LLVM dialect that
273/// allows for matching and rewriting against an instance of an OpInterface
274/// class.
275template <typename SourceOp>
277public:
279 const LLVMTypeConverter &typeConverter, PatternBenefit benefit = 1)
280 : ConvertToLLVMPattern(typeConverter, Pattern::MatchInterfaceOpTypeTag(),
281 SourceOp::getInterfaceID(), benefit,
282 &typeConverter.getContext()) {}
283
284 /// Wrappers around the RewritePattern methods that pass the derived op type.
285 LogicalResult
287 ConversionPatternRewriter &rewriter) const final {
288 return matchAndRewrite(cast<SourceOp>(op), operands, rewriter);
289 }
290 LogicalResult
292 ConversionPatternRewriter &rewriter) const final {
293 return matchAndRewrite(cast<SourceOp>(op), operands, rewriter);
294 }
295
296 /// Methods that operate on the SourceOp type. One of these must be
297 /// overridden by the derived pattern class.
298 virtual LogicalResult
299 matchAndRewrite(SourceOp op, ArrayRef<Value> operands,
300 ConversionPatternRewriter &rewriter) const {
301 llvm_unreachable("matchAndRewrite is not implemented");
302 }
303 virtual LogicalResult
305 ConversionPatternRewriter &rewriter) const {
306 return dispatchTo1To1(*this, op, operands, rewriter);
307 }
308
309private:
310 using ConvertToLLVMPattern::matchAndRewrite;
311};
312
313/// Generic implementation of one-to-one conversion from "SourceOp" to
314/// "TargetOp" where the latter belongs to the LLVM dialect or an equivalent.
315/// Upholds a convention that multi-result operations get converted into an
316/// operation returning the LLVM IR structure type, in which case individual
317/// values must be extracted from using LLVM::ExtractValueOp before being used.
318template <typename SourceOp, typename TargetOp>
320public:
323
324 /// Converts the type of the result to an LLVM type, pass operands as is,
325 /// preserve attributes.
326 LogicalResult
327 matchAndRewrite(SourceOp op, typename SourceOp::Adaptor adaptor,
328 ConversionPatternRewriter &rewriter) const override {
330 op, TargetOp::getOperationName(), adaptor.getOperands(), op->getAttrs(),
331 /*propertiesAttr=*/Attribute{}, *this->getTypeConverter(), rewriter);
332 }
333};
334
335} // namespace mlir
336
337#endif // MLIR_CONVERSION_LLVMCOMMON_PATTERN_H
b getContext())
Attributes are known-constant values of operations.
Definition Attributes.h:25
LogicalResult matchAndRewrite(Operation *op, ArrayRef< Value > operands, ConversionPatternRewriter &rewriter) const final
Wrappers around the RewritePattern methods that pass the derived op type.
Definition Pattern.h:286
virtual LogicalResult matchAndRewrite(SourceOp op, ArrayRef< ValueRange > operands, ConversionPatternRewriter &rewriter) const
Definition Pattern.h:304
ConvertOpInterfaceToLLVMPattern(const LLVMTypeConverter &typeConverter, PatternBenefit benefit=1)
Definition Pattern.h:278
virtual LogicalResult matchAndRewrite(SourceOp op, ArrayRef< Value > operands, ConversionPatternRewriter &rewriter) const
Methods that operate on the SourceOp type.
Definition Pattern.h:299
LogicalResult matchAndRewrite(Operation *op, ArrayRef< ValueRange > operands, ConversionPatternRewriter &rewriter) const final
Definition Pattern.h:291
ConvertOpToLLVMPattern(const LLVMTypeConverter &typeConverter, PatternBenefit benefit=1)
Definition Pattern.h:222
LogicalResult matchAndRewrite(Operation *op, ArrayRef< Value > operands, ConversionPatternRewriter &rewriter) const final
Wrappers around the RewritePattern methods that pass the derived op type.
Definition Pattern.h:230
typename SourceOp::template GenericAdaptor< ArrayRef< ValueRange > > OneToNOpAdaptor
Definition Pattern.h:219
virtual LogicalResult matchAndRewrite(SourceOp op, OpAdaptor adaptor, ConversionPatternRewriter &rewriter) const
Methods that operate on the SourceOp type.
Definition Pattern.h:258
virtual LogicalResult matchAndRewrite(SourceOp op, OneToNOpAdaptor adaptor, ConversionPatternRewriter &rewriter) const
Definition Pattern.h:263
LogicalResult matchAndRewrite(Operation *op, ArrayRef< ValueRange > operands, ConversionPatternRewriter &rewriter) const final
Definition Pattern.h:242
typename SourceOp::Adaptor OpAdaptor
Definition Pattern.h:218
Type getVoidType() const
Gets the MLIR type wrapping the LLVM void type.
Definition Pattern.cpp:45
MemRefDescriptor createMemRefDescriptor(Location loc, MemRefType memRefType, Value allocatedPtr, Value alignedPtr, ArrayRef< Value > sizes, ArrayRef< Value > strides, ConversionPatternRewriter &rewriter) const
Creates and populates a canonical memref descriptor struct.
Definition Pattern.cpp:190
ConvertToLLVMPattern(StringRef rootOpName, MLIRContext *context, const LLVMTypeConverter &typeConverter, PatternBenefit benefit=1)
Definition Pattern.cpp:22
Value getStridedElementPtr(ConversionPatternRewriter &rewriter, Location loc, MemRefType type, Value memRefDesc, ValueRange indices, LLVM::GEPNoWrapFlags noWrapFlags=LLVM::GEPNoWrapFlags::none) const
Convenience wrapper for the corresponding helper utility.
Definition Pattern.cpp:64
void getMemRefDescriptorSizes(Location loc, MemRefType memRefType, ValueRange dynamicSizes, ConversionPatternRewriter &rewriter, SmallVectorImpl< Value > &sizes, SmallVectorImpl< Value > &strides, Value &size, bool sizeInBytes=true) const
Computes sizes, strides and buffer size of memRefType with identity layout.
Definition Pattern.cpp:88
Type getPtrType(unsigned addressSpace=0) const
Get the MLIR type wrapping the LLVM ptr type.
Definition Pattern.cpp:49
Type getIndexType() const
Gets the MLIR type wrapping the LLVM integer type whose bit width is defined by the used type convert...
Definition Pattern.cpp:36
const LLVMTypeConverter * getTypeConverter() const
Definition Pattern.cpp:27
Value getNumElements(Location loc, MemRefType memRefType, ValueRange dynamicSizes, ConversionPatternRewriter &rewriter) const
Computes total number of elements for the given MemRef and dynamicSizes.
Definition Pattern.cpp:158
LLVM::LLVMDialect & getDialect() const
Returns the LLVM dialect.
Definition Pattern.cpp:32
Value getSizeInBytes(Location loc, Type type, ConversionPatternRewriter &rewriter) const
Computes the size of type in bytes.
Definition Pattern.cpp:143
Type getIntPtrType(unsigned addressSpace=0) const
Gets the MLIR type wrapping the LLVM integer type whose bit width corresponds to that of a LLVM point...
Definition Pattern.cpp:40
Value copyUnrankedDescriptor(OpBuilder &builder, Location loc, UnrankedMemRefType memRefType, Value operand, bool toDynamic) const
Copies the given unranked memory descriptor to heap-allocated memory (if toDynamic is true) or to sta...
Definition Pattern.cpp:219
LogicalResult copyUnrankedDescriptors(OpBuilder &builder, Location loc, TypeRange origTypes, SmallVectorImpl< Value > &operands, bool toDynamic) const
Copies the memory descriptor for any operands that were unranked descriptors originally to heap-alloc...
Definition Pattern.cpp:278
Type getElementPtrType(MemRefType type) const
Returns the type of a pointer to an element of the memref.
Definition Pattern.cpp:81
static Value createIndexAttrConstant(OpBuilder &builder, Location loc, Type resultType, int64_t value)
Create a constant Op producing a value of resultType from an index-typed integer attribute.
Definition Pattern.cpp:56
bool isConvertibleAndHasIdentityMaps(MemRefType type) const
Returns if the given memref type is convertible to LLVM and has an identity layout map.
Definition Pattern.cpp:74
Type getVoidPtrType() const
Get the MLIR type wrapping the LLVM i8* type.
Definition Pattern.cpp:54
Conversion from types to the LLVM IR dialect.
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:63
Helper class to produce LLVM dialect operations extracting or inserting elements of a MemRef descript...
Generic implementation of one-to-one conversion from "SourceOp" to "TargetOp" where the latter belong...
Definition Pattern.h:319
OneToOneConvertToLLVMPattern< SourceOp, TargetOp > Super
Definition Pattern.h:322
LogicalResult matchAndRewrite(SourceOp op, typename SourceOp::Adaptor adaptor, ConversionPatternRewriter &rewriter) const override
Converts the type of the result to an LLVM type, pass operands as is, preserve attributes.
Definition Pattern.h:327
This class helps build Operations.
Definition Builders.h:207
Operation is the basic unit of execution within MLIR.
Definition Operation.h:88
This class represents the benefit of a pattern match in a unitless scheme that ranges from 0 (very li...
This class contains all of the data related to a pattern, but does not contain any methods or logic f...
This class coordinates the application of a rewrite on a set of IR, providing a way for clients to tr...
This class provides an abstraction over the various different ranges of value types.
Definition TypeRange.h:37
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:387
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
bool isUnsupportedFloatingPointType(const TypeConverter &typeConverter, Type type)
Return "true" if the given type is an unsupported floating point type.
Definition Pattern.cpp:530
LogicalResult oneToOneRewrite(Operation *op, StringRef targetOp, ValueRange operands, ArrayRef< NamedAttribute > targetAttrs, Attribute propertiesAttr, const LLVMTypeConverter &typeConverter, ConversionPatternRewriter &rewriter)
Replaces the given operation "op" with a new operation of type "targetOp" and given operands.
Definition Pattern.cpp:301
bool opHasUnsupportedFloatingPointTypes(Operation *op, const TypeConverter &typeConverter)
Return "true" if the given op has any unsupported floating point types (either operands or results).
Definition Pattern.cpp:541
LogicalResult intrinsicRewrite(Operation *op, StringRef intrinsic, ValueRange operands, const LLVMTypeConverter &typeConverter, RewriterBase &rewriter)
Replaces the given operation "op" with a call to an LLVM intrinsic with the specified name "intrinsic...
Definition Pattern.cpp:340
Value getStridedElementPtr(OpBuilder &builder, Location loc, const LLVMTypeConverter &converter, MemRefType type, Value memRefDesc, ValueRange indices, LLVM::GEPNoWrapFlags noWrapFlags=LLVM::GEPNoWrapFlags::none)
Performs the index computation to get to the element at indices of the memory pointed to by memRefDes...
Definition Pattern.cpp:471
Value composeValue(OpBuilder &builder, Location loc, ValueRange src, Type dstType)
Composes a set of src values into a single value of type dstType through series of bitcasts and vecto...
Definition Pattern.cpp:432
SmallVector< Value > decomposeValue(OpBuilder &builder, Location loc, Value src, Type dstType)
Decomposes a src value into a set of values of type dstType through series of bitcasts and vector ops...
Definition Pattern.cpp:393
Include the generated interface declarations.