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/Support/Streams.h"
18 #include "llvm/ADT/GraphTraits.h"
19 #include "llvm/ADT/iterator"
34 /// This file contains the declaration of the Type class. For more "Type" type
35 /// stuff, look in DerivedTypes.h.
37 /// The instances of the Type class are immutable: once they are created,
38 /// they are never changed. Also note that only one instance of a particular
39 /// type is ever created. Thus seeing if two types are equal is a matter of
40 /// doing a trivial pointer comparison. To enforce that no two equal instances
41 /// are created, Type instances can only be created via static factory methods
42 /// in class Type and in derived classes.
44 /// Once allocated, Types are never free'd, unless they are an abstract type
45 /// that is resolved to a more concrete type.
47 /// Types themself don't have a name, and can be named either by:
48 /// - using SymbolTable instance, typically from some Module,
49 /// - using convenience methods in the Module class (which uses module's
52 /// Opaque types are simple derived types with no state. There may be many
53 /// different Opaque type objects floating around, but two are only considered
54 /// identical if they are pointer equals of each other. This allows us to have
55 /// two opaque types that end up resolving to different concrete types later.
57 /// Opaque types are also kinda weird and scary and different because they have
58 /// to keep a list of uses of the type. When, through linking, parsing, or
59 /// bytecode reading, they become resolved, they need to find and update all
60 /// users of the unknown type, causing them to reference a new, more concrete
61 /// type. Opaque types are deleted when their use list dwindles to zero users.
63 /// @brief Root of type hierarchy
64 class Type : public AbstractTypeUser {
66 ///===-------------------------------------------------------------------===//
67 /// Definitions of all of the base types for the Type system. Based on this
68 /// value, you can cast to a "DerivedType" subclass (see DerivedTypes.h)
69 /// Note: If you add an element to this, you need to add an element to the
70 /// Type::getPrimitiveType function, or else things will break!
73 // PrimitiveTypes .. make sure LastPrimitiveTyID stays up to date
74 VoidTyID = 0 , Int1TyID, // 0, 1: Basics...
75 Int8TyID, // 2 : 8 bit type...
76 Int16TyID, // 3 : 16 bit type...
77 Int32TyID, // 4 : 32 bit type...
78 Int64TyID, // 5 : 64 bit type...
79 FloatTyID, DoubleTyID, // 6, 7: Floating point types...
80 LabelTyID, // 8 : Labels...
82 // Derived types... see DerivedTypes.h file...
83 // Make sure FirstDerivedTyID stays up to date!!!
84 FunctionTyID , StructTyID, // Functions... Structs...
85 ArrayTyID , PointerTyID, // Array... pointer...
86 OpaqueTyID, // Opaque type instances...
87 PackedTyID, // SIMD 'packed' format...
88 BC_ONLY_PackedStructTyID, // packed struct, for BC rep only
91 NumTypeIDs, // Must remain as last defined ID
92 LastPrimitiveTyID = LabelTyID,
93 FirstDerivedTyID = FunctionTyID
97 TypeID ID : 8; // The current base type of this type.
98 bool Abstract : 1; // True if type contains an OpaqueType
99 bool SubclassData : 1; //Space for subclasses to store a flag
101 /// RefCount - This counts the number of PATypeHolders that are pointing to
102 /// this type. When this number falls to zero, if the type is abstract and
103 /// has no AbstractTypeUsers, the type is deleted. This is only sensical for
106 mutable unsigned RefCount;
108 const Type *getForwardedTypeInternal() const;
110 Type(const char *Name, TypeID id);
111 Type(TypeID id) : ID(id), Abstract(false), RefCount(0), ForwardType(0) {}
113 assert(AbstractTypeUsers.empty());
116 /// Types can become nonabstract later, if they are refined.
118 inline void setAbstract(bool Val) { Abstract = Val; }
120 unsigned getRefCount() const { return RefCount; }
122 bool getSubclassData() const { return SubclassData; }
123 void setSubclassData(bool b) { SubclassData = b; }
125 /// ForwardType - This field is used to implement the union find scheme for
126 /// abstract types. When types are refined to other types, this field is set
127 /// to the more refined type. Only abstract types can be forwarded.
128 mutable const Type *ForwardType;
130 /// ContainedTys - The list of types contained by this one. For example, this
131 /// includes the arguments of a function type, the elements of the structure,
132 /// the pointee of a pointer, etc. Note that keeping this vector in the Type
133 /// class wastes some space for types that do not contain anything (such as
134 /// primitive types). However, keeping it here allows the subtype_* members
135 /// to be implemented MUCH more efficiently, and dynamically very few types do
136 /// not contain any elements (most are derived).
137 std::vector<PATypeHandle> ContainedTys;
139 /// AbstractTypeUsers - Implement a list of the users that need to be notified
140 /// if I am a type, and I get resolved into a more concrete type.
142 mutable std::vector<AbstractTypeUser *> AbstractTypeUsers;
144 void print(std::ostream &O) const;
145 void print(std::ostream *O) const { if (O) print(*O); }
147 /// @brief Debugging support: print to stderr
150 //===--------------------------------------------------------------------===//
151 // Property accessors for dealing with types... Some of these virtual methods
152 // are defined in private classes defined in Type.cpp for primitive types.
155 /// getTypeID - Return the type id for the type. This will return one
156 /// of the TypeID enum elements defined above.
158 inline TypeID getTypeID() const { return ID; }
160 /// getDescription - Return the string representation of the type...
161 const std::string &getDescription() const;
163 /// isInteger - Equivalent to isSigned() || isUnsigned()
165 bool isInteger() const { return ID >= Int8TyID && ID <= Int64TyID; }
167 /// isIntegral - Returns true if this is an integral type, which is either
168 /// Int1Ty or one of the Integer types.
170 bool isIntegral() const { return isInteger() || this == Int1Ty; }
172 /// isFloatingPoint - Return true if this is one of the two floating point
174 bool isFloatingPoint() const { return ID == FloatTyID || ID == DoubleTyID; }
176 /// isFPOrFPVector - Return true if this is a FP type or a vector of FP types.
178 bool isFPOrFPVector() const;
180 /// isAbstract - True if the type is either an Opaque type, or is a derived
181 /// type that includes an opaque type somewhere in it.
183 inline bool isAbstract() const { return Abstract; }
185 /// canLosslesslyBitCastTo - Return true if this type could be converted
186 /// with a lossless BitCast to type 'Ty'. For example, uint to int. BitCasts
187 /// are valid for types of the same size only where no re-interpretation of
188 /// the bits is done.
189 /// @brief Determine if this type could be losslessly bitcast to Ty
190 bool canLosslesslyBitCastTo(const Type *Ty) const;
193 /// Here are some useful little methods to query what type derived types are
194 /// Note that all other types can just compare to see if this == Type::xxxTy;
196 inline bool isPrimitiveType() const { return ID <= LastPrimitiveTyID; }
197 inline bool isDerivedType() const { return ID >= FirstDerivedTyID; }
199 /// isFirstClassType - Return true if the value is holdable in a register.
201 inline bool isFirstClassType() const {
202 return (ID != VoidTyID && ID <= LastPrimitiveTyID) ||
203 ID == PointerTyID || ID == PackedTyID;
206 /// isSized - Return true if it makes sense to take the size of this type. To
207 /// get the actual size for a particular target, it is reasonable to use the
208 /// TargetData subsystem to do this.
210 bool isSized() const {
211 // If it's a primitive, it is always sized.
212 if (ID >= Int1TyID && ID <= DoubleTyID || ID == PointerTyID)
214 // If it is not something that can have a size (e.g. a function or label),
215 // it doesn't have a size.
216 if (ID != StructTyID && ID != ArrayTyID && ID != PackedTyID)
218 // If it is something that can have a size and it's concrete, it definitely
219 // has a size, otherwise we have to try harder to decide.
220 return !isAbstract() || isSizedDerivedType();
223 /// getPrimitiveSize - Return the basic size of this type if it is a primitive
224 /// type. These are fixed by LLVM and are not target dependent. This will
225 /// return zero if the type does not have a size or is not a primitive type.
227 unsigned getPrimitiveSize() const;
228 unsigned getPrimitiveSizeInBits() const;
230 /// getIntegralTypeMask - Return a bitmask with ones set for all of the bits
231 /// that can be set by an unsigned version of this type. This is 0xFF for
232 /// sbyte/ubyte, 0xFFFF for shorts, etc.
233 uint64_t getIntegralTypeMask() const {
234 assert(isIntegral() && "This only works for integral types!");
235 return ~uint64_t(0UL) >> (64-getPrimitiveSizeInBits());
238 /// getForwaredType - Return the type that this type has been resolved to if
239 /// it has been resolved to anything. This is used to implement the
240 /// union-find algorithm for type resolution, and shouldn't be used by general
242 const Type *getForwardedType() const {
243 if (!ForwardType) return 0;
244 return getForwardedTypeInternal();
247 /// getVAArgsPromotedType - Return the type an argument of this type
248 /// will be promoted to if passed through a variable argument
250 const Type *getVAArgsPromotedType() const {
251 if (ID == Int1TyID || ID == Int8TyID || ID == Int16TyID)
252 return Type::Int32Ty;
253 else if (ID == FloatTyID)
254 return Type::DoubleTy;
259 //===--------------------------------------------------------------------===//
260 // Type Iteration support
262 typedef std::vector<PATypeHandle>::const_iterator subtype_iterator;
263 subtype_iterator subtype_begin() const { return ContainedTys.begin(); }
264 subtype_iterator subtype_end() const { return ContainedTys.end(); }
266 /// getContainedType - This method is used to implement the type iterator
267 /// (defined a the end of the file). For derived types, this returns the
268 /// types 'contained' in the derived type.
270 const Type *getContainedType(unsigned i) const {
271 assert(i < ContainedTys.size() && "Index out of range!");
272 return ContainedTys[i];
275 /// getNumContainedTypes - Return the number of types in the derived type.
277 typedef std::vector<PATypeHandle>::size_type size_type;
278 size_type getNumContainedTypes() const { return ContainedTys.size(); }
280 //===--------------------------------------------------------------------===//
281 // Static members exported by the Type class itself. Useful for getting
282 // instances of Type.
285 /// getPrimitiveType - Return a type based on an identifier.
286 static const Type *getPrimitiveType(TypeID IDNumber);
288 //===--------------------------------------------------------------------===//
289 // These are the builtin types that are always available...
291 static Type *VoidTy , *Int1Ty;
292 static Type *Int8Ty , *Int16Ty,
294 static Type *FloatTy, *DoubleTy;
296 static Type* LabelTy;
298 /// Methods for support type inquiry through isa, cast, and dyn_cast:
299 static inline bool classof(const Type *T) { return true; }
301 void addRef() const {
302 assert(isAbstract() && "Cannot add a reference to a non-abstract type!");
306 void dropRef() const {
307 assert(isAbstract() && "Cannot drop a reference to a non-abstract type!");
308 assert(RefCount && "No objects are currently referencing this object!");
310 // If this is the last PATypeHolder using this object, and there are no
311 // PATypeHandles using it, the type is dead, delete it now.
312 if (--RefCount == 0 && AbstractTypeUsers.empty())
316 /// addAbstractTypeUser - Notify an abstract type that there is a new user of
317 /// it. This function is called primarily by the PATypeHandle class.
319 void addAbstractTypeUser(AbstractTypeUser *U) const {
320 assert(isAbstract() && "addAbstractTypeUser: Current type not abstract!");
321 AbstractTypeUsers.push_back(U);
324 /// removeAbstractTypeUser - Notify an abstract type that a user of the class
325 /// no longer has a handle to the type. This function is called primarily by
326 /// the PATypeHandle class. When there are no users of the abstract type, it
327 /// is annihilated, because there is no way to get a reference to it ever
330 void removeAbstractTypeUser(AbstractTypeUser *U) const;
333 /// isSizedDerivedType - Derived types like structures and arrays are sized
334 /// iff all of the members of the type are sized as well. Since asking for
335 /// their size is relatively uncommon, move this operation out of line.
336 bool isSizedDerivedType() const;
338 virtual void refineAbstractType(const DerivedType *OldTy, const Type *NewTy);
339 virtual void typeBecameConcrete(const DerivedType *AbsTy);
342 // PromoteAbstractToConcrete - This is an internal method used to calculate
343 // change "Abstract" from true to false when types are refined.
344 void PromoteAbstractToConcrete();
345 friend class TypeMapBase;
348 //===----------------------------------------------------------------------===//
349 // Define some inline methods for the AbstractTypeUser.h:PATypeHandle class.
350 // These are defined here because they MUST be inlined, yet are dependent on
351 // the definition of the Type class.
353 inline void PATypeHandle::addUser() {
354 assert(Ty && "Type Handle has a null type!");
355 if (Ty->isAbstract())
356 Ty->addAbstractTypeUser(User);
358 inline void PATypeHandle::removeUser() {
359 if (Ty->isAbstract())
360 Ty->removeAbstractTypeUser(User);
363 // Define inline methods for PATypeHolder...
365 inline void PATypeHolder::addRef() {
366 if (Ty->isAbstract())
370 inline void PATypeHolder::dropRef() {
371 if (Ty->isAbstract())
376 //===----------------------------------------------------------------------===//
377 // Provide specializations of GraphTraits to be able to treat a type as a
378 // graph of sub types...
380 template <> struct GraphTraits<Type*> {
381 typedef Type NodeType;
382 typedef Type::subtype_iterator ChildIteratorType;
384 static inline NodeType *getEntryNode(Type *T) { return T; }
385 static inline ChildIteratorType child_begin(NodeType *N) {
386 return N->subtype_begin();
388 static inline ChildIteratorType child_end(NodeType *N) {
389 return N->subtype_end();
393 template <> struct GraphTraits<const Type*> {
394 typedef const Type NodeType;
395 typedef Type::subtype_iterator ChildIteratorType;
397 static inline NodeType *getEntryNode(const Type *T) { return T; }
398 static inline ChildIteratorType child_begin(NodeType *N) {
399 return N->subtype_begin();
401 static inline ChildIteratorType child_end(NodeType *N) {
402 return N->subtype_end();
406 template <> inline bool isa_impl<PointerType, Type>(const Type &Ty) {
407 return Ty.getTypeID() == Type::PointerTyID;
410 std::ostream &operator<<(std::ostream &OS, const Type &T);
412 } // End llvm namespace