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