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 /// Opaque types are simple derived types with no state. There may be many
47 /// different Opaque type objects floating around, but two are only considered
48 /// identical if they are pointer equals of each other. This allows us to have
49 /// two opaque types that end up resolving to different concrete types later.
51 /// Opaque types are also kinda weird and scary and different because they have
52 /// to keep a list of uses of the type. When, through linking, parsing, or
53 /// bytecode reading, they become resolved, they need to find and update all
54 /// users of the unknown type, causing them to reference a new, more concrete
55 /// type. Opaque types are deleted when their use list dwindles to zero users.
57 /// @brief Root of type hierarchy
58 class Type : public AbstractTypeUser {
60 ///===-------------------------------------------------------------------===//
61 /// Definitions of all of the base types for the Type system. Based on this
62 /// value, you can cast to a "DerivedType" subclass (see DerivedTypes.h)
63 /// Note: If you add an element to this, you need to add an element to the
64 /// Type::getPrimitiveType function, or else things will break!
67 // PrimitiveTypes .. make sure LastPrimitiveTyID stays up to date
68 VoidTyID = 0 , BoolTyID, // 0, 1: Basics...
69 UByteTyID , SByteTyID, // 2, 3: 8 bit types...
70 UShortTyID , ShortTyID, // 4, 5: 16 bit types...
71 UIntTyID , IntTyID, // 6, 7: 32 bit types...
72 ULongTyID , LongTyID, // 8, 9: 64 bit types...
73 FloatTyID , DoubleTyID, // 10,11: Floating point types...
74 LabelTyID , // 12 : Labels...
76 // Derived types... see DerivedTypes.h file...
77 // Make sure FirstDerivedTyID stays up to date!!!
78 FunctionTyID , StructTyID, // Functions... Structs...
79 ArrayTyID , PointerTyID, // Array... pointer...
80 OpaqueTyID, // Opaque type instances...
81 PackedTyID, // SIMD 'packed' format...
84 NumTypeIDs, // Must remain as last defined ID
85 LastPrimitiveTyID = LabelTyID,
86 FirstDerivedTyID = FunctionTyID
90 TypeID ID : 8; // The current base type of this type.
91 bool Abstract : 1; // True if type contains an OpaqueType
93 /// RefCount - This counts the number of PATypeHolders that are pointing to
94 /// this type. When this number falls to zero, if the type is abstract and
95 /// has no AbstractTypeUsers, the type is deleted. This is only sensical for
98 mutable unsigned RefCount;
100 const Type *getForwardedTypeInternal() const;
102 Type(const char *Name, TypeID id);
103 Type(TypeID id) : ID(id), Abstract(false), RefCount(0), ForwardType(0) {}
105 assert(AbstractTypeUsers.empty());
108 /// Types can become nonabstract later, if they are refined.
110 inline void setAbstract(bool Val) { Abstract = Val; }
112 unsigned getRefCount() const { return RefCount; }
114 /// ForwardType - This field is used to implement the union find scheme for
115 /// abstract types. When types are refined to other types, this field is set
116 /// to the more refined type. Only abstract types can be forwarded.
117 mutable const Type *ForwardType;
119 /// ContainedTys - The list of types contained by this one. For example, this
120 /// includes the arguments of a function type, the elements of the structure,
121 /// the pointee of a pointer, etc. Note that keeping this vector in the Type
122 /// class wastes some space for types that do not contain anything (such as
123 /// primitive types). However, keeping it here allows the subtype_* members
124 /// to be implemented MUCH more efficiently, and dynamically very few types do
125 /// not contain any elements (most are derived).
126 std::vector<PATypeHandle> ContainedTys;
128 /// AbstractTypeUsers - Implement a list of the users that need to be notified
129 /// if I am a type, and I get resolved into a more concrete type.
131 mutable std::vector<AbstractTypeUser *> AbstractTypeUsers;
133 void print(std::ostream &O) const;
135 /// @brief Debugging support: print to stderr
138 //===--------------------------------------------------------------------===//
139 // Property accessors for dealing with types... Some of these virtual methods
140 // are defined in private classes defined in Type.cpp for primitive types.
143 /// getTypeID - Return the type id for the type. This will return one
144 /// of the TypeID enum elements defined above.
146 inline TypeID getTypeID() const { return ID; }
148 /// getDescription - Return the string representation of the type...
149 const std::string &getDescription() const;
151 /// isSigned - Return whether an integral numeric type is signed. This is
152 /// true for SByteTy, ShortTy, IntTy, LongTy. Note that this is not true for
153 /// Float and Double.
155 bool isSigned() const {
156 return ID == SByteTyID || ID == ShortTyID ||
157 ID == IntTyID || ID == LongTyID;
160 /// isUnsigned - Return whether a numeric type is unsigned. This is not quite
161 /// the complement of isSigned... nonnumeric types return false as they do
162 /// with isSigned. This returns true for UByteTy, UShortTy, UIntTy, and
165 bool isUnsigned() const {
166 return ID == UByteTyID || ID == UShortTyID ||
167 ID == UIntTyID || ID == ULongTyID;
170 /// isInteger - Equivalent to isSigned() || isUnsigned()
172 bool isInteger() const { return ID >= UByteTyID && ID <= LongTyID; }
174 /// isIntegral - Returns true if this is an integral type, which is either
175 /// BoolTy or one of the Integer types.
177 bool isIntegral() const { return isInteger() || this == BoolTy; }
179 /// isFloatingPoint - Return true if this is one of the two floating point
181 bool isFloatingPoint() const { return ID == FloatTyID || ID == DoubleTyID; }
183 /// isAbstract - True if the type is either an Opaque type, or is a derived
184 /// type that includes an opaque type somewhere in it.
186 inline bool isAbstract() const { return Abstract; }
188 /// isLosslesslyConvertibleTo - Return true if this type can be converted to
189 /// 'Ty' without any reinterpretation of bits. For example, uint to int.
191 bool isLosslesslyConvertibleTo(const Type *Ty) const;
194 /// Here are some useful little methods to query what type derived types are
195 /// Note that all other types can just compare to see if this == Type::xxxTy;
197 inline bool isPrimitiveType() const { return ID <= LastPrimitiveTyID; }
198 inline bool isDerivedType() const { return ID >= FirstDerivedTyID; }
200 /// isFirstClassType - Return true if the value is holdable in a register.
202 inline bool isFirstClassType() const {
203 return (ID != VoidTyID && ID <= LastPrimitiveTyID) ||
204 ID == PointerTyID || ID == PackedTyID;
207 /// isSized - Return true if it makes sense to take the size of this type. To
208 /// get the actual size for a particular target, it is reasonable to use the
209 /// TargetData subsystem to do this.
211 bool isSized() const {
212 // If it's a primitive, it is always sized.
213 if (ID >= BoolTyID && ID <= DoubleTyID || ID == PointerTyID)
215 // If it is not something that can have a size (e.g. a function or label),
216 // it doesn't have a size.
217 if (ID != StructTyID && ID != ArrayTyID && ID != PackedTyID)
219 // If it is something that can have a size and it's concrete, it definitely
220 // has a size, otherwise we have to try harder to decide.
221 return !isAbstract() || isSizedDerivedType();
224 /// getPrimitiveSize - Return the basic size of this type if it is a primitive
225 /// type. These are fixed by LLVM and are not target dependent. This will
226 /// return zero if the type does not have a size or is not a primitive type.
228 unsigned getPrimitiveSize() const;
229 unsigned getPrimitiveSizeInBits() const;
231 /// getUnsignedVersion - If this is an integer type, return the unsigned
232 /// variant of this type. For example int -> uint.
233 const Type *getUnsignedVersion() const;
235 /// getSignedVersion - If this is an integer type, return the signed variant
236 /// of this type. For example uint -> int.
237 const Type *getSignedVersion() const;
239 /// getIntegralTypeMask - Return a bitmask with ones set for all of the bits
240 /// that can be set by an unsigned version of this type. This is 0xFF for
241 /// sbyte/ubyte, 0xFFFF for shorts, etc.
242 uint64_t getIntegralTypeMask() const {
243 assert(isIntegral() && "This only works for integral types!");
244 return ~uint64_t(0UL) >> (64-getPrimitiveSizeInBits());
247 /// getForwaredType - Return the type that this type has been resolved to if
248 /// it has been resolved to anything. This is used to implement the
249 /// union-find algorithm for type resolution, and shouldn't be used by general
251 const Type *getForwardedType() const {
252 if (!ForwardType) return 0;
253 return getForwardedTypeInternal();
256 /// getVAArgsPromotedType - Return the type an argument of this type
257 /// will be promoted to if passed through a variable argument
259 const Type *getVAArgsPromotedType() const {
260 if (ID == BoolTyID || ID == UByteTyID || ID == UShortTyID)
262 else if (ID == SByteTyID || ID == ShortTyID)
264 else if (ID == FloatTyID)
265 return Type::DoubleTy;
270 //===--------------------------------------------------------------------===//
271 // Type Iteration support
273 typedef std::vector<PATypeHandle>::const_iterator subtype_iterator;
274 subtype_iterator subtype_begin() const { return ContainedTys.begin(); }
275 subtype_iterator subtype_end() const { return ContainedTys.end(); }
277 /// getContainedType - This method is used to implement the type iterator
278 /// (defined a the end of the file). For derived types, this returns the
279 /// types 'contained' in the derived type.
281 const Type *getContainedType(unsigned i) const {
282 assert(i < ContainedTys.size() && "Index out of range!");
283 return ContainedTys[i];
286 /// getNumContainedTypes - Return the number of types in the derived type.
288 typedef std::vector<PATypeHandle>::size_type size_type;
289 size_type getNumContainedTypes() const { return ContainedTys.size(); }
291 //===--------------------------------------------------------------------===//
292 // Static members exported by the Type class itself. Useful for getting
293 // instances of Type.
296 /// getPrimitiveType - Return a type based on an identifier.
297 static const Type *getPrimitiveType(TypeID IDNumber);
299 //===--------------------------------------------------------------------===//
300 // These are the builtin types that are always available...
302 static Type *VoidTy , *BoolTy;
303 static Type *SByteTy, *UByteTy,
307 static Type *FloatTy, *DoubleTy;
309 static Type* LabelTy;
311 /// Methods for support type inquiry through isa, cast, and dyn_cast:
312 static inline bool classof(const Type *T) { return true; }
314 void addRef() const {
315 assert(isAbstract() && "Cannot add a reference to a non-abstract type!");
319 void dropRef() const {
320 assert(isAbstract() && "Cannot drop a reference to a non-abstract type!");
321 assert(RefCount && "No objects are currently referencing this object!");
323 // If this is the last PATypeHolder using this object, and there are no
324 // PATypeHandles using it, the type is dead, delete it now.
325 if (--RefCount == 0 && AbstractTypeUsers.empty())
329 /// addAbstractTypeUser - Notify an abstract type that there is a new user of
330 /// it. This function is called primarily by the PATypeHandle class.
332 void addAbstractTypeUser(AbstractTypeUser *U) const {
333 assert(isAbstract() && "addAbstractTypeUser: Current type not abstract!");
334 AbstractTypeUsers.push_back(U);
337 /// removeAbstractTypeUser - Notify an abstract type that a user of the class
338 /// no longer has a handle to the type. This function is called primarily by
339 /// the PATypeHandle class. When there are no users of the abstract type, it
340 /// is annihilated, because there is no way to get a reference to it ever
343 void removeAbstractTypeUser(AbstractTypeUser *U) const;
345 /// clearAllTypeMaps - This method frees all internal memory used by the
346 /// type subsystem, which can be used in environments where this memory is
347 /// otherwise reported as a leak.
348 static void clearAllTypeMaps();
351 /// isSizedDerivedType - Derived types like structures and arrays are sized
352 /// iff all of the members of the type are sized as well. Since asking for
353 /// their size is relatively uncommon, move this operation out of line.
354 bool isSizedDerivedType() const;
356 virtual void refineAbstractType(const DerivedType *OldTy, const Type *NewTy);
357 virtual void typeBecameConcrete(const DerivedType *AbsTy);
360 // PromoteAbstractToConcrete - This is an internal method used to calculate
361 // change "Abstract" from true to false when types are refined.
362 void PromoteAbstractToConcrete();
363 friend class TypeMapBase;
366 //===----------------------------------------------------------------------===//
367 // Define some inline methods for the AbstractTypeUser.h:PATypeHandle class.
368 // These are defined here because they MUST be inlined, yet are dependent on
369 // the definition of the Type class. Of course Type derives from Value, which
370 // contains an AbstractTypeUser instance, so there is no good way to factor out
371 // the code. Hence this bit of uglyness.
373 // In the long term, Type should not derive from Value, allowing
374 // AbstractTypeUser.h to #include Type.h, allowing us to eliminate this
375 // nastyness entirely.
377 inline void PATypeHandle::addUser() {
378 assert(Ty && "Type Handle has a null type!");
379 if (Ty->isAbstract())
380 Ty->addAbstractTypeUser(User);
382 inline void PATypeHandle::removeUser() {
383 if (Ty->isAbstract())
384 Ty->removeAbstractTypeUser(User);
387 // Define inline methods for PATypeHolder...
389 inline void PATypeHolder::addRef() {
390 if (Ty->isAbstract())
394 inline void PATypeHolder::dropRef() {
395 if (Ty->isAbstract())
399 /// get - This implements the forwarding part of the union-find algorithm for
400 /// abstract types. Before every access to the Type*, we check to see if the
401 /// type we are pointing to is forwarding to a new type. If so, we drop our
402 /// reference to the type.
404 inline Type* PATypeHolder::get() const {
405 const Type *NewTy = Ty->getForwardedType();
406 if (!NewTy) return const_cast<Type*>(Ty);
407 return *const_cast<PATypeHolder*>(this) = NewTy;
412 //===----------------------------------------------------------------------===//
413 // Provide specializations of GraphTraits to be able to treat a type as a
414 // graph of sub types...
416 template <> struct GraphTraits<Type*> {
417 typedef Type NodeType;
418 typedef Type::subtype_iterator ChildIteratorType;
420 static inline NodeType *getEntryNode(Type *T) { return T; }
421 static inline ChildIteratorType child_begin(NodeType *N) {
422 return N->subtype_begin();
424 static inline ChildIteratorType child_end(NodeType *N) {
425 return N->subtype_end();
429 template <> struct GraphTraits<const Type*> {
430 typedef const Type NodeType;
431 typedef Type::subtype_iterator ChildIteratorType;
433 static inline NodeType *getEntryNode(const Type *T) { return T; }
434 static inline ChildIteratorType child_begin(NodeType *N) {
435 return N->subtype_begin();
437 static inline ChildIteratorType child_end(NodeType *N) {
438 return N->subtype_end();
442 template <> inline bool isa_impl<PointerType, Type>(const Type &Ty) {
443 return Ty.getTypeID() == Type::PointerTyID;
446 std::ostream &operator<<(std::ostream &OS, const Type &T);
448 } // End llvm namespace