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