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