[Alignment][NFC] Use MaybeAlign in AttrBuilder
[llvm-complete.git] / include / llvm / IR / DerivedTypes.h
blob20097ef3f31a559abd3d65085138cd8370956e34
1 //===- llvm/DerivedTypes.h - Classes for handling data 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 contains the declarations of classes that represent "derived
10 // types". These are things like "arrays of x" or "structure of x, y, z" or
11 // "function returning x taking (y,z) as parameters", etc...
13 // The implementations of these classes live in the Type.cpp file.
15 //===----------------------------------------------------------------------===//
17 #ifndef LLVM_IR_DERIVEDTYPES_H
18 #define LLVM_IR_DERIVEDTYPES_H
20 #include "llvm/ADT/ArrayRef.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/StringRef.h"
23 #include "llvm/IR/Type.h"
24 #include "llvm/Support/Casting.h"
25 #include "llvm/Support/Compiler.h"
26 #include "llvm/Support/TypeSize.h"
27 #include <cassert>
28 #include <cstdint>
30 namespace llvm {
32 class Value;
33 class APInt;
34 class LLVMContext;
36 /// Class to represent integer types. Note that this class is also used to
37 /// represent the built-in integer types: Int1Ty, Int8Ty, Int16Ty, Int32Ty and
38 /// Int64Ty.
39 /// Integer representation type
40 class IntegerType : public Type {
41 friend class LLVMContextImpl;
43 protected:
44 explicit IntegerType(LLVMContext &C, unsigned NumBits) : Type(C, IntegerTyID){
45 setSubclassData(NumBits);
48 public:
49 /// This enum is just used to hold constants we need for IntegerType.
50 enum {
51 MIN_INT_BITS = 1, ///< Minimum number of bits that can be specified
52 MAX_INT_BITS = (1<<24)-1 ///< Maximum number of bits that can be specified
53 ///< Note that bit width is stored in the Type classes SubclassData field
54 ///< which has 24 bits. This yields a maximum bit width of 16,777,215
55 ///< bits.
58 /// This static method is the primary way of constructing an IntegerType.
59 /// If an IntegerType with the same NumBits value was previously instantiated,
60 /// that instance will be returned. Otherwise a new one will be created. Only
61 /// one instance with a given NumBits value is ever created.
62 /// Get or create an IntegerType instance.
63 static IntegerType *get(LLVMContext &C, unsigned NumBits);
65 /// Returns type twice as wide the input type.
66 IntegerType *getExtendedType() const {
67 return Type::getIntNTy(getContext(), 2 * getScalarSizeInBits());
70 /// Get the number of bits in this IntegerType
71 unsigned getBitWidth() const { return getSubclassData(); }
73 /// Return a bitmask with ones set for all of the bits that can be set by an
74 /// unsigned version of this type. This is 0xFF for i8, 0xFFFF for i16, etc.
75 uint64_t getBitMask() const {
76 return ~uint64_t(0UL) >> (64-getBitWidth());
79 /// Return a uint64_t with just the most significant bit set (the sign bit, if
80 /// the value is treated as a signed number).
81 uint64_t getSignBit() const {
82 return 1ULL << (getBitWidth()-1);
85 /// For example, this is 0xFF for an 8 bit integer, 0xFFFF for i16, etc.
86 /// @returns a bit mask with ones set for all the bits of this type.
87 /// Get a bit mask for this type.
88 APInt getMask() const;
90 /// This method determines if the width of this IntegerType is a power-of-2
91 /// in terms of 8 bit bytes.
92 /// @returns true if this is a power-of-2 byte width.
93 /// Is this a power-of-2 byte-width IntegerType ?
94 bool isPowerOf2ByteWidth() const;
96 /// Methods for support type inquiry through isa, cast, and dyn_cast.
97 static bool classof(const Type *T) {
98 return T->getTypeID() == IntegerTyID;
102 unsigned Type::getIntegerBitWidth() const {
103 return cast<IntegerType>(this)->getBitWidth();
106 /// Class to represent function types
108 class FunctionType : public Type {
109 FunctionType(Type *Result, ArrayRef<Type*> Params, bool IsVarArgs);
111 public:
112 FunctionType(const FunctionType &) = delete;
113 FunctionType &operator=(const FunctionType &) = delete;
115 /// This static method is the primary way of constructing a FunctionType.
116 static FunctionType *get(Type *Result,
117 ArrayRef<Type*> Params, bool isVarArg);
119 /// Create a FunctionType taking no parameters.
120 static FunctionType *get(Type *Result, bool isVarArg);
122 /// Return true if the specified type is valid as a return type.
123 static bool isValidReturnType(Type *RetTy);
125 /// Return true if the specified type is valid as an argument type.
126 static bool isValidArgumentType(Type *ArgTy);
128 bool isVarArg() const { return getSubclassData()!=0; }
129 Type *getReturnType() const { return ContainedTys[0]; }
131 using param_iterator = Type::subtype_iterator;
133 param_iterator param_begin() const { return ContainedTys + 1; }
134 param_iterator param_end() const { return &ContainedTys[NumContainedTys]; }
135 ArrayRef<Type *> params() const {
136 return makeArrayRef(param_begin(), param_end());
139 /// Parameter type accessors.
140 Type *getParamType(unsigned i) const { return ContainedTys[i+1]; }
142 /// Return the number of fixed parameters this function type requires.
143 /// This does not consider varargs.
144 unsigned getNumParams() const { return NumContainedTys - 1; }
146 /// Methods for support type inquiry through isa, cast, and dyn_cast.
147 static bool classof(const Type *T) {
148 return T->getTypeID() == FunctionTyID;
151 static_assert(alignof(FunctionType) >= alignof(Type *),
152 "Alignment sufficient for objects appended to FunctionType");
154 bool Type::isFunctionVarArg() const {
155 return cast<FunctionType>(this)->isVarArg();
158 Type *Type::getFunctionParamType(unsigned i) const {
159 return cast<FunctionType>(this)->getParamType(i);
162 unsigned Type::getFunctionNumParams() const {
163 return cast<FunctionType>(this)->getNumParams();
166 /// A handy container for a FunctionType+Callee-pointer pair, which can be
167 /// passed around as a single entity. This assists in replacing the use of
168 /// PointerType::getElementType() to access the function's type, since that's
169 /// slated for removal as part of the [opaque pointer types] project.
170 class FunctionCallee {
171 public:
172 // Allow implicit conversion from types which have a getFunctionType member
173 // (e.g. Function and InlineAsm).
174 template <typename T, typename U = decltype(&T::getFunctionType)>
175 FunctionCallee(T *Fn)
176 : FnTy(Fn ? Fn->getFunctionType() : nullptr), Callee(Fn) {}
178 FunctionCallee(FunctionType *FnTy, Value *Callee)
179 : FnTy(FnTy), Callee(Callee) {
180 assert((FnTy == nullptr) == (Callee == nullptr));
183 FunctionCallee(std::nullptr_t) {}
185 FunctionCallee() = default;
187 FunctionType *getFunctionType() { return FnTy; }
189 Value *getCallee() { return Callee; }
191 explicit operator bool() { return Callee; }
193 private:
194 FunctionType *FnTy = nullptr;
195 Value *Callee = nullptr;
198 /// Common super class of ArrayType, StructType and VectorType.
199 class CompositeType : public Type {
200 protected:
201 explicit CompositeType(LLVMContext &C, TypeID tid) : Type(C, tid) {}
203 public:
204 /// Given an index value into the type, return the type of the element.
205 Type *getTypeAtIndex(const Value *V) const;
206 Type *getTypeAtIndex(unsigned Idx) const;
207 bool indexValid(const Value *V) const;
208 bool indexValid(unsigned Idx) const;
210 /// Methods for support type inquiry through isa, cast, and dyn_cast.
211 static bool classof(const Type *T) {
212 return T->getTypeID() == ArrayTyID ||
213 T->getTypeID() == StructTyID ||
214 T->getTypeID() == VectorTyID;
218 /// Class to represent struct types. There are two different kinds of struct
219 /// types: Literal structs and Identified structs.
221 /// Literal struct types (e.g. { i32, i32 }) are uniqued structurally, and must
222 /// always have a body when created. You can get one of these by using one of
223 /// the StructType::get() forms.
225 /// Identified structs (e.g. %foo or %42) may optionally have a name and are not
226 /// uniqued. The names for identified structs are managed at the LLVMContext
227 /// level, so there can only be a single identified struct with a given name in
228 /// a particular LLVMContext. Identified structs may also optionally be opaque
229 /// (have no body specified). You get one of these by using one of the
230 /// StructType::create() forms.
232 /// Independent of what kind of struct you have, the body of a struct type are
233 /// laid out in memory consecutively with the elements directly one after the
234 /// other (if the struct is packed) or (if not packed) with padding between the
235 /// elements as defined by DataLayout (which is required to match what the code
236 /// generator for a target expects).
238 class StructType : public CompositeType {
239 StructType(LLVMContext &C) : CompositeType(C, StructTyID) {}
241 enum {
242 /// This is the contents of the SubClassData field.
243 SCDB_HasBody = 1,
244 SCDB_Packed = 2,
245 SCDB_IsLiteral = 4,
246 SCDB_IsSized = 8
249 /// For a named struct that actually has a name, this is a pointer to the
250 /// symbol table entry (maintained by LLVMContext) for the struct.
251 /// This is null if the type is an literal struct or if it is a identified
252 /// type that has an empty name.
253 void *SymbolTableEntry = nullptr;
255 public:
256 StructType(const StructType &) = delete;
257 StructType &operator=(const StructType &) = delete;
259 /// This creates an identified struct.
260 static StructType *create(LLVMContext &Context, StringRef Name);
261 static StructType *create(LLVMContext &Context);
263 static StructType *create(ArrayRef<Type *> Elements, StringRef Name,
264 bool isPacked = false);
265 static StructType *create(ArrayRef<Type *> Elements);
266 static StructType *create(LLVMContext &Context, ArrayRef<Type *> Elements,
267 StringRef Name, bool isPacked = false);
268 static StructType *create(LLVMContext &Context, ArrayRef<Type *> Elements);
269 template <class... Tys>
270 static typename std::enable_if<are_base_of<Type, Tys...>::value,
271 StructType *>::type
272 create(StringRef Name, Type *elt1, Tys *... elts) {
273 assert(elt1 && "Cannot create a struct type with no elements with this");
274 SmallVector<llvm::Type *, 8> StructFields({elt1, elts...});
275 return create(StructFields, Name);
278 /// This static method is the primary way to create a literal StructType.
279 static StructType *get(LLVMContext &Context, ArrayRef<Type*> Elements,
280 bool isPacked = false);
282 /// Create an empty structure type.
283 static StructType *get(LLVMContext &Context, bool isPacked = false);
285 /// This static method is a convenience method for creating structure types by
286 /// specifying the elements as arguments. Note that this method always returns
287 /// a non-packed struct, and requires at least one element type.
288 template <class... Tys>
289 static typename std::enable_if<are_base_of<Type, Tys...>::value,
290 StructType *>::type
291 get(Type *elt1, Tys *... elts) {
292 assert(elt1 && "Cannot create a struct type with no elements with this");
293 LLVMContext &Ctx = elt1->getContext();
294 SmallVector<llvm::Type *, 8> StructFields({elt1, elts...});
295 return llvm::StructType::get(Ctx, StructFields);
298 bool isPacked() const { return (getSubclassData() & SCDB_Packed) != 0; }
300 /// Return true if this type is uniqued by structural equivalence, false if it
301 /// is a struct definition.
302 bool isLiteral() const { return (getSubclassData() & SCDB_IsLiteral) != 0; }
304 /// Return true if this is a type with an identity that has no body specified
305 /// yet. These prints as 'opaque' in .ll files.
306 bool isOpaque() const { return (getSubclassData() & SCDB_HasBody) == 0; }
308 /// isSized - Return true if this is a sized type.
309 bool isSized(SmallPtrSetImpl<Type *> *Visited = nullptr) const;
311 /// Return true if this is a named struct that has a non-empty name.
312 bool hasName() const { return SymbolTableEntry != nullptr; }
314 /// Return the name for this struct type if it has an identity.
315 /// This may return an empty string for an unnamed struct type. Do not call
316 /// this on an literal type.
317 StringRef getName() const;
319 /// Change the name of this type to the specified name, or to a name with a
320 /// suffix if there is a collision. Do not call this on an literal type.
321 void setName(StringRef Name);
323 /// Specify a body for an opaque identified type.
324 void setBody(ArrayRef<Type*> Elements, bool isPacked = false);
326 template <typename... Tys>
327 typename std::enable_if<are_base_of<Type, Tys...>::value, void>::type
328 setBody(Type *elt1, Tys *... elts) {
329 assert(elt1 && "Cannot create a struct type with no elements with this");
330 SmallVector<llvm::Type *, 8> StructFields({elt1, elts...});
331 setBody(StructFields);
334 /// Return true if the specified type is valid as a element type.
335 static bool isValidElementType(Type *ElemTy);
337 // Iterator access to the elements.
338 using element_iterator = Type::subtype_iterator;
340 element_iterator element_begin() const { return ContainedTys; }
341 element_iterator element_end() const { return &ContainedTys[NumContainedTys];}
342 ArrayRef<Type *> const elements() const {
343 return makeArrayRef(element_begin(), element_end());
346 /// Return true if this is layout identical to the specified struct.
347 bool isLayoutIdentical(StructType *Other) const;
349 /// Random access to the elements
350 unsigned getNumElements() const { return NumContainedTys; }
351 Type *getElementType(unsigned N) const {
352 assert(N < NumContainedTys && "Element number out of range!");
353 return ContainedTys[N];
356 /// Methods for support type inquiry through isa, cast, and dyn_cast.
357 static bool classof(const Type *T) {
358 return T->getTypeID() == StructTyID;
362 StringRef Type::getStructName() const {
363 return cast<StructType>(this)->getName();
366 unsigned Type::getStructNumElements() const {
367 return cast<StructType>(this)->getNumElements();
370 Type *Type::getStructElementType(unsigned N) const {
371 return cast<StructType>(this)->getElementType(N);
374 /// This is the superclass of the array and vector type classes. Both of these
375 /// represent "arrays" in memory. The array type represents a specifically sized
376 /// array, and the vector type represents a specifically sized array that allows
377 /// for use of SIMD instructions. SequentialType holds the common features of
378 /// both, which stem from the fact that both lay their components out in memory
379 /// identically.
380 class SequentialType : public CompositeType {
381 Type *ContainedType; ///< Storage for the single contained type.
382 uint64_t NumElements;
384 protected:
385 SequentialType(TypeID TID, Type *ElType, uint64_t NumElements)
386 : CompositeType(ElType->getContext(), TID), ContainedType(ElType),
387 NumElements(NumElements) {
388 ContainedTys = &ContainedType;
389 NumContainedTys = 1;
392 public:
393 SequentialType(const SequentialType &) = delete;
394 SequentialType &operator=(const SequentialType &) = delete;
396 /// For scalable vectors, this will return the minimum number of elements
397 /// in the vector.
398 uint64_t getNumElements() const { return NumElements; }
399 Type *getElementType() const { return ContainedType; }
401 /// Methods for support type inquiry through isa, cast, and dyn_cast.
402 static bool classof(const Type *T) {
403 return T->getTypeID() == ArrayTyID || T->getTypeID() == VectorTyID;
407 /// Class to represent array types.
408 class ArrayType : public SequentialType {
409 ArrayType(Type *ElType, uint64_t NumEl);
411 public:
412 ArrayType(const ArrayType &) = delete;
413 ArrayType &operator=(const ArrayType &) = delete;
415 /// This static method is the primary way to construct an ArrayType
416 static ArrayType *get(Type *ElementType, uint64_t NumElements);
418 /// Return true if the specified type is valid as a element type.
419 static bool isValidElementType(Type *ElemTy);
421 /// Methods for support type inquiry through isa, cast, and dyn_cast.
422 static bool classof(const Type *T) {
423 return T->getTypeID() == ArrayTyID;
427 uint64_t Type::getArrayNumElements() const {
428 return cast<ArrayType>(this)->getNumElements();
431 /// Class to represent vector types.
432 class VectorType : public SequentialType {
433 /// A fully specified VectorType is of the form <vscale x n x Ty>. 'n' is the
434 /// minimum number of elements of type Ty contained within the vector, and
435 /// 'vscale x' indicates that the total element count is an integer multiple
436 /// of 'n', where the multiple is either guaranteed to be one, or is
437 /// statically unknown at compile time.
439 /// If the multiple is known to be 1, then the extra term is discarded in
440 /// textual IR:
442 /// <4 x i32> - a vector containing 4 i32s
443 /// <vscale x 4 x i32> - a vector containing an unknown integer multiple
444 /// of 4 i32s
446 VectorType(Type *ElType, unsigned NumEl, bool Scalable = false);
447 VectorType(Type *ElType, ElementCount EC);
449 // If true, the total number of elements is an unknown multiple of the
450 // minimum 'NumElements' from SequentialType. Otherwise the total number
451 // of elements is exactly equal to 'NumElements'.
452 bool Scalable;
454 public:
455 VectorType(const VectorType &) = delete;
456 VectorType &operator=(const VectorType &) = delete;
458 /// This static method is the primary way to construct an VectorType.
459 static VectorType *get(Type *ElementType, ElementCount EC);
460 static VectorType *get(Type *ElementType, unsigned NumElements,
461 bool Scalable = false) {
462 return VectorType::get(ElementType, {NumElements, Scalable});
465 /// This static method gets a VectorType with the same number of elements as
466 /// the input type, and the element type is an integer type of the same width
467 /// as the input element type.
468 static VectorType *getInteger(VectorType *VTy) {
469 unsigned EltBits = VTy->getElementType()->getPrimitiveSizeInBits();
470 assert(EltBits && "Element size must be of a non-zero size");
471 Type *EltTy = IntegerType::get(VTy->getContext(), EltBits);
472 return VectorType::get(EltTy, VTy->getElementCount());
475 /// This static method is like getInteger except that the element types are
476 /// twice as wide as the elements in the input type.
477 static VectorType *getExtendedElementVectorType(VectorType *VTy) {
478 assert(VTy->isIntOrIntVectorTy() && "VTy expected to be a vector of ints.");
479 auto *EltTy = cast<IntegerType>(VTy->getElementType());
480 return VectorType::get(EltTy->getExtendedType(), VTy->getElementCount());
483 // This static method gets a VectorType with the same number of elements as
484 // the input type, and the element type is an integer or float type which
485 // is half as wide as the elements in the input type.
486 static VectorType *getTruncatedElementVectorType(VectorType *VTy) {
487 Type *EltTy;
488 if (VTy->getElementType()->isFloatingPointTy()) {
489 switch(VTy->getElementType()->getTypeID()) {
490 case DoubleTyID:
491 EltTy = Type::getFloatTy(VTy->getContext());
492 break;
493 case FloatTyID:
494 EltTy = Type::getHalfTy(VTy->getContext());
495 break;
496 default:
497 llvm_unreachable("Cannot create narrower fp vector element type");
499 } else {
500 unsigned EltBits = VTy->getElementType()->getPrimitiveSizeInBits();
501 assert((EltBits & 1) == 0 &&
502 "Cannot truncate vector element with odd bit-width");
503 EltTy = IntegerType::get(VTy->getContext(), EltBits / 2);
505 return VectorType::get(EltTy, VTy->getElementCount());
508 // This static method returns a VectorType with a smaller number of elements
509 // of a larger type than the input element type. For example, a <16 x i8>
510 // subdivided twice would return <4 x i32>
511 static VectorType *getSubdividedVectorType(VectorType *VTy, int NumSubdivs) {
512 for (int i = 0; i < NumSubdivs; ++i) {
513 VTy = VectorType::getDoubleElementsVectorType(VTy);
514 VTy = VectorType::getTruncatedElementVectorType(VTy);
516 return VTy;
519 /// This static method returns a VectorType with half as many elements as the
520 /// input type and the same element type.
521 static VectorType *getHalfElementsVectorType(VectorType *VTy) {
522 auto EltCnt = VTy->getElementCount();
523 assert ((EltCnt.Min & 1) == 0 &&
524 "Cannot halve vector with odd number of elements.");
525 return VectorType::get(VTy->getElementType(), EltCnt/2);
528 /// This static method returns a VectorType with twice as many elements as the
529 /// input type and the same element type.
530 static VectorType *getDoubleElementsVectorType(VectorType *VTy) {
531 auto EltCnt = VTy->getElementCount();
532 assert((VTy->getNumElements() * 2ull) <= UINT_MAX &&
533 "Too many elements in vector");
534 return VectorType::get(VTy->getElementType(), EltCnt*2);
537 /// Return true if the specified type is valid as a element type.
538 static bool isValidElementType(Type *ElemTy);
540 /// Return an ElementCount instance to represent the (possibly scalable)
541 /// number of elements in the vector.
542 ElementCount getElementCount() const {
543 uint64_t MinimumEltCnt = getNumElements();
544 assert(MinimumEltCnt <= UINT_MAX && "Too many elements in vector");
545 return { (unsigned)MinimumEltCnt, Scalable };
548 /// Returns whether or not this is a scalable vector (meaning the total
549 /// element count is a multiple of the minimum).
550 bool isScalable() const {
551 return Scalable;
554 /// Return the minimum number of bits in the Vector type.
555 /// Returns zero when the vector is a vector of pointers.
556 unsigned getBitWidth() const {
557 return getNumElements() * getElementType()->getPrimitiveSizeInBits();
560 /// Methods for support type inquiry through isa, cast, and dyn_cast.
561 static bool classof(const Type *T) {
562 return T->getTypeID() == VectorTyID;
566 unsigned Type::getVectorNumElements() const {
567 return cast<VectorType>(this)->getNumElements();
570 bool Type::getVectorIsScalable() const {
571 return cast<VectorType>(this)->isScalable();
574 ElementCount Type::getVectorElementCount() const {
575 return cast<VectorType>(this)->getElementCount();
578 /// Class to represent pointers.
579 class PointerType : public Type {
580 explicit PointerType(Type *ElType, unsigned AddrSpace);
582 Type *PointeeTy;
584 public:
585 PointerType(const PointerType &) = delete;
586 PointerType &operator=(const PointerType &) = delete;
588 /// This constructs a pointer to an object of the specified type in a numbered
589 /// address space.
590 static PointerType *get(Type *ElementType, unsigned AddressSpace);
592 /// This constructs a pointer to an object of the specified type in the
593 /// generic address space (address space zero).
594 static PointerType *getUnqual(Type *ElementType) {
595 return PointerType::get(ElementType, 0);
598 Type *getElementType() const { return PointeeTy; }
600 /// Return true if the specified type is valid as a element type.
601 static bool isValidElementType(Type *ElemTy);
603 /// Return true if we can load or store from a pointer to this type.
604 static bool isLoadableOrStorableType(Type *ElemTy);
606 /// Return the address space of the Pointer type.
607 inline unsigned getAddressSpace() const { return getSubclassData(); }
609 /// Implement support type inquiry through isa, cast, and dyn_cast.
610 static bool classof(const Type *T) {
611 return T->getTypeID() == PointerTyID;
615 Type *Type::getExtendedType() const {
616 assert(
617 isIntOrIntVectorTy() &&
618 "Original type expected to be a vector of integers or a scalar integer.");
619 if (auto *VTy = dyn_cast<VectorType>(this))
620 return VectorType::getExtendedElementVectorType(
621 const_cast<VectorType *>(VTy));
622 return cast<IntegerType>(this)->getExtendedType();
625 Type *Type::getWithNewBitWidth(unsigned NewBitWidth) const {
626 assert(
627 isIntOrIntVectorTy() &&
628 "Original type expected to be a vector of integers or a scalar integer.");
629 Type *NewType = getIntNTy(getContext(), NewBitWidth);
630 if (isVectorTy())
631 NewType = VectorType::get(NewType, getVectorElementCount());
632 return NewType;
635 unsigned Type::getPointerAddressSpace() const {
636 return cast<PointerType>(getScalarType())->getAddressSpace();
639 } // end namespace llvm
641 #endif // LLVM_IR_DERIVEDTYPES_H