Type.h revision 7353404303d84169bb8f422698949be79957eb1a
1//===-- llvm/Type.h - Classes for handling data types -----------*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10
11#ifndef LLVM_TYPE_H
12#define LLVM_TYPE_H
13
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.h"
19#include <string>
20#include <vector>
21
22namespace llvm {
23
24class DerivedType;
25class PointerType;
26class IntegerType;
27class TypeMapBase;
28class raw_ostream;
29
30/// This file contains the declaration of the Type class.  For more "Type" type
31/// stuff, look in DerivedTypes.h.
32///
33/// The instances of the Type class are immutable: once they are created,
34/// they are never changed.  Also note that only one instance of a particular
35/// type is ever created.  Thus seeing if two types are equal is a matter of
36/// doing a trivial pointer comparison. To enforce that no two equal instances
37/// are created, Type instances can only be created via static factory methods
38/// in class Type and in derived classes.
39///
40/// Once allocated, Types are never free'd, unless they are an abstract type
41/// that is resolved to a more concrete type.
42///
43/// Types themself don't have a name, and can be named either by:
44/// - using SymbolTable instance, typically from some Module,
45/// - using convenience methods in the Module class (which uses module's
46///    SymbolTable too).
47///
48/// Opaque types are simple derived types with no state.  There may be many
49/// different Opaque type objects floating around, but two are only considered
50/// identical if they are pointer equals of each other.  This allows us to have
51/// two opaque types that end up resolving to different concrete types later.
52///
53/// Opaque types are also kinda weird and scary and different because they have
54/// to keep a list of uses of the type.  When, through linking, parsing, or
55/// bitcode reading, they become resolved, they need to find and update all
56/// users of the unknown type, causing them to reference a new, more concrete
57/// type.  Opaque types are deleted when their use list dwindles to zero users.
58///
59/// @brief Root of type hierarchy
60class Type : public AbstractTypeUser {
61public:
62  //===-------------------------------------------------------------------===//
63  /// Definitions of all of the base types for the Type system.  Based on this
64  /// value, you can cast to a "DerivedType" subclass (see DerivedTypes.h)
65  /// Note: If you add an element to this, you need to add an element to the
66  /// Type::getPrimitiveType function, or else things will break!
67  ///
68  enum TypeID {
69    // PrimitiveTypes .. make sure LastPrimitiveTyID stays up to date
70    VoidTyID = 0,    ///<  0: type with no size
71    FloatTyID,       ///<  1: 32 bit floating point type
72    DoubleTyID,      ///<  2: 64 bit floating point type
73    X86_FP80TyID,    ///<  3: 80 bit floating point type (X87)
74    FP128TyID,       ///<  4: 128 bit floating point type (112-bit mantissa)
75    PPC_FP128TyID,   ///<  5: 128 bit floating point type (two 64-bits)
76    LabelTyID,       ///<  6: Labels
77
78    // Derived types... see DerivedTypes.h file...
79    // Make sure FirstDerivedTyID stays up to date!!!
80    IntegerTyID,     ///<  7: Arbitrary bit width integers
81    FunctionTyID,    ///<  8: Functions
82    StructTyID,      ///<  9: Structures
83    ArrayTyID,       ///< 10: Arrays
84    PointerTyID,     ///< 11: Pointers
85    OpaqueTyID,      ///< 12: Opaque: type with unknown structure
86    VectorTyID,      ///< 13: SIMD 'packed' format, or other vector type
87
88    NumTypeIDs,                         // Must remain as last defined ID
89    LastPrimitiveTyID = LabelTyID,
90    FirstDerivedTyID = IntegerTyID
91  };
92
93private:
94  TypeID   ID : 8;    // The current base type of this type.
95  bool     Abstract : 1;  // True if type contains an OpaqueType
96  unsigned SubclassData : 23; //Space for subclasses to store data
97
98  /// RefCount - This counts the number of PATypeHolders that are pointing to
99  /// this type.  When this number falls to zero, if the type is abstract and
100  /// has no AbstractTypeUsers, the type is deleted.  This is only sensical for
101  /// derived types.
102  ///
103  mutable unsigned RefCount;
104
105  const Type *getForwardedTypeInternal() const;
106
107  // Some Type instances are allocated as arrays, some aren't. So we provide
108  // this method to get the right kind of destruction for the type of Type.
109  void destroy() const; // const is a lie, this does "delete this"!
110
111protected:
112  explicit Type(TypeID id) : ID(id), Abstract(false), SubclassData(0),
113                             RefCount(0), ForwardType(0), NumContainedTys(0),
114                             ContainedTys(0) {}
115  virtual ~Type() {
116    assert(AbstractTypeUsers.empty() && "Abstract types remain");
117  }
118
119  /// Types can become nonabstract later, if they are refined.
120  ///
121  inline void setAbstract(bool Val) { Abstract = Val; }
122
123  unsigned getRefCount() const { return RefCount; }
124
125  unsigned getSubclassData() const { return SubclassData; }
126  void setSubclassData(unsigned val) { SubclassData = val; }
127
128  /// ForwardType - This field is used to implement the union find scheme for
129  /// abstract types.  When types are refined to other types, this field is set
130  /// to the more refined type.  Only abstract types can be forwarded.
131  mutable const Type *ForwardType;
132
133
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.
136  ///
137  mutable std::vector<AbstractTypeUser *> AbstractTypeUsers;
138
139  /// NumContainedTys - Keeps track of how many PATypeHandle instances there
140  /// are at the end of this type instance for the list of contained types. It
141  /// is the subclasses responsibility to set this up. Set to 0 if there are no
142  /// contained types in this type.
143  unsigned NumContainedTys;
144
145  /// ContainedTys - A pointer to the array of Types (PATypeHandle) contained
146  /// by this Type.  For example, this includes the arguments of a function
147  /// type, the elements of a structure, the pointee of a pointer, the element
148  /// type of an array, etc.  This pointer may be 0 for types that don't
149  /// contain other types (Integer, Double, Float).  In general, the subclass
150  /// should arrange for space for the PATypeHandles to be included in the
151  /// allocation of the type object and set this pointer to the address of the
152  /// first element. This allows the Type class to manipulate the ContainedTys
153  /// without understanding the subclass's placement for this array.  keeping
154  /// it here also allows the subtype_* members to be implemented MUCH more
155  /// efficiently, and dynamically very few types do not contain any elements.
156  PATypeHandle *ContainedTys;
157
158public:
159  void print(raw_ostream &O) const;
160  void print(std::ostream &O) const;
161
162  /// @brief Debugging support: print to stderr
163  void dump() const;
164
165  //===--------------------------------------------------------------------===//
166  // Property accessors for dealing with types... Some of these virtual methods
167  // are defined in private classes defined in Type.cpp for primitive types.
168  //
169
170  /// getTypeID - Return the type id for the type.  This will return one
171  /// of the TypeID enum elements defined above.
172  ///
173  inline TypeID getTypeID() const { return ID; }
174
175  /// getDescription - Return the string representation of the type...
176  const std::string &getDescription() const;
177
178  /// isInteger - True if this is an instance of IntegerType.
179  ///
180  bool isInteger() const { return ID == IntegerTyID; }
181
182  /// isIntOrIntVector - Return true if this is an integer type or a vector of
183  /// integer types.
184  ///
185  bool isIntOrIntVector() const;
186
187  /// isFloatingPoint - Return true if this is one of the two floating point
188  /// types
189  bool isFloatingPoint() const { return ID == FloatTyID || ID == DoubleTyID ||
190      ID == X86_FP80TyID || ID == FP128TyID || ID == PPC_FP128TyID; }
191
192  /// isFPOrFPVector - Return true if this is a FP type or a vector of FP types.
193  ///
194  bool isFPOrFPVector() const;
195
196  /// isAbstract - True if the type is either an Opaque type, or is a derived
197  /// type that includes an opaque type somewhere in it.
198  ///
199  inline bool isAbstract() const { return Abstract; }
200
201  /// canLosslesslyBitCastTo - Return true if this type could be converted
202  /// with a lossless BitCast to type 'Ty'. For example, uint to int. BitCasts
203  /// are valid for types of the same size only where no re-interpretation of
204  /// the bits is done.
205  /// @brief Determine if this type could be losslessly bitcast to Ty
206  bool canLosslesslyBitCastTo(const Type *Ty) const;
207
208
209  /// Here are some useful little methods to query what type derived types are
210  /// Note that all other types can just compare to see if this == Type::xxxTy;
211  ///
212  inline bool isPrimitiveType() const { return ID <= LastPrimitiveTyID; }
213  inline bool isDerivedType()   const { return ID >= FirstDerivedTyID; }
214
215  /// isFirstClassType - Return true if the type is "first class", meaning it
216  /// is a valid type for a Value.
217  ///
218  inline bool isFirstClassType() const {
219    // There are more first-class kinds than non-first-class kinds, so a
220    // negative test is simpler than a positive one.
221    return ID != FunctionTyID && ID != VoidTyID && ID != OpaqueTyID;
222  }
223
224  /// isSingleValueType - Return true if the type is a valid type for a
225  /// virtual register in codegen.  This includes all first-class types
226  /// except struct and array types.
227  ///
228  inline bool isSingleValueType() const {
229    return (ID != VoidTyID && ID <= LastPrimitiveTyID) ||
230            ID == IntegerTyID || ID == PointerTyID || ID == VectorTyID;
231  }
232
233  /// isAggregateType - Return true if the type is an aggregate type. This
234  /// means it is valid as the first operand of an insertvalue or
235  /// extractvalue instruction. This includes struct and array types, but
236  /// does not include vector types.
237  ///
238  inline bool isAggregateType() const {
239    return ID == StructTyID || ID == ArrayTyID;
240  }
241
242  /// isSized - Return true if it makes sense to take the size of this type.  To
243  /// get the actual size for a particular target, it is reasonable to use the
244  /// TargetData subsystem to do this.
245  ///
246  bool isSized() const {
247    // If it's a primitive, it is always sized.
248    if (ID == IntegerTyID || isFloatingPoint() || ID == PointerTyID)
249      return true;
250    // If it is not something that can have a size (e.g. a function or label),
251    // it doesn't have a size.
252    if (ID != StructTyID && ID != ArrayTyID && ID != VectorTyID)
253      return false;
254    // If it is something that can have a size and it's concrete, it definitely
255    // has a size, otherwise we have to try harder to decide.
256    return !isAbstract() || isSizedDerivedType();
257  }
258
259  /// getPrimitiveSizeInBits - Return the basic size of this type if it is a
260  /// primitive type.  These are fixed by LLVM and are not target dependent.
261  /// This will return zero if the type does not have a size or is not a
262  /// primitive type.
263  ///
264  unsigned getPrimitiveSizeInBits() const;
265
266  /// getFPMantissaWidth - Return the width of the mantissa of this type.  This
267  /// is only valid on scalar floating point types.  If the FP type does not
268  /// have a stable mantissa (e.g. ppc long double), this method returns -1.
269  int getFPMantissaWidth() const {
270    assert(isFloatingPoint() && "Not a floating point type!");
271    if (ID == FloatTyID) return 24;
272    if (ID == DoubleTyID) return 53;
273    if (ID == X86_FP80TyID) return 64;
274    if (ID == FP128TyID) return 113;
275    assert(ID == PPC_FP128TyID && "unknown fp type");
276    return -1;
277  }
278
279  /// getForwardedType - Return the type that this type has been resolved to if
280  /// it has been resolved to anything.  This is used to implement the
281  /// union-find algorithm for type resolution, and shouldn't be used by general
282  /// purpose clients.
283  const Type *getForwardedType() const {
284    if (!ForwardType) return 0;
285    return getForwardedTypeInternal();
286  }
287
288  /// getVAArgsPromotedType - Return the type an argument of this type
289  /// will be promoted to if passed through a variable argument
290  /// function.
291  const Type *getVAArgsPromotedType() const;
292
293  //===--------------------------------------------------------------------===//
294  // Type Iteration support
295  //
296  typedef PATypeHandle *subtype_iterator;
297  subtype_iterator subtype_begin() const { return ContainedTys; }
298  subtype_iterator subtype_end() const { return &ContainedTys[NumContainedTys];}
299
300  /// getContainedType - This method is used to implement the type iterator
301  /// (defined a the end of the file).  For derived types, this returns the
302  /// types 'contained' in the derived type.
303  ///
304  const Type *getContainedType(unsigned i) const {
305    assert(i < NumContainedTys && "Index out of range!");
306    return ContainedTys[i].get();
307  }
308
309  /// getNumContainedTypes - Return the number of types in the derived type.
310  ///
311  unsigned getNumContainedTypes() const { return NumContainedTys; }
312
313  //===--------------------------------------------------------------------===//
314  // Static members exported by the Type class itself.  Useful for getting
315  // instances of Type.
316  //
317
318  /// getPrimitiveType - Return a type based on an identifier.
319  static const Type *getPrimitiveType(TypeID IDNumber);
320
321  //===--------------------------------------------------------------------===//
322  // These are the builtin types that are always available...
323  //
324  static const Type *VoidTy, *LabelTy, *FloatTy, *DoubleTy;
325  static const Type *X86_FP80Ty, *FP128Ty, *PPC_FP128Ty;
326  static const IntegerType *Int1Ty, *Int8Ty, *Int16Ty, *Int32Ty, *Int64Ty;
327
328  /// Methods for support type inquiry through isa, cast, and dyn_cast:
329  static inline bool classof(const Type *) { return true; }
330
331  void addRef() const {
332    assert(isAbstract() && "Cannot add a reference to a non-abstract type!");
333    ++RefCount;
334  }
335
336  void dropRef() const {
337    assert(isAbstract() && "Cannot drop a reference to a non-abstract type!");
338    assert(RefCount && "No objects are currently referencing this object!");
339
340    // If this is the last PATypeHolder using this object, and there are no
341    // PATypeHandles using it, the type is dead, delete it now.
342    if (--RefCount == 0 && AbstractTypeUsers.empty())
343      this->destroy();
344  }
345
346  /// addAbstractTypeUser - Notify an abstract type that there is a new user of
347  /// it.  This function is called primarily by the PATypeHandle class.
348  ///
349  void addAbstractTypeUser(AbstractTypeUser *U) const {
350    assert(isAbstract() && "addAbstractTypeUser: Current type not abstract!");
351    AbstractTypeUsers.push_back(U);
352  }
353
354  /// removeAbstractTypeUser - Notify an abstract type that a user of the class
355  /// no longer has a handle to the type.  This function is called primarily by
356  /// the PATypeHandle class.  When there are no users of the abstract type, it
357  /// is annihilated, because there is no way to get a reference to it ever
358  /// again.
359  ///
360  void removeAbstractTypeUser(AbstractTypeUser *U) const;
361
362private:
363  /// isSizedDerivedType - Derived types like structures and arrays are sized
364  /// iff all of the members of the type are sized as well.  Since asking for
365  /// their size is relatively uncommon, move this operation out of line.
366  bool isSizedDerivedType() const;
367
368  virtual void refineAbstractType(const DerivedType *OldTy, const Type *NewTy);
369  virtual void typeBecameConcrete(const DerivedType *AbsTy);
370
371protected:
372  // PromoteAbstractToConcrete - This is an internal method used to calculate
373  // change "Abstract" from true to false when types are refined.
374  void PromoteAbstractToConcrete();
375  friend class TypeMapBase;
376};
377
378//===----------------------------------------------------------------------===//
379// Define some inline methods for the AbstractTypeUser.h:PATypeHandle class.
380// These are defined here because they MUST be inlined, yet are dependent on
381// the definition of the Type class.
382//
383inline void PATypeHandle::addUser() {
384  assert(Ty && "Type Handle has a null type!");
385  if (Ty->isAbstract())
386    Ty->addAbstractTypeUser(User);
387}
388inline void PATypeHandle::removeUser() {
389  if (Ty->isAbstract())
390    Ty->removeAbstractTypeUser(User);
391}
392
393// Define inline methods for PATypeHolder.
394
395/// get - This implements the forwarding part of the union-find algorithm for
396/// abstract types.  Before every access to the Type*, we check to see if the
397/// type we are pointing to is forwarding to a new type.  If so, we drop our
398/// reference to the type.
399///
400inline Type* PATypeHolder::get() const {
401  const Type *NewTy = Ty->getForwardedType();
402  if (!NewTy) return const_cast<Type*>(Ty);
403  return *const_cast<PATypeHolder*>(this) = NewTy;
404}
405
406inline void PATypeHolder::addRef() {
407  assert(Ty && "Type Holder has a null type!");
408  if (Ty->isAbstract())
409    Ty->addRef();
410}
411
412inline void PATypeHolder::dropRef() {
413  if (Ty->isAbstract())
414    Ty->dropRef();
415}
416
417
418//===----------------------------------------------------------------------===//
419// Provide specializations of GraphTraits to be able to treat a type as a
420// graph of sub types...
421
422template <> struct GraphTraits<Type*> {
423  typedef Type NodeType;
424  typedef Type::subtype_iterator ChildIteratorType;
425
426  static inline NodeType *getEntryNode(Type *T) { return T; }
427  static inline ChildIteratorType child_begin(NodeType *N) {
428    return N->subtype_begin();
429  }
430  static inline ChildIteratorType child_end(NodeType *N) {
431    return N->subtype_end();
432  }
433};
434
435template <> struct GraphTraits<const Type*> {
436  typedef const Type NodeType;
437  typedef Type::subtype_iterator ChildIteratorType;
438
439  static inline NodeType *getEntryNode(const Type *T) { return T; }
440  static inline ChildIteratorType child_begin(NodeType *N) {
441    return N->subtype_begin();
442  }
443  static inline ChildIteratorType child_end(NodeType *N) {
444    return N->subtype_end();
445  }
446};
447
448template <> inline bool isa_impl<PointerType, Type>(const Type &Ty) {
449  return Ty.getTypeID() == Type::PointerTyID;
450}
451
452std::ostream &operator<<(std::ostream &OS, const Type &T);
453raw_ostream &operator<<(raw_ostream &OS, const Type &T);
454
455} // End llvm namespace
456
457#endif
458