MDNodes that refer to an instruction are local to a function; in that case, explicitl...
[oota-llvm.git] / lib / VMCore / Type.cpp
1 //===-- Type.cpp - Implement the Type class -------------------------------===//
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 // This file implements the Type class for the VMCore library.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "LLVMContextImpl.h"
15 #include "llvm/DerivedTypes.h"
16 #include "llvm/Constants.h"
17 #include "llvm/Assembly/Writer.h"
18 #include "llvm/LLVMContext.h"
19 #include "llvm/Metadata.h"
20 #include "llvm/ADT/DepthFirstIterator.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/ADT/SCCIterator.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/Support/Compiler.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/ManagedStatic.h"
28 #include "llvm/Support/MathExtras.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/System/Threading.h"
31 #include <algorithm>
32 #include <cstdarg>
33 using namespace llvm;
34
35 // DEBUG_MERGE_TYPES - Enable this #define to see how and when derived types are
36 // created and later destroyed, all in an effort to make sure that there is only
37 // a single canonical version of a type.
38 //
39 // #define DEBUG_MERGE_TYPES 1
40
41 AbstractTypeUser::~AbstractTypeUser() {}
42
43 void AbstractTypeUser::setType(Value *V, const Type *NewTy) {
44   V->VTy = NewTy;
45 }
46
47 //===----------------------------------------------------------------------===//
48 //                         Type Class Implementation
49 //===----------------------------------------------------------------------===//
50
51 /// Because of the way Type subclasses are allocated, this function is necessary
52 /// to use the correct kind of "delete" operator to deallocate the Type object.
53 /// Some type objects (FunctionTy, StructTy) allocate additional space after 
54 /// the space for their derived type to hold the contained types array of
55 /// PATypeHandles. Using this allocation scheme means all the PATypeHandles are
56 /// allocated with the type object, decreasing allocations and eliminating the
57 /// need for a std::vector to be used in the Type class itself. 
58 /// @brief Type destruction function
59 void Type::destroy() const {
60
61   // Structures and Functions allocate their contained types past the end of
62   // the type object itself. These need to be destroyed differently than the
63   // other types.
64   if (isa<FunctionType>(this) || isa<StructType>(this)) {
65     // First, make sure we destruct any PATypeHandles allocated by these
66     // subclasses.  They must be manually destructed. 
67     for (unsigned i = 0; i < NumContainedTys; ++i)
68       ContainedTys[i].PATypeHandle::~PATypeHandle();
69
70     // Now call the destructor for the subclass directly because we're going
71     // to delete this as an array of char.
72     if (isa<FunctionType>(this))
73       static_cast<const FunctionType*>(this)->FunctionType::~FunctionType();
74     else
75       static_cast<const StructType*>(this)->StructType::~StructType();
76
77     // Finally, remove the memory as an array deallocation of the chars it was
78     // constructed from.
79     operator delete(const_cast<Type *>(this));
80
81     return;
82   }
83
84   // For all the other type subclasses, there is either no contained types or 
85   // just one (all Sequentials). For Sequentials, the PATypeHandle is not
86   // allocated past the type object, its included directly in the SequentialType
87   // class. This means we can safely just do "normal" delete of this object and
88   // all the destructors that need to run will be run.
89   delete this; 
90 }
91
92 const Type *Type::getPrimitiveType(LLVMContext &C, TypeID IDNumber) {
93   switch (IDNumber) {
94   case VoidTyID      : return getVoidTy(C);
95   case FloatTyID     : return getFloatTy(C);
96   case DoubleTyID    : return getDoubleTy(C);
97   case X86_FP80TyID  : return getX86_FP80Ty(C);
98   case FP128TyID     : return getFP128Ty(C);
99   case PPC_FP128TyID : return getPPC_FP128Ty(C);
100   case LabelTyID     : return getLabelTy(C);
101   case MetadataTyID  : return getMetadataTy(C);
102   default:
103     return 0;
104   }
105 }
106
107 const Type *Type::getVAArgsPromotedType(LLVMContext &C) const {
108   if (ID == IntegerTyID && getSubclassData() < 32)
109     return Type::getInt32Ty(C);
110   else if (ID == FloatTyID)
111     return Type::getDoubleTy(C);
112   else
113     return this;
114 }
115
116 /// getScalarType - If this is a vector type, return the element type,
117 /// otherwise return this.
118 const Type *Type::getScalarType() const {
119   if (const VectorType *VTy = dyn_cast<VectorType>(this))
120     return VTy->getElementType();
121   return this;
122 }
123
124 /// isIntOrIntVector - Return true if this is an integer type or a vector of
125 /// integer types.
126 ///
127 bool Type::isIntOrIntVector() const {
128   if (isInteger())
129     return true;
130   if (ID != Type::VectorTyID) return false;
131   
132   return cast<VectorType>(this)->getElementType()->isInteger();
133 }
134
135 /// isFPOrFPVector - Return true if this is a FP type or a vector of FP types.
136 ///
137 bool Type::isFPOrFPVector() const {
138   if (ID == Type::FloatTyID || ID == Type::DoubleTyID || 
139       ID == Type::FP128TyID || ID == Type::X86_FP80TyID || 
140       ID == Type::PPC_FP128TyID)
141     return true;
142   if (ID != Type::VectorTyID) return false;
143   
144   return cast<VectorType>(this)->getElementType()->isFloatingPoint();
145 }
146
147 // canLosslesslyBitCastTo - Return true if this type can be converted to
148 // 'Ty' without any reinterpretation of bits.  For example, i8* to i32*.
149 //
150 bool Type::canLosslesslyBitCastTo(const Type *Ty) const {
151   // Identity cast means no change so return true
152   if (this == Ty) 
153     return true;
154   
155   // They are not convertible unless they are at least first class types
156   if (!this->isFirstClassType() || !Ty->isFirstClassType())
157     return false;
158
159   // Vector -> Vector conversions are always lossless if the two vector types
160   // have the same size, otherwise not.
161   if (const VectorType *thisPTy = dyn_cast<VectorType>(this))
162     if (const VectorType *thatPTy = dyn_cast<VectorType>(Ty))
163       return thisPTy->getBitWidth() == thatPTy->getBitWidth();
164
165   // At this point we have only various mismatches of the first class types
166   // remaining and ptr->ptr. Just select the lossless conversions. Everything
167   // else is not lossless.
168   if (isa<PointerType>(this))
169     return isa<PointerType>(Ty);
170   return false;  // Other types have no identity values
171 }
172
173 unsigned Type::getPrimitiveSizeInBits() const {
174   switch (getTypeID()) {
175   case Type::FloatTyID: return 32;
176   case Type::DoubleTyID: return 64;
177   case Type::X86_FP80TyID: return 80;
178   case Type::FP128TyID: return 128;
179   case Type::PPC_FP128TyID: return 128;
180   case Type::IntegerTyID: return cast<IntegerType>(this)->getBitWidth();
181   case Type::VectorTyID:  return cast<VectorType>(this)->getBitWidth();
182   default: return 0;
183   }
184 }
185
186 /// getScalarSizeInBits - If this is a vector type, return the
187 /// getPrimitiveSizeInBits value for the element type. Otherwise return the
188 /// getPrimitiveSizeInBits value for this type.
189 unsigned Type::getScalarSizeInBits() const {
190   return getScalarType()->getPrimitiveSizeInBits();
191 }
192
193 /// getFPMantissaWidth - Return the width of the mantissa of this type.  This
194 /// is only valid on floating point types.  If the FP type does not
195 /// have a stable mantissa (e.g. ppc long double), this method returns -1.
196 int Type::getFPMantissaWidth() const {
197   if (const VectorType *VTy = dyn_cast<VectorType>(this))
198     return VTy->getElementType()->getFPMantissaWidth();
199   assert(isFloatingPoint() && "Not a floating point type!");
200   if (ID == FloatTyID) return 24;
201   if (ID == DoubleTyID) return 53;
202   if (ID == X86_FP80TyID) return 64;
203   if (ID == FP128TyID) return 113;
204   assert(ID == PPC_FP128TyID && "unknown fp type");
205   return -1;
206 }
207
208 /// isSizedDerivedType - Derived types like structures and arrays are sized
209 /// iff all of the members of the type are sized as well.  Since asking for
210 /// their size is relatively uncommon, move this operation out of line.
211 bool Type::isSizedDerivedType() const {
212   if (isa<IntegerType>(this))
213     return true;
214
215   if (const ArrayType *ATy = dyn_cast<ArrayType>(this))
216     return ATy->getElementType()->isSized();
217
218   if (const VectorType *PTy = dyn_cast<VectorType>(this))
219     return PTy->getElementType()->isSized();
220
221   if (!isa<StructType>(this)) 
222     return false;
223
224   // Okay, our struct is sized if all of the elements are...
225   for (subtype_iterator I = subtype_begin(), E = subtype_end(); I != E; ++I)
226     if (!(*I)->isSized()) 
227       return false;
228
229   return true;
230 }
231
232 /// getForwardedTypeInternal - This method is used to implement the union-find
233 /// algorithm for when a type is being forwarded to another type.
234 const Type *Type::getForwardedTypeInternal() const {
235   assert(ForwardType && "This type is not being forwarded to another type!");
236
237   // Check to see if the forwarded type has been forwarded on.  If so, collapse
238   // the forwarding links.
239   const Type *RealForwardedType = ForwardType->getForwardedType();
240   if (!RealForwardedType)
241     return ForwardType;  // No it's not forwarded again
242
243   // Yes, it is forwarded again.  First thing, add the reference to the new
244   // forward type.
245   if (RealForwardedType->isAbstract())
246     cast<DerivedType>(RealForwardedType)->addRef();
247
248   // Now drop the old reference.  This could cause ForwardType to get deleted.
249   cast<DerivedType>(ForwardType)->dropRef();
250
251   // Return the updated type.
252   ForwardType = RealForwardedType;
253   return ForwardType;
254 }
255
256 void Type::refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
257   llvm_unreachable("Attempting to refine a derived type!");
258 }
259 void Type::typeBecameConcrete(const DerivedType *AbsTy) {
260   llvm_unreachable("DerivedType is already a concrete type!");
261 }
262
263
264 std::string Type::getDescription() const {
265   LLVMContextImpl *pImpl = getContext().pImpl;
266   TypePrinting &Map =
267     isAbstract() ?
268       pImpl->AbstractTypeDescriptions :
269       pImpl->ConcreteTypeDescriptions;
270   
271   std::string DescStr;
272   raw_string_ostream DescOS(DescStr);
273   Map.print(this, DescOS);
274   return DescOS.str();
275 }
276
277
278 bool StructType::indexValid(const Value *V) const {
279   // Structure indexes require 32-bit integer constants.
280   if (V->getType() == Type::getInt32Ty(V->getContext()))
281     if (const ConstantInt *CU = dyn_cast<ConstantInt>(V))
282       return indexValid(CU->getZExtValue());
283   return false;
284 }
285
286 bool StructType::indexValid(unsigned V) const {
287   return V < NumContainedTys;
288 }
289
290 // getTypeAtIndex - Given an index value into the type, return the type of the
291 // element.  For a structure type, this must be a constant value...
292 //
293 const Type *StructType::getTypeAtIndex(const Value *V) const {
294   unsigned Idx = (unsigned)cast<ConstantInt>(V)->getZExtValue();
295   return getTypeAtIndex(Idx);
296 }
297
298 const Type *StructType::getTypeAtIndex(unsigned Idx) const {
299   assert(indexValid(Idx) && "Invalid structure index!");
300   return ContainedTys[Idx];
301 }
302
303 //===----------------------------------------------------------------------===//
304 //                          Primitive 'Type' data
305 //===----------------------------------------------------------------------===//
306
307 const Type *Type::getVoidTy(LLVMContext &C) {
308   return &C.pImpl->VoidTy;
309 }
310
311 const Type *Type::getLabelTy(LLVMContext &C) {
312   return &C.pImpl->LabelTy;
313 }
314
315 const Type *Type::getFloatTy(LLVMContext &C) {
316   return &C.pImpl->FloatTy;
317 }
318
319 const Type *Type::getDoubleTy(LLVMContext &C) {
320   return &C.pImpl->DoubleTy;
321 }
322
323 const Type *Type::getMetadataTy(LLVMContext &C) {
324   return &C.pImpl->MetadataTy;
325 }
326
327 const Type *Type::getX86_FP80Ty(LLVMContext &C) {
328   return &C.pImpl->X86_FP80Ty;
329 }
330
331 const Type *Type::getFP128Ty(LLVMContext &C) {
332   return &C.pImpl->FP128Ty;
333 }
334
335 const Type *Type::getPPC_FP128Ty(LLVMContext &C) {
336   return &C.pImpl->PPC_FP128Ty;
337 }
338
339 const IntegerType *Type::getInt1Ty(LLVMContext &C) {
340   return &C.pImpl->Int1Ty;
341 }
342
343 const IntegerType *Type::getInt8Ty(LLVMContext &C) {
344   return &C.pImpl->Int8Ty;
345 }
346
347 const IntegerType *Type::getInt16Ty(LLVMContext &C) {
348   return &C.pImpl->Int16Ty;
349 }
350
351 const IntegerType *Type::getInt32Ty(LLVMContext &C) {
352   return &C.pImpl->Int32Ty;
353 }
354
355 const IntegerType *Type::getInt64Ty(LLVMContext &C) {
356   return &C.pImpl->Int64Ty;
357 }
358
359 const PointerType *Type::getFloatPtrTy(LLVMContext &C, unsigned AS) {
360   return getFloatTy(C)->getPointerTo(AS);
361 }
362
363 const PointerType *Type::getDoublePtrTy(LLVMContext &C, unsigned AS) {
364   return getDoubleTy(C)->getPointerTo(AS);
365 }
366
367 const PointerType *Type::getX86_FP80PtrTy(LLVMContext &C, unsigned AS) {
368   return getX86_FP80Ty(C)->getPointerTo(AS);
369 }
370
371 const PointerType *Type::getFP128PtrTy(LLVMContext &C, unsigned AS) {
372   return getFP128Ty(C)->getPointerTo(AS);
373 }
374
375 const PointerType *Type::getPPC_FP128PtrTy(LLVMContext &C, unsigned AS) {
376   return getPPC_FP128Ty(C)->getPointerTo(AS);
377 }
378
379 const PointerType *Type::getInt1PtrTy(LLVMContext &C, unsigned AS) {
380   return getInt1Ty(C)->getPointerTo(AS);
381 }
382
383 const PointerType *Type::getInt8PtrTy(LLVMContext &C, unsigned AS) {
384   return getInt8Ty(C)->getPointerTo(AS);
385 }
386
387 const PointerType *Type::getInt16PtrTy(LLVMContext &C, unsigned AS) {
388   return getInt16Ty(C)->getPointerTo(AS);
389 }
390
391 const PointerType *Type::getInt32PtrTy(LLVMContext &C, unsigned AS) {
392   return getInt32Ty(C)->getPointerTo(AS);
393 }
394
395 const PointerType *Type::getInt64PtrTy(LLVMContext &C, unsigned AS) {
396   return getInt64Ty(C)->getPointerTo(AS);
397 }
398
399 //===----------------------------------------------------------------------===//
400 //                          Derived Type Constructors
401 //===----------------------------------------------------------------------===//
402
403 /// isValidReturnType - Return true if the specified type is valid as a return
404 /// type.
405 bool FunctionType::isValidReturnType(const Type *RetTy) {
406   return RetTy->getTypeID() != LabelTyID &&
407          RetTy->getTypeID() != MetadataTyID;
408 }
409
410 /// isValidArgumentType - Return true if the specified type is valid as an
411 /// argument type.
412 bool FunctionType::isValidArgumentType(const Type *ArgTy) {
413   return ArgTy->isFirstClassType() || isa<OpaqueType>(ArgTy);
414 }
415
416 FunctionType::FunctionType(const Type *Result,
417                            const std::vector<const Type*> &Params,
418                            bool IsVarArgs)
419   : DerivedType(Result->getContext(), FunctionTyID), isVarArgs(IsVarArgs) {
420   ContainedTys = reinterpret_cast<PATypeHandle*>(this+1);
421   NumContainedTys = Params.size() + 1; // + 1 for result type
422   assert(isValidReturnType(Result) && "invalid return type for function");
423
424
425   bool isAbstract = Result->isAbstract();
426   new (&ContainedTys[0]) PATypeHandle(Result, this);
427
428   for (unsigned i = 0; i != Params.size(); ++i) {
429     assert(isValidArgumentType(Params[i]) &&
430            "Not a valid type for function argument!");
431     new (&ContainedTys[i+1]) PATypeHandle(Params[i], this);
432     isAbstract |= Params[i]->isAbstract();
433   }
434
435   // Calculate whether or not this type is abstract
436   setAbstract(isAbstract);
437 }
438
439 StructType::StructType(LLVMContext &C, 
440                        const std::vector<const Type*> &Types, bool isPacked)
441   : CompositeType(C, StructTyID) {
442   ContainedTys = reinterpret_cast<PATypeHandle*>(this + 1);
443   NumContainedTys = Types.size();
444   setSubclassData(isPacked);
445   bool isAbstract = false;
446   for (unsigned i = 0; i < Types.size(); ++i) {
447     assert(Types[i] && "<null> type for structure field!");
448     assert(isValidElementType(Types[i]) &&
449            "Invalid type for structure element!");
450     new (&ContainedTys[i]) PATypeHandle(Types[i], this);
451     isAbstract |= Types[i]->isAbstract();
452   }
453
454   // Calculate whether or not this type is abstract
455   setAbstract(isAbstract);
456 }
457
458 ArrayType::ArrayType(const Type *ElType, uint64_t NumEl)
459   : SequentialType(ArrayTyID, ElType) {
460   NumElements = NumEl;
461
462   // Calculate whether or not this type is abstract
463   setAbstract(ElType->isAbstract());
464 }
465
466 VectorType::VectorType(const Type *ElType, unsigned NumEl)
467   : SequentialType(VectorTyID, ElType) {
468   NumElements = NumEl;
469   setAbstract(ElType->isAbstract());
470   assert(NumEl > 0 && "NumEl of a VectorType must be greater than 0");
471   assert(isValidElementType(ElType) &&
472          "Elements of a VectorType must be a primitive type");
473
474 }
475
476
477 PointerType::PointerType(const Type *E, unsigned AddrSpace)
478   : SequentialType(PointerTyID, E) {
479   AddressSpace = AddrSpace;
480   // Calculate whether or not this type is abstract
481   setAbstract(E->isAbstract());
482 }
483
484 OpaqueType::OpaqueType(LLVMContext &C) : DerivedType(C, OpaqueTyID) {
485   setAbstract(true);
486 #ifdef DEBUG_MERGE_TYPES
487   DEBUG(errs() << "Derived new type: " << *this << "\n");
488 #endif
489 }
490
491 void PATypeHolder::destroy() {
492   Ty = 0;
493 }
494
495 // dropAllTypeUses - When this (abstract) type is resolved to be equal to
496 // another (more concrete) type, we must eliminate all references to other
497 // types, to avoid some circular reference problems.
498 void DerivedType::dropAllTypeUses() {
499   if (NumContainedTys != 0) {
500     // The type must stay abstract.  To do this, we insert a pointer to a type
501     // that will never get resolved, thus will always be abstract.
502     static Type *AlwaysOpaqueTy = 0;
503     static PATypeHolder* Holder = 0;
504     Type *tmp = AlwaysOpaqueTy;
505     if (llvm_is_multithreaded()) {
506       sys::MemoryFence();
507       if (!tmp) {
508         llvm_acquire_global_lock();
509         tmp = AlwaysOpaqueTy;
510         if (!tmp) {
511           tmp = OpaqueType::get(getContext());
512           PATypeHolder* tmp2 = new PATypeHolder(tmp);
513           sys::MemoryFence();
514           AlwaysOpaqueTy = tmp;
515           Holder = tmp2;
516         }
517       
518         llvm_release_global_lock();
519       }
520     } else if (!AlwaysOpaqueTy) {
521       AlwaysOpaqueTy = OpaqueType::get(getContext());
522       Holder = new PATypeHolder(AlwaysOpaqueTy);
523     } 
524         
525     ContainedTys[0] = AlwaysOpaqueTy;
526
527     // Change the rest of the types to be Int32Ty's.  It doesn't matter what we
528     // pick so long as it doesn't point back to this type.  We choose something
529     // concrete to avoid overhead for adding to AbstractTypeUser lists and
530     // stuff.
531     const Type *ConcreteTy = Type::getInt32Ty(getContext());
532     for (unsigned i = 1, e = NumContainedTys; i != e; ++i)
533       ContainedTys[i] = ConcreteTy;
534   }
535 }
536
537
538 namespace {
539
540 /// TypePromotionGraph and graph traits - this is designed to allow us to do
541 /// efficient SCC processing of type graphs.  This is the exact same as
542 /// GraphTraits<Type*>, except that we pretend that concrete types have no
543 /// children to avoid processing them.
544 struct TypePromotionGraph {
545   Type *Ty;
546   TypePromotionGraph(Type *T) : Ty(T) {}
547 };
548
549 }
550
551 namespace llvm {
552   template <> struct GraphTraits<TypePromotionGraph> {
553     typedef Type NodeType;
554     typedef Type::subtype_iterator ChildIteratorType;
555
556     static inline NodeType *getEntryNode(TypePromotionGraph G) { return G.Ty; }
557     static inline ChildIteratorType child_begin(NodeType *N) {
558       if (N->isAbstract())
559         return N->subtype_begin();
560       else           // No need to process children of concrete types.
561         return N->subtype_end();
562     }
563     static inline ChildIteratorType child_end(NodeType *N) {
564       return N->subtype_end();
565     }
566   };
567 }
568
569
570 // PromoteAbstractToConcrete - This is a recursive function that walks a type
571 // graph calculating whether or not a type is abstract.
572 //
573 void Type::PromoteAbstractToConcrete() {
574   if (!isAbstract()) return;
575
576   scc_iterator<TypePromotionGraph> SI = scc_begin(TypePromotionGraph(this));
577   scc_iterator<TypePromotionGraph> SE = scc_end  (TypePromotionGraph(this));
578
579   for (; SI != SE; ++SI) {
580     std::vector<Type*> &SCC = *SI;
581
582     // Concrete types are leaves in the tree.  Since an SCC will either be all
583     // abstract or all concrete, we only need to check one type.
584     if (SCC[0]->isAbstract()) {
585       if (isa<OpaqueType>(SCC[0]))
586         return;     // Not going to be concrete, sorry.
587
588       // If all of the children of all of the types in this SCC are concrete,
589       // then this SCC is now concrete as well.  If not, neither this SCC, nor
590       // any parent SCCs will be concrete, so we might as well just exit.
591       for (unsigned i = 0, e = SCC.size(); i != e; ++i)
592         for (Type::subtype_iterator CI = SCC[i]->subtype_begin(),
593                E = SCC[i]->subtype_end(); CI != E; ++CI)
594           if ((*CI)->isAbstract())
595             // If the child type is in our SCC, it doesn't make the entire SCC
596             // abstract unless there is a non-SCC abstract type.
597             if (std::find(SCC.begin(), SCC.end(), *CI) == SCC.end())
598               return;               // Not going to be concrete, sorry.
599
600       // Okay, we just discovered this whole SCC is now concrete, mark it as
601       // such!
602       for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
603         assert(SCC[i]->isAbstract() && "Why are we processing concrete types?");
604
605         SCC[i]->setAbstract(false);
606       }
607
608       for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
609         assert(!SCC[i]->isAbstract() && "Concrete type became abstract?");
610         // The type just became concrete, notify all users!
611         cast<DerivedType>(SCC[i])->notifyUsesThatTypeBecameConcrete();
612       }
613     }
614   }
615 }
616
617
618 //===----------------------------------------------------------------------===//
619 //                      Type Structural Equality Testing
620 //===----------------------------------------------------------------------===//
621
622 // TypesEqual - Two types are considered structurally equal if they have the
623 // same "shape": Every level and element of the types have identical primitive
624 // ID's, and the graphs have the same edges/nodes in them.  Nodes do not have to
625 // be pointer equals to be equivalent though.  This uses an optimistic algorithm
626 // that assumes that two graphs are the same until proven otherwise.
627 //
628 static bool TypesEqual(const Type *Ty, const Type *Ty2,
629                        std::map<const Type *, const Type *> &EqTypes) {
630   if (Ty == Ty2) return true;
631   if (Ty->getTypeID() != Ty2->getTypeID()) return false;
632   if (isa<OpaqueType>(Ty))
633     return false;  // Two unequal opaque types are never equal
634
635   std::map<const Type*, const Type*>::iterator It = EqTypes.find(Ty);
636   if (It != EqTypes.end())
637     return It->second == Ty2;    // Looping back on a type, check for equality
638
639   // Otherwise, add the mapping to the table to make sure we don't get
640   // recursion on the types...
641   EqTypes.insert(It, std::make_pair(Ty, Ty2));
642
643   // Two really annoying special cases that breaks an otherwise nice simple
644   // algorithm is the fact that arraytypes have sizes that differentiates types,
645   // and that function types can be varargs or not.  Consider this now.
646   //
647   if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty)) {
648     const IntegerType *ITy2 = cast<IntegerType>(Ty2);
649     return ITy->getBitWidth() == ITy2->getBitWidth();
650   } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
651     const PointerType *PTy2 = cast<PointerType>(Ty2);
652     return PTy->getAddressSpace() == PTy2->getAddressSpace() &&
653            TypesEqual(PTy->getElementType(), PTy2->getElementType(), EqTypes);
654   } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
655     const StructType *STy2 = cast<StructType>(Ty2);
656     if (STy->getNumElements() != STy2->getNumElements()) return false;
657     if (STy->isPacked() != STy2->isPacked()) return false;
658     for (unsigned i = 0, e = STy2->getNumElements(); i != e; ++i)
659       if (!TypesEqual(STy->getElementType(i), STy2->getElementType(i), EqTypes))
660         return false;
661     return true;
662   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
663     const ArrayType *ATy2 = cast<ArrayType>(Ty2);
664     return ATy->getNumElements() == ATy2->getNumElements() &&
665            TypesEqual(ATy->getElementType(), ATy2->getElementType(), EqTypes);
666   } else if (const VectorType *PTy = dyn_cast<VectorType>(Ty)) {
667     const VectorType *PTy2 = cast<VectorType>(Ty2);
668     return PTy->getNumElements() == PTy2->getNumElements() &&
669            TypesEqual(PTy->getElementType(), PTy2->getElementType(), EqTypes);
670   } else if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
671     const FunctionType *FTy2 = cast<FunctionType>(Ty2);
672     if (FTy->isVarArg() != FTy2->isVarArg() ||
673         FTy->getNumParams() != FTy2->getNumParams() ||
674         !TypesEqual(FTy->getReturnType(), FTy2->getReturnType(), EqTypes))
675       return false;
676     for (unsigned i = 0, e = FTy2->getNumParams(); i != e; ++i) {
677       if (!TypesEqual(FTy->getParamType(i), FTy2->getParamType(i), EqTypes))
678         return false;
679     }
680     return true;
681   } else {
682     llvm_unreachable("Unknown derived type!");
683     return false;
684   }
685 }
686
687 static bool TypesEqual(const Type *Ty, const Type *Ty2) {
688   std::map<const Type *, const Type *> EqTypes;
689   return TypesEqual(Ty, Ty2, EqTypes);
690 }
691
692 // AbstractTypeHasCycleThrough - Return true there is a path from CurTy to
693 // TargetTy in the type graph.  We know that Ty is an abstract type, so if we
694 // ever reach a non-abstract type, we know that we don't need to search the
695 // subgraph.
696 static bool AbstractTypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
697                                 SmallPtrSet<const Type*, 128> &VisitedTypes) {
698   if (TargetTy == CurTy) return true;
699   if (!CurTy->isAbstract()) return false;
700
701   if (!VisitedTypes.insert(CurTy))
702     return false;  // Already been here.
703
704   for (Type::subtype_iterator I = CurTy->subtype_begin(),
705        E = CurTy->subtype_end(); I != E; ++I)
706     if (AbstractTypeHasCycleThrough(TargetTy, *I, VisitedTypes))
707       return true;
708   return false;
709 }
710
711 static bool ConcreteTypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
712                                 SmallPtrSet<const Type*, 128> &VisitedTypes) {
713   if (TargetTy == CurTy) return true;
714
715   if (!VisitedTypes.insert(CurTy))
716     return false;  // Already been here.
717
718   for (Type::subtype_iterator I = CurTy->subtype_begin(),
719        E = CurTy->subtype_end(); I != E; ++I)
720     if (ConcreteTypeHasCycleThrough(TargetTy, *I, VisitedTypes))
721       return true;
722   return false;
723 }
724
725 /// TypeHasCycleThroughItself - Return true if the specified type has a cycle
726 /// back to itself.
727 static bool TypeHasCycleThroughItself(const Type *Ty) {
728   SmallPtrSet<const Type*, 128> VisitedTypes;
729
730   if (Ty->isAbstract()) {  // Optimized case for abstract types.
731     for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
732          I != E; ++I)
733       if (AbstractTypeHasCycleThrough(Ty, *I, VisitedTypes))
734         return true;
735   } else {
736     for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
737          I != E; ++I)
738       if (ConcreteTypeHasCycleThrough(Ty, *I, VisitedTypes))
739         return true;
740   }
741   return false;
742 }
743
744 //===----------------------------------------------------------------------===//
745 // Function Type Factory and Value Class...
746 //
747 const IntegerType *IntegerType::get(LLVMContext &C, unsigned NumBits) {
748   assert(NumBits >= MIN_INT_BITS && "bitwidth too small");
749   assert(NumBits <= MAX_INT_BITS && "bitwidth too large");
750
751   // Check for the built-in integer types
752   switch (NumBits) {
753     case  1: return cast<IntegerType>(Type::getInt1Ty(C));
754     case  8: return cast<IntegerType>(Type::getInt8Ty(C));
755     case 16: return cast<IntegerType>(Type::getInt16Ty(C));
756     case 32: return cast<IntegerType>(Type::getInt32Ty(C));
757     case 64: return cast<IntegerType>(Type::getInt64Ty(C));
758     default: 
759       break;
760   }
761
762   LLVMContextImpl *pImpl = C.pImpl;
763   
764   IntegerValType IVT(NumBits);
765   IntegerType *ITy = 0;
766   
767   // First, see if the type is already in the table, for which
768   // a reader lock suffices.
769   ITy = pImpl->IntegerTypes.get(IVT);
770     
771   if (!ITy) {
772     // Value not found.  Derive a new type!
773     ITy = new IntegerType(C, NumBits);
774     pImpl->IntegerTypes.add(IVT, ITy);
775   }
776 #ifdef DEBUG_MERGE_TYPES
777   DEBUG(errs() << "Derived new type: " << *ITy << "\n");
778 #endif
779   return ITy;
780 }
781
782 bool IntegerType::isPowerOf2ByteWidth() const {
783   unsigned BitWidth = getBitWidth();
784   return (BitWidth > 7) && isPowerOf2_32(BitWidth);
785 }
786
787 APInt IntegerType::getMask() const {
788   return APInt::getAllOnesValue(getBitWidth());
789 }
790
791 FunctionValType FunctionValType::get(const FunctionType *FT) {
792   // Build up a FunctionValType
793   std::vector<const Type *> ParamTypes;
794   ParamTypes.reserve(FT->getNumParams());
795   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
796     ParamTypes.push_back(FT->getParamType(i));
797   return FunctionValType(FT->getReturnType(), ParamTypes, FT->isVarArg());
798 }
799
800
801 // FunctionType::get - The factory function for the FunctionType class...
802 FunctionType *FunctionType::get(const Type *ReturnType,
803                                 const std::vector<const Type*> &Params,
804                                 bool isVarArg) {
805   FunctionValType VT(ReturnType, Params, isVarArg);
806   FunctionType *FT = 0;
807   
808   LLVMContextImpl *pImpl = ReturnType->getContext().pImpl;
809   
810   FT = pImpl->FunctionTypes.get(VT);
811   
812   if (!FT) {
813     FT = (FunctionType*) operator new(sizeof(FunctionType) +
814                                     sizeof(PATypeHandle)*(Params.size()+1));
815     new (FT) FunctionType(ReturnType, Params, isVarArg);
816     pImpl->FunctionTypes.add(VT, FT);
817   }
818
819 #ifdef DEBUG_MERGE_TYPES
820   DEBUG(errs() << "Derived new type: " << FT << "\n");
821 #endif
822   return FT;
823 }
824
825 ArrayType *ArrayType::get(const Type *ElementType, uint64_t NumElements) {
826   assert(ElementType && "Can't get array of <null> types!");
827   assert(isValidElementType(ElementType) && "Invalid type for array element!");
828
829   ArrayValType AVT(ElementType, NumElements);
830   ArrayType *AT = 0;
831
832   LLVMContextImpl *pImpl = ElementType->getContext().pImpl;
833   
834   AT = pImpl->ArrayTypes.get(AVT);
835       
836   if (!AT) {
837     // Value not found.  Derive a new type!
838     pImpl->ArrayTypes.add(AVT, AT = new ArrayType(ElementType, NumElements));
839   }
840 #ifdef DEBUG_MERGE_TYPES
841   DEBUG(errs() << "Derived new type: " << *AT << "\n");
842 #endif
843   return AT;
844 }
845
846 bool ArrayType::isValidElementType(const Type *ElemTy) {
847   return ElemTy->getTypeID() != VoidTyID && ElemTy->getTypeID() != LabelTyID &&
848          ElemTy->getTypeID() != MetadataTyID && !isa<FunctionType>(ElemTy);
849 }
850
851 VectorType *VectorType::get(const Type *ElementType, unsigned NumElements) {
852   assert(ElementType && "Can't get vector of <null> types!");
853
854   VectorValType PVT(ElementType, NumElements);
855   VectorType *PT = 0;
856   
857   LLVMContextImpl *pImpl = ElementType->getContext().pImpl;
858   
859   PT = pImpl->VectorTypes.get(PVT);
860     
861   if (!PT) {
862     pImpl->VectorTypes.add(PVT, PT = new VectorType(ElementType, NumElements));
863   }
864 #ifdef DEBUG_MERGE_TYPES
865   DEBUG(errs() << "Derived new type: " << *PT << "\n");
866 #endif
867   return PT;
868 }
869
870 bool VectorType::isValidElementType(const Type *ElemTy) {
871   return ElemTy->isInteger() || ElemTy->isFloatingPoint() ||
872          isa<OpaqueType>(ElemTy);
873 }
874
875 //===----------------------------------------------------------------------===//
876 // Struct Type Factory...
877 //
878
879 StructType *StructType::get(LLVMContext &Context,
880                             const std::vector<const Type*> &ETypes, 
881                             bool isPacked) {
882   StructValType STV(ETypes, isPacked);
883   StructType *ST = 0;
884   
885   LLVMContextImpl *pImpl = Context.pImpl;
886   
887   ST = pImpl->StructTypes.get(STV);
888     
889   if (!ST) {
890     // Value not found.  Derive a new type!
891     ST = (StructType*) operator new(sizeof(StructType) +
892                                     sizeof(PATypeHandle) * ETypes.size());
893     new (ST) StructType(Context, ETypes, isPacked);
894     pImpl->StructTypes.add(STV, ST);
895   }
896 #ifdef DEBUG_MERGE_TYPES
897   DEBUG(errs() << "Derived new type: " << *ST << "\n");
898 #endif
899   return ST;
900 }
901
902 StructType *StructType::get(LLVMContext &Context, const Type *type, ...) {
903   va_list ap;
904   std::vector<const llvm::Type*> StructFields;
905   va_start(ap, type);
906   while (type) {
907     StructFields.push_back(type);
908     type = va_arg(ap, llvm::Type*);
909   }
910   return llvm::StructType::get(Context, StructFields);
911 }
912
913 bool StructType::isValidElementType(const Type *ElemTy) {
914   return ElemTy->getTypeID() != VoidTyID && ElemTy->getTypeID() != LabelTyID &&
915          ElemTy->getTypeID() != MetadataTyID && !isa<FunctionType>(ElemTy);
916 }
917
918
919 //===----------------------------------------------------------------------===//
920 // Pointer Type Factory...
921 //
922
923 PointerType *PointerType::get(const Type *ValueType, unsigned AddressSpace) {
924   assert(ValueType && "Can't get a pointer to <null> type!");
925   assert(ValueType->getTypeID() != VoidTyID &&
926          "Pointer to void is not valid, use i8* instead!");
927   assert(isValidElementType(ValueType) && "Invalid type for pointer element!");
928   PointerValType PVT(ValueType, AddressSpace);
929
930   PointerType *PT = 0;
931   
932   LLVMContextImpl *pImpl = ValueType->getContext().pImpl;
933   
934   PT = pImpl->PointerTypes.get(PVT);
935   
936   if (!PT) {
937     // Value not found.  Derive a new type!
938     pImpl->PointerTypes.add(PVT, PT = new PointerType(ValueType, AddressSpace));
939   }
940 #ifdef DEBUG_MERGE_TYPES
941   DEBUG(errs() << "Derived new type: " << *PT << "\n");
942 #endif
943   return PT;
944 }
945
946 const PointerType *Type::getPointerTo(unsigned addrs) const {
947   return PointerType::get(this, addrs);
948 }
949
950 bool PointerType::isValidElementType(const Type *ElemTy) {
951   return ElemTy->getTypeID() != VoidTyID &&
952          ElemTy->getTypeID() != LabelTyID &&
953          ElemTy->getTypeID() != MetadataTyID;
954 }
955
956
957 //===----------------------------------------------------------------------===//
958 //                     Derived Type Refinement Functions
959 //===----------------------------------------------------------------------===//
960
961 // addAbstractTypeUser - Notify an abstract type that there is a new user of
962 // it.  This function is called primarily by the PATypeHandle class.
963 void Type::addAbstractTypeUser(AbstractTypeUser *U) const {
964   assert(isAbstract() && "addAbstractTypeUser: Current type not abstract!");
965   AbstractTypeUsers.push_back(U);
966 }
967
968
969 // removeAbstractTypeUser - Notify an abstract type that a user of the class
970 // no longer has a handle to the type.  This function is called primarily by
971 // the PATypeHandle class.  When there are no users of the abstract type, it
972 // is annihilated, because there is no way to get a reference to it ever again.
973 //
974 void Type::removeAbstractTypeUser(AbstractTypeUser *U) const {
975   
976   // Search from back to front because we will notify users from back to
977   // front.  Also, it is likely that there will be a stack like behavior to
978   // users that register and unregister users.
979   //
980   unsigned i;
981   for (i = AbstractTypeUsers.size(); AbstractTypeUsers[i-1] != U; --i)
982     assert(i != 0 && "AbstractTypeUser not in user list!");
983
984   --i;  // Convert to be in range 0 <= i < size()
985   assert(i < AbstractTypeUsers.size() && "Index out of range!");  // Wraparound?
986
987   AbstractTypeUsers.erase(AbstractTypeUsers.begin()+i);
988
989 #ifdef DEBUG_MERGE_TYPES
990   DEBUG(errs() << "  remAbstractTypeUser[" << (void*)this << ", "
991                << *this << "][" << i << "] User = " << U << "\n");
992 #endif
993
994   if (AbstractTypeUsers.empty() && getRefCount() == 0 && isAbstract()) {
995 #ifdef DEBUG_MERGE_TYPES
996     DEBUG(errs() << "DELETEing unused abstract type: <" << *this
997                  << ">[" << (void*)this << "]" << "\n");
998 #endif
999   
1000   this->destroy();
1001   }
1002   
1003 }
1004
1005 // unlockedRefineAbstractTypeTo - This function is used when it is discovered
1006 // that the 'this' abstract type is actually equivalent to the NewType
1007 // specified. This causes all users of 'this' to switch to reference the more 
1008 // concrete type NewType and for 'this' to be deleted.  Only used for internal
1009 // callers.
1010 //
1011 void DerivedType::unlockedRefineAbstractTypeTo(const Type *NewType) {
1012   assert(isAbstract() && "refineAbstractTypeTo: Current type is not abstract!");
1013   assert(this != NewType && "Can't refine to myself!");
1014   assert(ForwardType == 0 && "This type has already been refined!");
1015
1016   LLVMContextImpl *pImpl = getContext().pImpl;
1017
1018   // The descriptions may be out of date.  Conservatively clear them all!
1019   pImpl->AbstractTypeDescriptions.clear();
1020
1021 #ifdef DEBUG_MERGE_TYPES
1022   DEBUG(errs() << "REFINING abstract type [" << (void*)this << " "
1023                << *this << "] to [" << (void*)NewType << " "
1024                << *NewType << "]!\n");
1025 #endif
1026
1027   // Make sure to put the type to be refined to into a holder so that if IT gets
1028   // refined, that we will not continue using a dead reference...
1029   //
1030   PATypeHolder NewTy(NewType);
1031   // Any PATypeHolders referring to this type will now automatically forward to
1032   // the type we are resolved to.
1033   ForwardType = NewType;
1034   if (NewType->isAbstract())
1035     cast<DerivedType>(NewType)->addRef();
1036
1037   // Add a self use of the current type so that we don't delete ourself until
1038   // after the function exits.
1039   //
1040   PATypeHolder CurrentTy(this);
1041
1042   // To make the situation simpler, we ask the subclass to remove this type from
1043   // the type map, and to replace any type uses with uses of non-abstract types.
1044   // This dramatically limits the amount of recursive type trouble we can find
1045   // ourselves in.
1046   dropAllTypeUses();
1047
1048   // Iterate over all of the uses of this type, invoking callback.  Each user
1049   // should remove itself from our use list automatically.  We have to check to
1050   // make sure that NewTy doesn't _become_ 'this'.  If it does, resolving types
1051   // will not cause users to drop off of the use list.  If we resolve to ourself
1052   // we succeed!
1053   //
1054   while (!AbstractTypeUsers.empty() && NewTy != this) {
1055     AbstractTypeUser *User = AbstractTypeUsers.back();
1056
1057     unsigned OldSize = AbstractTypeUsers.size(); OldSize=OldSize;
1058 #ifdef DEBUG_MERGE_TYPES
1059     DEBUG(errs() << " REFINING user " << OldSize-1 << "[" << (void*)User
1060                  << "] of abstract type [" << (void*)this << " "
1061                  << *this << "] to [" << (void*)NewTy.get() << " "
1062                  << *NewTy << "]!\n");
1063 #endif
1064     User->refineAbstractType(this, NewTy);
1065
1066     assert(AbstractTypeUsers.size() != OldSize &&
1067            "AbsTyUser did not remove self from user list!");
1068   }
1069
1070   // If we were successful removing all users from the type, 'this' will be
1071   // deleted when the last PATypeHolder is destroyed or updated from this type.
1072   // This may occur on exit of this function, as the CurrentTy object is
1073   // destroyed.
1074 }
1075
1076 // refineAbstractTypeTo - This function is used by external callers to notify
1077 // us that this abstract type is equivalent to another type.
1078 //
1079 void DerivedType::refineAbstractTypeTo(const Type *NewType) {
1080   // All recursive calls will go through unlockedRefineAbstractTypeTo,
1081   // to avoid deadlock problems.
1082   unlockedRefineAbstractTypeTo(NewType);
1083 }
1084
1085 // notifyUsesThatTypeBecameConcrete - Notify AbstractTypeUsers of this type that
1086 // the current type has transitioned from being abstract to being concrete.
1087 //
1088 void DerivedType::notifyUsesThatTypeBecameConcrete() {
1089 #ifdef DEBUG_MERGE_TYPES
1090   DEBUG(errs() << "typeIsREFINED type: " << (void*)this << " " << *this <<"\n");
1091 #endif
1092
1093   unsigned OldSize = AbstractTypeUsers.size(); OldSize=OldSize;
1094   while (!AbstractTypeUsers.empty()) {
1095     AbstractTypeUser *ATU = AbstractTypeUsers.back();
1096     ATU->typeBecameConcrete(this);
1097
1098     assert(AbstractTypeUsers.size() < OldSize-- &&
1099            "AbstractTypeUser did not remove itself from the use list!");
1100   }
1101 }
1102
1103 // refineAbstractType - Called when a contained type is found to be more
1104 // concrete - this could potentially change us from an abstract type to a
1105 // concrete type.
1106 //
1107 void FunctionType::refineAbstractType(const DerivedType *OldType,
1108                                       const Type *NewType) {
1109   LLVMContextImpl *pImpl = OldType->getContext().pImpl;
1110   pImpl->FunctionTypes.RefineAbstractType(this, OldType, NewType);
1111 }
1112
1113 void FunctionType::typeBecameConcrete(const DerivedType *AbsTy) {
1114   LLVMContextImpl *pImpl = AbsTy->getContext().pImpl;
1115   pImpl->FunctionTypes.TypeBecameConcrete(this, AbsTy);
1116 }
1117
1118
1119 // refineAbstractType - Called when a contained type is found to be more
1120 // concrete - this could potentially change us from an abstract type to a
1121 // concrete type.
1122 //
1123 void ArrayType::refineAbstractType(const DerivedType *OldType,
1124                                    const Type *NewType) {
1125   LLVMContextImpl *pImpl = OldType->getContext().pImpl;
1126   pImpl->ArrayTypes.RefineAbstractType(this, OldType, NewType);
1127 }
1128
1129 void ArrayType::typeBecameConcrete(const DerivedType *AbsTy) {
1130   LLVMContextImpl *pImpl = AbsTy->getContext().pImpl;
1131   pImpl->ArrayTypes.TypeBecameConcrete(this, AbsTy);
1132 }
1133
1134 // refineAbstractType - Called when a contained type is found to be more
1135 // concrete - this could potentially change us from an abstract type to a
1136 // concrete type.
1137 //
1138 void VectorType::refineAbstractType(const DerivedType *OldType,
1139                                    const Type *NewType) {
1140   LLVMContextImpl *pImpl = OldType->getContext().pImpl;
1141   pImpl->VectorTypes.RefineAbstractType(this, OldType, NewType);
1142 }
1143
1144 void VectorType::typeBecameConcrete(const DerivedType *AbsTy) {
1145   LLVMContextImpl *pImpl = AbsTy->getContext().pImpl;
1146   pImpl->VectorTypes.TypeBecameConcrete(this, AbsTy);
1147 }
1148
1149 // refineAbstractType - Called when a contained type is found to be more
1150 // concrete - this could potentially change us from an abstract type to a
1151 // concrete type.
1152 //
1153 void StructType::refineAbstractType(const DerivedType *OldType,
1154                                     const Type *NewType) {
1155   LLVMContextImpl *pImpl = OldType->getContext().pImpl;
1156   pImpl->StructTypes.RefineAbstractType(this, OldType, NewType);
1157 }
1158
1159 void StructType::typeBecameConcrete(const DerivedType *AbsTy) {
1160   LLVMContextImpl *pImpl = AbsTy->getContext().pImpl;
1161   pImpl->StructTypes.TypeBecameConcrete(this, AbsTy);
1162 }
1163
1164 // refineAbstractType - Called when a contained type is found to be more
1165 // concrete - this could potentially change us from an abstract type to a
1166 // concrete type.
1167 //
1168 void PointerType::refineAbstractType(const DerivedType *OldType,
1169                                      const Type *NewType) {
1170   LLVMContextImpl *pImpl = OldType->getContext().pImpl;
1171   pImpl->PointerTypes.RefineAbstractType(this, OldType, NewType);
1172 }
1173
1174 void PointerType::typeBecameConcrete(const DerivedType *AbsTy) {
1175   LLVMContextImpl *pImpl = AbsTy->getContext().pImpl;
1176   pImpl->PointerTypes.TypeBecameConcrete(this, AbsTy);
1177 }
1178
1179 bool SequentialType::indexValid(const Value *V) const {
1180   if (isa<IntegerType>(V->getType())) 
1181     return true;
1182   return false;
1183 }
1184
1185 namespace llvm {
1186 raw_ostream &operator<<(raw_ostream &OS, const Type &T) {
1187   T.print(OS);
1188   return OS;
1189 }
1190 }