MLIR  21.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 
17 namespace mlir {
18 class CallOpInterface;
19 
20 namespace LLVM {
21 namespace detail {
22 /// Handle generically setting flags as native properties on LLVM operations.
23 void setNativeProperties(Operation *op, IntegerOverflowFlags overflowFlags);
24 
25 /// Replaces the given operation "op" with a new operation of type "targetOp"
26 /// and given operands.
27 LogicalResult oneToOneRewrite(
28  Operation *op, StringRef targetOp, ValueRange operands,
29  ArrayRef<NamedAttribute> targetAttrs,
30  const LLVMTypeConverter &typeConverter, ConversionPatternRewriter &rewriter,
31  IntegerOverflowFlags overflowFlags = IntegerOverflowFlags::none);
32 
33 /// Replaces the given operation "op" with a call to an LLVM intrinsic with the
34 /// specified name "intrinsic" and operands.
35 ///
36 /// The rewrite performs a simple one-to-one matching between the op and LLVM
37 /// intrinsic. For example:
38 ///
39 /// ```mlir
40 /// %res = intr.op %val : vector<16xf32>
41 /// ```
42 ///
43 /// can be converted to
44 ///
45 /// ```mlir
46 /// %res = llvm.call_intrinsic "intrinsic"(%val)
47 /// ```
48 ///
49 /// The provided operands must be LLVM-compatible.
50 ///
51 /// Upholds a convention that multi-result operations get converted into an
52 /// operation returning the LLVM IR structure type, in which case individual
53 /// values are first extracted before replacing the original results.
54 LogicalResult intrinsicRewrite(Operation *op, StringRef intrinsic,
55  ValueRange operands,
56  const LLVMTypeConverter &typeConverter,
57  RewriterBase &rewriter);
58 
59 } // namespace detail
60 
61 /// Decomposes a `src` value into a set of values of type `dstType` through
62 /// series of bitcasts and vector ops. Src and dst types are expected to be int
63 /// or float types or vector types of them.
65  Type dstType);
66 
67 /// Composes a set of `src` values into a single value of type `dstType` through
68 /// series of bitcasts and vector ops. Inversely to `decomposeValue`, this
69 /// function is used to combine multiple values into a single value.
71  Type dstType);
72 
73 /// Performs the index computation to get to the element at `indices` of the
74 /// memory pointed to by `memRefDesc`, using the layout map of `type`.
75 /// The indices are linearized as:
76 /// `base_offset + index_0 * stride_0 + ... + index_n * stride_n`.
78  OpBuilder &builder, Location loc, const LLVMTypeConverter &converter,
79  MemRefType type, Value memRefDesc, ValueRange indices,
80  LLVM::GEPNoWrapFlags noWrapFlags = LLVM::GEPNoWrapFlags::none);
81 } // namespace LLVM
82 
83 /// Base class for operation conversions targeting the LLVM IR dialect. It
84 /// provides the conversion patterns with access to the LLVMTypeConverter and
85 /// the LowerToLLVMOptions. The class captures the LLVMTypeConverter and the
86 /// LowerToLLVMOptions by reference meaning the references have to remain alive
87 /// during the entire pattern lifetime.
89 public:
90  ConvertToLLVMPattern(StringRef rootOpName, MLIRContext *context,
92  PatternBenefit benefit = 1);
93 
94 protected:
95  /// Returns the LLVM dialect.
96  LLVM::LLVMDialect &getDialect() const;
97 
98  const LLVMTypeConverter *getTypeConverter() const;
99 
100  /// Gets the MLIR type wrapping the LLVM integer type whose bit width is
101  /// defined by the used type converter.
102  Type getIndexType() const;
103 
104  /// Gets the MLIR type wrapping the LLVM integer type whose bit width
105  /// corresponds to that of a LLVM pointer type.
106  Type getIntPtrType(unsigned addressSpace = 0) const;
107 
108  /// Gets the MLIR type wrapping the LLVM void type.
109  Type getVoidType() const;
110 
111  /// Get the MLIR type wrapping the LLVM i8* type.
112  Type getVoidPtrType() const;
113 
114  /// Create a constant Op producing a value of `resultType` from an index-typed
115  /// integer attribute.
116  static Value createIndexAttrConstant(OpBuilder &builder, Location loc,
117  Type resultType, int64_t value);
118 
119  /// Convenience wrapper for the corresponding helper utility.
120  /// This is a strided getElementPtr variant with linearized subscripts.
122  ConversionPatternRewriter &rewriter, Location loc, MemRefType type,
123  Value memRefDesc, ValueRange indices,
124  LLVM::GEPNoWrapFlags noWrapFlags = LLVM::GEPNoWrapFlags::none) const;
125 
126  /// Returns if the given memref type is convertible to LLVM and has an
127  /// identity layout map.
128  bool isConvertibleAndHasIdentityMaps(MemRefType type) const;
129 
130  /// Returns the type of a pointer to an element of the memref.
131  Type getElementPtrType(MemRefType type) const;
132 
133  /// Computes sizes, strides and buffer size of `memRefType` with identity
134  /// layout. Emits constant ops for the static sizes of `memRefType`, and uses
135  /// `dynamicSizes` for the others. Emits instructions to compute strides and
136  /// buffer size from these sizes.
137  ///
138  /// For example, memref<4x?xf32> with `sizeInBytes = true` emits:
139  /// `sizes[0]` = llvm.mlir.constant(4 : index) : i64
140  /// `sizes[1]` = `dynamicSizes[0]`
141  /// `strides[1]` = llvm.mlir.constant(1 : index) : i64
142  /// `strides[0]` = `sizes[0]`
143  /// %size = llvm.mul `sizes[0]`, `sizes[1]` : i64
144  /// %nullptr = llvm.mlir.zero : !llvm.ptr
145  /// %gep = llvm.getelementptr %nullptr[%size]
146  /// : (!llvm.ptr, i64) -> !llvm.ptr, f32
147  /// `sizeBytes` = llvm.ptrtoint %gep : !llvm.ptr to i64
148  ///
149  /// If `sizeInBytes = false`, memref<4x?xf32> emits:
150  /// `sizes[0]` = llvm.mlir.constant(4 : index) : i64
151  /// `sizes[1]` = `dynamicSizes[0]`
152  /// `strides[1]` = llvm.mlir.constant(1 : index) : i64
153  /// `strides[0]` = `sizes[0]`
154  /// %size = llvm.mul `sizes[0]`, `sizes[1]` : i64
155  void getMemRefDescriptorSizes(Location loc, MemRefType memRefType,
156  ValueRange dynamicSizes,
157  ConversionPatternRewriter &rewriter,
158  SmallVectorImpl<Value> &sizes,
159  SmallVectorImpl<Value> &strides, Value &size,
160  bool sizeInBytes = true) const;
161 
162  /// Computes the size of type in bytes.
163  Value getSizeInBytes(Location loc, Type type,
164  ConversionPatternRewriter &rewriter) const;
165 
166  /// Computes total number of elements for the given MemRef and dynamicSizes.
167  Value getNumElements(Location loc, MemRefType memRefType,
168  ValueRange dynamicSizes,
169  ConversionPatternRewriter &rewriter) const;
170 
171  /// Creates and populates a canonical memref descriptor struct.
173  createMemRefDescriptor(Location loc, MemRefType memRefType,
174  Value allocatedPtr, Value alignedPtr,
175  ArrayRef<Value> sizes, ArrayRef<Value> strides,
176  ConversionPatternRewriter &rewriter) const;
177 
178  /// Copies the memory descriptor for any operands that were unranked
179  /// descriptors originally to heap-allocated memory (if toDynamic is true) or
180  /// to stack-allocated memory (otherwise). Also frees the previously used
181  /// memory (that is assumed to be heap-allocated) if toDynamic is false.
182  LogicalResult copyUnrankedDescriptors(OpBuilder &builder, Location loc,
183  TypeRange origTypes,
184  SmallVectorImpl<Value> &operands,
185  bool toDynamic) const;
186 };
187 
188 /// Utility class for operation conversions targeting the LLVM dialect that
189 /// match exactly one source operation.
190 template <typename SourceOp>
192 public:
193  using OpAdaptor = typename SourceOp::Adaptor;
195  typename SourceOp::template GenericAdaptor<ArrayRef<ValueRange>>;
196 
198  PatternBenefit benefit = 1)
199  : ConvertToLLVMPattern(SourceOp::getOperationName(),
201  benefit) {}
202 
203  /// Wrappers around the RewritePattern methods that pass the derived op type.
204  LogicalResult
206  ConversionPatternRewriter &rewriter) const final {
207  auto sourceOp = cast<SourceOp>(op);
208  return matchAndRewrite(sourceOp, OpAdaptor(operands, sourceOp), rewriter);
209  }
210  LogicalResult
212  ConversionPatternRewriter &rewriter) const final {
213  auto sourceOp = cast<SourceOp>(op);
214  return matchAndRewrite(sourceOp, OneToNOpAdaptor(operands, sourceOp),
215  rewriter);
216  }
217 
218  /// Methods that operate on the SourceOp type. One of these must be
219  /// overridden by the derived pattern class.
220  virtual LogicalResult
221  matchAndRewrite(SourceOp op, OpAdaptor adaptor,
222  ConversionPatternRewriter &rewriter) const {
223  llvm_unreachable("matchAndRewrite is not implemented");
224  }
225  virtual LogicalResult
226  matchAndRewrite(SourceOp op, OneToNOpAdaptor adaptor,
227  ConversionPatternRewriter &rewriter) const {
228  SmallVector<Value> oneToOneOperands =
229  getOneToOneAdaptorOperands(adaptor.getOperands());
230  return matchAndRewrite(op, OpAdaptor(oneToOneOperands, adaptor), rewriter);
231  }
232 
233 private:
235 };
236 
237 /// Generic implementation of one-to-one conversion from "SourceOp" to
238 /// "TargetOp" where the latter belongs to the LLVM dialect or an equivalent.
239 /// Upholds a convention that multi-result operations get converted into an
240 /// operation returning the LLVM IR structure type, in which case individual
241 /// values must be extracted from using LLVM::ExtractValueOp before being used.
242 template <typename SourceOp, typename TargetOp>
244 public:
247 
248  /// Converts the type of the result to an LLVM type, pass operands as is,
249  /// preserve attributes.
250  LogicalResult
251  matchAndRewrite(SourceOp op, typename SourceOp::Adaptor adaptor,
252  ConversionPatternRewriter &rewriter) const override {
253  return LLVM::detail::oneToOneRewrite(op, TargetOp::getOperationName(),
254  adaptor.getOperands(), op->getAttrs(),
255  *this->getTypeConverter(), rewriter);
256  }
257 };
258 
259 } // namespace mlir
260 
261 #endif // MLIR_CONVERSION_LLVMCOMMON_PATTERN_H
This class implements a pattern rewriter for use with ConversionPatterns.
Base class for the conversion patterns.
SmallVector< Value > getOneToOneAdaptorOperands(ArrayRef< ValueRange > operands) const
Given an array of value ranges, which are the inputs to a 1:N adaptor, try to extract the single valu...
const TypeConverter * typeConverter
An optional type converter for use by this pattern.
virtual LogicalResult matchAndRewrite(Operation *op, ArrayRef< Value > operands, ConversionPatternRewriter &rewriter) const
Hook for derived classes to implement combined matching and rewriting.
Utility class for operation conversions targeting the LLVM dialect that match exactly one source oper...
Definition: Pattern.h:191
ConvertOpToLLVMPattern(const LLVMTypeConverter &typeConverter, PatternBenefit benefit=1)
Definition: Pattern.h:197
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:205
virtual LogicalResult matchAndRewrite(SourceOp op, OneToNOpAdaptor adaptor, ConversionPatternRewriter &rewriter) const
Definition: Pattern.h:226
virtual LogicalResult matchAndRewrite(SourceOp op, OpAdaptor adaptor, ConversionPatternRewriter &rewriter) const
Methods that operate on the SourceOp type.
Definition: Pattern.h:221
typename SourceOp::template GenericAdaptor< ArrayRef< ValueRange > > OneToNOpAdaptor
Definition: Pattern.h:195
LogicalResult matchAndRewrite(Operation *op, ArrayRef< ValueRange > operands, ConversionPatternRewriter &rewriter) const final
Hook for derived classes to implement combined matching and rewriting.
Definition: Pattern.h:211
typename SourceOp::Adaptor OpAdaptor
Definition: Pattern.h:193
Base class for operation conversions targeting the LLVM IR dialect.
Definition: Pattern.h:88
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:187
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:61
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:85
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:155
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:140
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
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:216
Type getElementPtrType(MemRefType type) const
Returns the type of a pointer to an element of the memref.
Definition: Pattern.cpp:78
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:53
bool isConvertibleAndHasIdentityMaps(MemRefType type) const
Returns if the given memref type is convertible to LLVM and has an identity layout map.
Definition: Pattern.cpp:71
Type getVoidPtrType() const
Get the MLIR type wrapping the LLVM i8* type.
Definition: Pattern.cpp:49
Conversion from types to the LLVM IR dialect.
Definition: TypeConverter.h:35
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:60
Helper class to produce LLVM dialect operations extracting or inserting elements of a MemRef descript...
Definition: MemRefBuilder.h:33
Generic implementation of one-to-one conversion from "SourceOp" to "TargetOp" where the latter belong...
Definition: Pattern.h:243
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:251
This class helps build Operations.
Definition: Builders.h:204
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...
Definition: PatternMatch.h:34
MLIRContext * getContext() const
Return the MLIRContext used to create this pattern.
Definition: PatternMatch.h:134
This class coordinates the application of a rewrite on a set of IR, providing a way for clients to tr...
Definition: PatternMatch.h:358
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
LogicalResult oneToOneRewrite(Operation *op, StringRef targetOp, ValueRange operands, ArrayRef< NamedAttribute > targetAttrs, const LLVMTypeConverter &typeConverter, ConversionPatternRewriter &rewriter, IntegerOverflowFlags overflowFlags=IntegerOverflowFlags::none)
Replaces the given operation "op" with a new operation of type "targetOp" and given operands.
Definition: Pattern.cpp:316
void setNativeProperties(Operation *op, IntegerOverflowFlags overflowFlags)
Handle generically setting flags as native properties on LLVM operations.
Definition: Pattern.cpp:308
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:356
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:487
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:448
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:409
Include the generated interface declarations.