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"
29 /// This file contains the declaration of the Type class. For more "Type" type
30 /// stuff, look in DerivedTypes.h.
32 /// The instances of the Type class are immutable: once they are created,
33 /// they are never changed. Also note that only one instance of a particular
34 /// type is ever created. Thus seeing if two types are equal is a matter of
35 /// doing a trivial pointer comparison. To enforce that no two equal instances
36 /// are created, Type instances can only be created via static factory methods
37 /// in class Type and in derived classes.
39 /// Once allocated, Types are never free'd, unless they are an abstract type
40 /// that is resolved to a more concrete type.
42 /// Types themself don't have a name, and can be named either by:
43 /// - using SymbolTable instance, typically from some Module,
44 /// - using convenience methods in the Module class (which uses module's
47 /// Opaque types are simple derived types with no state. There may be many
48 /// different Opaque type objects floating around, but two are only considered
49 /// identical if they are pointer equals of each other. This allows us to have
50 /// two opaque types that end up resolving to different concrete types later.
52 /// Opaque types are also kinda weird and scary and different because they have
53 /// to keep a list of uses of the type. When, through linking, parsing, or
54 /// bytecode reading, they become resolved, they need to find and update all
55 /// users of the unknown type, causing them to reference a new, more concrete
56 /// type. Opaque types are deleted when their use list dwindles to zero users.
58 /// @brief Root of type hierarchy
59 class Type : public AbstractTypeUser {
61 ///===-------------------------------------------------------------------===//
62 /// Definitions of all of the base types for the Type system. Based on this
63 /// value, you can cast to a "DerivedType" subclass (see DerivedTypes.h)
64 /// Note: If you add an element to this, you need to add an element to the
65 /// Type::getPrimitiveType function, or else things will break!
68 // PrimitiveTypes .. make sure LastPrimitiveTyID stays up to date
69 VoidTyID = 0, ///< 0: type with no size
70 FloatTyID, ///< 1: 32 bit floating point type
71 DoubleTyID, ///< 2: 64 bit floating point type
72 LabelTyID, ///< 3: Labels
74 // Derived types... see DerivedTypes.h file...
75 // Make sure FirstDerivedTyID stays up to date!!!
76 IntegerTyID, ///< 4: Arbitrary bit width integers
77 FunctionTyID, ///< 5: Functions
78 StructTyID, ///< 6: Structures
79 PackedStructTyID,///< 7: Packed Structure. This is for bytecode only
80 ArrayTyID, ///< 8: Arrays
81 PointerTyID, ///< 9: Pointers
82 OpaqueTyID, ///< 10: Opaque: type with unknown structure
83 PackedTyID, ///< 11: SIMD 'packed' format, or other vector type
85 NumTypeIDs, // Must remain as last defined ID
86 LastPrimitiveTyID = LabelTyID,
87 FirstDerivedTyID = IntegerTyID
91 TypeID ID : 8; // The current base type of this type.
92 bool Abstract : 1; // True if type contains an OpaqueType
93 unsigned SubclassData : 23; //Space for subclasses to store data
95 /// RefCount - This counts the number of PATypeHolders that are pointing to
96 /// this type. When this number falls to zero, if the type is abstract and
97 /// has no AbstractTypeUsers, the type is deleted. This is only sensical for
100 mutable unsigned RefCount;
102 const Type *getForwardedTypeInternal() const;
104 Type(const char *Name, TypeID id);
105 Type(TypeID id) : ID(id), Abstract(false), SubclassData(0), RefCount(0),
108 assert(AbstractTypeUsers.empty());
111 /// Types can become nonabstract later, if they are refined.
113 inline void setAbstract(bool Val) { Abstract = Val; }
115 unsigned getRefCount() const { return RefCount; }
117 unsigned getSubclassData() const { return SubclassData; }
118 void setSubclassData(unsigned val) { SubclassData = val; }
120 /// ForwardType - This field is used to implement the union find scheme for
121 /// abstract types. When types are refined to other types, this field is set
122 /// to the more refined type. Only abstract types can be forwarded.
123 mutable const Type *ForwardType;
125 /// ContainedTys - The list of types contained by this one. For example, this
126 /// includes the arguments of a function type, the elements of the structure,
127 /// the pointee of a pointer, etc. Note that keeping this vector in the Type
128 /// class wastes some space for types that do not contain anything (such as
129 /// primitive types). However, keeping it here allows the subtype_* members
130 /// to be implemented MUCH more efficiently, and dynamically very few types do
131 /// not contain any elements (most are derived).
132 std::vector<PATypeHandle> ContainedTys;
134 /// AbstractTypeUsers - Implement a list of the users that need to be notified
135 /// if I am a type, and I get resolved into a more concrete type.
137 mutable std::vector<AbstractTypeUser *> AbstractTypeUsers;
139 void print(std::ostream &O) const;
140 void print(std::ostream *O) const { if (O) print(*O); }
142 /// @brief Debugging support: print to stderr
145 //===--------------------------------------------------------------------===//
146 // Property accessors for dealing with types... Some of these virtual methods
147 // are defined in private classes defined in Type.cpp for primitive types.
150 /// getTypeID - Return the type id for the type. This will return one
151 /// of the TypeID enum elements defined above.
153 inline TypeID getTypeID() const { return ID; }
155 /// getDescription - Return the string representation of the type...
156 const std::string &getDescription() const;
158 /// isInteger - True if this is an instance of IntegerType.
160 bool isInteger() const { return ID == IntegerTyID; }
162 /// isFloatingPoint - Return true if this is one of the two floating point
164 bool isFloatingPoint() const { return ID == FloatTyID || ID == DoubleTyID; }
166 /// isFPOrFPVector - Return true if this is a FP type or a vector of FP types.
168 bool isFPOrFPVector() const;
170 /// isAbstract - True if the type is either an Opaque type, or is a derived
171 /// type that includes an opaque type somewhere in it.
173 inline bool isAbstract() const { return Abstract; }
175 /// canLosslesslyBitCastTo - Return true if this type could be converted
176 /// with a lossless BitCast to type 'Ty'. For example, uint to int. BitCasts
177 /// are valid for types of the same size only where no re-interpretation of
178 /// the bits is done.
179 /// @brief Determine if this type could be losslessly bitcast to Ty
180 bool canLosslesslyBitCastTo(const Type *Ty) const;
183 /// Here are some useful little methods to query what type derived types are
184 /// Note that all other types can just compare to see if this == Type::xxxTy;
186 inline bool isPrimitiveType() const { return ID <= LastPrimitiveTyID; }
187 inline bool isDerivedType() const { return ID >= FirstDerivedTyID; }
189 /// isFirstClassType - Return true if the value is holdable in a register.
191 inline bool isFirstClassType() const {
192 return (ID != VoidTyID && ID <= LastPrimitiveTyID) ||
193 ID == IntegerTyID || ID == PointerTyID || ID == PackedTyID;
196 /// isSized - Return true if it makes sense to take the size of this type. To
197 /// get the actual size for a particular target, it is reasonable to use the
198 /// TargetData subsystem to do this.
200 bool isSized() const {
201 // If it's a primitive, it is always sized.
202 if (ID == IntegerTyID || isFloatingPoint() || ID == PointerTyID)
204 // If it is not something that can have a size (e.g. a function or label),
205 // it doesn't have a size.
206 if (ID != StructTyID && ID != ArrayTyID && ID != PackedTyID &&
207 ID != PackedStructTyID)
209 // If it is something that can have a size and it's concrete, it definitely
210 // has a size, otherwise we have to try harder to decide.
211 return !isAbstract() || isSizedDerivedType();
214 /// getPrimitiveSize - Return the basic size of this type if it is a primitive
215 /// type. These are fixed by LLVM and are not target dependent. This will
216 /// return zero if the type does not have a size or is not a primitive type.
218 unsigned getPrimitiveSizeInBits() const;
220 /// getIntegerTypeMask - Return a bitmask with ones set for all of the bits
221 /// that can be set by an unsigned version of this type. This is 0xFF for
222 /// sbyte/ubyte, 0xFFFF for shorts, etc.
223 uint64_t getIntegerTypeMask() const {
224 assert(isInteger() && "This only works for integer types!");
225 return ~uint64_t(0UL) >> (64-getPrimitiveSizeInBits());
228 /// getForwaredType - Return the type that this type has been resolved to if
229 /// it has been resolved to anything. This is used to implement the
230 /// union-find algorithm for type resolution, and shouldn't be used by general
232 const Type *getForwardedType() const {
233 if (!ForwardType) return 0;
234 return getForwardedTypeInternal();
237 /// getVAArgsPromotedType - Return the type an argument of this type
238 /// will be promoted to if passed through a variable argument
240 const Type *getVAArgsPromotedType() const {
241 if (ID == IntegerTyID && getSubclassData() < 32)
242 return Type::Int32Ty;
243 else if (ID == FloatTyID)
244 return Type::DoubleTy;
249 //===--------------------------------------------------------------------===//
250 // Type Iteration support
252 typedef std::vector<PATypeHandle>::const_iterator subtype_iterator;
253 subtype_iterator subtype_begin() const { return ContainedTys.begin(); }
254 subtype_iterator subtype_end() const { return ContainedTys.end(); }
256 /// getContainedType - This method is used to implement the type iterator
257 /// (defined a the end of the file). For derived types, this returns the
258 /// types 'contained' in the derived type.
260 const Type *getContainedType(unsigned i) const {
261 assert(i < ContainedTys.size() && "Index out of range!");
262 return ContainedTys[i];
265 /// getNumContainedTypes - Return the number of types in the derived type.
267 typedef std::vector<PATypeHandle>::size_type size_type;
268 size_type getNumContainedTypes() const { return ContainedTys.size(); }
270 //===--------------------------------------------------------------------===//
271 // Static members exported by the Type class itself. Useful for getting
272 // instances of Type.
275 /// getPrimitiveType - Return a type based on an identifier.
276 static const Type *getPrimitiveType(TypeID IDNumber);
278 //===--------------------------------------------------------------------===//
279 // These are the builtin types that are always available...
281 static const Type *VoidTy, *LabelTy, *FloatTy, *DoubleTy;
282 static const Type *Int1Ty, *Int8Ty, *Int16Ty, *Int32Ty, *Int64Ty;
284 /// Methods for support type inquiry through isa, cast, and dyn_cast:
285 static inline bool classof(const Type *T) { return true; }
287 void addRef() const {
288 assert(isAbstract() && "Cannot add a reference to a non-abstract type!");
292 void dropRef() const {
293 assert(isAbstract() && "Cannot drop a reference to a non-abstract type!");
294 assert(RefCount && "No objects are currently referencing this object!");
296 // If this is the last PATypeHolder using this object, and there are no
297 // PATypeHandles using it, the type is dead, delete it now.
298 if (--RefCount == 0 && AbstractTypeUsers.empty())
302 /// addAbstractTypeUser - Notify an abstract type that there is a new user of
303 /// it. This function is called primarily by the PATypeHandle class.
305 void addAbstractTypeUser(AbstractTypeUser *U) const {
306 assert(isAbstract() && "addAbstractTypeUser: Current type not abstract!");
307 AbstractTypeUsers.push_back(U);
310 /// removeAbstractTypeUser - Notify an abstract type that a user of the class
311 /// no longer has a handle to the type. This function is called primarily by
312 /// the PATypeHandle class. When there are no users of the abstract type, it
313 /// is annihilated, because there is no way to get a reference to it ever
316 void removeAbstractTypeUser(AbstractTypeUser *U) const;
319 /// isSizedDerivedType - Derived types like structures and arrays are sized
320 /// iff all of the members of the type are sized as well. Since asking for
321 /// their size is relatively uncommon, move this operation out of line.
322 bool isSizedDerivedType() const;
324 virtual void refineAbstractType(const DerivedType *OldTy, const Type *NewTy);
325 virtual void typeBecameConcrete(const DerivedType *AbsTy);
328 // PromoteAbstractToConcrete - This is an internal method used to calculate
329 // change "Abstract" from true to false when types are refined.
330 void PromoteAbstractToConcrete();
331 friend class TypeMapBase;
334 //===----------------------------------------------------------------------===//
335 // Define some inline methods for the AbstractTypeUser.h:PATypeHandle class.
336 // These are defined here because they MUST be inlined, yet are dependent on
337 // the definition of the Type class.
339 inline void PATypeHandle::addUser() {
340 assert(Ty && "Type Handle has a null type!");
341 if (Ty->isAbstract())
342 Ty->addAbstractTypeUser(User);
344 inline void PATypeHandle::removeUser() {
345 if (Ty->isAbstract())
346 Ty->removeAbstractTypeUser(User);
349 // Define inline methods for PATypeHolder...
351 inline void PATypeHolder::addRef() {
352 if (Ty->isAbstract())
356 inline void PATypeHolder::dropRef() {
357 if (Ty->isAbstract())
362 //===----------------------------------------------------------------------===//
363 // Provide specializations of GraphTraits to be able to treat a type as a
364 // graph of sub types...
366 template <> struct GraphTraits<Type*> {
367 typedef Type NodeType;
368 typedef Type::subtype_iterator ChildIteratorType;
370 static inline NodeType *getEntryNode(Type *T) { return T; }
371 static inline ChildIteratorType child_begin(NodeType *N) {
372 return N->subtype_begin();
374 static inline ChildIteratorType child_end(NodeType *N) {
375 return N->subtype_end();
379 template <> struct GraphTraits<const Type*> {
380 typedef const Type NodeType;
381 typedef Type::subtype_iterator ChildIteratorType;
383 static inline NodeType *getEntryNode(const Type *T) { return T; }
384 static inline ChildIteratorType child_begin(NodeType *N) {
385 return N->subtype_begin();
387 static inline ChildIteratorType child_end(NodeType *N) {
388 return N->subtype_end();
392 template <> inline bool isa_impl<PointerType, Type>(const Type &Ty) {
393 return Ty.getTypeID() == Type::PointerTyID;
396 std::ostream &operator<<(std::ostream &OS, const Type &T);
398 } // End llvm namespace