Type.h revision 2abbe867ab7a50e658712624b34c8957e9600674
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 weird 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 "llvm/Support/Casting.h"
39#include "llvm/ADT/GraphTraits.h"
40#include "llvm/ADT/iterator"
41#include <string>
42#include <vector>
43
44namespace llvm {
45
46class ArrayType;
47class DerivedType;
48class FunctionType;
49class OpaqueType;
50class PointerType;
51class StructType;
52class PackedType;
53class TypeMapBase;
54
55class Type : public AbstractTypeUser {
56public:
57  ///===-------------------------------------------------------------------===//
58  /// Definitions of all of the base types for the Type system.  Based on this
59  /// value, you can cast to a "DerivedType" subclass (see DerivedTypes.h)
60  /// Note: If you add an element to this, you need to add an element to the
61  /// Type::getPrimitiveType function, or else things will break!
62  ///
63  enum TypeID {
64    // PrimitiveTypes .. make sure LastPrimitiveTyID stays up to date
65    VoidTyID = 0  , BoolTyID,           //  0, 1: Basics...
66    UByteTyID     , SByteTyID,          //  2, 3: 8 bit types...
67    UShortTyID    , ShortTyID,          //  4, 5: 16 bit types...
68    UIntTyID      , IntTyID,            //  6, 7: 32 bit types...
69    ULongTyID     , LongTyID,           //  8, 9: 64 bit types...
70    FloatTyID     , DoubleTyID,         // 10,11: Floating point types...
71    LabelTyID     ,                     // 12   : Labels...
72
73    // Derived types... see DerivedTypes.h file...
74    // Make sure FirstDerivedTyID stays up to date!!!
75    FunctionTyID  , StructTyID,         // Functions... Structs...
76    ArrayTyID     , PointerTyID,        // Array... pointer...
77    OpaqueTyID,                         // Opaque type instances...
78    PackedTyID,                         // SIMD 'packed' format...
79    //...
80
81    NumTypeIDs,                         // Must remain as last defined ID
82    LastPrimitiveTyID = LabelTyID,
83    FirstDerivedTyID = FunctionTyID
84  };
85
86private:
87  TypeID   ID : 8;    // The current base type of this type.
88  bool     Abstract : 1;  // True if type contains an OpaqueType
89
90  /// RefCount - This counts the number of PATypeHolders that are pointing to
91  /// this type.  When this number falls to zero, if the type is abstract and
92  /// has no AbstractTypeUsers, the type is deleted.  This is only sensical for
93  /// derived types.
94  ///
95  mutable unsigned RefCount;
96
97  const Type *getForwardedTypeInternal() const;
98protected:
99  Type(const char *Name, TypeID id);
100  Type(TypeID id) : ID(id), Abstract(false), RefCount(0), ForwardType(0) {}
101  virtual ~Type() {
102    assert(AbstractTypeUsers.empty());
103  }
104
105  /// Types can become nonabstract later, if they are refined.
106  ///
107  inline void setAbstract(bool Val) { Abstract = Val; }
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
125  /// AbstractTypeUsers - Implement a list of the users that need to be notified
126  /// if I am a type, and I get resolved into a more concrete type.
127  ///
128  mutable std::vector<AbstractTypeUser *> AbstractTypeUsers;
129public:
130  void print(std::ostream &O) const;
131
132  /// @brief Debugging support: print to stderr
133  void dump() const;
134
135  //===--------------------------------------------------------------------===//
136  // Property accessors for dealing with types... Some of these virtual methods
137  // are defined in private classes defined in Type.cpp for primitive types.
138  //
139
140  /// getTypeID - Return the type id for the type.  This will return one
141  /// of the TypeID enum elements defined above.
142  ///
143  inline TypeID getTypeID() const { return ID; }
144
145  /// getDescription - Return the string representation of the type...
146  const std::string &getDescription() const;
147
148  /// isSigned - Return whether an integral numeric type is signed.  This is
149  /// true for SByteTy, ShortTy, IntTy, LongTy.  Note that this is not true for
150  /// Float and Double.
151  ///
152  bool isSigned() const {
153    return ID == SByteTyID || ID == ShortTyID ||
154           ID == IntTyID || ID == LongTyID;
155  }
156
157  /// isUnsigned - Return whether a numeric type is unsigned.  This is not quite
158  /// the complement of isSigned... nonnumeric types return false as they do
159  /// with isSigned.  This returns true for UByteTy, UShortTy, UIntTy, and
160  /// ULongTy
161  ///
162  bool isUnsigned() const {
163    return ID == UByteTyID || ID == UShortTyID ||
164           ID == UIntTyID || ID == ULongTyID;
165  }
166
167  /// isInteger - Equivalent to isSigned() || isUnsigned()
168  ///
169  bool isInteger() const { return ID >= UByteTyID && ID <= LongTyID; }
170
171  /// isIntegral - Returns true if this is an integral type, which is either
172  /// BoolTy or one of the Integer types.
173  ///
174  bool isIntegral() const { return isInteger() || this == BoolTy; }
175
176  /// isFloatingPoint - Return true if this is one of the two floating point
177  /// types
178  bool isFloatingPoint() const { return ID == FloatTyID || ID == DoubleTyID; }
179
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.
182  ///
183  inline bool isAbstract() const { return Abstract; }
184
185  /// isLosslesslyConvertibleTo - Return true if this type can be converted to
186  /// 'Ty' without any reinterpretation of bits.  For example, uint to int.
187  ///
188  bool isLosslesslyConvertibleTo(const Type *Ty) const;
189
190
191  /// Here are some useful little methods to query what type derived types are
192  /// Note that all other types can just compare to see if this == Type::xxxTy;
193  ///
194  inline bool isPrimitiveType() const { return ID <= LastPrimitiveTyID; }
195  inline bool isDerivedType()   const { return ID >= FirstDerivedTyID; }
196
197  /// isFirstClassType - Return true if the value is holdable in a register.
198  ///
199  inline bool isFirstClassType() const {
200    return (ID != VoidTyID && ID <= LastPrimitiveTyID) ||
201            ID == PointerTyID || ID == PackedTyID;
202  }
203
204  /// isSized - Return true if it makes sense to take the size of this type.  To
205  /// get the actual size for a particular target, it is reasonable to use the
206  /// TargetData subsystem to do this.
207  ///
208  bool isSized() const {
209    // If it's a primitive, it is always sized.
210    if (ID >= BoolTyID && ID <= DoubleTyID || ID == PointerTyID)
211      return true;
212    // If it is not something that can have a size (e.g. a function or label),
213    // it doesn't have a size.
214    if (ID != StructTyID && ID != ArrayTyID && ID != PackedTyID)
215      return false;
216    // If it is something that can have a size and it's concrete, it definitely
217    // has a size, otherwise we have to try harder to decide.
218    return !isAbstract() || isSizedDerivedType();
219  }
220
221  /// getPrimitiveSize - Return the basic size of this type if it is a primitive
222  /// type.  These are fixed by LLVM and are not target dependent.  This will
223  /// return zero if the type does not have a size or is not a primitive type.
224  ///
225  unsigned getPrimitiveSize() const;
226  unsigned getPrimitiveSizeInBits() const;
227
228  /// getUnsignedVersion - If this is an integer type, return the unsigned
229  /// variant of this type.  For example int -> uint.
230  const Type *getUnsignedVersion() const;
231
232  /// getSignedVersion - If this is an integer type, return the signed variant
233  /// of this type.  For example uint -> int.
234  const Type *getSignedVersion() const;
235
236  /// getForwaredType - Return the type that this type has been resolved to if
237  /// it has been resolved to anything.  This is used to implement the
238  /// union-find algorithm for type resolution, and shouldn't be used by general
239  /// purpose clients.
240  const Type *getForwardedType() const {
241    if (!ForwardType) return 0;
242    return getForwardedTypeInternal();
243  }
244
245  /// getVAArgsPromotedType - Return the type an argument of this type
246  /// will be promoted to if passed through a variable argument
247  /// function.
248  const Type *getVAArgsPromotedType() const {
249    if (ID == BoolTyID || ID == UByteTyID || ID == UShortTyID)
250      return Type::UIntTy;
251    else if (ID == SByteTyID || ID == ShortTyID)
252      return Type::IntTy;
253    else if (ID == FloatTyID)
254      return Type::DoubleTy;
255    else
256      return this;
257  }
258
259  //===--------------------------------------------------------------------===//
260  // Type Iteration support
261  //
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(); }
265
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.
269  ///
270  const Type *getContainedType(unsigned i) const {
271    assert(i < ContainedTys.size() && "Index out of range!");
272    return ContainedTys[i];
273  }
274
275  /// getNumContainedTypes - Return the number of types in the derived type.
276  ///
277  typedef std::vector<PATypeHandle>::size_type size_type;
278  size_type getNumContainedTypes() const { return ContainedTys.size(); }
279
280  //===--------------------------------------------------------------------===//
281  // Static members exported by the Type class itself.  Useful for getting
282  // instances of Type.
283  //
284
285  /// getPrimitiveType - Return a type based on an identifier.
286  static const Type *getPrimitiveType(TypeID IDNumber);
287
288  //===--------------------------------------------------------------------===//
289  // These are the builtin types that are always available...
290  //
291  static Type *VoidTy , *BoolTy;
292  static Type *SByteTy, *UByteTy,
293              *ShortTy, *UShortTy,
294              *IntTy  , *UIntTy,
295              *LongTy , *ULongTy;
296  static Type *FloatTy, *DoubleTy;
297
298  static Type* LabelTy;
299
300  /// Methods for support type inquiry through isa, cast, and dyn_cast:
301  static inline bool classof(const Type *T) { return true; }
302
303  void addRef() const {
304    assert(isAbstract() && "Cannot add a reference to a non-abstract type!");
305    ++RefCount;
306  }
307
308  void dropRef() const {
309    assert(isAbstract() && "Cannot drop a reference to a non-abstract type!");
310    assert(RefCount && "No objects are currently referencing this object!");
311
312    // If this is the last PATypeHolder using this object, and there are no
313    // PATypeHandles using it, the type is dead, delete it now.
314    if (--RefCount == 0 && AbstractTypeUsers.empty())
315      delete this;
316  }
317
318  /// addAbstractTypeUser - Notify an abstract type that there is a new user of
319  /// it.  This function is called primarily by the PATypeHandle class.
320  ///
321  void addAbstractTypeUser(AbstractTypeUser *U) const {
322    assert(isAbstract() && "addAbstractTypeUser: Current type not abstract!");
323    AbstractTypeUsers.push_back(U);
324  }
325
326  /// removeAbstractTypeUser - Notify an abstract type that a user of the class
327  /// no longer has a handle to the type.  This function is called primarily by
328  /// the PATypeHandle class.  When there are no users of the abstract type, it
329  /// is annihilated, because there is no way to get a reference to it ever
330  /// again.
331  ///
332  void removeAbstractTypeUser(AbstractTypeUser *U) const;
333
334  /// clearAllTypeMaps - This method frees all internal memory used by the
335  /// type subsystem, which can be used in environments where this memory is
336  /// otherwise reported as a leak.
337  static void clearAllTypeMaps();
338
339private:
340  /// isSizedDerivedType - Derived types like structures and arrays are sized
341  /// iff all of the members of the type are sized as well.  Since asking for
342  /// their size is relatively uncommon, move this operation out of line.
343  bool isSizedDerivedType() const;
344
345  virtual void refineAbstractType(const DerivedType *OldTy, const Type *NewTy);
346  virtual void typeBecameConcrete(const DerivedType *AbsTy);
347
348protected:
349  // PromoteAbstractToConcrete - This is an internal method used to calculate
350  // change "Abstract" from true to false when types are refined.
351  void PromoteAbstractToConcrete();
352  friend class TypeMapBase;
353};
354
355//===----------------------------------------------------------------------===//
356// Define some inline methods for the AbstractTypeUser.h:PATypeHandle class.
357// These are defined here because they MUST be inlined, yet are dependent on
358// the definition of the Type class.  Of course Type derives from Value, which
359// contains an AbstractTypeUser instance, so there is no good way to factor out
360// the code.  Hence this bit of uglyness.
361//
362// In the long term, Type should not derive from Value, allowing
363// AbstractTypeUser.h to #include Type.h, allowing us to eliminate this
364// nastyness entirely.
365//
366inline void PATypeHandle::addUser() {
367  assert(Ty && "Type Handle has a null type!");
368  if (Ty->isAbstract())
369    Ty->addAbstractTypeUser(User);
370}
371inline void PATypeHandle::removeUser() {
372  if (Ty->isAbstract())
373    Ty->removeAbstractTypeUser(User);
374}
375
376// Define inline methods for PATypeHolder...
377
378inline void PATypeHolder::addRef() {
379  if (Ty->isAbstract())
380    Ty->addRef();
381}
382
383inline void PATypeHolder::dropRef() {
384  if (Ty->isAbstract())
385    Ty->dropRef();
386}
387
388/// get - This implements the forwarding part of the union-find algorithm for
389/// abstract types.  Before every access to the Type*, we check to see if the
390/// type we are pointing to is forwarding to a new type.  If so, we drop our
391/// reference to the type.
392///
393inline Type* PATypeHolder::get() const {
394  const Type *NewTy = Ty->getForwardedType();
395  if (!NewTy) return const_cast<Type*>(Ty);
396  return *const_cast<PATypeHolder*>(this) = NewTy;
397}
398
399
400
401//===----------------------------------------------------------------------===//
402// Provide specializations of GraphTraits to be able to treat a type as a
403// graph of sub types...
404
405template <> struct GraphTraits<Type*> {
406  typedef Type NodeType;
407  typedef Type::subtype_iterator ChildIteratorType;
408
409  static inline NodeType *getEntryNode(Type *T) { return T; }
410  static inline ChildIteratorType child_begin(NodeType *N) {
411    return N->subtype_begin();
412  }
413  static inline ChildIteratorType child_end(NodeType *N) {
414    return N->subtype_end();
415  }
416};
417
418template <> struct GraphTraits<const Type*> {
419  typedef const Type NodeType;
420  typedef Type::subtype_iterator ChildIteratorType;
421
422  static inline NodeType *getEntryNode(const Type *T) { return T; }
423  static inline ChildIteratorType child_begin(NodeType *N) {
424    return N->subtype_begin();
425  }
426  static inline ChildIteratorType child_end(NodeType *N) {
427    return N->subtype_end();
428  }
429};
430
431template <> inline bool isa_impl<PointerType, Type>(const Type &Ty) {
432  return Ty.getTypeID() == Type::PointerTyID;
433}
434
435std::ostream &operator<<(std::ostream &OS, const Type &T);
436
437} // End llvm namespace
438
439#endif
440