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