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