1 //===- LLVMDialect.h - MLIR LLVM dialect types ------------------*- 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 // This file defines the types for the LLVM dialect in MLIR. These MLIR types
10 // correspond to the LLVM IR type system.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef MLIR_DIALECT_LLVMIR_LLVMTYPES_H_
15 #define MLIR_DIALECT_LLVMIR_LLVMTYPES_H_
16 
17 #include "mlir/IR/SubElementInterfaces.h"
18 #include "mlir/IR/Types.h"
19 #include "mlir/Interfaces/DataLayoutInterfaces.h"
20 
21 namespace llvm {
22 class ElementCount;
23 class TypeSize;
24 } // namespace llvm
25 
26 namespace mlir {
27 
28 class AsmParser;
29 class AsmPrinter;
30 
31 namespace LLVM {
32 class LLVMDialect;
33 
34 namespace detail {
35 struct LLVMFunctionTypeStorage;
36 struct LLVMPointerTypeStorage;
37 struct LLVMStructTypeStorage;
38 struct LLVMTypeAndSizeStorage;
39 } // namespace detail
40 } // namespace LLVM
41 } // namespace mlir
42 
43 #include "mlir/Dialect/LLVMIR/LLVMTypeInterfaces.h.inc"
44 
45 namespace mlir {
46 namespace LLVM {
47 
48 //===----------------------------------------------------------------------===//
49 // Trivial types.
50 //===----------------------------------------------------------------------===//
51 
52 // Batch-define trivial types.
53 #define DEFINE_TRIVIAL_LLVM_TYPE(ClassName)                                    \
54   class ClassName : public Type::TypeBase<ClassName, Type, TypeStorage> {      \
55   public:                                                                      \
56     using Base::Base;                                                          \
57   }
58 
59 DEFINE_TRIVIAL_LLVM_TYPE(LLVMVoidType);
60 DEFINE_TRIVIAL_LLVM_TYPE(LLVMPPCFP128Type);
61 DEFINE_TRIVIAL_LLVM_TYPE(LLVMX86MMXType);
62 DEFINE_TRIVIAL_LLVM_TYPE(LLVMTokenType);
63 DEFINE_TRIVIAL_LLVM_TYPE(LLVMLabelType);
64 DEFINE_TRIVIAL_LLVM_TYPE(LLVMMetadataType);
65 
66 #undef DEFINE_TRIVIAL_LLVM_TYPE
67 
68 //===----------------------------------------------------------------------===//
69 // LLVMArrayType.
70 //===----------------------------------------------------------------------===//
71 
72 /// LLVM dialect array type. It is an aggregate type representing consecutive
73 /// elements in memory, parameterized by the number of elements and the element
74 /// type.
75 class LLVMArrayType
76     : public Type::TypeBase<LLVMArrayType, Type, detail::LLVMTypeAndSizeStorage,
77                             DataLayoutTypeInterface::Trait,
78                             SubElementTypeInterface::Trait> {
79 public:
80   /// Inherit base constructors.
81   using Base::Base;
82   using Base::getChecked;
83 
84   /// Checks if the given type can be used inside an array type.
85   static bool isValidElementType(Type type);
86 
87   /// Gets or creates an instance of LLVM dialect array type containing
88   /// `numElements` of `elementType`, in the same context as `elementType`.
89   static LLVMArrayType get(Type elementType, unsigned numElements);
90   static LLVMArrayType getChecked(function_ref<InFlightDiagnostic()> emitError,
91                                   Type elementType, unsigned numElements);
92 
93   /// Returns the element type of the array.
94   Type getElementType() const;
95 
96   /// Returns the number of elements in the array type.
97   unsigned getNumElements() const;
98 
99   /// Verifies that the type about to be constructed is well-formed.
100   static LogicalResult verify(function_ref<InFlightDiagnostic()> emitError,
101                               Type elementType, unsigned numElements);
102 
103   /// Hooks for DataLayoutTypeInterface. Should not be called directly. Obtain a
104   /// DataLayout instance and query it instead.
105   unsigned getTypeSizeInBits(const DataLayout &dataLayout,
106                              DataLayoutEntryListRef params) const;
107 
108   unsigned getTypeSize(const DataLayout &dataLayout,
109                        DataLayoutEntryListRef params) const;
110 
111   unsigned getABIAlignment(const DataLayout &dataLayout,
112                            DataLayoutEntryListRef params) const;
113 
114   unsigned getPreferredAlignment(const DataLayout &dataLayout,
115                                  DataLayoutEntryListRef params) const;
116 
117   void walkImmediateSubElements(function_ref<void(Attribute)> walkAttrsFn,
118                                 function_ref<void(Type)> walkTypesFn) const;
119   Type replaceImmediateSubElements(ArrayRef<Attribute> replAttrs,
120                                    ArrayRef<Type> replTypes) const;
121 };
122 
123 //===----------------------------------------------------------------------===//
124 // LLVMFunctionType.
125 //===----------------------------------------------------------------------===//
126 
127 /// LLVM dialect function type. It consists of a single return type (unlike MLIR
128 /// which can have multiple), a list of parameter types and can optionally be
129 /// variadic.
130 class LLVMFunctionType : public Type::TypeBase<LLVMFunctionType, Type,
131                                                detail::LLVMFunctionTypeStorage,
132                                                SubElementTypeInterface::Trait> {
133 public:
134   /// Inherit base constructors.
135   using Base::Base;
136   using Base::getChecked;
137 
138   /// Checks if the given type can be used an argument in a function type.
139   static bool isValidArgumentType(Type type);
140 
141   /// Checks if the given type can be used as a result in a function type.
142   static bool isValidResultType(Type type);
143 
144   /// Returns whether the function is variadic.
145   bool isVarArg() const;
146 
147   /// Gets or creates an instance of LLVM dialect function in the same context
148   /// as the `result` type.
149   static LLVMFunctionType get(Type result, ArrayRef<Type> arguments,
150                               bool isVarArg = false);
151   static LLVMFunctionType
152   getChecked(function_ref<InFlightDiagnostic()> emitError, Type result,
153              ArrayRef<Type> arguments, bool isVarArg = false);
154 
155   /// Returns a clone of this function type with the given argument
156   /// and result types.
157   LLVMFunctionType clone(TypeRange inputs, TypeRange results) const;
158 
159   /// Returns the result type of the function.
160   Type getReturnType() const;
161 
162   /// Returns the result type of the function as an ArrayRef, enabling better
163   /// integration with generic MLIR utilities.
164   ArrayRef<Type> getReturnTypes() const;
165 
166   /// Returns the number of arguments to the function.
167   unsigned getNumParams();
168 
169   /// Returns `i`-th argument of the function. Asserts on out-of-bounds.
170   Type getParamType(unsigned i);
171 
172   /// Returns a list of argument types of the function.
173   ArrayRef<Type> getParams() const;
params()174   ArrayRef<Type> params() { return getParams(); }
175 
176   /// Verifies that the type about to be constructed is well-formed.
177   static LogicalResult verify(function_ref<InFlightDiagnostic()> emitError,
178                               Type result, ArrayRef<Type> arguments, bool);
179 
180   void walkImmediateSubElements(function_ref<void(Attribute)> walkAttrsFn,
181                                 function_ref<void(Type)> walkTypesFn) const;
182   Type replaceImmediateSubElements(ArrayRef<Attribute> replAttrs,
183                                    ArrayRef<Type> replTypes) const;
184 };
185 
186 //===----------------------------------------------------------------------===//
187 // LLVMPointerType.
188 //===----------------------------------------------------------------------===//
189 
190 /// LLVM dialect pointer type. This type typically represents a reference to an
191 /// object in memory. Pointers may be opaque or parameterized by the element
192 /// type. Both opaque and non-opaque pointers are additionally parameterized by
193 /// the address space.
194 class LLVMPointerType
195     : public Type::TypeBase<
196           LLVMPointerType, Type, detail::LLVMPointerTypeStorage,
197           DataLayoutTypeInterface::Trait, SubElementTypeInterface::Trait> {
198 public:
199   /// Inherit base constructors.
200   using Base::Base;
201 
202   /// Checks if the given type can have a pointer type pointing to it.
203   static bool isValidElementType(Type type);
204 
205   /// Gets or creates an instance of LLVM dialect pointer type pointing to an
206   /// object of `pointee` type in the given address space. The pointer type is
207   /// created in the same context as `pointee`. If the pointee is not provided,
208   /// creates an opaque pointer in the given context and address space.
209   static LLVMPointerType get(MLIRContext *context, unsigned addressSpace = 0);
210   static LLVMPointerType get(Type pointee, unsigned addressSpace = 0);
211   static LLVMPointerType
212   getChecked(function_ref<InFlightDiagnostic()> emitError, Type pointee,
213              unsigned addressSpace = 0);
214   static LLVMPointerType
215   getChecked(function_ref<InFlightDiagnostic()> emitError, MLIRContext *context,
216              unsigned addressSpace = 0);
217 
218   /// Returns the pointed-to type. It may be null if the pointer is opaque.
219   Type getElementType() const;
220 
221   /// Returns `true` if this type is the opaque pointer type, i.e., it has no
222   /// pointed-to type.
223   bool isOpaque() const;
224 
225   /// Returns the address space of the pointer.
226   unsigned getAddressSpace() const;
227 
228   /// Verifies that the type about to be constructed is well-formed.
229   static LogicalResult verify(function_ref<InFlightDiagnostic()> emitError,
230                               Type pointee, unsigned);
verify(function_ref<InFlightDiagnostic ()> emitError,MLIRContext * context,unsigned)231   static LogicalResult verify(function_ref<InFlightDiagnostic()> emitError,
232                               MLIRContext *context, unsigned) {
233     return success();
234   }
235 
236   /// Hooks for DataLayoutTypeInterface. Should not be called directly. Obtain a
237   /// DataLayout instance and query it instead.
238   unsigned getTypeSizeInBits(const DataLayout &dataLayout,
239                              DataLayoutEntryListRef params) const;
240   unsigned getABIAlignment(const DataLayout &dataLayout,
241                            DataLayoutEntryListRef params) const;
242   unsigned getPreferredAlignment(const DataLayout &dataLayout,
243                                  DataLayoutEntryListRef params) const;
244   bool areCompatible(DataLayoutEntryListRef oldLayout,
245                      DataLayoutEntryListRef newLayout) const;
246   LogicalResult verifyEntries(DataLayoutEntryListRef entries,
247                               Location loc) const;
248 
249   void walkImmediateSubElements(function_ref<void(Attribute)> walkAttrsFn,
250                                 function_ref<void(Type)> walkTypesFn) const;
251   Type replaceImmediateSubElements(ArrayRef<Attribute> replAttrs,
252                                    ArrayRef<Type> replTypes) const;
253 };
254 
255 //===----------------------------------------------------------------------===//
256 // LLVMStructType.
257 //===----------------------------------------------------------------------===//
258 
259 /// LLVM dialect structure type representing a collection of different-typed
260 /// elements manipulated together. Structured can optionally be packed, meaning
261 /// that their elements immediately follow each other in memory without
262 /// accounting for potential alignment.
263 ///
264 /// Structure types can be identified (named) or literal. Literal structures
265 /// are uniquely represented by the list of types they contain and packedness.
266 /// Literal structure types are immutable after construction.
267 ///
268 /// Identified structures are uniquely represented by their name, a string. They
269 /// have a mutable component, consisting of the list of types they contain,
270 /// the packedness and the opacity bits. Identified structs can be created
271 /// without providing the lists of element types, making them suitable to
272 /// represent recursive, i.e. self-referring, structures. Identified structs
273 /// without body are considered opaque. For such structs, one can set the body.
274 /// Identified structs can be created as intentionally-opaque, implying that the
275 /// caller does not intend to ever set the body (e.g. forward-declarations of
276 /// structs from another module) and wants to disallow further modification of
277 /// the body. For intentionally-opaque structs or non-opaque structs with the
278 /// body, one is not allowed to set another body (however, one can set exactly
279 /// the same body).
280 ///
281 /// Note that the packedness of the struct takes place in uniquing of literal
282 /// structs, but does not in uniquing of identified structs.
283 class LLVMStructType
284     : public Type::TypeBase<LLVMStructType, Type, detail::LLVMStructTypeStorage,
285                             DataLayoutTypeInterface::Trait,
286                             SubElementTypeInterface::Trait,
287                             TypeTrait::IsMutable> {
288 public:
289   /// Inherit base constructors.
290   using Base::Base;
291 
292   /// Checks if the given type can be contained in a structure type.
293   static bool isValidElementType(Type type);
294 
295   /// Gets or creates an identified struct with the given name in the provided
296   /// context. Note that unlike llvm::StructType::create, this function will
297   /// _NOT_ rename a struct in case a struct with the same name already exists
298   /// in the context. Instead, it will just return the existing struct,
299   /// similarly to the rest of MLIR type ::get methods.
300   static LLVMStructType getIdentified(MLIRContext *context, StringRef name);
301   static LLVMStructType
302   getIdentifiedChecked(function_ref<InFlightDiagnostic()> emitError,
303                        MLIRContext *context, StringRef name);
304 
305   /// Gets a new identified struct with the given body. The body _cannot_ be
306   /// changed later. If a struct with the given name already exists, renames
307   /// the struct by appending a `.` followed by a number to the name. Renaming
308   /// happens even if the existing struct has the same body.
309   static LLVMStructType getNewIdentified(MLIRContext *context, StringRef name,
310                                          ArrayRef<Type> elements,
311                                          bool isPacked = false);
312 
313   /// Gets or creates a literal struct with the given body in the provided
314   /// context.
315   static LLVMStructType getLiteral(MLIRContext *context, ArrayRef<Type> types,
316                                    bool isPacked = false);
317   static LLVMStructType
318   getLiteralChecked(function_ref<InFlightDiagnostic()> emitError,
319                     MLIRContext *context, ArrayRef<Type> types,
320                     bool isPacked = false);
321 
322   /// Gets or creates an intentionally-opaque identified struct. Such a struct
323   /// cannot have its body set. To create an opaque struct with a mutable body,
324   /// use `getIdentified`. Note that unlike llvm::StructType::create, this
325   /// function will _NOT_ rename a struct in case a struct with the same name
326   /// already exists in the context. Instead, it will just return the existing
327   /// struct, similarly to the rest of MLIR type ::get methods.
328   static LLVMStructType getOpaque(StringRef name, MLIRContext *context);
329   static LLVMStructType
330   getOpaqueChecked(function_ref<InFlightDiagnostic()> emitError,
331                    MLIRContext *context, StringRef name);
332 
333   /// Set the body of an identified struct. Returns failure if the body could
334   /// not be set, e.g. if the struct already has a body or if it was marked as
335   /// intentionally opaque. This might happen in a multi-threaded context when a
336   /// different thread modified the struct after it was created. Most callers
337   /// are likely to assert this always succeeds, but it is possible to implement
338   /// a local renaming scheme based on the result of this call.
339   LogicalResult setBody(ArrayRef<Type> types, bool isPacked);
340 
341   /// Checks if a struct is packed.
342   bool isPacked() const;
343 
344   /// Checks if a struct is identified.
345   bool isIdentified() const;
346 
347   /// Checks if a struct is opaque.
348   bool isOpaque();
349 
350   /// Checks if a struct is initialized.
351   bool isInitialized();
352 
353   /// Returns the name of an identified struct.
354   StringRef getName();
355 
356   /// Returns the list of element types contained in a non-opaque struct.
357   ArrayRef<Type> getBody() const;
358 
359   /// Verifies that the type about to be constructed is well-formed.
360   static LogicalResult verify(function_ref<InFlightDiagnostic()> emitError,
361                               StringRef, bool);
362   static LogicalResult verify(function_ref<InFlightDiagnostic()> emitError,
363                               ArrayRef<Type> types, bool);
364 
365   /// Hooks for DataLayoutTypeInterface. Should not be called directly. Obtain a
366   /// DataLayout instance and query it instead.
367   unsigned getTypeSizeInBits(const DataLayout &dataLayout,
368                              DataLayoutEntryListRef params) const;
369 
370   unsigned getABIAlignment(const DataLayout &dataLayout,
371                            DataLayoutEntryListRef params) const;
372 
373   unsigned getPreferredAlignment(const DataLayout &dataLayout,
374                                  DataLayoutEntryListRef params) const;
375 
376   bool areCompatible(DataLayoutEntryListRef oldLayout,
377                      DataLayoutEntryListRef newLayout) const;
378 
379   LogicalResult verifyEntries(DataLayoutEntryListRef entries,
380                               Location loc) const;
381 
382   void walkImmediateSubElements(function_ref<void(Attribute)> walkAttrsFn,
383                                 function_ref<void(Type)> walkTypesFn) const;
384   Type replaceImmediateSubElements(ArrayRef<Attribute> replAttrs,
385                                    ArrayRef<Type> replTypes) const;
386 };
387 
388 //===----------------------------------------------------------------------===//
389 // LLVMFixedVectorType.
390 //===----------------------------------------------------------------------===//
391 
392 /// LLVM dialect fixed vector type, represents a sequence of elements of known
393 /// length that can be processed as one.
394 class LLVMFixedVectorType
395     : public Type::TypeBase<LLVMFixedVectorType, Type,
396                             detail::LLVMTypeAndSizeStorage,
397                             SubElementTypeInterface::Trait> {
398 public:
399   /// Inherit base constructor.
400   using Base::Base;
401   using Base::getChecked;
402 
403   /// Gets or creates a fixed vector type containing `numElements` of
404   /// `elementType` in the same context as `elementType`.
405   static LLVMFixedVectorType get(Type elementType, unsigned numElements);
406   static LLVMFixedVectorType
407   getChecked(function_ref<InFlightDiagnostic()> emitError, Type elementType,
408              unsigned numElements);
409 
410   /// Checks if the given type can be used in a vector type. This type supports
411   /// only a subset of LLVM dialect types that don't have a built-in
412   /// counter-part, e.g., pointers.
413   static bool isValidElementType(Type type);
414 
415   /// Returns the element type of the vector.
416   Type getElementType() const;
417 
418   /// Returns the number of elements in the fixed vector.
419   unsigned getNumElements() const;
420 
421   /// Verifies that the type about to be constructed is well-formed.
422   static LogicalResult verify(function_ref<InFlightDiagnostic()> emitError,
423                               Type elementType, unsigned numElements);
424 
425   void walkImmediateSubElements(function_ref<void(Attribute)> walkAttrsFn,
426                                 function_ref<void(Type)> walkTypesFn) const;
427   Type replaceImmediateSubElements(ArrayRef<Attribute> replAttrs,
428                                    ArrayRef<Type> replTypes) const;
429 };
430 
431 //===----------------------------------------------------------------------===//
432 // LLVMScalableVectorType.
433 //===----------------------------------------------------------------------===//
434 
435 /// LLVM dialect scalable vector type, represents a sequence of elements of
436 /// unknown length that is known to be divisible by some constant. These
437 /// elements can be processed as one in SIMD context.
438 class LLVMScalableVectorType
439     : public Type::TypeBase<LLVMScalableVectorType, Type,
440                             detail::LLVMTypeAndSizeStorage,
441                             SubElementTypeInterface::Trait> {
442 public:
443   /// Inherit base constructor.
444   using Base::Base;
445   using Base::getChecked;
446 
447   /// Gets or creates a scalable vector type containing a non-zero multiple of
448   /// `minNumElements` of `elementType` in the same context as `elementType`.
449   static LLVMScalableVectorType get(Type elementType, unsigned minNumElements);
450   static LLVMScalableVectorType
451   getChecked(function_ref<InFlightDiagnostic()> emitError, Type elementType,
452              unsigned minNumElements);
453 
454   /// Checks if the given type can be used in a vector type.
455   static bool isValidElementType(Type type);
456 
457   /// Returns the element type of the vector.
458   Type getElementType() const;
459 
460   /// Returns the scaling factor of the number of elements in the vector. The
461   /// vector contains at least the resulting number of elements, or any non-zero
462   /// multiple of this number.
463   unsigned getMinNumElements() const;
464 
465   /// Verifies that the type about to be constructed is well-formed.
466   static LogicalResult verify(function_ref<InFlightDiagnostic()> emitError,
467                               Type elementType, unsigned minNumElements);
468 
469   void walkImmediateSubElements(function_ref<void(Attribute)> walkAttrsFn,
470                                 function_ref<void(Type)> walkTypesFn) const;
471   Type replaceImmediateSubElements(ArrayRef<Attribute> replAttrs,
472                                    ArrayRef<Type> replTypes) const;
473 };
474 
475 //===----------------------------------------------------------------------===//
476 // Printing and parsing.
477 //===----------------------------------------------------------------------===//
478 
479 namespace detail {
480 /// Parses an LLVM dialect type.
481 Type parseType(DialectAsmParser &parser);
482 
483 /// Prints an LLVM Dialect type.
484 void printType(Type type, AsmPrinter &printer);
485 } // namespace detail
486 
487 //===----------------------------------------------------------------------===//
488 // Utility functions.
489 //===----------------------------------------------------------------------===//
490 
491 /// Returns `true` if the given type is compatible with the LLVM dialect. This
492 /// is an alias to `LLVMDialect::isCompatibleType`.
493 bool isCompatibleType(Type type);
494 
495 /// Returns `true` if the given outer type is compatible with the LLVM dialect
496 /// without checking its potential nested types such as struct elements.
497 bool isCompatibleOuterType(Type type);
498 
499 /// Returns `true` if the given type is a floating-point type compatible with
500 /// the LLVM dialect.
501 bool isCompatibleFloatingPointType(Type type);
502 
503 /// Returns `true` if the given type is a vector type compatible with the LLVM
504 /// dialect. Compatible types include 1D built-in vector types of built-in
505 /// integers and floating-point values, LLVM dialect fixed vector types of LLVM
506 /// dialect pointers and LLVM dialect scalable vector types.
507 bool isCompatibleVectorType(Type type);
508 
509 /// Returns the element type of any vector type compatible with the LLVM
510 /// dialect.
511 Type getVectorElementType(Type type);
512 
513 /// Returns the element count of any LLVM-compatible vector type.
514 llvm::ElementCount getVectorNumElements(Type type);
515 
516 /// Returns whether a vector type is scalable or not.
517 bool isScalableVectorType(Type vectorType);
518 
519 /// Creates an LLVM dialect-compatible vector type with the given element type
520 /// and length.
521 Type getVectorType(Type elementType, unsigned numElements,
522                    bool isScalable = false);
523 
524 /// Creates an LLVM dialect-compatible type with the given element type and
525 /// length.
526 Type getFixedVectorType(Type elementType, unsigned numElements);
527 
528 /// Creates an LLVM dialect-compatible type with the given element type and
529 /// length.
530 Type getScalableVectorType(Type elementType, unsigned numElements);
531 
532 /// Returns the size of the given primitive LLVM dialect-compatible type
533 /// (including vectors) in bits, for example, the size of i16 is 16 and
534 /// the size of vector<4xi16> is 64. Returns 0 for non-primitive
535 /// (aggregates such as struct) or types that don't have a size (such as void).
536 llvm::TypeSize getPrimitiveTypeSizeInBits(Type type);
537 
538 } // namespace LLVM
539 } // namespace mlir
540 
541 #endif // MLIR_DIALECT_LLVMIR_LLVMTYPES_H_
542