1 //===-- llvm/Type.h - Classes for handling data types -----------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
14 #include "llvm/AbstractTypeUser.h"
15 #include "llvm/Support/Casting.h"
16 #include "llvm/Support/DataTypes.h"
17 #include "llvm/ADT/GraphTraits.h"
18 #include "llvm/ADT/iterator"
33 /// This file contains the declaration of the Type class. For more "Type" type
34 /// stuff, look in DerivedTypes.h.
36 /// The instances of the Type class are immutable: once they are created,
37 /// they are never changed. Also note that only one instance of a particular
38 /// type is ever created. Thus seeing if two types are equal is a matter of
39 /// doing a trivial pointer comparison. To enforce that no two equal instances
40 /// are created, Type instances can only be created via static factory methods
41 /// in class Type and in derived classes.
43 /// Once allocated, Types are never free'd, unless they are an abstract type
44 /// that is resolved to a more concrete type.
46 /// Types themself don't have a name, and can be named either by:
47 /// - using SymbolTable instance, typically from some Module,
48 /// - using convenience methods in the Module class (which uses module's
51 /// Opaque types are simple derived types with no state. There may be many
52 /// different Opaque type objects floating around, but two are only considered
53 /// identical if they are pointer equals of each other. This allows us to have
54 /// two opaque types that end up resolving to different concrete types later.
56 /// Opaque types are also kinda weird and scary and different because they have
57 /// to keep a list of uses of the type. When, through linking, parsing, or
58 /// bytecode reading, they become resolved, they need to find and update all
59 /// users of the unknown type, causing them to reference a new, more concrete
60 /// type. Opaque types are deleted when their use list dwindles to zero users.
62 /// @brief Root of type hierarchy
63 class Type : public AbstractTypeUser {
65 ///===-------------------------------------------------------------------===//
66 /// Definitions of all of the base types for the Type system. Based on this
67 /// value, you can cast to a "DerivedType" subclass (see DerivedTypes.h)
68 /// Note: If you add an element to this, you need to add an element to the
69 /// Type::getPrimitiveType function, or else things will break!
72 // PrimitiveTypes .. make sure LastPrimitiveTyID stays up to date
73 VoidTyID = 0 , BoolTyID, // 0, 1: Basics...
74 UByteTyID , SByteTyID, // 2, 3: 8 bit types...
75 UShortTyID , ShortTyID, // 4, 5: 16 bit types...
76 UIntTyID , IntTyID, // 6, 7: 32 bit types...
77 ULongTyID , LongTyID, // 8, 9: 64 bit types...
78 FloatTyID , DoubleTyID, // 10,11: Floating point types...
79 LabelTyID , // 12 : Labels...
81 // Derived types... see DerivedTypes.h file...
82 // Make sure FirstDerivedTyID stays up to date!!!
83 FunctionTyID , StructTyID, // Functions... Structs...
84 ArrayTyID , PointerTyID, // Array... pointer...
85 OpaqueTyID, // Opaque type instances...
86 PackedTyID, // SIMD 'packed' format...
89 NumTypeIDs, // Must remain as last defined ID
90 LastPrimitiveTyID = LabelTyID,
91 FirstDerivedTyID = FunctionTyID
95 TypeID ID : 8; // The current base type of this type.
96 bool Abstract : 1; // True if type contains an OpaqueType
98 /// RefCount - This counts the number of PATypeHolders that are pointing to
99 /// this type. When this number falls to zero, if the type is abstract and
100 /// has no AbstractTypeUsers, the type is deleted. This is only sensical for
103 mutable unsigned RefCount;
105 const Type *getForwardedTypeInternal() const;
107 Type(const char *Name, TypeID id);
108 Type(TypeID id) : ID(id), Abstract(false), RefCount(0), ForwardType(0) {}
110 assert(AbstractTypeUsers.empty());
113 /// Types can become nonabstract later, if they are refined.
115 inline void setAbstract(bool Val) { Abstract = Val; }
117 unsigned getRefCount() const { return RefCount; }
119 /// ForwardType - This field is used to implement the union find scheme for
120 /// abstract types. When types are refined to other types, this field is set
121 /// to the more refined type. Only abstract types can be forwarded.
122 mutable const Type *ForwardType;
124 /// ContainedTys - The list of types contained by this one. For example, this
125 /// includes the arguments of a function type, the elements of the structure,
126 /// the pointee of a pointer, etc. Note that keeping this vector in the Type
127 /// class wastes some space for types that do not contain anything (such as
128 /// primitive types). However, keeping it here allows the subtype_* members
129 /// to be implemented MUCH more efficiently, and dynamically very few types do
130 /// not contain any elements (most are derived).
131 std::vector<PATypeHandle> ContainedTys;
133 /// AbstractTypeUsers - Implement a list of the users that need to be notified
134 /// if I am a type, and I get resolved into a more concrete type.
136 mutable std::vector<AbstractTypeUser *> AbstractTypeUsers;
138 void print(std::ostream &O) const;
140 /// @brief Debugging support: print to stderr
143 //===--------------------------------------------------------------------===//
144 // Property accessors for dealing with types... Some of these virtual methods
145 // are defined in private classes defined in Type.cpp for primitive types.
148 /// getTypeID - Return the type id for the type. This will return one
149 /// of the TypeID enum elements defined above.
151 inline TypeID getTypeID() const { return ID; }
153 /// getDescription - Return the string representation of the type...
154 const std::string &getDescription() const;
156 /// isSigned - Return whether an integral numeric type is signed. This is
157 /// true for SByteTy, ShortTy, IntTy, LongTy. Note that this is not true for
158 /// Float and Double.
160 bool isSigned() const {
161 return ID == SByteTyID || ID == ShortTyID ||
162 ID == IntTyID || ID == LongTyID;
165 /// isUnsigned - Return whether a numeric type is unsigned. This is not quite
166 /// the complement of isSigned... nonnumeric types return false as they do
167 /// with isSigned. This returns true for UByteTy, UShortTy, UIntTy, and
170 bool isUnsigned() const {
171 return ID == UByteTyID || ID == UShortTyID ||
172 ID == UIntTyID || ID == ULongTyID;
175 /// isInteger - Equivalent to isSigned() || isUnsigned()
177 bool isInteger() const { return ID >= UByteTyID && ID <= LongTyID; }
179 /// isIntegral - Returns true if this is an integral type, which is either
180 /// BoolTy or one of the Integer types.
182 bool isIntegral() const { return isInteger() || this == BoolTy; }
184 /// isFloatingPoint - Return true if this is one of the two floating point
186 bool isFloatingPoint() const { return ID == FloatTyID || ID == DoubleTyID; }
188 /// isFPOrFPVector - Return true if this is a FP type or a vector of FP types.
190 bool isFPOrFPVector() const;
192 /// isAbstract - True if the type is either an Opaque type, or is a derived
193 /// type that includes an opaque type somewhere in it.
195 inline bool isAbstract() const { return Abstract; }
197 /// isLosslesslyConvertibleTo - Return true if this type can be converted to
198 /// 'Ty' without any reinterpretation of bits. For example, uint to int.
200 bool isLosslesslyConvertibleTo(const Type *Ty) const;
203 /// Here are some useful little methods to query what type derived types are
204 /// Note that all other types can just compare to see if this == Type::xxxTy;
206 inline bool isPrimitiveType() const { return ID <= LastPrimitiveTyID; }
207 inline bool isDerivedType() const { return ID >= FirstDerivedTyID; }
209 /// isFirstClassType - Return true if the value is holdable in a register.
211 inline bool isFirstClassType() const {
212 return (ID != VoidTyID && ID <= LastPrimitiveTyID) ||
213 ID == PointerTyID || ID == PackedTyID;
216 /// isSized - Return true if it makes sense to take the size of this type. To
217 /// get the actual size for a particular target, it is reasonable to use the
218 /// TargetData subsystem to do this.
220 bool isSized() const {
221 // If it's a primitive, it is always sized.
222 if (ID >= BoolTyID && ID <= DoubleTyID || ID == PointerTyID)
224 // If it is not something that can have a size (e.g. a function or label),
225 // it doesn't have a size.
226 if (ID != StructTyID && ID != ArrayTyID && ID != PackedTyID)
228 // If it is something that can have a size and it's concrete, it definitely
229 // has a size, otherwise we have to try harder to decide.
230 return !isAbstract() || isSizedDerivedType();
233 /// getPrimitiveSize - Return the basic size of this type if it is a primitive
234 /// type. These are fixed by LLVM and are not target dependent. This will
235 /// return zero if the type does not have a size or is not a primitive type.
237 unsigned getPrimitiveSize() const;
238 unsigned getPrimitiveSizeInBits() const;
240 /// getUnsignedVersion - If this is an integer type, return the unsigned
241 /// variant of this type. For example int -> uint.
242 const Type *getUnsignedVersion() const;
244 /// getSignedVersion - If this is an integer type, return the signed variant
245 /// of this type. For example uint -> int.
246 const Type *getSignedVersion() const;
248 /// getIntegralTypeMask - Return a bitmask with ones set for all of the bits
249 /// that can be set by an unsigned version of this type. This is 0xFF for
250 /// sbyte/ubyte, 0xFFFF for shorts, etc.
251 uint64_t getIntegralTypeMask() const {
252 assert(isIntegral() && "This only works for integral types!");
253 return ~uint64_t(0UL) >> (64-getPrimitiveSizeInBits());
256 /// getForwaredType - Return the type that this type has been resolved to if
257 /// it has been resolved to anything. This is used to implement the
258 /// union-find algorithm for type resolution, and shouldn't be used by general
260 const Type *getForwardedType() const {
261 if (!ForwardType) return 0;
262 return getForwardedTypeInternal();
265 /// getVAArgsPromotedType - Return the type an argument of this type
266 /// will be promoted to if passed through a variable argument
268 const Type *getVAArgsPromotedType() const {
269 if (ID == BoolTyID || ID == UByteTyID || ID == UShortTyID)
271 else if (ID == SByteTyID || ID == ShortTyID)
273 else if (ID == FloatTyID)
274 return Type::DoubleTy;
279 //===--------------------------------------------------------------------===//
280 // Type Iteration support
282 typedef std::vector<PATypeHandle>::const_iterator subtype_iterator;
283 subtype_iterator subtype_begin() const { return ContainedTys.begin(); }
284 subtype_iterator subtype_end() const { return ContainedTys.end(); }
286 /// getContainedType - This method is used to implement the type iterator
287 /// (defined a the end of the file). For derived types, this returns the
288 /// types 'contained' in the derived type.
290 const Type *getContainedType(unsigned i) const {
291 assert(i < ContainedTys.size() && "Index out of range!");
292 return ContainedTys[i];
295 /// getNumContainedTypes - Return the number of types in the derived type.
297 typedef std::vector<PATypeHandle>::size_type size_type;
298 size_type getNumContainedTypes() const { return ContainedTys.size(); }
300 //===--------------------------------------------------------------------===//
301 // Static members exported by the Type class itself. Useful for getting
302 // instances of Type.
305 /// getPrimitiveType - Return a type based on an identifier.
306 static const Type *getPrimitiveType(TypeID IDNumber);
308 //===--------------------------------------------------------------------===//
309 // These are the builtin types that are always available...
311 static Type *VoidTy , *BoolTy;
312 static Type *SByteTy, *UByteTy,
316 static Type *FloatTy, *DoubleTy;
318 static Type* LabelTy;
320 /// Methods for support type inquiry through isa, cast, and dyn_cast:
321 static inline bool classof(const Type *T) { return true; }
323 void addRef() const {
324 assert(isAbstract() && "Cannot add a reference to a non-abstract type!");
328 void dropRef() const {
329 assert(isAbstract() && "Cannot drop a reference to a non-abstract type!");
330 assert(RefCount && "No objects are currently referencing this object!");
332 // If this is the last PATypeHolder using this object, and there are no
333 // PATypeHandles using it, the type is dead, delete it now.
334 if (--RefCount == 0 && AbstractTypeUsers.empty())
338 /// addAbstractTypeUser - Notify an abstract type that there is a new user of
339 /// it. This function is called primarily by the PATypeHandle class.
341 void addAbstractTypeUser(AbstractTypeUser *U) const {
342 assert(isAbstract() && "addAbstractTypeUser: Current type not abstract!");
343 AbstractTypeUsers.push_back(U);
346 /// removeAbstractTypeUser - Notify an abstract type that a user of the class
347 /// no longer has a handle to the type. This function is called primarily by
348 /// the PATypeHandle class. When there are no users of the abstract type, it
349 /// is annihilated, because there is no way to get a reference to it ever
352 void removeAbstractTypeUser(AbstractTypeUser *U) const;
355 /// isSizedDerivedType - Derived types like structures and arrays are sized
356 /// iff all of the members of the type are sized as well. Since asking for
357 /// their size is relatively uncommon, move this operation out of line.
358 bool isSizedDerivedType() const;
360 virtual void refineAbstractType(const DerivedType *OldTy, const Type *NewTy);
361 virtual void typeBecameConcrete(const DerivedType *AbsTy);
364 // PromoteAbstractToConcrete - This is an internal method used to calculate
365 // change "Abstract" from true to false when types are refined.
366 void PromoteAbstractToConcrete();
367 friend class TypeMapBase;
370 //===----------------------------------------------------------------------===//
371 // Define some inline methods for the AbstractTypeUser.h:PATypeHandle class.
372 // These are defined here because they MUST be inlined, yet are dependent on
373 // the definition of the Type class.
375 inline void PATypeHandle::addUser() {
376 assert(Ty && "Type Handle has a null type!");
377 if (Ty->isAbstract())
378 Ty->addAbstractTypeUser(User);
380 inline void PATypeHandle::removeUser() {
381 if (Ty->isAbstract())
382 Ty->removeAbstractTypeUser(User);
385 // Define inline methods for PATypeHolder...
387 inline void PATypeHolder::addRef() {
388 if (Ty->isAbstract())
392 inline void PATypeHolder::dropRef() {
393 if (Ty->isAbstract())
398 //===----------------------------------------------------------------------===//
399 // Provide specializations of GraphTraits to be able to treat a type as a
400 // graph of sub types...
402 template <> struct GraphTraits<Type*> {
403 typedef Type NodeType;
404 typedef Type::subtype_iterator ChildIteratorType;
406 static inline NodeType *getEntryNode(Type *T) { return T; }
407 static inline ChildIteratorType child_begin(NodeType *N) {
408 return N->subtype_begin();
410 static inline ChildIteratorType child_end(NodeType *N) {
411 return N->subtype_end();
415 template <> struct GraphTraits<const Type*> {
416 typedef const Type NodeType;
417 typedef Type::subtype_iterator ChildIteratorType;
419 static inline NodeType *getEntryNode(const Type *T) { return T; }
420 static inline ChildIteratorType child_begin(NodeType *N) {
421 return N->subtype_begin();
423 static inline ChildIteratorType child_end(NodeType *N) {
424 return N->subtype_end();
428 template <> inline bool isa_impl<PointerType, Type>(const Type &Ty) {
429 return Ty.getTypeID() == Type::PointerTyID;
432 std::ostream &operator<<(std::ostream &OS, const Type &T);
434 } // End llvm namespace