MLIR 23.0.0git
BuiltinTypes.h
Go to the documentation of this file.
1//===- BuiltinTypes.h - MLIR Builtin Type Classes ---------------*- 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_IR_BUILTINTYPES_H
10#define MLIR_IR_BUILTINTYPES_H
11
15
16namespace llvm {
17class BitVector;
18struct fltSemantics;
19} // namespace llvm
20
21//===----------------------------------------------------------------------===//
22// Tablegen Interface Declarations
23//===----------------------------------------------------------------------===//
24
25namespace mlir {
26class AffineExpr;
27class AffineMap;
28class IndexType;
29class IntegerType;
30class MemRefType;
31class RankedTensorType;
32class StringAttr;
33class TypeRange;
34
35namespace detail {
38struct TupleTypeStorage;
39} // namespace detail
40
41/// Type trait indicating that the type has value semantics.
42template <typename ConcreteType>
44 : public TypeTrait::TraitBase<ConcreteType, ValueSemantics> {};
45
46//===----------------------------------------------------------------------===//
47// TensorType
48//===----------------------------------------------------------------------===//
49
50/// Tensor types represent multi-dimensional arrays, and have two variants:
51/// RankedTensorType and UnrankedTensorType.
52/// Note: This class attaches the ShapedType trait to act as a mixin to
53/// provide many useful utility functions. This inheritance has no effect
54/// on derived tensor types.
55class TensorType : public Type, public ShapedType::Trait<TensorType> {
56public:
57 using Type::Type;
58
59 /// Returns the element type of this tensor type.
60 Type getElementType() const;
61
62 /// Returns if this type is ranked, i.e. it has a known number of dimensions.
63 bool hasRank() const;
64
65 /// Returns the shape of this tensor type.
67
68 /// Clone this type with the given shape and element type. If the
69 /// provided shape is `std::nullopt`, the current shape of the type is used.
71 Type elementType) const;
72
73 // Make sure that base class overloads are visible.
74 using ShapedType::Trait<TensorType>::clone;
75
76 /// Return a clone of this type with the given new shape and element type.
77 /// The returned type is ranked, even if this type is unranked.
78 RankedTensorType clone(ArrayRef<int64_t> shape, Type elementType) const;
79
80 /// Return a clone of this type with the given new shape. The returned type
81 /// is ranked, even if this type is unranked.
82 RankedTensorType clone(ArrayRef<int64_t> shape) const;
83
84 /// Return true if the specified element type is ok in a tensor.
85 static bool isValidElementType(Type type);
86
87 /// Methods for support type inquiry through isa, cast, and dyn_cast.
88 static bool classof(Type type);
89
90 /// Allow implicit conversion to ShapedType.
91 operator ShapedType() const { return llvm::cast<ShapedType>(*this); }
92};
93
94//===----------------------------------------------------------------------===//
95// BaseMemRefType
96//===----------------------------------------------------------------------===//
97
98/// This class provides a shared interface for ranked and unranked memref types.
99/// Note: This class attaches the ShapedType trait to act as a mixin to
100/// provide many useful utility functions. This inheritance has no effect
101/// on derived memref types.
102class BaseMemRefType : public Type,
103 public PtrLikeTypeInterface::Trait<BaseMemRefType>,
104 public ShapedType::Trait<BaseMemRefType> {
105public:
106 using Type::Type;
107
108 /// Returns the element type of this memref type.
109 Type getElementType() const;
110
111 /// Returns if this type is ranked, i.e. it has a known number of dimensions.
112 bool hasRank() const;
113
114 /// Returns the shape of this memref type.
116
117 /// Clone this type with the given shape and element type. If the
118 /// provided shape is `std::nullopt`, the current shape of the type is used.
120 Type elementType) const;
121
122 /// Clone this type with the given memory space and element type. If the
123 /// provided element type is `std::nullopt`, the current element type of the
124 /// type is used.
125 FailureOr<PtrLikeTypeInterface>
126 clonePtrWith(Attribute memorySpace, std::optional<Type> elementType) const;
127
128 // Make sure that base class overloads are visible.
129 using ShapedType::Trait<BaseMemRefType>::clone;
130
131 /// Return a clone of this type with the given new shape and element type.
132 /// The returned type is ranked, even if this type is unranked.
133 MemRefType clone(ArrayRef<int64_t> shape, Type elementType) const;
134
135 /// Return a clone of this type with the given new shape. The returned type
136 /// is ranked, even if this type is unranked.
137 MemRefType clone(ArrayRef<int64_t> shape) const;
138
139 /// Return true if the specified element type is ok in a memref.
140 static bool isValidElementType(Type type);
141
142 /// Methods for support type inquiry through isa, cast, and dyn_cast.
143 static bool classof(Type type);
144
145 /// Returns the memory space in which data referred to by this memref resides.
147
148 /// [deprecated] Returns the memory space in old raw integer representation.
149 /// New `Attribute getMemorySpace()` method should be used instead.
150 unsigned getMemorySpaceAsInt() const;
151
152 /// Returns that this ptr-like object has non-empty ptr metadata.
153 bool hasPtrMetadata() const { return true; }
154
155 /// Allow implicit conversion to ShapedType.
156 operator ShapedType() const { return llvm::cast<ShapedType>(*this); }
157
158 /// Allow implicit conversion to PtrLikeTypeInterface.
159 operator PtrLikeTypeInterface() const {
160 return llvm::cast<PtrLikeTypeInterface>(*this);
161 }
162};
163
164} // namespace mlir
165
166//===----------------------------------------------------------------------===//
167// Tablegen Type Declarations
168//===----------------------------------------------------------------------===//
169
171
172#define GET_TYPEDEF_CLASSES
173#include "mlir/IR/BuiltinTypes.h.inc"
174
175namespace mlir {
176#include "mlir/IR/BuiltinTypeConstraints.h.inc"
177
178//===----------------------------------------------------------------------===//
179// MemRefType
180//===----------------------------------------------------------------------===//
181
182/// This is a builder type that keeps local references to arguments. Arguments
183/// that are passed into the builder must outlive the builder.
185public:
186 // Build from another MemRefType.
187 explicit Builder(MemRefType other)
188 : shape(other.getShape()), elementType(other.getElementType()),
189 layout(other.getLayout()), memorySpace(other.getMemorySpace()) {}
190
191 // Build from scratch.
192 Builder(ArrayRef<int64_t> shape, Type elementType)
193 : shape(shape), elementType(elementType) {}
194
196 shape = newShape;
197 return *this;
198 }
199
200 Builder &setElementType(Type newElementType) {
201 elementType = newElementType;
202 return *this;
203 }
204
205 Builder &setLayout(MemRefLayoutAttrInterface newLayout) {
206 layout = newLayout;
207 return *this;
208 }
209
211 memorySpace = newMemorySpace;
212 return *this;
213 }
214
215 operator MemRefType() {
216 return MemRefType::get(shape, elementType, layout, memorySpace);
217 }
218
219private:
221 Type elementType;
222 MemRefLayoutAttrInterface layout;
223 Attribute memorySpace;
224};
225
226//===----------------------------------------------------------------------===//
227// RankedTensorType
228//===----------------------------------------------------------------------===//
229
230/// This is a builder type that keeps local references to arguments. Arguments
231/// that are passed into the builder must outlive the builder.
233public:
234 /// Build from another RankedTensorType.
235 explicit Builder(RankedTensorType other)
236 : shape(other.getShape()), elementType(other.getElementType()),
237 encoding(other.getEncoding()) {}
238
239 /// Build from scratch.
240 Builder(ArrayRef<int64_t> shape, Type elementType, Attribute encoding)
241 : shape(shape), elementType(elementType), encoding(encoding) {}
242
244 shape = newShape;
245 return *this;
246 }
247
248 Builder &setElementType(Type newElementType) {
249 elementType = newElementType;
250 return *this;
251 }
252
254 encoding = newEncoding;
255 return *this;
256 }
257
258 /// Erase a dim from shape @pos.
259 Builder &dropDim(unsigned pos) {
260 assert(pos < shape.size() && "overflow");
261 shape.erase(pos);
262 return *this;
263 }
264
265 /// Insert a val into shape @pos.
266 Builder &insertDim(int64_t val, unsigned pos) {
267 assert(pos <= shape.size() && "overflow");
268 shape.insert(pos, val);
269 return *this;
270 }
271
272 operator RankedTensorType() {
273 return RankedTensorType::get(shape, elementType, encoding);
274 }
275
276private:
278 Type elementType;
279 Attribute encoding;
280};
281
282//===----------------------------------------------------------------------===//
283// VectorType
284//===----------------------------------------------------------------------===//
285
286/// This is a builder type that keeps local references to arguments. Arguments
287/// that are passed into the builder must outlive the builder.
289public:
290 /// Build from another VectorType.
291 explicit Builder(VectorType other)
292 : elementType(other.getElementType()), shape(other.getShape()),
293 scalableDims(other.getScalableDims()) {}
294
295 /// Build from scratch.
296 Builder(ArrayRef<int64_t> shape, Type elementType,
297 ArrayRef<bool> scalableDims = {})
298 : elementType(elementType), shape(shape), scalableDims(scalableDims) {}
299
301 ArrayRef<bool> newIsScalableDim = {}) {
302 shape = newShape;
303 scalableDims = newIsScalableDim;
304 return *this;
305 }
306
307 Builder &setElementType(Type newElementType) {
308 elementType = newElementType;
309 return *this;
310 }
311
312 /// Erase a dim from shape @pos.
313 Builder &dropDim(unsigned pos) {
314 assert(pos < shape.size() && "overflow");
315 shape.erase(pos);
316 if (!scalableDims.empty())
317 scalableDims.erase(pos);
318 return *this;
319 }
320
321 /// Set a dim in shape @pos to val.
322 Builder &setDim(unsigned pos, int64_t val) {
323 assert(pos < shape.size() && "overflow");
324 shape.set(pos, val);
325 return *this;
326 }
327
328 operator VectorType() {
329 return VectorType::get(shape, elementType, scalableDims);
330 }
331
332private:
333 Type elementType;
335 CopyOnWriteArrayRef<bool> scalableDims;
336};
337
338/// Given an `originalShape` and a `reducedShape` assumed to be a subset of
339/// `originalShape` with some `1` entries erased, return the set of indices
340/// that specifies which of the entries of `originalShape` are dropped to obtain
341/// `reducedShape`. The returned mask can be applied as a projection to
342/// `originalShape` to obtain the `reducedShape`. This mask is useful to track
343/// which dimensions must be kept when e.g. compute MemRef strides under
344/// rank-reducing operations. Return std::nullopt if reducedShape cannot be
345/// obtained by dropping only `1` entries in `originalShape`.
346/// If `matchDynamic` is true, then dynamic dims in `originalShape` and
347/// `reducedShape` will be considered matching with non-dynamic dims, unless
348/// the non-dynamic dim is from `originalShape` and equal to 1. For example,
349/// in ([1, 3, ?], [?, 5]), the mask would be {1, 0, 0}, since 3 and 5 will
350/// match with the corresponding dynamic dims.
351std::optional<llvm::SmallDenseSet<unsigned>>
353 ArrayRef<int64_t> reducedShape,
354 bool matchDynamic = false);
355
356/// Enum that captures information related to verifier error conditions on
357/// slice insert/extract type of ops.
363 // Error codes to ops with a memory space and a layout annotation.
366};
367
368/// Check if `originalType` can be rank reduced to `candidateReducedType` type
369/// by dropping some dimensions with static size `1`.
370/// Return `SliceVerificationResult::Success` on success or an appropriate error
371/// code.
372SliceVerificationResult isRankReducedType(ShapedType originalType,
373 ShapedType candidateReducedType);
374
375//===----------------------------------------------------------------------===//
376// Convenience wrappers for VectorType
377//
378// These are provided to allow idiomatic code like:
379// * isa<vector::ScalableVectorType>(type)
380//===----------------------------------------------------------------------===//
381/// A vector type containing at least one scalable dimension.
382class ScalableVectorType : public VectorType {
383public:
384 using VectorType::VectorType;
385
386 static bool classof(Type type) {
387 auto vecTy = llvm::dyn_cast<VectorType>(type);
388 if (!vecTy)
389 return false;
390 return vecTy.isScalable();
391 }
392};
393
394/// A vector type with no scalable dimensions.
395class FixedVectorType : public VectorType {
396public:
397 using VectorType::VectorType;
398
399 static bool classof(Type type) {
400 auto vecTy = llvm::dyn_cast<VectorType>(type);
401 if (!vecTy)
402 return false;
403 return !vecTy.isScalable();
404 }
405};
406
407//===----------------------------------------------------------------------===//
408// Deferred Method Definitions
409//===----------------------------------------------------------------------===//
410
411inline bool BaseMemRefType::classof(Type type) {
412 return llvm::isa<MemRefType, UnrankedMemRefType>(type);
413}
414
416 return type.isIntOrIndexOrFloat() ||
417 llvm::isa<ComplexType, MemRefType, VectorType, UnrankedMemRefType>(
418 type) ||
419 llvm::isa<MemRefElementTypeInterface>(type);
420}
421
422inline bool TensorType::classof(Type type) {
423 return llvm::isa<RankedTensorType, UnrankedTensorType>(type);
424}
425
426//===----------------------------------------------------------------------===//
427// Type Utilities
428//===----------------------------------------------------------------------===//
429
430/// Given MemRef `sizes` that are either static or dynamic, returns the
431/// canonical "contiguous" strides AffineExpr. Strides are multiplicative and
432/// once a dynamic dimension is encountered, all canonical strides become
433/// dynamic and need to be encoded with a different symbol.
434/// For canonical strides expressions, the offset is always 0 and the fastest
435/// varying stride is always `1`.
436///
437/// Examples:
438/// - memref<3x4x5xf32> has canonical stride expression
439/// `20*exprs[0] + 5*exprs[1] + exprs[2]`.
440/// - memref<3x?x5xf32> has canonical stride expression
441/// `s0*exprs[0] + 5*exprs[1] + exprs[2]`.
442/// - memref<3x4x?xf32> has canonical stride expression
443/// `s1*exprs[0] + s0*exprs[1] + exprs[2]`.
446 MLIRContext *context);
447
448/// Return the result of makeCanonicalStrudedLayoutExpr for the common case
449/// where `exprs` is {d0, d1, .., d_(sizes.size()-1)}
451 MLIRContext *context);
452} // namespace mlir
453
454#endif // MLIR_IR_BUILTINTYPES_H
static Type getElementType(Type type)
Determine the element type of type.
static ArrayRef< int64_t > getShape(Type type)
Returns the shape of the given type.
Definition Traits.cpp:117
Base type for affine expression.
Definition AffineExpr.h:68
A multi-dimensional affine map Affine map's are immutable like Type's, and they are uniqued.
Definition AffineMap.h:46
Attributes are known-constant values of operations.
Definition Attributes.h:25
This class provides a shared interface for ranked and unranked memref types.
MemRefType clone(ArrayRef< int64_t > shape) const
Return a clone of this type with the given new shape.
ArrayRef< int64_t > getShape() const
Returns the shape of this memref type.
static bool isValidElementType(Type type)
Return true if the specified element type is ok in a memref.
FailureOr< PtrLikeTypeInterface > clonePtrWith(Attribute memorySpace, std::optional< Type > elementType) const
Clone this type with the given memory space and element type.
bool hasPtrMetadata() const
Returns that this ptr-like object has non-empty ptr metadata.
constexpr Type()=default
Attribute getMemorySpace() const
Returns the memory space in which data referred to by this memref resides.
static bool classof(Type type)
Methods for support type inquiry through isa, cast, and dyn_cast.
unsigned getMemorySpaceAsInt() const
[deprecated] Returns the memory space in old raw integer representation.
BaseMemRefType cloneWith(std::optional< ArrayRef< int64_t > > shape, Type elementType) const
Clone this type with the given shape and element type.
bool hasRank() const
Returns if this type is ranked, i.e. it has a known number of dimensions.
Type getElementType() const
Returns the element type of this memref type.
MemRefType clone(ArrayRef< int64_t > shape, Type elementType) const
Return a clone of this type with the given new shape and element type.
A vector type with no scalable dimensions.
static bool classof(Type type)
MLIRContext is the top-level object for a collection of MLIR operations.
Definition MLIRContext.h:63
This is a builder type that keeps local references to arguments.
Builder(ArrayRef< int64_t > shape, Type elementType)
Builder & setShape(ArrayRef< int64_t > newShape)
Builder(MemRefType other)
Builder & setMemorySpace(Attribute newMemorySpace)
Builder & setElementType(Type newElementType)
Builder & setLayout(MemRefLayoutAttrInterface newLayout)
This is a builder type that keeps local references to arguments.
Builder & setEncoding(Attribute newEncoding)
Builder(ArrayRef< int64_t > shape, Type elementType, Attribute encoding)
Build from scratch.
Builder & setElementType(Type newElementType)
Builder & setShape(ArrayRef< int64_t > newShape)
Builder(RankedTensorType other)
Build from another RankedTensorType.
Builder & insertDim(int64_t val, unsigned pos)
Insert a val into shape @pos.
Builder & dropDim(unsigned pos)
Erase a dim from shape @pos.
A vector type containing at least one scalable dimension.
static bool classof(Type type)
Tensor types represent multi-dimensional arrays, and have two variants: RankedTensorType and Unranked...
TensorType cloneWith(std::optional< ArrayRef< int64_t > > shape, Type elementType) const
Clone this type with the given shape and element type.
RankedTensorType clone(ArrayRef< int64_t > shape) const
Return a clone of this type with the given new shape.
static bool classof(Type type)
Methods for support type inquiry through isa, cast, and dyn_cast.
constexpr Type()=default
static bool isValidElementType(Type type)
Return true if the specified element type is ok in a tensor.
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.
RankedTensorType clone(ArrayRef< int64_t > shape, Type elementType) const
Return a clone of this type with the given new shape and element type.
Type getElementType() const
Returns the element type of this tensor type.
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
constexpr Type()=default
bool isIntOrIndexOrFloat() const
Return true if this is an integer (of any signedness), index, or float type.
Definition Types.cpp:122
Type trait indicating that the type has value semantics.
This is a builder type that keeps local references to arguments.
Builder & setElementType(Type newElementType)
Builder & setDim(unsigned pos, int64_t val)
Set a dim in shape @pos to val.
Builder(VectorType other)
Build from another VectorType.
Builder & setShape(ArrayRef< int64_t > newShape, ArrayRef< bool > newIsScalableDim={})
Builder & dropDim(unsigned pos)
Erase a dim from shape @pos.
Builder(ArrayRef< int64_t > shape, Type elementType, ArrayRef< bool > scalableDims={})
Build from scratch.
The OpAsmOpInterface, see OpAsmInterface.td for more details.
Definition CallGraph.h:229
detail::StorageUserTraitBase< ConcreteType, TraitType > TraitBase
This class represents the base of a type trait.
Definition Types.h:252
AttrTypeReplacer.
Include the generated interface declarations.
SliceVerificationResult
Enum that captures information related to verifier error conditions on slice insert/extract type of o...
AffineExpr makeCanonicalStridedLayoutExpr(ArrayRef< int64_t > sizes, ArrayRef< AffineExpr > exprs, MLIRContext *context)
Given MemRef sizes that are either static or dynamic, returns the canonical "contiguous" strides Affi...
std::optional< llvm::SmallDenseSet< unsigned > > computeRankReductionMask(ArrayRef< int64_t > originalShape, ArrayRef< int64_t > reducedShape, bool matchDynamic=false)
Given an originalShape and a reducedShape assumed to be a subset of originalShape with some 1 entries...
SliceVerificationResult isRankReducedType(ShapedType originalType, ShapedType candidateReducedType)
Check if originalType can be rank reduced to candidateReducedType type by dropping some dimensions wi...
Function Type Storage and Uniquing.
Definition TypeDetail.h:57
Integer Type Storage and Uniquing.
Definition TypeDetail.h:28
A type representing a collection of other types.
Definition TypeDetail.h:105