1 //===-- Type.cpp - Implement the Type class -------------------------------===//
3 // This file implements the Type class for the VMCore library.
5 //===----------------------------------------------------------------------===//
7 #include "llvm/DerivedTypes.h"
8 #include "llvm/SymbolTable.h"
9 #include "llvm/Constants.h"
10 #include "Support/StringExtras.h"
11 #include "Support/STLExtras.h"
14 // DEBUG_MERGE_TYPES - Enable this #define to see how and when derived types are
15 // created and later destroyed, all in an effort to make sure that there is only
16 // a single canonical version of a type.
18 //#define DEBUG_MERGE_TYPES 1
21 //===----------------------------------------------------------------------===//
22 // Type Class Implementation
23 //===----------------------------------------------------------------------===//
25 static unsigned CurUID = 0;
26 static std::vector<const Type *> UIDMappings;
28 // Concrete/Abstract TypeDescriptions - We lazily calculate type descriptions
29 // for types as they are needed. Because resolution of types must invalidate
30 // all of the abstract type descriptions, we keep them in a seperate map to make
32 static std::map<const Type*, std::string> ConcreteTypeDescriptions;
33 static std::map<const Type*, std::string> AbstractTypeDescriptions;
35 void PATypeHolder::dump() const {
36 std::cerr << "PATypeHolder(" << (void*)this << ")\n";
40 Type::Type(const std::string &name, PrimitiveID id)
41 : Value(Type::TypeTy, Value::TypeVal) {
43 ConcreteTypeDescriptions[this] = name;
46 UID = CurUID++; // Assign types UID's as they are created
47 UIDMappings.push_back(this);
50 void Type::setName(const std::string &Name, SymbolTable *ST) {
51 assert(ST && "Type::setName - Must provide symbol table argument!");
53 if (Name.size()) ST->insert(Name, this);
57 const Type *Type::getUniqueIDType(unsigned UID) {
58 assert(UID < UIDMappings.size() &&
59 "Type::getPrimitiveType: UID out of range!");
60 return UIDMappings[UID];
63 const Type *Type::getPrimitiveType(PrimitiveID IDNumber) {
65 case VoidTyID : return VoidTy;
66 case BoolTyID : return BoolTy;
67 case UByteTyID : return UByteTy;
68 case SByteTyID : return SByteTy;
69 case UShortTyID: return UShortTy;
70 case ShortTyID : return ShortTy;
71 case UIntTyID : return UIntTy;
72 case IntTyID : return IntTy;
73 case ULongTyID : return ULongTy;
74 case LongTyID : return LongTy;
75 case FloatTyID : return FloatTy;
76 case DoubleTyID: return DoubleTy;
77 case TypeTyID : return TypeTy;
78 case LabelTyID : return LabelTy;
84 // isLosslesslyConvertibleTo - Return true if this type can be converted to
85 // 'Ty' without any reinterpretation of bits. For example, uint to int.
87 bool Type::isLosslesslyConvertibleTo(const Type *Ty) const {
88 if (this == Ty) return true;
89 if ((!isPrimitiveType() && !isa<PointerType>(this)) ||
90 (!isa<PointerType>(Ty) && !Ty->isPrimitiveType())) return false;
92 if (getPrimitiveID() == Ty->getPrimitiveID())
93 return true; // Handles identity cast, and cast of differing pointer types
95 // Now we know that they are two differing primitive or pointer types
96 switch (getPrimitiveID()) {
97 case Type::UByteTyID: return Ty == Type::SByteTy;
98 case Type::SByteTyID: return Ty == Type::UByteTy;
99 case Type::UShortTyID: return Ty == Type::ShortTy;
100 case Type::ShortTyID: return Ty == Type::UShortTy;
101 case Type::UIntTyID: return Ty == Type::IntTy;
102 case Type::IntTyID: return Ty == Type::UIntTy;
103 case Type::ULongTyID:
105 case Type::PointerTyID:
106 return Ty == Type::ULongTy || Ty == Type::LongTy || isa<PointerType>(Ty);
108 return false; // Other types have no identity values
112 // getPrimitiveSize - Return the basic size of this type if it is a primative
113 // type. These are fixed by LLVM and are not target dependent. This will
114 // return zero if the type does not have a size or is not a primitive type.
116 unsigned Type::getPrimitiveSize() const {
117 switch (getPrimitiveID()) {
118 #define HANDLE_PRIM_TYPE(TY,SIZE) case TY##TyID: return SIZE;
119 #include "llvm/Type.def"
125 // getTypeDescription - This is a recursive function that walks a type hierarchy
126 // calculating the description for a type.
128 static std::string getTypeDescription(const Type *Ty,
129 std::vector<const Type *> &TypeStack) {
130 if (isa<OpaqueType>(Ty)) { // Base case for the recursion
131 std::map<const Type*, std::string>::iterator I =
132 AbstractTypeDescriptions.lower_bound(Ty);
133 if (I != AbstractTypeDescriptions.end() && I->first == Ty)
135 std::string Desc = "opaque"+utostr(Ty->getUniqueID());
136 AbstractTypeDescriptions.insert(std::make_pair(Ty, Desc));
140 if (!Ty->isAbstract()) { // Base case for the recursion
141 std::map<const Type*, std::string>::iterator I =
142 ConcreteTypeDescriptions.find(Ty);
143 if (I != ConcreteTypeDescriptions.end()) return I->second;
146 // Check to see if the Type is already on the stack...
147 unsigned Slot = 0, CurSize = TypeStack.size();
148 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
150 // This is another base case for the recursion. In this case, we know
151 // that we have looped back to a type that we have previously visited.
152 // Generate the appropriate upreference to handle this.
155 return "\\" + utostr(CurSize-Slot); // Here's the upreference
157 // Recursive case: derived types...
159 TypeStack.push_back(Ty); // Add us to the stack..
161 switch (Ty->getPrimitiveID()) {
162 case Type::FunctionTyID: {
163 const FunctionType *FTy = cast<FunctionType>(Ty);
164 Result = getTypeDescription(FTy->getReturnType(), TypeStack) + " (";
165 for (FunctionType::ParamTypes::const_iterator
166 I = FTy->getParamTypes().begin(),
167 E = FTy->getParamTypes().end(); I != E; ++I) {
168 if (I != FTy->getParamTypes().begin())
170 Result += getTypeDescription(*I, TypeStack);
172 if (FTy->isVarArg()) {
173 if (!FTy->getParamTypes().empty()) Result += ", ";
179 case Type::StructTyID: {
180 const StructType *STy = cast<StructType>(Ty);
182 for (StructType::ElementTypes::const_iterator
183 I = STy->getElementTypes().begin(),
184 E = STy->getElementTypes().end(); I != E; ++I) {
185 if (I != STy->getElementTypes().begin())
187 Result += getTypeDescription(*I, TypeStack);
192 case Type::PointerTyID: {
193 const PointerType *PTy = cast<PointerType>(Ty);
194 Result = getTypeDescription(PTy->getElementType(), TypeStack) + " *";
197 case Type::ArrayTyID: {
198 const ArrayType *ATy = cast<ArrayType>(Ty);
199 unsigned NumElements = ATy->getNumElements();
201 Result += utostr(NumElements) + " x ";
202 Result += getTypeDescription(ATy->getElementType(), TypeStack) + "]";
207 assert(0 && "Unhandled type in getTypeDescription!");
210 TypeStack.pop_back(); // Remove self from stack...
217 static const std::string &getOrCreateDesc(std::map<const Type*,std::string>&Map,
219 std::map<const Type*, std::string>::iterator I = Map.find(Ty);
220 if (I != Map.end()) return I->second;
222 std::vector<const Type *> TypeStack;
223 return Map[Ty] = getTypeDescription(Ty, TypeStack);
227 const std::string &Type::getDescription() const {
229 return getOrCreateDesc(AbstractTypeDescriptions, this);
231 return getOrCreateDesc(ConcreteTypeDescriptions, this);
235 bool StructType::indexValid(const Value *V) const {
236 if (!isa<Constant>(V)) return false;
237 if (V->getType() != Type::UByteTy) return false;
238 unsigned Idx = cast<ConstantUInt>(V)->getValue();
239 return Idx < ETypes.size();
242 // getTypeAtIndex - Given an index value into the type, return the type of the
243 // element. For a structure type, this must be a constant value...
245 const Type *StructType::getTypeAtIndex(const Value *V) const {
246 assert(isa<Constant>(V) && "Structure index must be a constant!!");
247 assert(V->getType() == Type::UByteTy && "Structure index must be ubyte!");
248 unsigned Idx = cast<ConstantUInt>(V)->getValue();
249 assert(Idx < ETypes.size() && "Structure index out of range!");
250 assert(indexValid(V) && "Invalid structure index!"); // Duplicate check
256 //===----------------------------------------------------------------------===//
257 // Auxilliary classes
258 //===----------------------------------------------------------------------===//
260 // These classes are used to implement specialized behavior for each different
263 struct SignedIntType : public Type {
264 SignedIntType(const std::string &Name, PrimitiveID id) : Type(Name, id) {}
266 // isSigned - Return whether a numeric type is signed.
267 virtual bool isSigned() const { return 1; }
269 // isInteger - Equivalent to isSigned() || isUnsigned, but with only a single
270 // virtual function invocation.
272 virtual bool isInteger() const { return 1; }
275 struct UnsignedIntType : public Type {
276 UnsignedIntType(const std::string &N, PrimitiveID id) : Type(N, id) {}
278 // isUnsigned - Return whether a numeric type is signed.
279 virtual bool isUnsigned() const { return 1; }
281 // isInteger - Equivalent to isSigned() || isUnsigned, but with only a single
282 // virtual function invocation.
284 virtual bool isInteger() const { return 1; }
287 struct OtherType : public Type {
288 OtherType(const std::string &N, PrimitiveID id) : Type(N, id) {}
291 static struct TypeType : public Type {
292 TypeType() : Type("type", TypeTyID) {}
293 } TheTypeTy; // Implement the type that is global.
296 //===----------------------------------------------------------------------===//
297 // Static 'Type' data
298 //===----------------------------------------------------------------------===//
300 static OtherType TheVoidTy ("void" , Type::VoidTyID);
301 static OtherType TheBoolTy ("bool" , Type::BoolTyID);
302 static SignedIntType TheSByteTy ("sbyte" , Type::SByteTyID);
303 static UnsignedIntType TheUByteTy ("ubyte" , Type::UByteTyID);
304 static SignedIntType TheShortTy ("short" , Type::ShortTyID);
305 static UnsignedIntType TheUShortTy("ushort", Type::UShortTyID);
306 static SignedIntType TheIntTy ("int" , Type::IntTyID);
307 static UnsignedIntType TheUIntTy ("uint" , Type::UIntTyID);
308 static SignedIntType TheLongTy ("long" , Type::LongTyID);
309 static UnsignedIntType TheULongTy ("ulong" , Type::ULongTyID);
310 static OtherType TheFloatTy ("float" , Type::FloatTyID);
311 static OtherType TheDoubleTy("double", Type::DoubleTyID);
312 static OtherType TheLabelTy ("label" , Type::LabelTyID);
314 Type *Type::VoidTy = &TheVoidTy;
315 Type *Type::BoolTy = &TheBoolTy;
316 Type *Type::SByteTy = &TheSByteTy;
317 Type *Type::UByteTy = &TheUByteTy;
318 Type *Type::ShortTy = &TheShortTy;
319 Type *Type::UShortTy = &TheUShortTy;
320 Type *Type::IntTy = &TheIntTy;
321 Type *Type::UIntTy = &TheUIntTy;
322 Type *Type::LongTy = &TheLongTy;
323 Type *Type::ULongTy = &TheULongTy;
324 Type *Type::FloatTy = &TheFloatTy;
325 Type *Type::DoubleTy = &TheDoubleTy;
326 Type *Type::TypeTy = &TheTypeTy;
327 Type *Type::LabelTy = &TheLabelTy;
330 //===----------------------------------------------------------------------===//
331 // Derived Type Constructors
332 //===----------------------------------------------------------------------===//
334 FunctionType::FunctionType(const Type *Result,
335 const std::vector<const Type*> &Params,
336 bool IsVarArgs) : DerivedType(FunctionTyID),
337 ResultType(PATypeHandle(Result, this)),
338 isVarArgs(IsVarArgs) {
339 bool isAbstract = Result->isAbstract();
340 ParamTys.reserve(Params.size());
341 for (unsigned i = 0; i < Params.size(); ++i) {
342 ParamTys.push_back(PATypeHandle(Params[i], this));
343 isAbstract |= Params[i]->isAbstract();
346 // Calculate whether or not this type is abstract
347 setAbstract(isAbstract);
350 StructType::StructType(const std::vector<const Type*> &Types)
351 : CompositeType(StructTyID) {
352 ETypes.reserve(Types.size());
353 bool isAbstract = false;
354 for (unsigned i = 0; i < Types.size(); ++i) {
355 assert(Types[i] != Type::VoidTy && "Void type in method prototype!!");
356 ETypes.push_back(PATypeHandle(Types[i], this));
357 isAbstract |= Types[i]->isAbstract();
360 // Calculate whether or not this type is abstract
361 setAbstract(isAbstract);
364 ArrayType::ArrayType(const Type *ElType, unsigned NumEl)
365 : SequentialType(ArrayTyID, ElType) {
368 // Calculate whether or not this type is abstract
369 setAbstract(ElType->isAbstract());
372 PointerType::PointerType(const Type *E) : SequentialType(PointerTyID, E) {
373 // Calculate whether or not this type is abstract
374 setAbstract(E->isAbstract());
377 OpaqueType::OpaqueType() : DerivedType(OpaqueTyID) {
379 #ifdef DEBUG_MERGE_TYPES
380 std::cerr << "Derived new type: " << *this << "\n";
385 // isTypeAbstract - This is a recursive function that walks a type hierarchy
386 // calculating whether or not a type is abstract. Worst case it will have to do
387 // a lot of traversing if you have some whacko opaque types, but in most cases,
388 // it will do some simple stuff when it hits non-abstract types that aren't
391 bool Type::isTypeAbstract() {
392 if (!isAbstract()) // Base case for the recursion
393 return false; // Primitive = leaf type
395 if (isa<OpaqueType>(this)) // Base case for the recursion
396 return true; // This whole type is abstract!
398 // We have to guard against recursion. To do this, we temporarily mark this
399 // type as concrete, so that if we get back to here recursively we will think
400 // it's not abstract, and thus not scan it again.
403 // Scan all of the sub-types. If any of them are abstract, than so is this
405 for (Type::subtype_iterator I = subtype_begin(), E = subtype_end();
407 if (const_cast<Type*>(*I)->isTypeAbstract()) {
408 setAbstract(true); // Restore the abstract bit.
409 return true; // This type is abstract if subtype is abstract!
412 // Restore the abstract bit.
415 // Nothing looks abstract here...
420 //===----------------------------------------------------------------------===//
421 // Type Structural Equality Testing
422 //===----------------------------------------------------------------------===//
424 // TypesEqual - Two types are considered structurally equal if they have the
425 // same "shape": Every level and element of the types have identical primitive
426 // ID's, and the graphs have the same edges/nodes in them. Nodes do not have to
427 // be pointer equals to be equivalent though. This uses an optimistic algorithm
428 // that assumes that two graphs are the same until proven otherwise.
430 static bool TypesEqual(const Type *Ty, const Type *Ty2,
431 std::map<const Type *, const Type *> &EqTypes) {
432 if (Ty == Ty2) return true;
433 if (Ty->getPrimitiveID() != Ty2->getPrimitiveID()) return false;
434 if (Ty->isPrimitiveType()) return true;
435 if (isa<OpaqueType>(Ty))
436 return false; // Two nonequal opaque types are never equal
438 std::map<const Type*, const Type*>::iterator It = EqTypes.find(Ty);
439 if (It != EqTypes.end())
440 return It->second == Ty2; // Looping back on a type, check for equality
442 // Otherwise, add the mapping to the table to make sure we don't get
443 // recursion on the types...
444 EqTypes.insert(std::make_pair(Ty, Ty2));
446 // Iterate over the types and make sure the the contents are equivalent...
447 Type::subtype_iterator I = Ty ->subtype_begin(), IE = Ty ->subtype_end();
448 Type::subtype_iterator I2 = Ty2->subtype_begin(), IE2 = Ty2->subtype_end();
449 for (; I != IE && I2 != IE2; ++I, ++I2)
450 if (!TypesEqual(*I, *I2, EqTypes)) return false;
452 // Two really annoying special cases that breaks an otherwise nice simple
453 // algorithm is the fact that arraytypes have sizes that differentiates types,
454 // and that function types can be varargs or not. Consider this now.
455 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
456 if (ATy->getNumElements() != cast<ArrayType>(Ty2)->getNumElements())
458 } else if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
459 if (FTy->isVarArg() != cast<FunctionType>(Ty2)->isVarArg())
463 return I == IE && I2 == IE2; // Types equal if both iterators are done
466 static bool TypesEqual(const Type *Ty, const Type *Ty2) {
467 std::map<const Type *, const Type *> EqTypes;
468 return TypesEqual(Ty, Ty2, EqTypes);
473 //===----------------------------------------------------------------------===//
474 // Derived Type Factory Functions
475 //===----------------------------------------------------------------------===//
477 // TypeMap - Make sure that only one instance of a particular type may be
478 // created on any given run of the compiler... note that this involves updating
479 // our map if an abstract type gets refined somehow...
481 template<class ValType, class TypeClass>
482 class TypeMap : public AbstractTypeUser {
483 typedef std::map<ValType, PATypeHandle> MapTy;
486 typedef typename MapTy::iterator iterator;
487 ~TypeMap() { print("ON EXIT"); }
489 inline TypeClass *get(const ValType &V) {
490 iterator I = Map.find(V);
491 return I != Map.end() ? (TypeClass*)I->second.get() : 0;
494 inline void add(const ValType &V, TypeClass *T) {
495 Map.insert(std::make_pair(V, PATypeHandle(T, this)));
499 iterator getEntryForType(TypeClass *Ty) {
500 iterator I = Map.find(ValType::get(Ty));
501 if (I == Map.end()) print("ERROR!");
502 assert(I != Map.end() && "Didn't find type entry!");
503 assert(T->second == Ty && "Type entry wrong?");
508 void finishRefinement(TypeClass *Ty) {
509 //const TypeClass *Ty = (const TypeClass*)TyIt->second.get();
510 for (iterator I = Map.begin(), E = Map.end(); I != E; ++I)
511 if (I->second.get() != Ty && TypesEqual(Ty, I->second.get())) {
512 assert(Ty->isAbstract() && "Replacing a non-abstract type?");
513 TypeClass *NewTy = (TypeClass*)I->second.get();
515 //Map.erase(TyIt); // The old entry is now dead!
517 // Refined to a different type altogether?
518 Ty->refineAbstractTypeToInternal(NewTy, false);
522 // If the type is currently thought to be abstract, rescan all of our
523 // subtypes to see if the type has just become concrete!
524 if (Ty->isAbstract())
525 Ty->setAbstract(Ty->isTypeAbstract());
527 // This method may be called with either an abstract or a concrete type.
528 // Concrete types might get refined if a subelement type got refined which
529 // was previously marked as abstract, but was realized to be concrete. This
530 // can happen for recursive types.
531 Ty->typeIsRefined(); // Same type, different contents...
534 // refineAbstractType - This is called when one of the contained abstract
535 // types gets refined... this simply removes the abstract type from our table.
536 // We expect that whoever refined the type will add it back to the table,
539 virtual void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
540 #ifdef DEBUG_MERGE_TYPES
541 std::cerr << "Removing Old type from Tab: " << (void*)OldTy << ", "
542 << *OldTy << " replacement == " << (void*)NewTy
543 << ", " << *NewTy << "\n";
545 for (iterator I = Map.begin(), E = Map.end(); I != E; ++I)
546 if (I->second.get() == OldTy) {
547 // Check to see if the type just became concrete. If so, remove self
549 I->second.removeUserFromConcrete();
550 I->second = cast<TypeClass>(NewTy);
554 void remove(const ValType &OldVal) {
555 iterator I = Map.find(OldVal);
556 assert(I != Map.end() && "TypeMap::remove, element not found!");
560 void remove(iterator I) {
561 assert(I != Map.end() && "Cannot remove invalid iterator pointer!");
565 void print(const char *Arg) const {
566 #ifdef DEBUG_MERGE_TYPES
567 std::cerr << "TypeMap<>::" << Arg << " table contents:\n";
569 for (typename MapTy::const_iterator I = Map.begin(), E = Map.end();
571 std::cerr << " " << (++i) << ". " << (void*)I->second.get() << " "
572 << *I->second.get() << "\n";
576 void dump() const { print("dump output"); }
580 // ValTypeBase - This is the base class that is used by the various
581 // instantiations of TypeMap. This class is an AbstractType user that notifies
582 // the underlying TypeMap when it gets modified.
584 template<class ValType, class TypeClass>
585 class ValTypeBase : public AbstractTypeUser {
586 TypeMap<ValType, TypeClass> &MyTable;
588 inline ValTypeBase(TypeMap<ValType, TypeClass> &tab) : MyTable(tab) {}
590 // Subclass should override this... to update self as usual
591 virtual void doRefinement(const DerivedType *OldTy, const Type *NewTy) = 0;
593 // typeBecameConcrete - This callback occurs when a contained type refines
594 // to itself, but becomes concrete in the process. Our subclass should remove
595 // itself from the ATU list of the specified type.
597 virtual void typeBecameConcrete(const DerivedType *Ty) = 0;
599 virtual void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
600 assert(OldTy == NewTy || OldTy->isAbstract());
602 if (!OldTy->isAbstract())
603 typeBecameConcrete(OldTy);
605 TypeMap<ValType, TypeClass> &Table = MyTable; // Copy MyTable reference
606 ValType Tmp(*(ValType*)this); // Copy this.
607 PATypeHandle OldType(Table.get(*(ValType*)this), this);
608 Table.remove(*(ValType*)this); // Destroy's this!
610 // Refine temporary to new state...
612 Tmp.doRefinement(OldTy, NewTy);
614 // FIXME: when types are not const!
615 Table.add((ValType&)Tmp, (TypeClass*)OldType.get());
619 std::cerr << "ValTypeBase instance!\n";
625 //===----------------------------------------------------------------------===//
626 // Function Type Factory and Value Class...
629 // FunctionValType - Define a class to hold the key that goes into the TypeMap
631 class FunctionValType : public ValTypeBase<FunctionValType, FunctionType> {
633 std::vector<PATypeHandle> ArgTypes;
636 FunctionValType(const Type *ret, const std::vector<const Type*> &args,
637 bool IVA, TypeMap<FunctionValType, FunctionType> &Tab)
638 : ValTypeBase<FunctionValType, FunctionType>(Tab), RetTy(ret, this),
640 for (unsigned i = 0; i < args.size(); ++i)
641 ArgTypes.push_back(PATypeHandle(args[i], this));
644 // We *MUST* have an explicit copy ctor so that the TypeHandles think that
645 // this FunctionValType owns them, not the old one!
647 FunctionValType(const FunctionValType &MVT)
648 : ValTypeBase<FunctionValType, FunctionType>(MVT), RetTy(MVT.RetTy, this),
649 isVarArg(MVT.isVarArg) {
650 ArgTypes.reserve(MVT.ArgTypes.size());
651 for (unsigned i = 0; i < MVT.ArgTypes.size(); ++i)
652 ArgTypes.push_back(PATypeHandle(MVT.ArgTypes[i], this));
655 static FunctionValType get(const FunctionType *FT);
657 // Subclass should override this... to update self as usual
658 virtual void doRefinement(const DerivedType *OldType, const Type *NewType) {
659 if (RetTy == OldType) RetTy = NewType;
660 for (unsigned i = 0, e = ArgTypes.size(); i != e; ++i)
661 if (ArgTypes[i] == OldType) ArgTypes[i] = NewType;
664 virtual void typeBecameConcrete(const DerivedType *Ty) {
665 if (RetTy == Ty) RetTy.removeUserFromConcrete();
667 for (unsigned i = 0; i < ArgTypes.size(); ++i)
668 if (ArgTypes[i] == Ty) ArgTypes[i].removeUserFromConcrete();
671 inline bool operator<(const FunctionValType &MTV) const {
672 if (RetTy.get() < MTV.RetTy.get()) return true;
673 if (RetTy.get() > MTV.RetTy.get()) return false;
675 if (ArgTypes < MTV.ArgTypes) return true;
676 return (ArgTypes == MTV.ArgTypes) && isVarArg < MTV.isVarArg;
680 // Define the actual map itself now...
681 static TypeMap<FunctionValType, FunctionType> FunctionTypes;
683 FunctionValType FunctionValType::get(const FunctionType *FT) {
684 // Build up a FunctionValType
685 std::vector<const Type *> ParamTypes;
686 ParamTypes.reserve(FT->getParamTypes().size());
687 for (unsigned i = 0, e = FT->getParamTypes().size(); i != e; ++i)
688 ParamTypes.push_back(FT->getParamType(i));
689 return FunctionValType(FT->getReturnType(), ParamTypes, FT->isVarArg(),
694 // FunctionType::get - The factory function for the FunctionType class...
695 FunctionType *FunctionType::get(const Type *ReturnType,
696 const std::vector<const Type*> &Params,
698 FunctionValType VT(ReturnType, Params, isVarArg, FunctionTypes);
699 FunctionType *MT = FunctionTypes.get(VT);
702 FunctionTypes.add(VT, MT = new FunctionType(ReturnType, Params, isVarArg));
704 #ifdef DEBUG_MERGE_TYPES
705 std::cerr << "Derived new type: " << MT << "\n";
710 void FunctionType::dropAllTypeUses(bool inMap) {
712 if (inMap) FunctionTypes.remove(FunctionTypes.getEntryForType(this));
713 // Drop all uses of other types, which might be recursive.
715 ResultType = OpaqueType::get();
720 //===----------------------------------------------------------------------===//
721 // Array Type Factory...
723 class ArrayValType : public ValTypeBase<ArrayValType, ArrayType> {
727 ArrayValType(const Type *val, int sz, TypeMap<ArrayValType, ArrayType> &Tab)
728 : ValTypeBase<ArrayValType, ArrayType>(Tab), ValTy(val, this), Size(sz) {}
730 // We *MUST* have an explicit copy ctor so that the ValTy thinks that this
731 // ArrayValType owns it, not the old one!
733 ArrayValType(const ArrayValType &AVT)
734 : ValTypeBase<ArrayValType, ArrayType>(AVT), ValTy(AVT.ValTy, this),
737 static ArrayValType get(const ArrayType *AT);
740 // Subclass should override this... to update self as usual
741 virtual void doRefinement(const DerivedType *OldType, const Type *NewType) {
742 assert(ValTy == OldType);
746 virtual void typeBecameConcrete(const DerivedType *Ty) {
747 assert(ValTy == Ty &&
748 "Contained type became concrete but we're not using it!");
749 ValTy.removeUserFromConcrete();
752 inline bool operator<(const ArrayValType &MTV) const {
753 if (Size < MTV.Size) return true;
754 return Size == MTV.Size && ValTy.get() < MTV.ValTy.get();
758 static TypeMap<ArrayValType, ArrayType> ArrayTypes;
760 ArrayValType ArrayValType::get(const ArrayType *AT) {
761 return ArrayValType(AT->getElementType(), AT->getNumElements(), ArrayTypes);
765 ArrayType *ArrayType::get(const Type *ElementType, unsigned NumElements) {
766 assert(ElementType && "Can't get array of null types!");
768 ArrayValType AVT(ElementType, NumElements, ArrayTypes);
769 ArrayType *AT = ArrayTypes.get(AVT);
770 if (AT) return AT; // Found a match, return it!
772 // Value not found. Derive a new type!
773 ArrayTypes.add(AVT, AT = new ArrayType(ElementType, NumElements));
775 #ifdef DEBUG_MERGE_TYPES
776 std::cerr << "Derived new type: " << *AT << "\n";
781 void ArrayType::dropAllTypeUses(bool inMap) {
783 if (inMap) ArrayTypes.remove(ArrayTypes.getEntryForType(this));
785 ElementType = OpaqueType::get();
791 //===----------------------------------------------------------------------===//
792 // Struct Type Factory...
795 // StructValType - Define a class to hold the key that goes into the TypeMap
797 class StructValType : public ValTypeBase<StructValType, StructType> {
798 std::vector<PATypeHandle> ElTypes;
800 StructValType(const std::vector<const Type*> &args,
801 TypeMap<StructValType, StructType> &Tab)
802 : ValTypeBase<StructValType, StructType>(Tab) {
803 ElTypes.reserve(args.size());
804 for (unsigned i = 0, e = args.size(); i != e; ++i)
805 ElTypes.push_back(PATypeHandle(args[i], this));
808 // We *MUST* have an explicit copy ctor so that the TypeHandles think that
809 // this StructValType owns them, not the old one!
811 StructValType(const StructValType &SVT)
812 : ValTypeBase<StructValType, StructType>(SVT){
813 ElTypes.reserve(SVT.ElTypes.size());
814 for (unsigned i = 0, e = SVT.ElTypes.size(); i != e; ++i)
815 ElTypes.push_back(PATypeHandle(SVT.ElTypes[i], this));
818 static StructValType get(const StructType *ST);
820 // Subclass should override this... to update self as usual
821 virtual void doRefinement(const DerivedType *OldType, const Type *NewType) {
822 for (unsigned i = 0; i < ElTypes.size(); ++i)
823 if (ElTypes[i] == OldType) ElTypes[i] = NewType;
826 virtual void typeBecameConcrete(const DerivedType *Ty) {
827 for (unsigned i = 0, e = ElTypes.size(); i != e; ++i)
828 if (ElTypes[i] == Ty)
829 ElTypes[i].removeUserFromConcrete();
832 inline bool operator<(const StructValType &STV) const {
833 return ElTypes < STV.ElTypes;
837 static TypeMap<StructValType, StructType> StructTypes;
839 StructValType StructValType::get(const StructType *ST) {
840 std::vector<const Type *> ElTypes;
841 ElTypes.reserve(ST->getElementTypes().size());
842 for (unsigned i = 0, e = ST->getElementTypes().size(); i != e; ++i)
843 ElTypes.push_back(ST->getElementTypes()[i]);
845 return StructValType(ElTypes, StructTypes);
850 StructType *StructType::get(const std::vector<const Type*> &ETypes) {
851 StructValType STV(ETypes, StructTypes);
852 StructType *ST = StructTypes.get(STV);
855 // Value not found. Derive a new type!
856 StructTypes.add(STV, ST = new StructType(ETypes));
858 #ifdef DEBUG_MERGE_TYPES
859 std::cerr << "Derived new type: " << *ST << "\n";
864 void StructType::dropAllTypeUses(bool inMap) {
866 if (inMap) StructTypes.remove(StructTypes.getEntryForType(this));
869 ETypes.push_back(PATypeHandle(OpaqueType::get(), this));
874 //===----------------------------------------------------------------------===//
875 // Pointer Type Factory...
878 // PointerValType - Define a class to hold the key that goes into the TypeMap
880 class PointerValType : public ValTypeBase<PointerValType, PointerType> {
883 PointerValType(const Type *val, TypeMap<PointerValType, PointerType> &Tab)
884 : ValTypeBase<PointerValType, PointerType>(Tab), ValTy(val, this) {}
886 // We *MUST* have an explicit copy ctor so that the ValTy thinks that this
887 // PointerValType owns it, not the old one!
889 PointerValType(const PointerValType &PVT)
890 : ValTypeBase<PointerValType, PointerType>(PVT), ValTy(PVT.ValTy, this) {}
892 static PointerValType get(const PointerType *PT);
894 // Subclass should override this... to update self as usual
895 virtual void doRefinement(const DerivedType *OldType, const Type *NewType) {
896 assert(ValTy == OldType);
900 virtual void typeBecameConcrete(const DerivedType *Ty) {
901 assert(ValTy == Ty &&
902 "Contained type became concrete but we're not using it!");
903 ValTy.removeUserFromConcrete();
906 inline bool operator<(const PointerValType &MTV) const {
907 return ValTy.get() < MTV.ValTy.get();
911 static TypeMap<PointerValType, PointerType> PointerTypes;
913 PointerValType PointerValType::get(const PointerType *PT) {
914 return PointerValType(PT->getElementType(), PointerTypes);
918 PointerType *PointerType::get(const Type *ValueType) {
919 assert(ValueType && "Can't get a pointer to <null> type!");
920 PointerValType PVT(ValueType, PointerTypes);
922 PointerType *PT = PointerTypes.get(PVT);
925 // Value not found. Derive a new type!
926 PointerTypes.add(PVT, PT = new PointerType(ValueType));
928 #ifdef DEBUG_MERGE_TYPES
929 std::cerr << "Derived new type: " << *PT << "\n";
934 void PointerType::dropAllTypeUses(bool inMap) {
936 if (inMap) PointerTypes.remove(PointerTypes.getEntryForType(this));
938 ElementType = OpaqueType::get();
941 void debug_type_tables() {
942 FunctionTypes.dump();
949 //===----------------------------------------------------------------------===//
950 // Derived Type Refinement Functions
951 //===----------------------------------------------------------------------===//
953 // addAbstractTypeUser - Notify an abstract type that there is a new user of
954 // it. This function is called primarily by the PATypeHandle class.
956 void DerivedType::addAbstractTypeUser(AbstractTypeUser *U) const {
957 assert(isAbstract() && "addAbstractTypeUser: Current type not abstract!");
959 #if DEBUG_MERGE_TYPES
960 std::cerr << " addAbstractTypeUser[" << (void*)this << ", "
961 << *this << "][" << AbstractTypeUsers.size()
962 << "] User = " << U << "\n";
964 AbstractTypeUsers.push_back(U);
968 // removeAbstractTypeUser - Notify an abstract type that a user of the class
969 // no longer has a handle to the type. This function is called primarily by
970 // the PATypeHandle class. When there are no users of the abstract type, it
971 // is anihilated, because there is no way to get a reference to it ever again.
973 void DerivedType::removeAbstractTypeUser(AbstractTypeUser *U) const {
974 // Search from back to front because we will notify users from back to
975 // front. Also, it is likely that there will be a stack like behavior to
976 // users that register and unregister users.
979 for (i = AbstractTypeUsers.size(); AbstractTypeUsers[i-1] != U; --i)
980 assert(i != 0 && "AbstractTypeUser not in user list!");
982 --i; // Convert to be in range 0 <= i < size()
983 assert(i < AbstractTypeUsers.size() && "Index out of range!"); // Wraparound?
985 AbstractTypeUsers.erase(AbstractTypeUsers.begin()+i);
987 #ifdef DEBUG_MERGE_TYPES
988 std::cerr << " remAbstractTypeUser[" << (void*)this << ", "
989 << *this << "][" << i << "] User = " << U << "\n";
992 if (AbstractTypeUsers.empty() && isAbstract()) {
993 #ifdef DEBUG_MERGE_TYPES
994 std::cerr << "DELETEing unused abstract type: <" << *this
995 << ">[" << (void*)this << "]" << "\n";
997 delete this; // No users of this abstract type!
1002 // refineAbstractTypeToInternal - This function is used to when it is discovered
1003 // that the 'this' abstract type is actually equivalent to the NewType
1004 // specified. This causes all users of 'this' to switch to reference the more
1005 // concrete type NewType and for 'this' to be deleted.
1007 void DerivedType::refineAbstractTypeToInternal(const Type *NewType, bool inMap){
1008 assert(isAbstract() && "refineAbstractTypeTo: Current type is not abstract!");
1009 assert(this != NewType && "Can't refine to myself!");
1011 // The descriptions may be out of date. Conservatively clear them all!
1012 AbstractTypeDescriptions.clear();
1014 #ifdef DEBUG_MERGE_TYPES
1015 std::cerr << "REFINING abstract type [" << (void*)this << " "
1016 << *this << "] to [" << (void*)NewType << " "
1017 << *NewType << "]!\n";
1021 // Make sure to put the type to be refined to into a holder so that if IT gets
1022 // refined, that we will not continue using a dead reference...
1024 PATypeHolder NewTy(NewType);
1026 // Add a self use of the current type so that we don't delete ourself until
1027 // after this while loop. We are careful to never invoke refine on ourself,
1028 // so this extra reference shouldn't be a problem. Note that we must only
1029 // remove a single reference at the end, but we must tolerate multiple self
1030 // references because we could be refineAbstractTypeTo'ing recursively on the
1033 addAbstractTypeUser(this);
1035 // To make the situation simpler, we ask the subclass to remove this type from
1036 // the type map, and to replace any type uses with uses of non-abstract types.
1037 // This dramatically limits the amount of recursive type trouble we can find
1039 dropAllTypeUses(inMap);
1041 // Count the number of self uses. Stop looping when sizeof(list) == NSU.
1042 unsigned NumSelfUses = 0;
1044 // Iterate over all of the uses of this type, invoking callback. Each user
1045 // should remove itself from our use list automatically. We have to check to
1046 // make sure that NewTy doesn't _become_ 'this'. If it does, resolving types
1047 // will not cause users to drop off of the use list. If we resolve to ourself
1050 while (AbstractTypeUsers.size() > NumSelfUses && NewTy != this) {
1051 AbstractTypeUser *User = AbstractTypeUsers.back();
1054 // Move self use to the start of the list. Increment NSU.
1055 std::swap(AbstractTypeUsers.back(), AbstractTypeUsers[NumSelfUses++]);
1057 unsigned OldSize = AbstractTypeUsers.size();
1058 #ifdef DEBUG_MERGE_TYPES
1059 std::cerr << " REFINING user " << OldSize-1 << "[" << (void*)User
1060 << "] of abstract type [" << (void*)this << " "
1061 << *this << "] to [" << (void*)NewTy.get() << " "
1062 << *NewTy << "]!\n";
1064 User->refineAbstractType(this, NewTy);
1066 #ifdef DEBUG_MERGE_TYPES
1067 if (AbstractTypeUsers.size() == OldSize) {
1068 User->refineAbstractType(this, NewTy);
1069 if (AbstractTypeUsers.back() != User)
1070 std::cerr << "User changed!\n";
1071 std::cerr << "Top of user list is:\n";
1072 AbstractTypeUsers.back()->dump();
1074 std::cerr <<"\nOld User=\n";
1078 assert(AbstractTypeUsers.size() != OldSize &&
1079 "AbsTyUser did not remove self from user list!");
1083 // Remove a single self use, even though there may be several here. This will
1084 // probably 'delete this', so no instance variables may be used after this
1087 assert((NewTy == this || AbstractTypeUsers.back() == this) &&
1088 "Only self uses should be left!");
1091 assert(AbstractTypeUsers.size() == 1 && "This type should get deleted!");
1093 removeAbstractTypeUser(this);
1096 // typeIsRefined - Notify AbstractTypeUsers of this type that the current type
1097 // has been refined a bit. The pointer is still valid and still should be
1098 // used, but the subtypes have changed.
1100 void DerivedType::typeIsRefined() {
1101 assert(isRefining >= 0 && isRefining <= 2 && "isRefining out of bounds!");
1102 if (isRefining == 1) return; // Kill recursion here...
1105 #ifdef DEBUG_MERGE_TYPES
1106 std::cerr << "typeIsREFINED type: " << (void*)this << " " << *this << "\n";
1109 // In this loop we have to be very careful not to get into infinite loops and
1110 // other problem cases. Specifically, we loop through all of the abstract
1111 // type users in the user list, notifying them that the type has been refined.
1112 // At their choice, they may or may not choose to remove themselves from the
1113 // list of users. Regardless of whether they do or not, we have to be sure
1114 // that we only notify each user exactly once. Because the refineAbstractType
1115 // method can cause an arbitrary permutation to the user list, we cannot loop
1116 // through it in any particular order and be guaranteed that we will be
1117 // successful at this aim. Because of this, we keep track of all the users we
1118 // have visited and only visit users we have not seen. Because this user list
1119 // should be small, we use a vector instead of a full featured set to keep
1120 // track of what users we have notified so far.
1122 std::vector<AbstractTypeUser*> Refined;
1125 for (i = AbstractTypeUsers.size(); i != 0; --i)
1126 if (find(Refined.begin(), Refined.end(), AbstractTypeUsers[i-1]) ==
1128 break; // Found an unrefined user?
1130 if (i == 0) break; // Noone to refine left, break out of here!
1132 AbstractTypeUser *ATU = AbstractTypeUsers[--i];
1133 Refined.push_back(ATU); // Keep track of which users we have refined!
1135 #ifdef DEBUG_MERGE_TYPES
1136 std::cerr << " typeIsREFINED user " << i << "[" << ATU
1137 << "] of abstract type [" << (void*)this << " "
1140 ATU->refineAbstractType(this, this);
1146 if (!(isAbstract() || AbstractTypeUsers.empty()))
1147 for (unsigned i = 0; i < AbstractTypeUsers.size(); ++i) {
1148 if (AbstractTypeUsers[i] != this) {
1150 std::cerr << "FOUND FAILURE\nUser: ";
1151 AbstractTypeUsers[i]->dump();
1152 std::cerr << "\nCatch:\n";
1153 AbstractTypeUsers[i]->refineAbstractType(this, this);
1154 assert(0 && "Type became concrete,"
1155 " but it still has abstract type users hanging around!");
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
1168 void FunctionType::refineAbstractType(const DerivedType *OldType,
1169 const Type *NewType) {
1170 assert((isAbstract() || !OldType->isAbstract()) &&
1171 "Refining a non-abstract type!");
1172 #ifdef DEBUG_MERGE_TYPES
1173 std::cerr << "FunctionTy::refineAbstractTy(" << (void*)OldType << "["
1174 << *OldType << "], " << (void*)NewType << " ["
1175 << *NewType << "])\n";
1178 // Look up our current type map entry..
1180 TypeMap<FunctionValType, FunctionType>::iterator TMI =
1181 FunctionTypes.getEntryForType(this);
1184 // Find the type element we are refining...
1185 if (ResultType == OldType) {
1186 ResultType.removeUserFromConcrete();
1187 ResultType = NewType;
1189 for (unsigned i = 0, e = ParamTys.size(); i != e; ++i)
1190 if (ParamTys[i] == OldType) {
1191 ParamTys[i].removeUserFromConcrete();
1192 ParamTys[i] = NewType;
1195 FunctionTypes.finishRefinement(this);
1199 // refineAbstractType - Called when a contained type is found to be more
1200 // concrete - this could potentially change us from an abstract type to a
1203 void ArrayType::refineAbstractType(const DerivedType *OldType,
1204 const Type *NewType) {
1205 assert((isAbstract() || !OldType->isAbstract()) &&
1206 "Refining a non-abstract type!");
1207 #ifdef DEBUG_MERGE_TYPES
1208 std::cerr << "ArrayTy::refineAbstractTy(" << (void*)OldType << "["
1209 << *OldType << "], " << (void*)NewType << " ["
1210 << *NewType << "])\n";
1214 // Look up our current type map entry..
1215 TypeMap<ArrayValType, ArrayType>::iterator TMI =
1216 ArrayTypes.getEntryForType(this);
1219 assert(getElementType() == OldType);
1220 ElementType.removeUserFromConcrete();
1221 ElementType = NewType;
1223 ArrayTypes.finishRefinement(this);
1227 // refineAbstractType - Called when a contained type is found to be more
1228 // concrete - this could potentially change us from an abstract type to a
1231 void StructType::refineAbstractType(const DerivedType *OldType,
1232 const Type *NewType) {
1233 assert((isAbstract() || !OldType->isAbstract()) &&
1234 "Refining a non-abstract type!");
1235 #ifdef DEBUG_MERGE_TYPES
1236 std::cerr << "StructTy::refineAbstractTy(" << (void*)OldType << "["
1237 << *OldType << "], " << (void*)NewType << " ["
1238 << *NewType << "])\n";
1242 // Look up our current type map entry..
1243 TypeMap<StructValType, StructType>::iterator TMI =
1244 StructTypes.getEntryForType(this);
1247 for (int i = ETypes.size()-1; i >= 0; --i)
1248 if (ETypes[i] == OldType) {
1249 ETypes[i].removeUserFromConcrete();
1251 // Update old type to new type in the array...
1252 ETypes[i] = NewType;
1255 StructTypes.finishRefinement(this);
1258 // refineAbstractType - Called when a contained type is found to be more
1259 // concrete - this could potentially change us from an abstract type to a
1262 void PointerType::refineAbstractType(const DerivedType *OldType,
1263 const Type *NewType) {
1264 assert((isAbstract() || !OldType->isAbstract()) &&
1265 "Refining a non-abstract type!");
1266 #ifdef DEBUG_MERGE_TYPES
1267 std::cerr << "PointerTy::refineAbstractTy(" << (void*)OldType << "["
1268 << *OldType << "], " << (void*)NewType << " ["
1269 << *NewType << "])\n";
1273 // Look up our current type map entry..
1274 TypeMap<PointerValType, PointerType>::iterator TMI =
1275 PointerTypes.getEntryForType(this);
1278 assert(ElementType == OldType);
1279 ElementType.removeUserFromConcrete();
1280 ElementType = NewType;
1282 PointerTypes.finishRefinement(this);