LLVM API Documentation

Type.h

Go to the documentation of this file.
00001 //===-- llvm/Type.h - Classes for handling data types -----------*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file was developed by the LLVM research group and is distributed under
00006 // the University of Illinois Open Source License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 
00010 
00011 #ifndef LLVM_TYPE_H
00012 #define LLVM_TYPE_H
00013 
00014 #include "llvm/AbstractTypeUser.h"
00015 #include "llvm/Support/Casting.h"
00016 #include "llvm/Support/DataTypes.h"
00017 #include "llvm/ADT/GraphTraits.h"
00018 #include "llvm/ADT/iterator"
00019 #include <string>
00020 #include <vector>
00021 
00022 namespace llvm {
00023 
00024 class ArrayType;
00025 class DerivedType;
00026 class FunctionType;
00027 class OpaqueType;
00028 class PointerType;
00029 class StructType;
00030 class PackedType;
00031 class TypeMapBase;
00032 
00033 /// This file contains the declaration of the Type class.  For more "Type" type
00034 /// stuff, look in DerivedTypes.h.
00035 ///
00036 /// The instances of the Type class are immutable: once they are created,
00037 /// they are never changed.  Also note that only one instance of a particular
00038 /// type is ever created.  Thus seeing if two types are equal is a matter of
00039 /// doing a trivial pointer comparison. To enforce that no two equal instances
00040 /// are created, Type instances can only be created via static factory methods 
00041 /// in class Type and in derived classes.
00042 /// 
00043 /// Once allocated, Types are never free'd, unless they are an abstract type
00044 /// that is resolved to a more concrete type.
00045 /// 
00046 /// Types themself don't have a name, and can be named either by:
00047 /// - using SymbolTable instance, typically from some Module,
00048 /// - using convenience methods in the Module class (which uses module's 
00049 ///    SymbolTable too).
00050 ///
00051 /// Opaque types are simple derived types with no state.  There may be many
00052 /// different Opaque type objects floating around, but two are only considered
00053 /// identical if they are pointer equals of each other.  This allows us to have
00054 /// two opaque types that end up resolving to different concrete types later.
00055 ///
00056 /// Opaque types are also kinda weird and scary and different because they have
00057 /// to keep a list of uses of the type.  When, through linking, parsing, or
00058 /// bytecode reading, they become resolved, they need to find and update all
00059 /// users of the unknown type, causing them to reference a new, more concrete
00060 /// type.  Opaque types are deleted when their use list dwindles to zero users.
00061 ///
00062 /// @brief Root of type hierarchy
00063 class Type : public AbstractTypeUser {
00064 public:
00065   ///===-------------------------------------------------------------------===//
00066   /// Definitions of all of the base types for the Type system.  Based on this
00067   /// value, you can cast to a "DerivedType" subclass (see DerivedTypes.h)
00068   /// Note: If you add an element to this, you need to add an element to the
00069   /// Type::getPrimitiveType function, or else things will break!
00070   ///
00071   enum TypeID {
00072     // PrimitiveTypes .. make sure LastPrimitiveTyID stays up to date
00073     VoidTyID = 0  , BoolTyID,           //  0, 1: Basics...
00074     UByteTyID     , SByteTyID,          //  2, 3: 8 bit types...
00075     UShortTyID    , ShortTyID,          //  4, 5: 16 bit types...
00076     UIntTyID      , IntTyID,            //  6, 7: 32 bit types...
00077     ULongTyID     , LongTyID,           //  8, 9: 64 bit types...
00078     FloatTyID     , DoubleTyID,         // 10,11: Floating point types...
00079     LabelTyID     ,                     // 12   : Labels...
00080 
00081     // Derived types... see DerivedTypes.h file...
00082     // Make sure FirstDerivedTyID stays up to date!!!
00083     FunctionTyID  , StructTyID,         // Functions... Structs...
00084     ArrayTyID     , PointerTyID,        // Array... pointer...
00085     OpaqueTyID,                         // Opaque type instances...
00086     PackedTyID,                         // SIMD 'packed' format...
00087     //...
00088 
00089     NumTypeIDs,                         // Must remain as last defined ID
00090     LastPrimitiveTyID = LabelTyID,
00091     FirstDerivedTyID = FunctionTyID
00092   };
00093 
00094 private:
00095   TypeID   ID : 8;    // The current base type of this type.
00096   bool     Abstract : 1;  // True if type contains an OpaqueType
00097 
00098   /// RefCount - This counts the number of PATypeHolders that are pointing to
00099   /// this type.  When this number falls to zero, if the type is abstract and
00100   /// has no AbstractTypeUsers, the type is deleted.  This is only sensical for
00101   /// derived types.
00102   ///
00103   mutable unsigned RefCount;
00104 
00105   const Type *getForwardedTypeInternal() const;
00106 protected:
00107   Type(const char *Name, TypeID id);
00108   Type(TypeID id) : ID(id), Abstract(false), RefCount(0), ForwardType(0) {}
00109   virtual ~Type() {
00110     assert(AbstractTypeUsers.empty());
00111   }
00112 
00113   /// Types can become nonabstract later, if they are refined.
00114   ///
00115   inline void setAbstract(bool Val) { Abstract = Val; }
00116 
00117   unsigned getRefCount() const { return RefCount; }
00118 
00119   /// ForwardType - This field is used to implement the union find scheme for
00120   /// abstract types.  When types are refined to other types, this field is set
00121   /// to the more refined type.  Only abstract types can be forwarded.
00122   mutable const Type *ForwardType;
00123 
00124   /// ContainedTys - The list of types contained by this one.  For example, this
00125   /// includes the arguments of a function type, the elements of the structure,
00126   /// the pointee of a pointer, etc.  Note that keeping this vector in the Type
00127   /// class wastes some space for types that do not contain anything (such as
00128   /// primitive types).  However, keeping it here allows the subtype_* members
00129   /// to be implemented MUCH more efficiently, and dynamically very few types do
00130   /// not contain any elements (most are derived).
00131   std::vector<PATypeHandle> ContainedTys;
00132 
00133   /// AbstractTypeUsers - Implement a list of the users that need to be notified
00134   /// if I am a type, and I get resolved into a more concrete type.
00135   ///
00136   mutable std::vector<AbstractTypeUser *> AbstractTypeUsers;
00137 public:
00138   void print(std::ostream &O) const;
00139 
00140   /// @brief Debugging support: print to stderr
00141   void dump() const;
00142 
00143   //===--------------------------------------------------------------------===//
00144   // Property accessors for dealing with types... Some of these virtual methods
00145   // are defined in private classes defined in Type.cpp for primitive types.
00146   //
00147 
00148   /// getTypeID - Return the type id for the type.  This will return one
00149   /// of the TypeID enum elements defined above.
00150   ///
00151   inline TypeID getTypeID() const { return ID; }
00152 
00153   /// getDescription - Return the string representation of the type...
00154   const std::string &getDescription() const;
00155 
00156   /// isSigned - Return whether an integral numeric type is signed.  This is
00157   /// true for SByteTy, ShortTy, IntTy, LongTy.  Note that this is not true for
00158   /// Float and Double.
00159   ///
00160   bool isSigned() const {
00161     return ID == SByteTyID || ID == ShortTyID ||
00162            ID == IntTyID || ID == LongTyID;
00163   }
00164 
00165   /// isUnsigned - Return whether a numeric type is unsigned.  This is not quite
00166   /// the complement of isSigned... nonnumeric types return false as they do
00167   /// with isSigned.  This returns true for UByteTy, UShortTy, UIntTy, and
00168   /// ULongTy
00169   ///
00170   bool isUnsigned() const {
00171     return ID == UByteTyID || ID == UShortTyID ||
00172            ID == UIntTyID || ID == ULongTyID;
00173   }
00174 
00175   /// isInteger - Equivalent to isSigned() || isUnsigned()
00176   ///
00177   bool isInteger() const { return ID >= UByteTyID && ID <= LongTyID; }
00178 
00179   /// isIntegral - Returns true if this is an integral type, which is either
00180   /// BoolTy or one of the Integer types.
00181   ///
00182   bool isIntegral() const { return isInteger() || this == BoolTy; }
00183 
00184   /// isFloatingPoint - Return true if this is one of the two floating point
00185   /// types
00186   bool isFloatingPoint() const { return ID == FloatTyID || ID == DoubleTyID; }
00187 
00188   /// isAbstract - True if the type is either an Opaque type, or is a derived
00189   /// type that includes an opaque type somewhere in it.
00190   ///
00191   inline bool isAbstract() const { return Abstract; }
00192 
00193   /// isLosslesslyConvertibleTo - Return true if this type can be converted to
00194   /// 'Ty' without any reinterpretation of bits.  For example, uint to int.
00195   ///
00196   bool isLosslesslyConvertibleTo(const Type *Ty) const;
00197 
00198 
00199   /// Here are some useful little methods to query what type derived types are
00200   /// Note that all other types can just compare to see if this == Type::xxxTy;
00201   ///
00202   inline bool isPrimitiveType() const { return ID <= LastPrimitiveTyID; }
00203   inline bool isDerivedType()   const { return ID >= FirstDerivedTyID; }
00204 
00205   /// isFirstClassType - Return true if the value is holdable in a register.
00206   ///
00207   inline bool isFirstClassType() const {
00208     return (ID != VoidTyID && ID <= LastPrimitiveTyID) ||
00209             ID == PointerTyID || ID == PackedTyID;
00210   }
00211 
00212   /// isSized - Return true if it makes sense to take the size of this type.  To
00213   /// get the actual size for a particular target, it is reasonable to use the
00214   /// TargetData subsystem to do this.
00215   ///
00216   bool isSized() const {
00217     // If it's a primitive, it is always sized.
00218     if (ID >= BoolTyID && ID <= DoubleTyID || ID == PointerTyID)
00219       return true;
00220     // If it is not something that can have a size (e.g. a function or label),
00221     // it doesn't have a size.
00222     if (ID != StructTyID && ID != ArrayTyID && ID != PackedTyID)
00223       return false;
00224     // If it is something that can have a size and it's concrete, it definitely
00225     // has a size, otherwise we have to try harder to decide.
00226     return !isAbstract() || isSizedDerivedType();
00227   }
00228 
00229   /// getPrimitiveSize - Return the basic size of this type if it is a primitive
00230   /// type.  These are fixed by LLVM and are not target dependent.  This will
00231   /// return zero if the type does not have a size or is not a primitive type.
00232   ///
00233   unsigned getPrimitiveSize() const;
00234   unsigned getPrimitiveSizeInBits() const;
00235 
00236   /// getUnsignedVersion - If this is an integer type, return the unsigned
00237   /// variant of this type.  For example int -> uint.
00238   const Type *getUnsignedVersion() const;
00239 
00240   /// getSignedVersion - If this is an integer type, return the signed variant
00241   /// of this type.  For example uint -> int.
00242   const Type *getSignedVersion() const;
00243   
00244   /// getIntegralTypeMask - Return a bitmask with ones set for all of the bits
00245   /// that can be set by an unsigned version of this type.  This is 0xFF for
00246   /// sbyte/ubyte, 0xFFFF for shorts, etc.
00247   uint64_t getIntegralTypeMask() const {
00248     assert(isIntegral() && "This only works for integral types!");
00249     return ~uint64_t(0UL) >> (64-getPrimitiveSizeInBits());
00250   }
00251 
00252   /// getForwaredType - Return the type that this type has been resolved to if
00253   /// it has been resolved to anything.  This is used to implement the
00254   /// union-find algorithm for type resolution, and shouldn't be used by general
00255   /// purpose clients.
00256   const Type *getForwardedType() const {
00257     if (!ForwardType) return 0;
00258     return getForwardedTypeInternal();
00259   }
00260 
00261   /// getVAArgsPromotedType - Return the type an argument of this type
00262   /// will be promoted to if passed through a variable argument
00263   /// function.
00264   const Type *getVAArgsPromotedType() const {
00265     if (ID == BoolTyID || ID == UByteTyID || ID == UShortTyID)
00266       return Type::UIntTy;
00267     else if (ID == SByteTyID || ID == ShortTyID)
00268       return Type::IntTy;
00269     else if (ID == FloatTyID)
00270       return Type::DoubleTy;
00271     else
00272       return this;
00273   }
00274 
00275   //===--------------------------------------------------------------------===//
00276   // Type Iteration support
00277   //
00278   typedef std::vector<PATypeHandle>::const_iterator subtype_iterator;
00279   subtype_iterator subtype_begin() const { return ContainedTys.begin(); }
00280   subtype_iterator subtype_end() const { return ContainedTys.end(); }
00281 
00282   /// getContainedType - This method is used to implement the type iterator
00283   /// (defined a the end of the file).  For derived types, this returns the
00284   /// types 'contained' in the derived type.
00285   ///
00286   const Type *getContainedType(unsigned i) const {
00287     assert(i < ContainedTys.size() && "Index out of range!");
00288     return ContainedTys[i];
00289   }
00290 
00291   /// getNumContainedTypes - Return the number of types in the derived type.
00292   ///
00293   typedef std::vector<PATypeHandle>::size_type size_type;
00294   size_type getNumContainedTypes() const { return ContainedTys.size(); }
00295 
00296   //===--------------------------------------------------------------------===//
00297   // Static members exported by the Type class itself.  Useful for getting
00298   // instances of Type.
00299   //
00300 
00301   /// getPrimitiveType - Return a type based on an identifier.
00302   static const Type *getPrimitiveType(TypeID IDNumber);
00303 
00304   //===--------------------------------------------------------------------===//
00305   // These are the builtin types that are always available...
00306   //
00307   static Type *VoidTy , *BoolTy;
00308   static Type *SByteTy, *UByteTy,
00309               *ShortTy, *UShortTy,
00310               *IntTy  , *UIntTy,
00311               *LongTy , *ULongTy;
00312   static Type *FloatTy, *DoubleTy;
00313 
00314   static Type* LabelTy;
00315 
00316   /// Methods for support type inquiry through isa, cast, and dyn_cast:
00317   static inline bool classof(const Type *T) { return true; }
00318 
00319   void addRef() const {
00320     assert(isAbstract() && "Cannot add a reference to a non-abstract type!");
00321     ++RefCount;
00322   }
00323 
00324   void dropRef() const {
00325     assert(isAbstract() && "Cannot drop a reference to a non-abstract type!");
00326     assert(RefCount && "No objects are currently referencing this object!");
00327 
00328     // If this is the last PATypeHolder using this object, and there are no
00329     // PATypeHandles using it, the type is dead, delete it now.
00330     if (--RefCount == 0 && AbstractTypeUsers.empty())
00331       delete this;
00332   }
00333   
00334   /// addAbstractTypeUser - Notify an abstract type that there is a new user of
00335   /// it.  This function is called primarily by the PATypeHandle class.
00336   ///
00337   void addAbstractTypeUser(AbstractTypeUser *U) const {
00338     assert(isAbstract() && "addAbstractTypeUser: Current type not abstract!");
00339     AbstractTypeUsers.push_back(U);
00340   }
00341   
00342   /// removeAbstractTypeUser - Notify an abstract type that a user of the class
00343   /// no longer has a handle to the type.  This function is called primarily by
00344   /// the PATypeHandle class.  When there are no users of the abstract type, it
00345   /// is annihilated, because there is no way to get a reference to it ever
00346   /// again.
00347   ///
00348   void removeAbstractTypeUser(AbstractTypeUser *U) const;
00349 
00350   /// clearAllTypeMaps - This method frees all internal memory used by the
00351   /// type subsystem, which can be used in environments where this memory is
00352   /// otherwise reported as a leak.
00353   static void clearAllTypeMaps();
00354 
00355 private:
00356   /// isSizedDerivedType - Derived types like structures and arrays are sized
00357   /// iff all of the members of the type are sized as well.  Since asking for
00358   /// their size is relatively uncommon, move this operation out of line.
00359   bool isSizedDerivedType() const;
00360 
00361   virtual void refineAbstractType(const DerivedType *OldTy, const Type *NewTy);
00362   virtual void typeBecameConcrete(const DerivedType *AbsTy);
00363 
00364 protected:
00365   // PromoteAbstractToConcrete - This is an internal method used to calculate
00366   // change "Abstract" from true to false when types are refined.
00367   void PromoteAbstractToConcrete();
00368   friend class TypeMapBase;
00369 };
00370 
00371 //===----------------------------------------------------------------------===//
00372 // Define some inline methods for the AbstractTypeUser.h:PATypeHandle class.
00373 // These are defined here because they MUST be inlined, yet are dependent on
00374 // the definition of the Type class.  Of course Type derives from Value, which
00375 // contains an AbstractTypeUser instance, so there is no good way to factor out
00376 // the code.  Hence this bit of uglyness.
00377 //
00378 // In the long term, Type should not derive from Value, allowing
00379 // AbstractTypeUser.h to #include Type.h, allowing us to eliminate this
00380 // nastyness entirely.
00381 //
00382 inline void PATypeHandle::addUser() {
00383   assert(Ty && "Type Handle has a null type!");
00384   if (Ty->isAbstract())
00385     Ty->addAbstractTypeUser(User);
00386 }
00387 inline void PATypeHandle::removeUser() {
00388   if (Ty->isAbstract())
00389     Ty->removeAbstractTypeUser(User);
00390 }
00391 
00392 // Define inline methods for PATypeHolder...
00393 
00394 inline void PATypeHolder::addRef() {
00395   if (Ty->isAbstract())
00396     Ty->addRef();
00397 }
00398 
00399 inline void PATypeHolder::dropRef() {
00400   if (Ty->isAbstract())
00401     Ty->dropRef();
00402 }
00403 
00404 
00405 //===----------------------------------------------------------------------===//
00406 // Provide specializations of GraphTraits to be able to treat a type as a
00407 // graph of sub types...
00408 
00409 template <> struct GraphTraits<Type*> {
00410   typedef Type NodeType;
00411   typedef Type::subtype_iterator ChildIteratorType;
00412 
00413   static inline NodeType *getEntryNode(Type *T) { return T; }
00414   static inline ChildIteratorType child_begin(NodeType *N) {
00415     return N->subtype_begin();
00416   }
00417   static inline ChildIteratorType child_end(NodeType *N) {
00418     return N->subtype_end();
00419   }
00420 };
00421 
00422 template <> struct GraphTraits<const Type*> {
00423   typedef const Type NodeType;
00424   typedef Type::subtype_iterator ChildIteratorType;
00425 
00426   static inline NodeType *getEntryNode(const Type *T) { return T; }
00427   static inline ChildIteratorType child_begin(NodeType *N) {
00428     return N->subtype_begin();
00429   }
00430   static inline ChildIteratorType child_end(NodeType *N) {
00431     return N->subtype_end();
00432   }
00433 };
00434 
00435 template <> inline bool isa_impl<PointerType, Type>(const Type &Ty) {
00436   return Ty.getTypeID() == Type::PointerTyID;
00437 }
00438 
00439 std::ostream &operator<<(std::ostream &OS, const Type &T);
00440 
00441 } // End llvm namespace
00442 
00443 #endif