Type.h revision e1d6799661f9b7fe7f5729005f9ff4afb9df9592
1//===-- llvm/Type.h - Classes for handling data types -----------*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
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.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file contains the declaration of the Type class.  For more "Type" type
11// stuff, look in DerivedTypes.h.
12//
13// Note that instances of the Type class are immutable: once they are created,
14// they are never changed.  Also note that only one instance of a particular
15// type is ever created.  Thus seeing if two types are equal is a matter of
16// doing a trivial pointer comparison.
17//
18// Types, once allocated, are never free'd, unless they are an abstract type
19// that is resolved to a more concrete type.
20//
21// Opaque types are simple derived types with no state.  There may be many
22// different Opaque type objects floating around, but two are only considered
23// identical if they are pointer equals of each other.  This allows us to have
24// two opaque types that end up resolving to different concrete types later.
25//
26// Opaque types are also kinda wierd and scary and different because they have
27// to keep a list of uses of the type.  When, through linking, parsing, or
28// bytecode reading, they become resolved, they need to find and update all
29// users of the unknown type, causing them to reference a new, more concrete
30// type.  Opaque types are deleted when their use list dwindles to zero users.
31//
32//===----------------------------------------------------------------------===//
33
34#ifndef LLVM_TYPE_H
35#define LLVM_TYPE_H
36
37#include "AbstractTypeUser.h"
38#include "Support/Casting.h"
39#include "Support/GraphTraits.h"
40#include "Support/iterator"
41#include <vector>
42
43namespace llvm {
44
45class ArrayType;
46class DerivedType;
47class FunctionType;
48class OpaqueType;
49class PointerType;
50class StructType;
51class SymbolTable;
52
53struct Type {
54  ///===-------------------------------------------------------------------===//
55  /// Definitions of all of the base types for the Type system.  Based on this
56  /// value, you can cast to a "DerivedType" subclass (see DerivedTypes.h)
57  /// Note: If you add an element to this, you need to add an element to the
58  /// Type::getPrimitiveType function, or else things will break!
59  ///
60  enum TypeID {
61    // PrimitiveTypes .. make sure LastPrimitiveTyID stays up to date
62    VoidTyID = 0  , BoolTyID,           //  0, 1: Basics...
63    UByteTyID     , SByteTyID,          //  2, 3: 8 bit types...
64    UShortTyID    , ShortTyID,          //  4, 5: 16 bit types...
65    UIntTyID      , IntTyID,            //  6, 7: 32 bit types...
66    ULongTyID     , LongTyID,           //  8, 9: 64 bit types...
67    FloatTyID     , DoubleTyID,         // 10,11: Floating point types...
68    LabelTyID     ,                     // 12   : Labels...
69
70    // Derived types... see DerivedTypes.h file...
71    // Make sure FirstDerivedTyID stays up to date!!!
72    FunctionTyID  , StructTyID,         // Functions... Structs...
73    ArrayTyID     , PointerTyID,        // Array... pointer...
74    OpaqueTyID,                         // Opaque type instances...
75    //PackedTyID  ,                     // SIMD 'packed' format... TODO
76    //...
77
78    NumTypeIDs,                         // Must remain as last defined ID
79    LastPrimitiveTyID = LabelTyID,
80    FirstDerivedTyID = FunctionTyID,
81  };
82
83private:
84  TypeID   ID : 8;    // The current base type of this type.
85  bool     Abstract;  // True if type contains an OpaqueType
86  unsigned UID;       // The unique ID number for this class
87
88  /// RefCount - This counts the number of PATypeHolders that are pointing to
89  /// this type.  When this number falls to zero, if the type is abstract and
90  /// has no AbstractTypeUsers, the type is deleted.  This is only sensical for
91  /// derived types.
92  ///
93  mutable unsigned RefCount;
94
95  const Type *getForwardedTypeInternal() const;
96protected:
97  Type(const std::string& Name, TypeID id);
98  virtual ~Type() {}
99
100
101  /// Types can become nonabstract later, if they are refined.
102  ///
103  inline void setAbstract(bool Val) { Abstract = Val; }
104
105  /// isTypeAbstract - This method is used to calculate the Abstract bit.
106  ///
107  bool isTypeAbstract();
108
109  unsigned getRefCount() const { return RefCount; }
110
111  /// ForwardType - This field is used to implement the union find scheme for
112  /// abstract types.  When types are refined to other types, this field is set
113  /// to the more refined type.  Only abstract types can be forwarded.
114  mutable const Type *ForwardType;
115
116  /// ContainedTys - The list of types contained by this one.  For example, this
117  /// includes the arguments of a function type, the elements of the structure,
118  /// the pointee of a pointer, etc.  Note that keeping this vector in the Type
119  /// class wastes some space for types that do not contain anything (such as
120  /// primitive types).  However, keeping it here allows the subtype_* members
121  /// to be implemented MUCH more efficiently, and dynamically very few types do
122  /// not contain any elements (most are derived).
123  std::vector<PATypeHandle> ContainedTys;
124
125public:
126  virtual void print(std::ostream &O) const;
127
128  /// @brief Debugging support: print to stderr
129  virtual void dump() const;
130
131  /// setName - Associate the name with this type in the symbol table, but don't
132  /// set the local name to be equal specified name.
133  ///
134  virtual void setName(const std::string &Name, SymbolTable *ST = 0);
135
136  //===--------------------------------------------------------------------===//
137  // Property accessors for dealing with types... Some of these virtual methods
138  // are defined in private classes defined in Type.cpp for primitive types.
139  //
140
141  /// getTypeID - Return the type id for the type.  This will return one
142  /// of the TypeID enum elements defined above.
143  ///
144  inline TypeID getTypeID() const { return ID; }
145
146  /// getUniqueID - Returns the UID of the type.  This can be thought of as a
147  /// small integer version of the pointer to the type class.  Two types that
148  /// are structurally different have different UIDs.  This can be used for
149  /// indexing types into an array.
150  ///
151  inline unsigned getUniqueID() const { return UID; }
152
153  /// getDescription - Return the string representation of the type...
154  const std::string &getDescription() const;
155
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.
159  ///
160  bool isSigned() const {
161    return ID == SByteTyID || ID == ShortTyID ||
162           ID == IntTyID || ID == LongTyID;
163  }
164
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
168  /// ULongTy
169  ///
170  bool isUnsigned() const {
171    return ID == UByteTyID || ID == UShortTyID ||
172           ID == UIntTyID || ID == ULongTyID;
173  }
174
175  /// isInteger - Equilivant to isSigned() || isUnsigned()
176  ///
177  bool isInteger() const { return ID >= UByteTyID && ID <= LongTyID; }
178
179  /// isIntegral - Returns true if this is an integral type, which is either
180  /// BoolTy or one of the Integer types.
181  ///
182  bool isIntegral() const { return isInteger() || this == BoolTy; }
183
184  /// isFloatingPoint - Return true if this is one of the two floating point
185  /// types
186  bool isFloatingPoint() const { return ID == FloatTyID || ID == DoubleTyID; }
187
188  /// isAbstract - True if the type is either an Opaque type, or is a derived
189  /// type that includes an opaque type somewhere in it.
190  ///
191  inline bool isAbstract() const { return Abstract; }
192
193  /// isLosslesslyConvertibleTo - Return true if this type can be converted to
194  /// 'Ty' without any reinterpretation of bits.  For example, uint to int.
195  ///
196  bool isLosslesslyConvertibleTo(const Type *Ty) const;
197
198
199  /// Here are some useful little methods to query what type derived types are
200  /// Note that all other types can just compare to see if this == Type::xxxTy;
201  ///
202  inline bool isPrimitiveType() const { return ID <= LastPrimitiveTyID; }
203  inline bool isDerivedType()   const { return ID >= FirstDerivedTyID; }
204
205  /// isFirstClassType - Return true if the value is holdable in a register.
206  inline bool isFirstClassType() const {
207    return (ID != VoidTyID && ID <= LastPrimitiveTyID) || ID == PointerTyID;
208  }
209
210  /// isSized - Return true if it makes sense to take the size of this type.  To
211  /// get the actual size for a particular target, it is reasonable to use the
212  /// TargetData subsystem to do this.
213  ///
214  bool isSized() const {
215    return (ID >= BoolTyID && ID <= DoubleTyID) || ID == PointerTyID ||
216           isSizedDerivedType();
217  }
218
219  /// getPrimitiveSize - Return the basic size of this type if it is a primative
220  /// type.  These are fixed by LLVM and are not target dependent.  This will
221  /// return zero if the type does not have a size or is not a primitive type.
222  ///
223  unsigned getPrimitiveSize() const;
224
225  /// getUnsignedVersion - If this is an integer type, return the unsigned
226  /// variant of this type.  For example int -> uint.
227  const Type *getUnsignedVersion() const;
228
229  /// getSignedVersion - If this is an integer type, return the signed variant
230  /// of this type.  For example uint -> int.
231  const Type *getSignedVersion() const;
232
233  /// getForwaredType - Return the type that this type has been resolved to if
234  /// it has been resolved to anything.  This is used to implement the
235  /// union-find algorithm for type resolution, and shouldn't be used by general
236  /// purpose clients.
237  const Type *getForwardedType() const {
238    if (!ForwardType) return 0;
239    return getForwardedTypeInternal();
240  }
241
242  //===--------------------------------------------------------------------===//
243  // Type Iteration support
244  //
245  typedef std::vector<PATypeHandle>::const_iterator subtype_iterator;
246  subtype_iterator subtype_begin() const { return ContainedTys.begin(); }
247  subtype_iterator subtype_end() const { return ContainedTys.end(); }
248
249  /// getContainedType - This method is used to implement the type iterator
250  /// (defined a the end of the file).  For derived types, this returns the
251  /// types 'contained' in the derived type.
252  ///
253  const Type *getContainedType(unsigned i) const {
254    assert(i < ContainedTys.size() && "Index out of range!");
255    return ContainedTys[i];
256  }
257
258  /// getNumContainedTypes - Return the number of types in the derived type.
259  ///
260  unsigned getNumContainedTypes() const { return ContainedTys.size(); }
261
262  //===--------------------------------------------------------------------===//
263  // Static members exported by the Type class itself.  Useful for getting
264  // instances of Type.
265  //
266
267  /// getPrimitiveType/getUniqueIDType - Return a type based on an identifier.
268  static const Type *getPrimitiveType(TypeID IDNumber);
269  static const Type *getUniqueIDType(unsigned UID);
270
271  //===--------------------------------------------------------------------===//
272  // These are the builtin types that are always available...
273  //
274  static Type *VoidTy , *BoolTy;
275  static Type *SByteTy, *UByteTy,
276              *ShortTy, *UShortTy,
277              *IntTy  , *UIntTy,
278              *LongTy , *ULongTy;
279  static Type *FloatTy, *DoubleTy;
280
281  static Type* LabelTy;
282
283  /// Methods for support type inquiry through isa, cast, and dyn_cast:
284  static inline bool classof(const Type *T) { return true; }
285
286#include "llvm/Type.def"
287
288  // Virtual methods used by callbacks below.  These should only be implemented
289  // in the DerivedType class.
290  virtual void addAbstractTypeUser(AbstractTypeUser *U) const {
291    abort(); // Only on derived types!
292  }
293  virtual void removeAbstractTypeUser(AbstractTypeUser *U) const {
294    abort(); // Only on derived types!
295  }
296
297  void addRef() const {
298    assert(isAbstract() && "Cannot add a reference to a non-abstract type!");
299    ++RefCount;
300  }
301
302  void dropRef() const {
303    assert(isAbstract() && "Cannot drop a refernce to a non-abstract type!");
304    assert(RefCount && "No objects are currently referencing this object!");
305
306    // If this is the last PATypeHolder using this object, and there are no
307    // PATypeHandles using it, the type is dead, delete it now.
308    if (--RefCount == 0)
309      RefCountIsZero();
310  }
311private:
312  /// isSizedDerivedType - Derived types like structures and arrays are sized
313  /// iff all of the members of the type are sized as well.  Since asking for
314  /// their size is relatively uncommon, move this operation out of line.
315  bool isSizedDerivedType() const;
316
317  virtual void RefCountIsZero() const {
318    abort(); // only on derived types!
319  }
320
321};
322
323//===----------------------------------------------------------------------===//
324// Define some inline methods for the AbstractTypeUser.h:PATypeHandle class.
325// These are defined here because they MUST be inlined, yet are dependent on
326// the definition of the Type class.  Of course Type derives from Value, which
327// contains an AbstractTypeUser instance, so there is no good way to factor out
328// the code.  Hence this bit of uglyness.
329//
330// In the long term, Type should not derive from Value, allowing
331// AbstractTypeUser.h to #include Type.h, allowing us to eliminate this
332// nastyness entirely.
333//
334inline void PATypeHandle::addUser() {
335  assert(Ty && "Type Handle has a null type!");
336  if (Ty->isAbstract())
337    Ty->addAbstractTypeUser(User);
338}
339inline void PATypeHandle::removeUser() {
340  if (Ty->isAbstract())
341    Ty->removeAbstractTypeUser(User);
342}
343
344inline void PATypeHandle::removeUserFromConcrete() {
345  if (!Ty->isAbstract())
346    Ty->removeAbstractTypeUser(User);
347}
348
349// Define inline methods for PATypeHolder...
350
351inline void PATypeHolder::addRef() {
352  if (Ty->isAbstract())
353    Ty->addRef();
354}
355
356inline void PATypeHolder::dropRef() {
357  if (Ty->isAbstract())
358    Ty->dropRef();
359}
360
361/// get - This implements the forwarding part of the union-find algorithm for
362/// abstract types.  Before every access to the Type*, we check to see if the
363/// type we are pointing to is forwarding to a new type.  If so, we drop our
364/// reference to the type.
365///
366inline const Type* PATypeHolder::get() const {
367  const Type *NewTy = Ty->getForwardedType();
368  if (!NewTy) return Ty;
369  return *const_cast<PATypeHolder*>(this) = NewTy;
370}
371
372
373
374//===----------------------------------------------------------------------===//
375// Provide specializations of GraphTraits to be able to treat a type as a
376// graph of sub types...
377
378template <> struct GraphTraits<Type*> {
379  typedef Type NodeType;
380  typedef Type::subtype_iterator ChildIteratorType;
381
382  static inline NodeType *getEntryNode(Type *T) { return T; }
383  static inline ChildIteratorType child_begin(NodeType *N) {
384    return N->subtype_begin();
385  }
386  static inline ChildIteratorType child_end(NodeType *N) {
387    return N->subtype_end();
388  }
389};
390
391template <> struct GraphTraits<const Type*> {
392  typedef const Type NodeType;
393  typedef Type::subtype_iterator ChildIteratorType;
394
395  static inline NodeType *getEntryNode(const Type *T) { return T; }
396  static inline ChildIteratorType child_begin(NodeType *N) {
397    return N->subtype_begin();
398  }
399  static inline ChildIteratorType child_end(NodeType *N) {
400    return N->subtype_end();
401  }
402};
403
404template <> inline bool isa_impl<PointerType, Type>(const Type &Ty) {
405  return Ty.getTypeID() == Type::PointerTyID;
406}
407
408std::ostream &operator<<(std::ostream &OS, const Type *T);
409std::ostream &operator<<(std::ostream &OS, const Type &T);
410
411} // End llvm namespace
412
413#endif
414