clang API Documentation

ASTContext.cpp
Go to the documentation of this file.
00001 //===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 //  This file implements the ASTContext interface.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "clang/AST/ASTContext.h"
00015 #include "clang/AST/CharUnits.h"
00016 #include "clang/AST/DeclCXX.h"
00017 #include "clang/AST/DeclObjC.h"
00018 #include "clang/AST/DeclTemplate.h"
00019 #include "clang/AST/TypeLoc.h"
00020 #include "clang/AST/Expr.h"
00021 #include "clang/AST/ExprCXX.h"
00022 #include "clang/AST/ExternalASTSource.h"
00023 #include "clang/AST/ASTMutationListener.h"
00024 #include "clang/AST/RecordLayout.h"
00025 #include "clang/AST/Mangle.h"
00026 #include "clang/Basic/Builtins.h"
00027 #include "clang/Basic/SourceManager.h"
00028 #include "clang/Basic/TargetInfo.h"
00029 #include "llvm/ADT/SmallString.h"
00030 #include "llvm/ADT/StringExtras.h"
00031 #include "llvm/Support/MathExtras.h"
00032 #include "llvm/Support/raw_ostream.h"
00033 #include "llvm/Support/Capacity.h"
00034 #include "CXXABI.h"
00035 #include <map>
00036 
00037 using namespace clang;
00038 
00039 unsigned ASTContext::NumImplicitDefaultConstructors;
00040 unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
00041 unsigned ASTContext::NumImplicitCopyConstructors;
00042 unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
00043 unsigned ASTContext::NumImplicitMoveConstructors;
00044 unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
00045 unsigned ASTContext::NumImplicitCopyAssignmentOperators;
00046 unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
00047 unsigned ASTContext::NumImplicitMoveAssignmentOperators;
00048 unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
00049 unsigned ASTContext::NumImplicitDestructors;
00050 unsigned ASTContext::NumImplicitDestructorsDeclared;
00051 
00052 enum FloatingRank {
00053   HalfRank, FloatRank, DoubleRank, LongDoubleRank
00054 };
00055 
00056 void 
00057 ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID, 
00058                                                TemplateTemplateParmDecl *Parm) {
00059   ID.AddInteger(Parm->getDepth());
00060   ID.AddInteger(Parm->getPosition());
00061   ID.AddBoolean(Parm->isParameterPack());
00062 
00063   TemplateParameterList *Params = Parm->getTemplateParameters();
00064   ID.AddInteger(Params->size());
00065   for (TemplateParameterList::const_iterator P = Params->begin(), 
00066                                           PEnd = Params->end();
00067        P != PEnd; ++P) {
00068     if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
00069       ID.AddInteger(0);
00070       ID.AddBoolean(TTP->isParameterPack());
00071       continue;
00072     }
00073     
00074     if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
00075       ID.AddInteger(1);
00076       ID.AddBoolean(NTTP->isParameterPack());
00077       ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
00078       if (NTTP->isExpandedParameterPack()) {
00079         ID.AddBoolean(true);
00080         ID.AddInteger(NTTP->getNumExpansionTypes());
00081         for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
00082           QualType T = NTTP->getExpansionType(I);
00083           ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
00084         }
00085       } else 
00086         ID.AddBoolean(false);
00087       continue;
00088     }
00089     
00090     TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
00091     ID.AddInteger(2);
00092     Profile(ID, TTP);
00093   }
00094 }
00095 
00096 TemplateTemplateParmDecl *
00097 ASTContext::getCanonicalTemplateTemplateParmDecl(
00098                                           TemplateTemplateParmDecl *TTP) const {
00099   // Check if we already have a canonical template template parameter.
00100   llvm::FoldingSetNodeID ID;
00101   CanonicalTemplateTemplateParm::Profile(ID, TTP);
00102   void *InsertPos = 0;
00103   CanonicalTemplateTemplateParm *Canonical
00104     = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
00105   if (Canonical)
00106     return Canonical->getParam();
00107   
00108   // Build a canonical template parameter list.
00109   TemplateParameterList *Params = TTP->getTemplateParameters();
00110   SmallVector<NamedDecl *, 4> CanonParams;
00111   CanonParams.reserve(Params->size());
00112   for (TemplateParameterList::const_iterator P = Params->begin(), 
00113                                           PEnd = Params->end();
00114        P != PEnd; ++P) {
00115     if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
00116       CanonParams.push_back(
00117                   TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(), 
00118                                                SourceLocation(),
00119                                                SourceLocation(),
00120                                                TTP->getDepth(),
00121                                                TTP->getIndex(), 0, false,
00122                                                TTP->isParameterPack()));
00123     else if (NonTypeTemplateParmDecl *NTTP
00124              = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
00125       QualType T = getCanonicalType(NTTP->getType());
00126       TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
00127       NonTypeTemplateParmDecl *Param;
00128       if (NTTP->isExpandedParameterPack()) {
00129         SmallVector<QualType, 2> ExpandedTypes;
00130         SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
00131         for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
00132           ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
00133           ExpandedTInfos.push_back(
00134                                 getTrivialTypeSourceInfo(ExpandedTypes.back()));
00135         }
00136         
00137         Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
00138                                                 SourceLocation(),
00139                                                 SourceLocation(),
00140                                                 NTTP->getDepth(),
00141                                                 NTTP->getPosition(), 0, 
00142                                                 T,
00143                                                 TInfo,
00144                                                 ExpandedTypes.data(),
00145                                                 ExpandedTypes.size(),
00146                                                 ExpandedTInfos.data());
00147       } else {
00148         Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
00149                                                 SourceLocation(),
00150                                                 SourceLocation(),
00151                                                 NTTP->getDepth(),
00152                                                 NTTP->getPosition(), 0, 
00153                                                 T,
00154                                                 NTTP->isParameterPack(),
00155                                                 TInfo);
00156       }
00157       CanonParams.push_back(Param);
00158 
00159     } else
00160       CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
00161                                            cast<TemplateTemplateParmDecl>(*P)));
00162   }
00163 
00164   TemplateTemplateParmDecl *CanonTTP
00165     = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(), 
00166                                        SourceLocation(), TTP->getDepth(),
00167                                        TTP->getPosition(), 
00168                                        TTP->isParameterPack(),
00169                                        0,
00170                          TemplateParameterList::Create(*this, SourceLocation(),
00171                                                        SourceLocation(),
00172                                                        CanonParams.data(),
00173                                                        CanonParams.size(),
00174                                                        SourceLocation()));
00175 
00176   // Get the new insert position for the node we care about.
00177   Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
00178   assert(Canonical == 0 && "Shouldn't be in the map!");
00179   (void)Canonical;
00180 
00181   // Create the canonical template template parameter entry.
00182   Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
00183   CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
00184   return CanonTTP;
00185 }
00186 
00187 CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
00188   if (!LangOpts.CPlusPlus) return 0;
00189 
00190   switch (T.getCXXABI()) {
00191   case CXXABI_ARM:
00192     return CreateARMCXXABI(*this);
00193   case CXXABI_Itanium:
00194     return CreateItaniumCXXABI(*this);
00195   case CXXABI_Microsoft:
00196     return CreateMicrosoftCXXABI(*this);
00197   }
00198   llvm_unreachable("Invalid CXXABI type!");
00199 }
00200 
00201 static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
00202                                              const LangOptions &LOpts) {
00203   if (LOpts.FakeAddressSpaceMap) {
00204     // The fake address space map must have a distinct entry for each
00205     // language-specific address space.
00206     static const unsigned FakeAddrSpaceMap[] = {
00207       1, // opencl_global
00208       2, // opencl_local
00209       3  // opencl_constant
00210     };
00211     return &FakeAddrSpaceMap;
00212   } else {
00213     return &T.getAddressSpaceMap();
00214   }
00215 }
00216 
00217 ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
00218                        const TargetInfo *t,
00219                        IdentifierTable &idents, SelectorTable &sels,
00220                        Builtin::Context &builtins,
00221                        unsigned size_reserve,
00222                        bool DelayInitialization) 
00223   : FunctionProtoTypes(this_()),
00224     TemplateSpecializationTypes(this_()),
00225     DependentTemplateSpecializationTypes(this_()),
00226     SubstTemplateTemplateParmPacks(this_()),
00227     GlobalNestedNameSpecifier(0), 
00228     Int128Decl(0), UInt128Decl(0),
00229     ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
00230     CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
00231     FILEDecl(0), 
00232     jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
00233     BlockDescriptorType(0), BlockDescriptorExtendedType(0),
00234     cudaConfigureCallDecl(0),
00235     NullTypeSourceInfo(QualType()), 
00236     FirstLocalImport(), LastLocalImport(),
00237     SourceMgr(SM), LangOpts(LOpts), 
00238     AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
00239     Idents(idents), Selectors(sels),
00240     BuiltinInfo(builtins),
00241     DeclarationNames(*this),
00242     ExternalSource(0), Listener(0),
00243     LastSDM(0, 0),
00244     UniqueBlockByRefTypeID(0) 
00245 {
00246   if (size_reserve > 0) Types.reserve(size_reserve);
00247   TUDecl = TranslationUnitDecl::Create(*this);
00248   
00249   if (!DelayInitialization) {
00250     assert(t && "No target supplied for ASTContext initialization");
00251     InitBuiltinTypes(*t);
00252   }
00253 }
00254 
00255 ASTContext::~ASTContext() {
00256   // Release the DenseMaps associated with DeclContext objects.
00257   // FIXME: Is this the ideal solution?
00258   ReleaseDeclContextMaps();
00259 
00260   // Call all of the deallocation functions.
00261   for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
00262     Deallocations[I].first(Deallocations[I].second);
00263   
00264   // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
00265   // because they can contain DenseMaps.
00266   for (llvm::DenseMap<const ObjCContainerDecl*,
00267        const ASTRecordLayout*>::iterator
00268        I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
00269     // Increment in loop to prevent using deallocated memory.
00270     if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
00271       R->Destroy(*this);
00272 
00273   for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
00274        I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
00275     // Increment in loop to prevent using deallocated memory.
00276     if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
00277       R->Destroy(*this);
00278   }
00279   
00280   for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
00281                                                     AEnd = DeclAttrs.end();
00282        A != AEnd; ++A)
00283     A->second->~AttrVec();
00284 }
00285 
00286 void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
00287   Deallocations.push_back(std::make_pair(Callback, Data));
00288 }
00289 
00290 void
00291 ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
00292   ExternalSource.reset(Source.take());
00293 }
00294 
00295 void ASTContext::PrintStats() const {
00296   llvm::errs() << "\n*** AST Context Stats:\n";
00297   llvm::errs() << "  " << Types.size() << " types total.\n";
00298 
00299   unsigned counts[] = {
00300 #define TYPE(Name, Parent) 0,
00301 #define ABSTRACT_TYPE(Name, Parent)
00302 #include "clang/AST/TypeNodes.def"
00303     0 // Extra
00304   };
00305 
00306   for (unsigned i = 0, e = Types.size(); i != e; ++i) {
00307     Type *T = Types[i];
00308     counts[(unsigned)T->getTypeClass()]++;
00309   }
00310 
00311   unsigned Idx = 0;
00312   unsigned TotalBytes = 0;
00313 #define TYPE(Name, Parent)                                              \
00314   if (counts[Idx])                                                      \
00315     llvm::errs() << "    " << counts[Idx] << " " << #Name               \
00316                  << " types\n";                                         \
00317   TotalBytes += counts[Idx] * sizeof(Name##Type);                       \
00318   ++Idx;
00319 #define ABSTRACT_TYPE(Name, Parent)
00320 #include "clang/AST/TypeNodes.def"
00321 
00322   llvm::errs() << "Total bytes = " << TotalBytes << "\n";
00323 
00324   // Implicit special member functions.
00325   llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
00326                << NumImplicitDefaultConstructors
00327                << " implicit default constructors created\n";
00328   llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
00329                << NumImplicitCopyConstructors
00330                << " implicit copy constructors created\n";
00331   if (getLangOpts().CPlusPlus)
00332     llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
00333                  << NumImplicitMoveConstructors
00334                  << " implicit move constructors created\n";
00335   llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
00336                << NumImplicitCopyAssignmentOperators
00337                << " implicit copy assignment operators created\n";
00338   if (getLangOpts().CPlusPlus)
00339     llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
00340                  << NumImplicitMoveAssignmentOperators
00341                  << " implicit move assignment operators created\n";
00342   llvm::errs() << NumImplicitDestructorsDeclared << "/"
00343                << NumImplicitDestructors
00344                << " implicit destructors created\n";
00345 
00346   if (ExternalSource.get()) {
00347     llvm::errs() << "\n";
00348     ExternalSource->PrintStats();
00349   }
00350 
00351   BumpAlloc.PrintStats();
00352 }
00353 
00354 TypedefDecl *ASTContext::getInt128Decl() const {
00355   if (!Int128Decl) {
00356     TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
00357     Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this), 
00358                                      getTranslationUnitDecl(),
00359                                      SourceLocation(),
00360                                      SourceLocation(),
00361                                      &Idents.get("__int128_t"),
00362                                      TInfo);
00363   }
00364   
00365   return Int128Decl;
00366 }
00367 
00368 TypedefDecl *ASTContext::getUInt128Decl() const {
00369   if (!UInt128Decl) {
00370     TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
00371     UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this), 
00372                                      getTranslationUnitDecl(),
00373                                      SourceLocation(),
00374                                      SourceLocation(),
00375                                      &Idents.get("__uint128_t"),
00376                                      TInfo);
00377   }
00378   
00379   return UInt128Decl;
00380 }
00381 
00382 void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
00383   BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
00384   R = CanQualType::CreateUnsafe(QualType(Ty, 0));
00385   Types.push_back(Ty);
00386 }
00387 
00388 void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
00389   assert((!this->Target || this->Target == &Target) &&
00390          "Incorrect target reinitialization");
00391   assert(VoidTy.isNull() && "Context reinitialized?");
00392 
00393   this->Target = &Target;
00394   
00395   ABI.reset(createCXXABI(Target));
00396   AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
00397   
00398   // C99 6.2.5p19.
00399   InitBuiltinType(VoidTy,              BuiltinType::Void);
00400 
00401   // C99 6.2.5p2.
00402   InitBuiltinType(BoolTy,              BuiltinType::Bool);
00403   // C99 6.2.5p3.
00404   if (LangOpts.CharIsSigned)
00405     InitBuiltinType(CharTy,            BuiltinType::Char_S);
00406   else
00407     InitBuiltinType(CharTy,            BuiltinType::Char_U);
00408   // C99 6.2.5p4.
00409   InitBuiltinType(SignedCharTy,        BuiltinType::SChar);
00410   InitBuiltinType(ShortTy,             BuiltinType::Short);
00411   InitBuiltinType(IntTy,               BuiltinType::Int);
00412   InitBuiltinType(LongTy,              BuiltinType::Long);
00413   InitBuiltinType(LongLongTy,          BuiltinType::LongLong);
00414 
00415   // C99 6.2.5p6.
00416   InitBuiltinType(UnsignedCharTy,      BuiltinType::UChar);
00417   InitBuiltinType(UnsignedShortTy,     BuiltinType::UShort);
00418   InitBuiltinType(UnsignedIntTy,       BuiltinType::UInt);
00419   InitBuiltinType(UnsignedLongTy,      BuiltinType::ULong);
00420   InitBuiltinType(UnsignedLongLongTy,  BuiltinType::ULongLong);
00421 
00422   // C99 6.2.5p10.
00423   InitBuiltinType(FloatTy,             BuiltinType::Float);
00424   InitBuiltinType(DoubleTy,            BuiltinType::Double);
00425   InitBuiltinType(LongDoubleTy,        BuiltinType::LongDouble);
00426 
00427   // GNU extension, 128-bit integers.
00428   InitBuiltinType(Int128Ty,            BuiltinType::Int128);
00429   InitBuiltinType(UnsignedInt128Ty,    BuiltinType::UInt128);
00430 
00431   if (LangOpts.CPlusPlus) { // C++ 3.9.1p5
00432     if (TargetInfo::isTypeSigned(Target.getWCharType()))
00433       InitBuiltinType(WCharTy,           BuiltinType::WChar_S);
00434     else  // -fshort-wchar makes wchar_t be unsigned.
00435       InitBuiltinType(WCharTy,           BuiltinType::WChar_U);
00436   } else // C99
00437     WCharTy = getFromTargetType(Target.getWCharType());
00438 
00439   WIntTy = getFromTargetType(Target.getWIntType());
00440 
00441   if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
00442     InitBuiltinType(Char16Ty,           BuiltinType::Char16);
00443   else // C99
00444     Char16Ty = getFromTargetType(Target.getChar16Type());
00445 
00446   if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
00447     InitBuiltinType(Char32Ty,           BuiltinType::Char32);
00448   else // C99
00449     Char32Ty = getFromTargetType(Target.getChar32Type());
00450 
00451   // Placeholder type for type-dependent expressions whose type is
00452   // completely unknown. No code should ever check a type against
00453   // DependentTy and users should never see it; however, it is here to
00454   // help diagnose failures to properly check for type-dependent
00455   // expressions.
00456   InitBuiltinType(DependentTy,         BuiltinType::Dependent);
00457 
00458   // Placeholder type for functions.
00459   InitBuiltinType(OverloadTy,          BuiltinType::Overload);
00460 
00461   // Placeholder type for bound members.
00462   InitBuiltinType(BoundMemberTy,       BuiltinType::BoundMember);
00463 
00464   // Placeholder type for pseudo-objects.
00465   InitBuiltinType(PseudoObjectTy,      BuiltinType::PseudoObject);
00466 
00467   // "any" type; useful for debugger-like clients.
00468   InitBuiltinType(UnknownAnyTy,        BuiltinType::UnknownAny);
00469 
00470   // Placeholder type for unbridged ARC casts.
00471   InitBuiltinType(ARCUnbridgedCastTy,  BuiltinType::ARCUnbridgedCast);
00472 
00473   // C99 6.2.5p11.
00474   FloatComplexTy      = getComplexType(FloatTy);
00475   DoubleComplexTy     = getComplexType(DoubleTy);
00476   LongDoubleComplexTy = getComplexType(LongDoubleTy);
00477 
00478   BuiltinVaListType = QualType();
00479 
00480   // Builtin types for 'id', 'Class', and 'SEL'.
00481   InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
00482   InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
00483   InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
00484   
00485   // Builtin type for __objc_yes and __objc_no
00486   ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
00487                        SignedCharTy : BoolTy);
00488   
00489   ObjCConstantStringType = QualType();
00490 
00491   // void * type
00492   VoidPtrTy = getPointerType(VoidTy);
00493 
00494   // nullptr type (C++0x 2.14.7)
00495   InitBuiltinType(NullPtrTy,           BuiltinType::NullPtr);
00496 
00497   // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
00498   InitBuiltinType(HalfTy, BuiltinType::Half);
00499 }
00500 
00501 DiagnosticsEngine &ASTContext::getDiagnostics() const {
00502   return SourceMgr.getDiagnostics();
00503 }
00504 
00505 AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
00506   AttrVec *&Result = DeclAttrs[D];
00507   if (!Result) {
00508     void *Mem = Allocate(sizeof(AttrVec));
00509     Result = new (Mem) AttrVec;
00510   }
00511     
00512   return *Result;
00513 }
00514 
00515 /// \brief Erase the attributes corresponding to the given declaration.
00516 void ASTContext::eraseDeclAttrs(const Decl *D) { 
00517   llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
00518   if (Pos != DeclAttrs.end()) {
00519     Pos->second->~AttrVec();
00520     DeclAttrs.erase(Pos);
00521   }
00522 }
00523 
00524 MemberSpecializationInfo *
00525 ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
00526   assert(Var->isStaticDataMember() && "Not a static data member");
00527   llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
00528     = InstantiatedFromStaticDataMember.find(Var);
00529   if (Pos == InstantiatedFromStaticDataMember.end())
00530     return 0;
00531 
00532   return Pos->second;
00533 }
00534 
00535 void
00536 ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
00537                                                 TemplateSpecializationKind TSK,
00538                                           SourceLocation PointOfInstantiation) {
00539   assert(Inst->isStaticDataMember() && "Not a static data member");
00540   assert(Tmpl->isStaticDataMember() && "Not a static data member");
00541   assert(!InstantiatedFromStaticDataMember[Inst] &&
00542          "Already noted what static data member was instantiated from");
00543   InstantiatedFromStaticDataMember[Inst] 
00544     = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
00545 }
00546 
00547 FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
00548                                                      const FunctionDecl *FD){
00549   assert(FD && "Specialization is 0");
00550   llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
00551     = ClassScopeSpecializationPattern.find(FD);
00552   if (Pos == ClassScopeSpecializationPattern.end())
00553     return 0;
00554 
00555   return Pos->second;
00556 }
00557 
00558 void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
00559                                         FunctionDecl *Pattern) {
00560   assert(FD && "Specialization is 0");
00561   assert(Pattern && "Class scope specialization pattern is 0");
00562   ClassScopeSpecializationPattern[FD] = Pattern;
00563 }
00564 
00565 NamedDecl *
00566 ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
00567   llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
00568     = InstantiatedFromUsingDecl.find(UUD);
00569   if (Pos == InstantiatedFromUsingDecl.end())
00570     return 0;
00571 
00572   return Pos->second;
00573 }
00574 
00575 void
00576 ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
00577   assert((isa<UsingDecl>(Pattern) ||
00578           isa<UnresolvedUsingValueDecl>(Pattern) ||
00579           isa<UnresolvedUsingTypenameDecl>(Pattern)) && 
00580          "pattern decl is not a using decl");
00581   assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
00582   InstantiatedFromUsingDecl[Inst] = Pattern;
00583 }
00584 
00585 UsingShadowDecl *
00586 ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
00587   llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
00588     = InstantiatedFromUsingShadowDecl.find(Inst);
00589   if (Pos == InstantiatedFromUsingShadowDecl.end())
00590     return 0;
00591 
00592   return Pos->second;
00593 }
00594 
00595 void
00596 ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
00597                                                UsingShadowDecl *Pattern) {
00598   assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
00599   InstantiatedFromUsingShadowDecl[Inst] = Pattern;
00600 }
00601 
00602 FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
00603   llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
00604     = InstantiatedFromUnnamedFieldDecl.find(Field);
00605   if (Pos == InstantiatedFromUnnamedFieldDecl.end())
00606     return 0;
00607 
00608   return Pos->second;
00609 }
00610 
00611 void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
00612                                                      FieldDecl *Tmpl) {
00613   assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
00614   assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
00615   assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
00616          "Already noted what unnamed field was instantiated from");
00617 
00618   InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
00619 }
00620 
00621 bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD, 
00622                                     const FieldDecl *LastFD) const {
00623   return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
00624           FD->getBitWidthValue(*this) == 0);
00625 }
00626 
00627 bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
00628                                              const FieldDecl *LastFD) const {
00629   return (FD->isBitField() && LastFD && LastFD->isBitField() &&
00630           FD->getBitWidthValue(*this) == 0 &&
00631           LastFD->getBitWidthValue(*this) != 0);
00632 }
00633 
00634 bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
00635                                          const FieldDecl *LastFD) const {
00636   return (FD->isBitField() && LastFD && LastFD->isBitField() &&
00637           FD->getBitWidthValue(*this) &&
00638           LastFD->getBitWidthValue(*this));
00639 }
00640 
00641 bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
00642                                          const FieldDecl *LastFD) const {
00643   return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
00644           LastFD->getBitWidthValue(*this));
00645 }
00646 
00647 bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
00648                                              const FieldDecl *LastFD) const {
00649   return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
00650           FD->getBitWidthValue(*this));
00651 }
00652 
00653 ASTContext::overridden_cxx_method_iterator
00654 ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
00655   llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
00656     = OverriddenMethods.find(Method);
00657   if (Pos == OverriddenMethods.end())
00658     return 0;
00659 
00660   return Pos->second.begin();
00661 }
00662 
00663 ASTContext::overridden_cxx_method_iterator
00664 ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
00665   llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
00666     = OverriddenMethods.find(Method);
00667   if (Pos == OverriddenMethods.end())
00668     return 0;
00669 
00670   return Pos->second.end();
00671 }
00672 
00673 unsigned
00674 ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
00675   llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
00676     = OverriddenMethods.find(Method);
00677   if (Pos == OverriddenMethods.end())
00678     return 0;
00679 
00680   return Pos->second.size();
00681 }
00682 
00683 void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method, 
00684                                      const CXXMethodDecl *Overridden) {
00685   OverriddenMethods[Method].push_back(Overridden);
00686 }
00687 
00688 void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
00689   assert(!Import->NextLocalImport && "Import declaration already in the chain");
00690   assert(!Import->isFromASTFile() && "Non-local import declaration");
00691   if (!FirstLocalImport) {
00692     FirstLocalImport = Import;
00693     LastLocalImport = Import;
00694     return;
00695   }
00696   
00697   LastLocalImport->NextLocalImport = Import;
00698   LastLocalImport = Import;
00699 }
00700 
00701 //===----------------------------------------------------------------------===//
00702 //                         Type Sizing and Analysis
00703 //===----------------------------------------------------------------------===//
00704 
00705 /// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
00706 /// scalar floating point type.
00707 const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
00708   const BuiltinType *BT = T->getAs<BuiltinType>();
00709   assert(BT && "Not a floating point type!");
00710   switch (BT->getKind()) {
00711   default: llvm_unreachable("Not a floating point type!");
00712   case BuiltinType::Half:       return Target->getHalfFormat();
00713   case BuiltinType::Float:      return Target->getFloatFormat();
00714   case BuiltinType::Double:     return Target->getDoubleFormat();
00715   case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
00716   }
00717 }
00718 
00719 /// getDeclAlign - Return a conservative estimate of the alignment of the
00720 /// specified decl.  Note that bitfields do not have a valid alignment, so
00721 /// this method will assert on them.
00722 /// If @p RefAsPointee, references are treated like their underlying type
00723 /// (for alignof), else they're treated like pointers (for CodeGen).
00724 CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
00725   unsigned Align = Target->getCharWidth();
00726 
00727   bool UseAlignAttrOnly = false;
00728   if (unsigned AlignFromAttr = D->getMaxAlignment()) {
00729     Align = AlignFromAttr;
00730 
00731     // __attribute__((aligned)) can increase or decrease alignment
00732     // *except* on a struct or struct member, where it only increases
00733     // alignment unless 'packed' is also specified.
00734     //
00735     // It is an error for alignas to decrease alignment, so we can
00736     // ignore that possibility;  Sema should diagnose it.
00737     if (isa<FieldDecl>(D)) {
00738       UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
00739         cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
00740     } else {
00741       UseAlignAttrOnly = true;
00742     }
00743   }
00744   else if (isa<FieldDecl>(D))
00745       UseAlignAttrOnly = 
00746         D->hasAttr<PackedAttr>() ||
00747         cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
00748 
00749   // If we're using the align attribute only, just ignore everything
00750   // else about the declaration and its type.
00751   if (UseAlignAttrOnly) {
00752     // do nothing
00753 
00754   } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
00755     QualType T = VD->getType();
00756     if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
00757       if (RefAsPointee)
00758         T = RT->getPointeeType();
00759       else
00760         T = getPointerType(RT->getPointeeType());
00761     }
00762     if (!T->isIncompleteType() && !T->isFunctionType()) {
00763       // Adjust alignments of declarations with array type by the
00764       // large-array alignment on the target.
00765       unsigned MinWidth = Target->getLargeArrayMinWidth();
00766       const ArrayType *arrayType;
00767       if (MinWidth && (arrayType = getAsArrayType(T))) {
00768         if (isa<VariableArrayType>(arrayType))
00769           Align = std::max(Align, Target->getLargeArrayAlign());
00770         else if (isa<ConstantArrayType>(arrayType) &&
00771                  MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
00772           Align = std::max(Align, Target->getLargeArrayAlign());
00773 
00774         // Walk through any array types while we're at it.
00775         T = getBaseElementType(arrayType);
00776       }
00777       Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
00778     }
00779 
00780     // Fields can be subject to extra alignment constraints, like if
00781     // the field is packed, the struct is packed, or the struct has a
00782     // a max-field-alignment constraint (#pragma pack).  So calculate
00783     // the actual alignment of the field within the struct, and then
00784     // (as we're expected to) constrain that by the alignment of the type.
00785     if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
00786       // So calculate the alignment of the field.
00787       const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
00788 
00789       // Start with the record's overall alignment.
00790       unsigned fieldAlign = toBits(layout.getAlignment());
00791 
00792       // Use the GCD of that and the offset within the record.
00793       uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
00794       if (offset > 0) {
00795         // Alignment is always a power of 2, so the GCD will be a power of 2,
00796         // which means we get to do this crazy thing instead of Euclid's.
00797         uint64_t lowBitOfOffset = offset & (~offset + 1);
00798         if (lowBitOfOffset < fieldAlign)
00799           fieldAlign = static_cast<unsigned>(lowBitOfOffset);
00800       }
00801 
00802       Align = std::min(Align, fieldAlign);
00803     }
00804   }
00805 
00806   return toCharUnitsFromBits(Align);
00807 }
00808 
00809 std::pair<CharUnits, CharUnits>
00810 ASTContext::getTypeInfoInChars(const Type *T) const {
00811   std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
00812   return std::make_pair(toCharUnitsFromBits(Info.first),
00813                         toCharUnitsFromBits(Info.second));
00814 }
00815 
00816 std::pair<CharUnits, CharUnits>
00817 ASTContext::getTypeInfoInChars(QualType T) const {
00818   return getTypeInfoInChars(T.getTypePtr());
00819 }
00820 
00821 std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
00822   TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
00823   if (it != MemoizedTypeInfo.end())
00824     return it->second;
00825 
00826   std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
00827   MemoizedTypeInfo.insert(std::make_pair(T, Info));
00828   return Info;
00829 }
00830 
00831 /// getTypeInfoImpl - Return the size of the specified type, in bits.  This
00832 /// method does not work on incomplete types.
00833 ///
00834 /// FIXME: Pointers into different addr spaces could have different sizes and
00835 /// alignment requirements: getPointerInfo should take an AddrSpace, this
00836 /// should take a QualType, &c.
00837 std::pair<uint64_t, unsigned>
00838 ASTContext::getTypeInfoImpl(const Type *T) const {
00839   uint64_t Width=0;
00840   unsigned Align=8;
00841   switch (T->getTypeClass()) {
00842 #define TYPE(Class, Base)
00843 #define ABSTRACT_TYPE(Class, Base)
00844 #define NON_CANONICAL_TYPE(Class, Base)
00845 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
00846 #include "clang/AST/TypeNodes.def"
00847     llvm_unreachable("Should not see dependent types");
00848 
00849   case Type::FunctionNoProto:
00850   case Type::FunctionProto:
00851     // GCC extension: alignof(function) = 32 bits
00852     Width = 0;
00853     Align = 32;
00854     break;
00855 
00856   case Type::IncompleteArray:
00857   case Type::VariableArray:
00858     Width = 0;
00859     Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
00860     break;
00861 
00862   case Type::ConstantArray: {
00863     const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
00864 
00865     std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
00866     uint64_t Size = CAT->getSize().getZExtValue();
00867     assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) && 
00868            "Overflow in array type bit size evaluation");
00869     Width = EltInfo.first*Size;
00870     Align = EltInfo.second;
00871     Width = llvm::RoundUpToAlignment(Width, Align);
00872     break;
00873   }
00874   case Type::ExtVector:
00875   case Type::Vector: {
00876     const VectorType *VT = cast<VectorType>(T);
00877     std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
00878     Width = EltInfo.first*VT->getNumElements();
00879     Align = Width;
00880     // If the alignment is not a power of 2, round up to the next power of 2.
00881     // This happens for non-power-of-2 length vectors.
00882     if (Align & (Align-1)) {
00883       Align = llvm::NextPowerOf2(Align);
00884       Width = llvm::RoundUpToAlignment(Width, Align);
00885     }
00886     break;
00887   }
00888 
00889   case Type::Builtin:
00890     switch (cast<BuiltinType>(T)->getKind()) {
00891     default: llvm_unreachable("Unknown builtin type!");
00892     case BuiltinType::Void:
00893       // GCC extension: alignof(void) = 8 bits.
00894       Width = 0;
00895       Align = 8;
00896       break;
00897 
00898     case BuiltinType::Bool:
00899       Width = Target->getBoolWidth();
00900       Align = Target->getBoolAlign();
00901       break;
00902     case BuiltinType::Char_S:
00903     case BuiltinType::Char_U:
00904     case BuiltinType::UChar:
00905     case BuiltinType::SChar:
00906       Width = Target->getCharWidth();
00907       Align = Target->getCharAlign();
00908       break;
00909     case BuiltinType::WChar_S:
00910     case BuiltinType::WChar_U:
00911       Width = Target->getWCharWidth();
00912       Align = Target->getWCharAlign();
00913       break;
00914     case BuiltinType::Char16:
00915       Width = Target->getChar16Width();
00916       Align = Target->getChar16Align();
00917       break;
00918     case BuiltinType::Char32:
00919       Width = Target->getChar32Width();
00920       Align = Target->getChar32Align();
00921       break;
00922     case BuiltinType::UShort:
00923     case BuiltinType::Short:
00924       Width = Target->getShortWidth();
00925       Align = Target->getShortAlign();
00926       break;
00927     case BuiltinType::UInt:
00928     case BuiltinType::Int:
00929       Width = Target->getIntWidth();
00930       Align = Target->getIntAlign();
00931       break;
00932     case BuiltinType::ULong:
00933     case BuiltinType::Long:
00934       Width = Target->getLongWidth();
00935       Align = Target->getLongAlign();
00936       break;
00937     case BuiltinType::ULongLong:
00938     case BuiltinType::LongLong:
00939       Width = Target->getLongLongWidth();
00940       Align = Target->getLongLongAlign();
00941       break;
00942     case BuiltinType::Int128:
00943     case BuiltinType::UInt128:
00944       Width = 128;
00945       Align = 128; // int128_t is 128-bit aligned on all targets.
00946       break;
00947     case BuiltinType::Half:
00948       Width = Target->getHalfWidth();
00949       Align = Target->getHalfAlign();
00950       break;
00951     case BuiltinType::Float:
00952       Width = Target->getFloatWidth();
00953       Align = Target->getFloatAlign();
00954       break;
00955     case BuiltinType::Double:
00956       Width = Target->getDoubleWidth();
00957       Align = Target->getDoubleAlign();
00958       break;
00959     case BuiltinType::LongDouble:
00960       Width = Target->getLongDoubleWidth();
00961       Align = Target->getLongDoubleAlign();
00962       break;
00963     case BuiltinType::NullPtr:
00964       Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
00965       Align = Target->getPointerAlign(0); //   == sizeof(void*)
00966       break;
00967     case BuiltinType::ObjCId:
00968     case BuiltinType::ObjCClass:
00969     case BuiltinType::ObjCSel:
00970       Width = Target->getPointerWidth(0); 
00971       Align = Target->getPointerAlign(0);
00972       break;
00973     }
00974     break;
00975   case Type::ObjCObjectPointer:
00976     Width = Target->getPointerWidth(0);
00977     Align = Target->getPointerAlign(0);
00978     break;
00979   case Type::BlockPointer: {
00980     unsigned AS = getTargetAddressSpace(
00981         cast<BlockPointerType>(T)->getPointeeType());
00982     Width = Target->getPointerWidth(AS);
00983     Align = Target->getPointerAlign(AS);
00984     break;
00985   }
00986   case Type::LValueReference:
00987   case Type::RValueReference: {
00988     // alignof and sizeof should never enter this code path here, so we go
00989     // the pointer route.
00990     unsigned AS = getTargetAddressSpace(
00991         cast<ReferenceType>(T)->getPointeeType());
00992     Width = Target->getPointerWidth(AS);
00993     Align = Target->getPointerAlign(AS);
00994     break;
00995   }
00996   case Type::Pointer: {
00997     unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
00998     Width = Target->getPointerWidth(AS);
00999     Align = Target->getPointerAlign(AS);
01000     break;
01001   }
01002   case Type::MemberPointer: {
01003     const MemberPointerType *MPT = cast<MemberPointerType>(T);
01004     std::pair<uint64_t, unsigned> PtrDiffInfo =
01005       getTypeInfo(getPointerDiffType());
01006     Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
01007     Align = PtrDiffInfo.second;
01008     break;
01009   }
01010   case Type::Complex: {
01011     // Complex types have the same alignment as their elements, but twice the
01012     // size.
01013     std::pair<uint64_t, unsigned> EltInfo =
01014       getTypeInfo(cast<ComplexType>(T)->getElementType());
01015     Width = EltInfo.first*2;
01016     Align = EltInfo.second;
01017     break;
01018   }
01019   case Type::ObjCObject:
01020     return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
01021   case Type::ObjCInterface: {
01022     const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
01023     const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
01024     Width = toBits(Layout.getSize());
01025     Align = toBits(Layout.getAlignment());
01026     break;
01027   }
01028   case Type::Record:
01029   case Type::Enum: {
01030     const TagType *TT = cast<TagType>(T);
01031 
01032     if (TT->getDecl()->isInvalidDecl()) {
01033       Width = 8;
01034       Align = 8;
01035       break;
01036     }
01037 
01038     if (const EnumType *ET = dyn_cast<EnumType>(TT))
01039       return getTypeInfo(ET->getDecl()->getIntegerType());
01040 
01041     const RecordType *RT = cast<RecordType>(TT);
01042     const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
01043     Width = toBits(Layout.getSize());
01044     Align = toBits(Layout.getAlignment());
01045     break;
01046   }
01047 
01048   case Type::SubstTemplateTypeParm:
01049     return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
01050                        getReplacementType().getTypePtr());
01051 
01052   case Type::Auto: {
01053     const AutoType *A = cast<AutoType>(T);
01054     assert(A->isDeduced() && "Cannot request the size of a dependent type");
01055     return getTypeInfo(A->getDeducedType().getTypePtr());
01056   }
01057 
01058   case Type::Paren:
01059     return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
01060 
01061   case Type::Typedef: {
01062     const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
01063     std::pair<uint64_t, unsigned> Info
01064       = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
01065     // If the typedef has an aligned attribute on it, it overrides any computed
01066     // alignment we have.  This violates the GCC documentation (which says that
01067     // attribute(aligned) can only round up) but matches its implementation.
01068     if (unsigned AttrAlign = Typedef->getMaxAlignment())
01069       Align = AttrAlign;
01070     else
01071       Align = Info.second;
01072     Width = Info.first;
01073     break;
01074   }
01075 
01076   case Type::TypeOfExpr:
01077     return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
01078                          .getTypePtr());
01079 
01080   case Type::TypeOf:
01081     return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
01082 
01083   case Type::Decltype:
01084     return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
01085                         .getTypePtr());
01086 
01087   case Type::UnaryTransform:
01088     return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
01089 
01090   case Type::Elaborated:
01091     return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
01092 
01093   case Type::Attributed:
01094     return getTypeInfo(
01095                   cast<AttributedType>(T)->getEquivalentType().getTypePtr());
01096 
01097   case Type::TemplateSpecialization: {
01098     assert(getCanonicalType(T) != T &&
01099            "Cannot request the size of a dependent type");
01100     const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
01101     // A type alias template specialization may refer to a typedef with the
01102     // aligned attribute on it.
01103     if (TST->isTypeAlias())
01104       return getTypeInfo(TST->getAliasedType().getTypePtr());
01105     else
01106       return getTypeInfo(getCanonicalType(T));
01107   }
01108 
01109   case Type::Atomic: {
01110     std::pair<uint64_t, unsigned> Info
01111       = getTypeInfo(cast<AtomicType>(T)->getValueType());
01112     Width = Info.first;
01113     Align = Info.second;
01114     if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth() &&
01115         llvm::isPowerOf2_64(Width)) {
01116       // We can potentially perform lock-free atomic operations for this
01117       // type; promote the alignment appropriately.
01118       // FIXME: We could potentially promote the width here as well...
01119       // is that worthwhile?  (Non-struct atomic types generally have
01120       // power-of-two size anyway, but structs might not.  Requires a bit
01121       // of implementation work to make sure we zero out the extra bits.)
01122       Align = static_cast<unsigned>(Width);
01123     }
01124   }
01125 
01126   }
01127 
01128   assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
01129   return std::make_pair(Width, Align);
01130 }
01131 
01132 /// toCharUnitsFromBits - Convert a size in bits to a size in characters.
01133 CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
01134   return CharUnits::fromQuantity(BitSize / getCharWidth());
01135 }
01136 
01137 /// toBits - Convert a size in characters to a size in characters.
01138 int64_t ASTContext::toBits(CharUnits CharSize) const {
01139   return CharSize.getQuantity() * getCharWidth();
01140 }
01141 
01142 /// getTypeSizeInChars - Return the size of the specified type, in characters.
01143 /// This method does not work on incomplete types.
01144 CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
01145   return toCharUnitsFromBits(getTypeSize(T));
01146 }
01147 CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
01148   return toCharUnitsFromBits(getTypeSize(T));
01149 }
01150 
01151 /// getTypeAlignInChars - Return the ABI-specified alignment of a type, in 
01152 /// characters. This method does not work on incomplete types.
01153 CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
01154   return toCharUnitsFromBits(getTypeAlign(T));
01155 }
01156 CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
01157   return toCharUnitsFromBits(getTypeAlign(T));
01158 }
01159 
01160 /// getPreferredTypeAlign - Return the "preferred" alignment of the specified
01161 /// type for the current target in bits.  This can be different than the ABI
01162 /// alignment in cases where it is beneficial for performance to overalign
01163 /// a data type.
01164 unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
01165   unsigned ABIAlign = getTypeAlign(T);
01166 
01167   // Double and long long should be naturally aligned if possible.
01168   if (const ComplexType* CT = T->getAs<ComplexType>())
01169     T = CT->getElementType().getTypePtr();
01170   if (T->isSpecificBuiltinType(BuiltinType::Double) ||
01171       T->isSpecificBuiltinType(BuiltinType::LongLong) ||
01172       T->isSpecificBuiltinType(BuiltinType::ULongLong))
01173     return std::max(ABIAlign, (unsigned)getTypeSize(T));
01174 
01175   return ABIAlign;
01176 }
01177 
01178 /// DeepCollectObjCIvars -
01179 /// This routine first collects all declared, but not synthesized, ivars in
01180 /// super class and then collects all ivars, including those synthesized for
01181 /// current class. This routine is used for implementation of current class
01182 /// when all ivars, declared and synthesized are known.
01183 ///
01184 void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
01185                                       bool leafClass,
01186                             SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
01187   if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
01188     DeepCollectObjCIvars(SuperClass, false, Ivars);
01189   if (!leafClass) {
01190     for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
01191          E = OI->ivar_end(); I != E; ++I)
01192       Ivars.push_back(&*I);
01193   } else {
01194     ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
01195     for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv; 
01196          Iv= Iv->getNextIvar())
01197       Ivars.push_back(Iv);
01198   }
01199 }
01200 
01201 /// CollectInheritedProtocols - Collect all protocols in current class and
01202 /// those inherited by it.
01203 void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
01204                           llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
01205   if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
01206     // We can use protocol_iterator here instead of
01207     // all_referenced_protocol_iterator since we are walking all categories.    
01208     for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
01209          PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
01210       ObjCProtocolDecl *Proto = (*P);
01211       Protocols.insert(Proto->getCanonicalDecl());
01212       for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
01213            PE = Proto->protocol_end(); P != PE; ++P) {
01214         Protocols.insert((*P)->getCanonicalDecl());
01215         CollectInheritedProtocols(*P, Protocols);
01216       }
01217     }
01218     
01219     // Categories of this Interface.
01220     for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList(); 
01221          CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
01222       CollectInheritedProtocols(CDeclChain, Protocols);
01223     if (ObjCInterfaceDecl *SD = OI->getSuperClass())
01224       while (SD) {
01225         CollectInheritedProtocols(SD, Protocols);
01226         SD = SD->getSuperClass();
01227       }
01228   } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
01229     for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
01230          PE = OC->protocol_end(); P != PE; ++P) {
01231       ObjCProtocolDecl *Proto = (*P);
01232       Protocols.insert(Proto->getCanonicalDecl());
01233       for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
01234            PE = Proto->protocol_end(); P != PE; ++P)
01235         CollectInheritedProtocols(*P, Protocols);
01236     }
01237   } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
01238     for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
01239          PE = OP->protocol_end(); P != PE; ++P) {
01240       ObjCProtocolDecl *Proto = (*P);
01241       Protocols.insert(Proto->getCanonicalDecl());
01242       for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
01243            PE = Proto->protocol_end(); P != PE; ++P)
01244         CollectInheritedProtocols(*P, Protocols);
01245     }
01246   }
01247 }
01248 
01249 unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
01250   unsigned count = 0;  
01251   // Count ivars declared in class extension.
01252   for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
01253        CDecl = CDecl->getNextClassExtension())
01254     count += CDecl->ivar_size();
01255 
01256   // Count ivar defined in this class's implementation.  This
01257   // includes synthesized ivars.
01258   if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
01259     count += ImplDecl->ivar_size();
01260 
01261   return count;
01262 }
01263 
01264 bool ASTContext::isSentinelNullExpr(const Expr *E) {
01265   if (!E)
01266     return false;
01267 
01268   // nullptr_t is always treated as null.
01269   if (E->getType()->isNullPtrType()) return true;
01270 
01271   if (E->getType()->isAnyPointerType() &&
01272       E->IgnoreParenCasts()->isNullPointerConstant(*this,
01273                                                 Expr::NPC_ValueDependentIsNull))
01274     return true;
01275 
01276   // Unfortunately, __null has type 'int'.
01277   if (isa<GNUNullExpr>(E)) return true;
01278 
01279   return false;
01280 }
01281 
01282 /// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
01283 ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
01284   llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
01285     I = ObjCImpls.find(D);
01286   if (I != ObjCImpls.end())
01287     return cast<ObjCImplementationDecl>(I->second);
01288   return 0;
01289 }
01290 /// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
01291 ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
01292   llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
01293     I = ObjCImpls.find(D);
01294   if (I != ObjCImpls.end())
01295     return cast<ObjCCategoryImplDecl>(I->second);
01296   return 0;
01297 }
01298 
01299 /// \brief Set the implementation of ObjCInterfaceDecl.
01300 void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
01301                            ObjCImplementationDecl *ImplD) {
01302   assert(IFaceD && ImplD && "Passed null params");
01303   ObjCImpls[IFaceD] = ImplD;
01304 }
01305 /// \brief Set the implementation of ObjCCategoryDecl.
01306 void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
01307                            ObjCCategoryImplDecl *ImplD) {
01308   assert(CatD && ImplD && "Passed null params");
01309   ObjCImpls[CatD] = ImplD;
01310 }
01311 
01312 ObjCInterfaceDecl *ASTContext::getObjContainingInterface(NamedDecl *ND) const {
01313   if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
01314     return ID;
01315   if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
01316     return CD->getClassInterface();
01317   if (ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
01318     return IMD->getClassInterface();
01319 
01320   return 0;
01321 }
01322 
01323 /// \brief Get the copy initialization expression of VarDecl,or NULL if 
01324 /// none exists.
01325 Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
01326   assert(VD && "Passed null params");
01327   assert(VD->hasAttr<BlocksAttr>() && 
01328          "getBlockVarCopyInits - not __block var");
01329   llvm::DenseMap<const VarDecl*, Expr*>::iterator
01330     I = BlockVarCopyInits.find(VD);
01331   return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
01332 }
01333 
01334 /// \brief Set the copy inialization expression of a block var decl.
01335 void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
01336   assert(VD && Init && "Passed null params");
01337   assert(VD->hasAttr<BlocksAttr>() && 
01338          "setBlockVarCopyInits - not __block var");
01339   BlockVarCopyInits[VD] = Init;
01340 }
01341 
01342 /// \brief Allocate an uninitialized TypeSourceInfo.
01343 ///
01344 /// The caller should initialize the memory held by TypeSourceInfo using
01345 /// the TypeLoc wrappers.
01346 ///
01347 /// \param T the type that will be the basis for type source info. This type
01348 /// should refer to how the declarator was written in source code, not to
01349 /// what type semantic analysis resolved the declarator to.
01350 TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
01351                                                  unsigned DataSize) const {
01352   if (!DataSize)
01353     DataSize = TypeLoc::getFullDataSizeForType(T);
01354   else
01355     assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
01356            "incorrect data size provided to CreateTypeSourceInfo!");
01357 
01358   TypeSourceInfo *TInfo =
01359     (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
01360   new (TInfo) TypeSourceInfo(T);
01361   return TInfo;
01362 }
01363 
01364 TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
01365                                                      SourceLocation L) const {
01366   TypeSourceInfo *DI = CreateTypeSourceInfo(T);
01367   DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
01368   return DI;
01369 }
01370 
01371 const ASTRecordLayout &
01372 ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
01373   return getObjCLayout(D, 0);
01374 }
01375 
01376 const ASTRecordLayout &
01377 ASTContext::getASTObjCImplementationLayout(
01378                                         const ObjCImplementationDecl *D) const {
01379   return getObjCLayout(D->getClassInterface(), D);
01380 }
01381 
01382 //===----------------------------------------------------------------------===//
01383 //                   Type creation/memoization methods
01384 //===----------------------------------------------------------------------===//
01385 
01386 QualType
01387 ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
01388   unsigned fastQuals = quals.getFastQualifiers();
01389   quals.removeFastQualifiers();
01390 
01391   // Check if we've already instantiated this type.
01392   llvm::FoldingSetNodeID ID;
01393   ExtQuals::Profile(ID, baseType, quals);
01394   void *insertPos = 0;
01395   if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
01396     assert(eq->getQualifiers() == quals);
01397     return QualType(eq, fastQuals);
01398   }
01399 
01400   // If the base type is not canonical, make the appropriate canonical type.
01401   QualType canon;
01402   if (!baseType->isCanonicalUnqualified()) {
01403     SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
01404     canonSplit.Quals.addConsistentQualifiers(quals);
01405     canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
01406 
01407     // Re-find the insert position.
01408     (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
01409   }
01410 
01411   ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
01412   ExtQualNodes.InsertNode(eq, insertPos);
01413   return QualType(eq, fastQuals);
01414 }
01415 
01416 QualType
01417 ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
01418   QualType CanT = getCanonicalType(T);
01419   if (CanT.getAddressSpace() == AddressSpace)
01420     return T;
01421 
01422   // If we are composing extended qualifiers together, merge together
01423   // into one ExtQuals node.
01424   QualifierCollector Quals;
01425   const Type *TypeNode = Quals.strip(T);
01426 
01427   // If this type already has an address space specified, it cannot get
01428   // another one.
01429   assert(!Quals.hasAddressSpace() &&
01430          "Type cannot be in multiple addr spaces!");
01431   Quals.addAddressSpace(AddressSpace);
01432 
01433   return getExtQualType(TypeNode, Quals);
01434 }
01435 
01436 QualType ASTContext::getObjCGCQualType(QualType T,
01437                                        Qualifiers::GC GCAttr) const {
01438   QualType CanT = getCanonicalType(T);
01439   if (CanT.getObjCGCAttr() == GCAttr)
01440     return T;
01441 
01442   if (const PointerType *ptr = T->getAs<PointerType>()) {
01443     QualType Pointee = ptr->getPointeeType();
01444     if (Pointee->isAnyPointerType()) {
01445       QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
01446       return getPointerType(ResultType);
01447     }
01448   }
01449 
01450   // If we are composing extended qualifiers together, merge together
01451   // into one ExtQuals node.
01452   QualifierCollector Quals;
01453   const Type *TypeNode = Quals.strip(T);
01454 
01455   // If this type already has an ObjCGC specified, it cannot get
01456   // another one.
01457   assert(!Quals.hasObjCGCAttr() &&
01458          "Type cannot have multiple ObjCGCs!");
01459   Quals.addObjCGCAttr(GCAttr);
01460 
01461   return getExtQualType(TypeNode, Quals);
01462 }
01463 
01464 const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
01465                                                    FunctionType::ExtInfo Info) {
01466   if (T->getExtInfo() == Info)
01467     return T;
01468 
01469   QualType Result;
01470   if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
01471     Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
01472   } else {
01473     const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
01474     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
01475     EPI.ExtInfo = Info;
01476     Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
01477                              FPT->getNumArgs(), EPI);
01478   }
01479 
01480   return cast<FunctionType>(Result.getTypePtr());
01481 }
01482 
01483 /// getComplexType - Return the uniqued reference to the type for a complex
01484 /// number with the specified element type.
01485 QualType ASTContext::getComplexType(QualType T) const {
01486   // Unique pointers, to guarantee there is only one pointer of a particular
01487   // structure.
01488   llvm::FoldingSetNodeID ID;
01489   ComplexType::Profile(ID, T);
01490 
01491   void *InsertPos = 0;
01492   if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
01493     return QualType(CT, 0);
01494 
01495   // If the pointee type isn't canonical, this won't be a canonical type either,
01496   // so fill in the canonical type field.
01497   QualType Canonical;
01498   if (!T.isCanonical()) {
01499     Canonical = getComplexType(getCanonicalType(T));
01500 
01501     // Get the new insert position for the node we care about.
01502     ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
01503     assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
01504   }
01505   ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
01506   Types.push_back(New);
01507   ComplexTypes.InsertNode(New, InsertPos);
01508   return QualType(New, 0);
01509 }
01510 
01511 /// getPointerType - Return the uniqued reference to the type for a pointer to
01512 /// the specified type.
01513 QualType ASTContext::getPointerType(QualType T) const {
01514   // Unique pointers, to guarantee there is only one pointer of a particular
01515   // structure.
01516   llvm::FoldingSetNodeID ID;
01517   PointerType::Profile(ID, T);
01518 
01519   void *InsertPos = 0;
01520   if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
01521     return QualType(PT, 0);
01522 
01523   // If the pointee type isn't canonical, this won't be a canonical type either,
01524   // so fill in the canonical type field.
01525   QualType Canonical;
01526   if (!T.isCanonical()) {
01527     Canonical = getPointerType(getCanonicalType(T));
01528 
01529     // Get the new insert position for the node we care about.
01530     PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
01531     assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
01532   }
01533   PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
01534   Types.push_back(New);
01535   PointerTypes.InsertNode(New, InsertPos);
01536   return QualType(New, 0);
01537 }
01538 
01539 /// getBlockPointerType - Return the uniqued reference to the type for
01540 /// a pointer to the specified block.
01541 QualType ASTContext::getBlockPointerType(QualType T) const {
01542   assert(T->isFunctionType() && "block of function types only");
01543   // Unique pointers, to guarantee there is only one block of a particular
01544   // structure.
01545   llvm::FoldingSetNodeID ID;
01546   BlockPointerType::Profile(ID, T);
01547 
01548   void *InsertPos = 0;
01549   if (BlockPointerType *PT =
01550         BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
01551     return QualType(PT, 0);
01552 
01553   // If the block pointee type isn't canonical, this won't be a canonical
01554   // type either so fill in the canonical type field.
01555   QualType Canonical;
01556   if (!T.isCanonical()) {
01557     Canonical = getBlockPointerType(getCanonicalType(T));
01558 
01559     // Get the new insert position for the node we care about.
01560     BlockPointerType *NewIP =
01561       BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
01562     assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
01563   }
01564   BlockPointerType *New
01565     = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
01566   Types.push_back(New);
01567   BlockPointerTypes.InsertNode(New, InsertPos);
01568   return QualType(New, 0);
01569 }
01570 
01571 /// getLValueReferenceType - Return the uniqued reference to the type for an
01572 /// lvalue reference to the specified type.
01573 QualType
01574 ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
01575   assert(getCanonicalType(T) != OverloadTy && 
01576          "Unresolved overloaded function type");
01577   
01578   // Unique pointers, to guarantee there is only one pointer of a particular
01579   // structure.
01580   llvm::FoldingSetNodeID ID;
01581   ReferenceType::Profile(ID, T, SpelledAsLValue);
01582 
01583   void *InsertPos = 0;
01584   if (LValueReferenceType *RT =
01585         LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
01586     return QualType(RT, 0);
01587 
01588   const ReferenceType *InnerRef = T->getAs<ReferenceType>();
01589 
01590   // If the referencee type isn't canonical, this won't be a canonical type
01591   // either, so fill in the canonical type field.
01592   QualType Canonical;
01593   if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
01594     QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
01595     Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
01596 
01597     // Get the new insert position for the node we care about.
01598     LValueReferenceType *NewIP =
01599       LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
01600     assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
01601   }
01602 
01603   LValueReferenceType *New
01604     = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
01605                                                      SpelledAsLValue);
01606   Types.push_back(New);
01607   LValueReferenceTypes.InsertNode(New, InsertPos);
01608 
01609   return QualType(New, 0);
01610 }
01611 
01612 /// getRValueReferenceType - Return the uniqued reference to the type for an
01613 /// rvalue reference to the specified type.
01614 QualType ASTContext::getRValueReferenceType(QualType T) const {
01615   // Unique pointers, to guarantee there is only one pointer of a particular
01616   // structure.
01617   llvm::FoldingSetNodeID ID;
01618   ReferenceType::Profile(ID, T, false);
01619 
01620   void *InsertPos = 0;
01621   if (RValueReferenceType *RT =
01622         RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
01623     return QualType(RT, 0);
01624 
01625   const ReferenceType *InnerRef = T->getAs<ReferenceType>();
01626 
01627   // If the referencee type isn't canonical, this won't be a canonical type
01628   // either, so fill in the canonical type field.
01629   QualType Canonical;
01630   if (InnerRef || !T.isCanonical()) {
01631     QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
01632     Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
01633 
01634     // Get the new insert position for the node we care about.
01635     RValueReferenceType *NewIP =
01636       RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
01637     assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
01638   }
01639 
01640   RValueReferenceType *New
01641     = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
01642   Types.push_back(New);
01643   RValueReferenceTypes.InsertNode(New, InsertPos);
01644   return QualType(New, 0);
01645 }
01646 
01647 /// getMemberPointerType - Return the uniqued reference to the type for a
01648 /// member pointer to the specified type, in the specified class.
01649 QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
01650   // Unique pointers, to guarantee there is only one pointer of a particular
01651   // structure.
01652   llvm::FoldingSetNodeID ID;
01653   MemberPointerType::Profile(ID, T, Cls);
01654 
01655   void *InsertPos = 0;
01656   if (MemberPointerType *PT =
01657       MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
01658     return QualType(PT, 0);
01659 
01660   // If the pointee or class type isn't canonical, this won't be a canonical
01661   // type either, so fill in the canonical type field.
01662   QualType Canonical;
01663   if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
01664     Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
01665 
01666     // Get the new insert position for the node we care about.
01667     MemberPointerType *NewIP =
01668       MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
01669     assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
01670   }
01671   MemberPointerType *New
01672     = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
01673   Types.push_back(New);
01674   MemberPointerTypes.InsertNode(New, InsertPos);
01675   return QualType(New, 0);
01676 }
01677 
01678 /// getConstantArrayType - Return the unique reference to the type for an
01679 /// array of the specified element type.
01680 QualType ASTContext::getConstantArrayType(QualType EltTy,
01681                                           const llvm::APInt &ArySizeIn,
01682                                           ArrayType::ArraySizeModifier ASM,
01683                                           unsigned IndexTypeQuals) const {
01684   assert((EltTy->isDependentType() ||
01685           EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
01686          "Constant array of VLAs is illegal!");
01687 
01688   // Convert the array size into a canonical width matching the pointer size for
01689   // the target.
01690   llvm::APInt ArySize(ArySizeIn);
01691   ArySize =
01692     ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
01693 
01694   llvm::FoldingSetNodeID ID;
01695   ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
01696 
01697   void *InsertPos = 0;
01698   if (ConstantArrayType *ATP =
01699       ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
01700     return QualType(ATP, 0);
01701 
01702   // If the element type isn't canonical or has qualifiers, this won't
01703   // be a canonical type either, so fill in the canonical type field.
01704   QualType Canon;
01705   if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
01706     SplitQualType canonSplit = getCanonicalType(EltTy).split();
01707     Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
01708                                  ASM, IndexTypeQuals);
01709     Canon = getQualifiedType(Canon, canonSplit.Quals);
01710 
01711     // Get the new insert position for the node we care about.
01712     ConstantArrayType *NewIP =
01713       ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
01714     assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
01715   }
01716 
01717   ConstantArrayType *New = new(*this,TypeAlignment)
01718     ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
01719   ConstantArrayTypes.InsertNode(New, InsertPos);
01720   Types.push_back(New);
01721   return QualType(New, 0);
01722 }
01723 
01724 /// getVariableArrayDecayedType - Turns the given type, which may be
01725 /// variably-modified, into the corresponding type with all the known
01726 /// sizes replaced with [*].
01727 QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
01728   // Vastly most common case.
01729   if (!type->isVariablyModifiedType()) return type;
01730 
01731   QualType result;
01732 
01733   SplitQualType split = type.getSplitDesugaredType();
01734   const Type *ty = split.Ty;
01735   switch (ty->getTypeClass()) {
01736 #define TYPE(Class, Base)
01737 #define ABSTRACT_TYPE(Class, Base)
01738 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
01739 #include "clang/AST/TypeNodes.def"
01740     llvm_unreachable("didn't desugar past all non-canonical types?");
01741 
01742   // These types should never be variably-modified.
01743   case Type::Builtin:
01744   case Type::Complex:
01745   case Type::Vector:
01746   case Type::ExtVector:
01747   case Type::DependentSizedExtVector:
01748   case Type::ObjCObject:
01749   case Type::ObjCInterface:
01750   case Type::ObjCObjectPointer:
01751   case Type::Record:
01752   case Type::Enum:
01753   case Type::UnresolvedUsing:
01754   case Type::TypeOfExpr:
01755   case Type::TypeOf:
01756   case Type::Decltype:
01757   case Type::UnaryTransform:
01758   case Type::DependentName:
01759   case Type::InjectedClassName:
01760   case Type::TemplateSpecialization:
01761   case Type::DependentTemplateSpecialization:
01762   case Type::TemplateTypeParm:
01763   case Type::SubstTemplateTypeParmPack:
01764   case Type::Auto:
01765   case Type::PackExpansion:
01766     llvm_unreachable("type should never be variably-modified");
01767 
01768   // These types can be variably-modified but should never need to
01769   // further decay.
01770   case Type::FunctionNoProto:
01771   case Type::FunctionProto:
01772   case Type::BlockPointer:
01773   case Type::MemberPointer:
01774     return type;
01775 
01776   // These types can be variably-modified.  All these modifications
01777   // preserve structure except as noted by comments.
01778   // TODO: if we ever care about optimizing VLAs, there are no-op
01779   // optimizations available here.
01780   case Type::Pointer:
01781     result = getPointerType(getVariableArrayDecayedType(
01782                               cast<PointerType>(ty)->getPointeeType()));
01783     break;
01784 
01785   case Type::LValueReference: {
01786     const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
01787     result = getLValueReferenceType(
01788                  getVariableArrayDecayedType(lv->getPointeeType()),
01789                                     lv->isSpelledAsLValue());
01790     break;
01791   }
01792 
01793   case Type::RValueReference: {
01794     const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
01795     result = getRValueReferenceType(
01796                  getVariableArrayDecayedType(lv->getPointeeType()));
01797     break;
01798   }
01799 
01800   case Type::Atomic: {
01801     const AtomicType *at = cast<AtomicType>(ty);
01802     result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
01803     break;
01804   }
01805 
01806   case Type::ConstantArray: {
01807     const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
01808     result = getConstantArrayType(
01809                  getVariableArrayDecayedType(cat->getElementType()),
01810                                   cat->getSize(),
01811                                   cat->getSizeModifier(),
01812                                   cat->getIndexTypeCVRQualifiers());
01813     break;
01814   }
01815 
01816   case Type::DependentSizedArray: {
01817     const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
01818     result = getDependentSizedArrayType(
01819                  getVariableArrayDecayedType(dat->getElementType()),
01820                                         dat->getSizeExpr(),
01821                                         dat->getSizeModifier(),
01822                                         dat->getIndexTypeCVRQualifiers(),
01823                                         dat->getBracketsRange());
01824     break;
01825   }
01826 
01827   // Turn incomplete types into [*] types.
01828   case Type::IncompleteArray: {
01829     const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
01830     result = getVariableArrayType(
01831                  getVariableArrayDecayedType(iat->getElementType()),
01832                                   /*size*/ 0,
01833                                   ArrayType::Normal,
01834                                   iat->getIndexTypeCVRQualifiers(),
01835                                   SourceRange());
01836     break;
01837   }
01838 
01839   // Turn VLA types into [*] types.
01840   case Type::VariableArray: {
01841     const VariableArrayType *vat = cast<VariableArrayType>(ty);
01842     result = getVariableArrayType(
01843                  getVariableArrayDecayedType(vat->getElementType()),
01844                                   /*size*/ 0,
01845                                   ArrayType::Star,
01846                                   vat->getIndexTypeCVRQualifiers(),
01847                                   vat->getBracketsRange());
01848     break;
01849   }
01850   }
01851 
01852   // Apply the top-level qualifiers from the original.
01853   return getQualifiedType(result, split.Quals);
01854 }
01855 
01856 /// getVariableArrayType - Returns a non-unique reference to the type for a
01857 /// variable array of the specified element type.
01858 QualType ASTContext::getVariableArrayType(QualType EltTy,
01859                                           Expr *NumElts,
01860                                           ArrayType::ArraySizeModifier ASM,
01861                                           unsigned IndexTypeQuals,
01862                                           SourceRange Brackets) const {
01863   // Since we don't unique expressions, it isn't possible to unique VLA's
01864   // that have an expression provided for their size.
01865   QualType Canon;
01866   
01867   // Be sure to pull qualifiers off the element type.
01868   if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
01869     SplitQualType canonSplit = getCanonicalType(EltTy).split();
01870     Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
01871                                  IndexTypeQuals, Brackets);
01872     Canon = getQualifiedType(Canon, canonSplit.Quals);
01873   }
01874   
01875   VariableArrayType *New = new(*this, TypeAlignment)
01876     VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
01877 
01878   VariableArrayTypes.push_back(New);
01879   Types.push_back(New);
01880   return QualType(New, 0);
01881 }
01882 
01883 /// getDependentSizedArrayType - Returns a non-unique reference to
01884 /// the type for a dependently-sized array of the specified element
01885 /// type.
01886 QualType ASTContext::getDependentSizedArrayType(QualType elementType,
01887                                                 Expr *numElements,
01888                                                 ArrayType::ArraySizeModifier ASM,
01889                                                 unsigned elementTypeQuals,
01890                                                 SourceRange brackets) const {
01891   assert((!numElements || numElements->isTypeDependent() || 
01892           numElements->isValueDependent()) &&
01893          "Size must be type- or value-dependent!");
01894 
01895   // Dependently-sized array types that do not have a specified number
01896   // of elements will have their sizes deduced from a dependent
01897   // initializer.  We do no canonicalization here at all, which is okay
01898   // because they can't be used in most locations.
01899   if (!numElements) {
01900     DependentSizedArrayType *newType
01901       = new (*this, TypeAlignment)
01902           DependentSizedArrayType(*this, elementType, QualType(),
01903                                   numElements, ASM, elementTypeQuals,
01904                                   brackets);
01905     Types.push_back(newType);
01906     return QualType(newType, 0);
01907   }
01908 
01909   // Otherwise, we actually build a new type every time, but we
01910   // also build a canonical type.
01911 
01912   SplitQualType canonElementType = getCanonicalType(elementType).split();
01913 
01914   void *insertPos = 0;
01915   llvm::FoldingSetNodeID ID;
01916   DependentSizedArrayType::Profile(ID, *this,
01917                                    QualType(canonElementType.Ty, 0),
01918                                    ASM, elementTypeQuals, numElements);
01919 
01920   // Look for an existing type with these properties.
01921   DependentSizedArrayType *canonTy =
01922     DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
01923 
01924   // If we don't have one, build one.
01925   if (!canonTy) {
01926     canonTy = new (*this, TypeAlignment)
01927       DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
01928                               QualType(), numElements, ASM, elementTypeQuals,
01929                               brackets);
01930     DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
01931     Types.push_back(canonTy);
01932   }
01933 
01934   // Apply qualifiers from the element type to the array.
01935   QualType canon = getQualifiedType(QualType(canonTy,0),
01936                                     canonElementType.Quals);
01937 
01938   // If we didn't need extra canonicalization for the element type,
01939   // then just use that as our result.
01940   if (QualType(canonElementType.Ty, 0) == elementType)
01941     return canon;
01942 
01943   // Otherwise, we need to build a type which follows the spelling
01944   // of the element type.
01945   DependentSizedArrayType *sugaredType
01946     = new (*this, TypeAlignment)
01947         DependentSizedArrayType(*this, elementType, canon, numElements,
01948                                 ASM, elementTypeQuals, brackets);
01949   Types.push_back(sugaredType);
01950   return QualType(sugaredType, 0);
01951 }
01952 
01953 QualType ASTContext::getIncompleteArrayType(QualType elementType,
01954                                             ArrayType::ArraySizeModifier ASM,
01955                                             unsigned elementTypeQuals) const {
01956   llvm::FoldingSetNodeID ID;
01957   IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
01958 
01959   void *insertPos = 0;
01960   if (IncompleteArrayType *iat =
01961        IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
01962     return QualType(iat, 0);
01963 
01964   // If the element type isn't canonical, this won't be a canonical type
01965   // either, so fill in the canonical type field.  We also have to pull
01966   // qualifiers off the element type.
01967   QualType canon;
01968 
01969   if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
01970     SplitQualType canonSplit = getCanonicalType(elementType).split();
01971     canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
01972                                    ASM, elementTypeQuals);
01973     canon = getQualifiedType(canon, canonSplit.Quals);
01974 
01975     // Get the new insert position for the node we care about.
01976     IncompleteArrayType *existing =
01977       IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
01978     assert(!existing && "Shouldn't be in the map!"); (void) existing;
01979   }
01980 
01981   IncompleteArrayType *newType = new (*this, TypeAlignment)
01982     IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
01983 
01984   IncompleteArrayTypes.InsertNode(newType, insertPos);
01985   Types.push_back(newType);
01986   return QualType(newType, 0);
01987 }
01988 
01989 /// getVectorType - Return the unique reference to a vector type of
01990 /// the specified element type and size. VectorType must be a built-in type.
01991 QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
01992                                    VectorType::VectorKind VecKind) const {
01993   assert(vecType->isBuiltinType());
01994 
01995   // Check if we've already instantiated a vector of this type.
01996   llvm::FoldingSetNodeID ID;
01997   VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
01998 
01999   void *InsertPos = 0;
02000   if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
02001     return QualType(VTP, 0);
02002 
02003   // If the element type isn't canonical, this won't be a canonical type either,
02004   // so fill in the canonical type field.
02005   QualType Canonical;
02006   if (!vecType.isCanonical()) {
02007     Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
02008 
02009     // Get the new insert position for the node we care about.
02010     VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
02011     assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
02012   }
02013   VectorType *New = new (*this, TypeAlignment)
02014     VectorType(vecType, NumElts, Canonical, VecKind);
02015   VectorTypes.InsertNode(New, InsertPos);
02016   Types.push_back(New);
02017   return QualType(New, 0);
02018 }
02019 
02020 /// getExtVectorType - Return the unique reference to an extended vector type of
02021 /// the specified element type and size. VectorType must be a built-in type.
02022 QualType
02023 ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
02024   assert(vecType->isBuiltinType() || vecType->isDependentType());
02025 
02026   // Check if we've already instantiated a vector of this type.
02027   llvm::FoldingSetNodeID ID;
02028   VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
02029                       VectorType::GenericVector);
02030   void *InsertPos = 0;
02031   if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
02032     return QualType(VTP, 0);
02033 
02034   // If the element type isn't canonical, this won't be a canonical type either,
02035   // so fill in the canonical type field.
02036   QualType Canonical;
02037   if (!vecType.isCanonical()) {
02038     Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
02039 
02040     // Get the new insert position for the node we care about.
02041     VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
02042     assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
02043   }
02044   ExtVectorType *New = new (*this, TypeAlignment)
02045     ExtVectorType(vecType, NumElts, Canonical);
02046   VectorTypes.InsertNode(New, InsertPos);
02047   Types.push_back(New);
02048   return QualType(New, 0);
02049 }
02050 
02051 QualType
02052 ASTContext::getDependentSizedExtVectorType(QualType vecType,
02053                                            Expr *SizeExpr,
02054                                            SourceLocation AttrLoc) const {
02055   llvm::FoldingSetNodeID ID;
02056   DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
02057                                        SizeExpr);
02058 
02059   void *InsertPos = 0;
02060   DependentSizedExtVectorType *Canon
02061     = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
02062   DependentSizedExtVectorType *New;
02063   if (Canon) {
02064     // We already have a canonical version of this array type; use it as
02065     // the canonical type for a newly-built type.
02066     New = new (*this, TypeAlignment)
02067       DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
02068                                   SizeExpr, AttrLoc);
02069   } else {
02070     QualType CanonVecTy = getCanonicalType(vecType);
02071     if (CanonVecTy == vecType) {
02072       New = new (*this, TypeAlignment)
02073         DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
02074                                     AttrLoc);
02075 
02076       DependentSizedExtVectorType *CanonCheck
02077         = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
02078       assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
02079       (void)CanonCheck;
02080       DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
02081     } else {
02082       QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
02083                                                       SourceLocation());
02084       New = new (*this, TypeAlignment) 
02085         DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
02086     }
02087   }
02088 
02089   Types.push_back(New);
02090   return QualType(New, 0);
02091 }
02092 
02093 /// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
02094 ///
02095 QualType
02096 ASTContext::getFunctionNoProtoType(QualType ResultTy,
02097                                    const FunctionType::ExtInfo &Info) const {
02098   const CallingConv DefaultCC = Info.getCC();
02099   const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
02100                                CC_X86StdCall : DefaultCC;
02101   // Unique functions, to guarantee there is only one function of a particular
02102   // structure.
02103   llvm::FoldingSetNodeID ID;
02104   FunctionNoProtoType::Profile(ID, ResultTy, Info);
02105 
02106   void *InsertPos = 0;
02107   if (FunctionNoProtoType *FT =
02108         FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
02109     return QualType(FT, 0);
02110 
02111   QualType Canonical;
02112   if (!ResultTy.isCanonical() ||
02113       getCanonicalCallConv(CallConv) != CallConv) {
02114     Canonical =
02115       getFunctionNoProtoType(getCanonicalType(ResultTy),
02116                      Info.withCallingConv(getCanonicalCallConv(CallConv)));
02117 
02118     // Get the new insert position for the node we care about.
02119     FunctionNoProtoType *NewIP =
02120       FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
02121     assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
02122   }
02123 
02124   FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
02125   FunctionNoProtoType *New = new (*this, TypeAlignment)
02126     FunctionNoProtoType(ResultTy, Canonical, newInfo);
02127   Types.push_back(New);
02128   FunctionNoProtoTypes.InsertNode(New, InsertPos);
02129   return QualType(New, 0);
02130 }
02131 
02132 /// getFunctionType - Return a normal function type with a typed argument
02133 /// list.  isVariadic indicates whether the argument list includes '...'.
02134 QualType
02135 ASTContext::getFunctionType(QualType ResultTy,
02136                             const QualType *ArgArray, unsigned NumArgs,
02137                             const FunctionProtoType::ExtProtoInfo &EPI) const {
02138   // Unique functions, to guarantee there is only one function of a particular
02139   // structure.
02140   llvm::FoldingSetNodeID ID;
02141   FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
02142 
02143   void *InsertPos = 0;
02144   if (FunctionProtoType *FTP =
02145         FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
02146     return QualType(FTP, 0);
02147 
02148   // Determine whether the type being created is already canonical or not.
02149   bool isCanonical =
02150     EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical() &&
02151     !EPI.HasTrailingReturn;
02152   for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
02153     if (!ArgArray[i].isCanonicalAsParam())
02154       isCanonical = false;
02155 
02156   const CallingConv DefaultCC = EPI.ExtInfo.getCC();
02157   const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
02158                                CC_X86StdCall : DefaultCC;
02159 
02160   // If this type isn't canonical, get the canonical version of it.
02161   // The exception spec is not part of the canonical type.
02162   QualType Canonical;
02163   if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
02164     SmallVector<QualType, 16> CanonicalArgs;
02165     CanonicalArgs.reserve(NumArgs);
02166     for (unsigned i = 0; i != NumArgs; ++i)
02167       CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
02168 
02169     FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
02170     CanonicalEPI.HasTrailingReturn = false;
02171     CanonicalEPI.ExceptionSpecType = EST_None;
02172     CanonicalEPI.NumExceptions = 0;
02173     CanonicalEPI.ExtInfo
02174       = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
02175 
02176     Canonical = getFunctionType(getCanonicalType(ResultTy),
02177                                 CanonicalArgs.data(), NumArgs,
02178                                 CanonicalEPI);
02179 
02180     // Get the new insert position for the node we care about.
02181     FunctionProtoType *NewIP =
02182       FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
02183     assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
02184   }
02185 
02186   // FunctionProtoType objects are allocated with extra bytes after
02187   // them for three variable size arrays at the end:
02188   //  - parameter types
02189   //  - exception types
02190   //  - consumed-arguments flags
02191   // Instead of the exception types, there could be a noexcept
02192   // expression.
02193   size_t Size = sizeof(FunctionProtoType) +
02194                 NumArgs * sizeof(QualType);
02195   if (EPI.ExceptionSpecType == EST_Dynamic)
02196     Size += EPI.NumExceptions * sizeof(QualType);
02197   else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
02198     Size += sizeof(Expr*);
02199   } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
02200     Size += 2 * sizeof(FunctionDecl*);
02201   }
02202   if (EPI.ConsumedArguments)
02203     Size += NumArgs * sizeof(bool);
02204 
02205   FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
02206   FunctionProtoType::ExtProtoInfo newEPI = EPI;
02207   newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
02208   new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
02209   Types.push_back(FTP);
02210   FunctionProtoTypes.InsertNode(FTP, InsertPos);
02211   return QualType(FTP, 0);
02212 }
02213 
02214 #ifndef NDEBUG
02215 static bool NeedsInjectedClassNameType(const RecordDecl *D) {
02216   if (!isa<CXXRecordDecl>(D)) return false;
02217   const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
02218   if (isa<ClassTemplatePartialSpecializationDecl>(RD))
02219     return true;
02220   if (RD->getDescribedClassTemplate() &&
02221       !isa<ClassTemplateSpecializationDecl>(RD))
02222     return true;
02223   return false;
02224 }
02225 #endif
02226 
02227 /// getInjectedClassNameType - Return the unique reference to the
02228 /// injected class name type for the specified templated declaration.
02229 QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
02230                                               QualType TST) const {
02231   assert(NeedsInjectedClassNameType(Decl));
02232   if (Decl->TypeForDecl) {
02233     assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
02234   } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
02235     assert(PrevDecl->TypeForDecl && "previous declaration has no type");
02236     Decl->TypeForDecl = PrevDecl->TypeForDecl;
02237     assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
02238   } else {
02239     Type *newType =
02240       new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
02241     Decl->TypeForDecl = newType;
02242     Types.push_back(newType);
02243   }
02244   return QualType(Decl->TypeForDecl, 0);
02245 }
02246 
02247 /// getTypeDeclType - Return the unique reference to the type for the
02248 /// specified type declaration.
02249 QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
02250   assert(Decl && "Passed null for Decl param");
02251   assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
02252 
02253   if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
02254     return getTypedefType(Typedef);
02255 
02256   assert(!isa<TemplateTypeParmDecl>(Decl) &&
02257          "Template type parameter types are always available.");
02258 
02259   if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
02260     assert(!Record->getPreviousDecl() &&
02261            "struct/union has previous declaration");
02262     assert(!NeedsInjectedClassNameType(Record));
02263     return getRecordType(Record);
02264   } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
02265     assert(!Enum->getPreviousDecl() &&
02266            "enum has previous declaration");
02267     return getEnumType(Enum);
02268   } else if (const UnresolvedUsingTypenameDecl *Using =
02269                dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
02270     Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
02271     Decl->TypeForDecl = newType;
02272     Types.push_back(newType);
02273   } else
02274     llvm_unreachable("TypeDecl without a type?");
02275 
02276   return QualType(Decl->TypeForDecl, 0);
02277 }
02278 
02279 /// getTypedefType - Return the unique reference to the type for the
02280 /// specified typedef name decl.
02281 QualType
02282 ASTContext::getTypedefType(const TypedefNameDecl *Decl,
02283                            QualType Canonical) const {
02284   if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
02285 
02286   if (Canonical.isNull())
02287     Canonical = getCanonicalType(Decl->getUnderlyingType());
02288   TypedefType *newType = new(*this, TypeAlignment)
02289     TypedefType(Type::Typedef, Decl, Canonical);
02290   Decl->TypeForDecl = newType;
02291   Types.push_back(newType);
02292   return QualType(newType, 0);
02293 }
02294 
02295 QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
02296   if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
02297 
02298   if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
02299     if (PrevDecl->TypeForDecl)
02300       return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0); 
02301 
02302   RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
02303   Decl->TypeForDecl = newType;
02304   Types.push_back(newType);
02305   return QualType(newType, 0);
02306 }
02307 
02308 QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
02309   if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
02310 
02311   if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
02312     if (PrevDecl->TypeForDecl)
02313       return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0); 
02314 
02315   EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
02316   Decl->TypeForDecl = newType;
02317   Types.push_back(newType);
02318   return QualType(newType, 0);
02319 }
02320 
02321 QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
02322                                        QualType modifiedType,
02323                                        QualType equivalentType) {
02324   llvm::FoldingSetNodeID id;
02325   AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
02326 
02327   void *insertPos = 0;
02328   AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
02329   if (type) return QualType(type, 0);
02330 
02331   QualType canon = getCanonicalType(equivalentType);
02332   type = new (*this, TypeAlignment)
02333            AttributedType(canon, attrKind, modifiedType, equivalentType);
02334 
02335   Types.push_back(type);
02336   AttributedTypes.InsertNode(type, insertPos);
02337 
02338   return QualType(type, 0);
02339 }
02340 
02341 
02342 /// \brief Retrieve a substitution-result type.
02343 QualType
02344 ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
02345                                          QualType Replacement) const {
02346   assert(Replacement.isCanonical()
02347          && "replacement types must always be canonical");
02348 
02349   llvm::FoldingSetNodeID ID;
02350   SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
02351   void *InsertPos = 0;
02352   SubstTemplateTypeParmType *SubstParm
02353     = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
02354 
02355   if (!SubstParm) {
02356     SubstParm = new (*this, TypeAlignment)
02357       SubstTemplateTypeParmType(Parm, Replacement);
02358     Types.push_back(SubstParm);
02359     SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
02360   }
02361 
02362   return QualType(SubstParm, 0);
02363 }
02364 
02365 /// \brief Retrieve a 
02366 QualType ASTContext::getSubstTemplateTypeParmPackType(
02367                                           const TemplateTypeParmType *Parm,
02368                                               const TemplateArgument &ArgPack) {
02369 #ifndef NDEBUG
02370   for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(), 
02371                                     PEnd = ArgPack.pack_end();
02372        P != PEnd; ++P) {
02373     assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
02374     assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
02375   }
02376 #endif
02377   
02378   llvm::FoldingSetNodeID ID;
02379   SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
02380   void *InsertPos = 0;
02381   if (SubstTemplateTypeParmPackType *SubstParm
02382         = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
02383     return QualType(SubstParm, 0);
02384   
02385   QualType Canon;
02386   if (!Parm->isCanonicalUnqualified()) {
02387     Canon = getCanonicalType(QualType(Parm, 0));
02388     Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
02389                                              ArgPack);
02390     SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
02391   }
02392 
02393   SubstTemplateTypeParmPackType *SubstParm
02394     = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
02395                                                                ArgPack);
02396   Types.push_back(SubstParm);
02397   SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
02398   return QualType(SubstParm, 0);  
02399 }
02400 
02401 /// \brief Retrieve the template type parameter type for a template
02402 /// parameter or parameter pack with the given depth, index, and (optionally)
02403 /// name.
02404 QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
02405                                              bool ParameterPack,
02406                                              TemplateTypeParmDecl *TTPDecl) const {
02407   llvm::FoldingSetNodeID ID;
02408   TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
02409   void *InsertPos = 0;
02410   TemplateTypeParmType *TypeParm
02411     = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
02412 
02413   if (TypeParm)
02414     return QualType(TypeParm, 0);
02415 
02416   if (TTPDecl) {
02417     QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
02418     TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
02419 
02420     TemplateTypeParmType *TypeCheck 
02421       = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
02422     assert(!TypeCheck && "Template type parameter canonical type broken");
02423     (void)TypeCheck;
02424   } else
02425     TypeParm = new (*this, TypeAlignment)
02426       TemplateTypeParmType(Depth, Index, ParameterPack);
02427 
02428   Types.push_back(TypeParm);
02429   TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
02430 
02431   return QualType(TypeParm, 0);
02432 }
02433 
02434 TypeSourceInfo *
02435 ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
02436                                               SourceLocation NameLoc,
02437                                         const TemplateArgumentListInfo &Args,
02438                                               QualType Underlying) const {
02439   assert(!Name.getAsDependentTemplateName() && 
02440          "No dependent template names here!");
02441   QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
02442 
02443   TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
02444   TemplateSpecializationTypeLoc TL
02445     = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
02446   TL.setTemplateKeywordLoc(SourceLocation());
02447   TL.setTemplateNameLoc(NameLoc);
02448   TL.setLAngleLoc(Args.getLAngleLoc());
02449   TL.setRAngleLoc(Args.getRAngleLoc());
02450   for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
02451     TL.setArgLocInfo(i, Args[i].getLocInfo());
02452   return DI;
02453 }
02454 
02455 QualType
02456 ASTContext::getTemplateSpecializationType(TemplateName Template,
02457                                           const TemplateArgumentListInfo &Args,
02458                                           QualType Underlying) const {
02459   assert(!Template.getAsDependentTemplateName() && 
02460          "No dependent template names here!");
02461   
02462   unsigned NumArgs = Args.size();
02463 
02464   SmallVector<TemplateArgument, 4> ArgVec;
02465   ArgVec.reserve(NumArgs);
02466   for (unsigned i = 0; i != NumArgs; ++i)
02467     ArgVec.push_back(Args[i].getArgument());
02468 
02469   return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
02470                                        Underlying);
02471 }
02472 
02473 #ifndef NDEBUG
02474 static bool hasAnyPackExpansions(const TemplateArgument *Args,
02475                                  unsigned NumArgs) {
02476   for (unsigned I = 0; I != NumArgs; ++I)
02477     if (Args[I].isPackExpansion())
02478       return true;
02479   
02480   return true;
02481 }
02482 #endif
02483 
02484 QualType
02485 ASTContext::getTemplateSpecializationType(TemplateName Template,
02486                                           const TemplateArgument *Args,
02487                                           unsigned NumArgs,
02488                                           QualType Underlying) const {
02489   assert(!Template.getAsDependentTemplateName() && 
02490          "No dependent template names here!");
02491   // Look through qualified template names.
02492   if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
02493     Template = TemplateName(QTN->getTemplateDecl());
02494   
02495   bool IsTypeAlias = 
02496     Template.getAsTemplateDecl() &&
02497     isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
02498   QualType CanonType;
02499   if (!Underlying.isNull())
02500     CanonType = getCanonicalType(Underlying);
02501   else {
02502     // We can get here with an alias template when the specialization contains
02503     // a pack expansion that does not match up with a parameter pack.
02504     assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
02505            "Caller must compute aliased type");
02506     IsTypeAlias = false;
02507     CanonType = getCanonicalTemplateSpecializationType(Template, Args,
02508                                                        NumArgs);
02509   }
02510 
02511   // Allocate the (non-canonical) template specialization type, but don't
02512   // try to unique it: these types typically have location information that
02513   // we don't unique and don't want to lose.
02514   void *Mem = Allocate(sizeof(TemplateSpecializationType) +
02515                        sizeof(TemplateArgument) * NumArgs +
02516                        (IsTypeAlias? sizeof(QualType) : 0),
02517                        TypeAlignment);
02518   TemplateSpecializationType *Spec
02519     = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
02520                                          IsTypeAlias ? Underlying : QualType());
02521 
02522   Types.push_back(Spec);
02523   return QualType(Spec, 0);
02524 }
02525 
02526 QualType
02527 ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
02528                                                    const TemplateArgument *Args,
02529                                                    unsigned NumArgs) const {
02530   assert(!Template.getAsDependentTemplateName() && 
02531          "No dependent template names here!");
02532 
02533   // Look through qualified template names.
02534   if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
02535     Template = TemplateName(QTN->getTemplateDecl());
02536   
02537   // Build the canonical template specialization type.
02538   TemplateName CanonTemplate = getCanonicalTemplateName(Template);
02539   SmallVector<TemplateArgument, 4> CanonArgs;
02540   CanonArgs.reserve(NumArgs);
02541   for (unsigned I = 0; I != NumArgs; ++I)
02542     CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
02543 
02544   // Determine whether this canonical template specialization type already
02545   // exists.
02546   llvm::FoldingSetNodeID ID;
02547   TemplateSpecializationType::Profile(ID, CanonTemplate,
02548                                       CanonArgs.data(), NumArgs, *this);
02549 
02550   void *InsertPos = 0;
02551   TemplateSpecializationType *Spec
02552     = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
02553 
02554   if (!Spec) {
02555     // Allocate a new canonical template specialization type.
02556     void *Mem = Allocate((sizeof(TemplateSpecializationType) +
02557                           sizeof(TemplateArgument) * NumArgs),
02558                          TypeAlignment);
02559     Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
02560                                                 CanonArgs.data(), NumArgs,
02561                                                 QualType(), QualType());
02562     Types.push_back(Spec);
02563     TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
02564   }
02565 
02566   assert(Spec->isDependentType() &&
02567          "Non-dependent template-id type must have a canonical type");
02568   return QualType(Spec, 0);
02569 }
02570 
02571 QualType
02572 ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
02573                               NestedNameSpecifier *NNS,
02574                               QualType NamedType) const {
02575   llvm::FoldingSetNodeID ID;
02576   ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
02577 
02578   void *InsertPos = 0;
02579   ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
02580   if (T)
02581     return QualType(T, 0);
02582 
02583   QualType Canon = NamedType;
02584   if (!Canon.isCanonical()) {
02585     Canon = getCanonicalType(NamedType);
02586     ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
02587     assert(!CheckT && "Elaborated canonical type broken");
02588     (void)CheckT;
02589   }
02590 
02591   T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
02592   Types.push_back(T);
02593   ElaboratedTypes.InsertNode(T, InsertPos);
02594   return QualType(T, 0);
02595 }
02596 
02597 QualType
02598 ASTContext::getParenType(QualType InnerType) const {
02599   llvm::FoldingSetNodeID ID;
02600   ParenType::Profile(ID, InnerType);
02601 
02602   void *InsertPos = 0;
02603   ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
02604   if (T)
02605     return QualType(T, 0);
02606 
02607   QualType Canon = InnerType;
02608   if (!Canon.isCanonical()) {
02609     Canon = getCanonicalType(InnerType);
02610     ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
02611     assert(!CheckT && "Paren canonical type broken");
02612     (void)CheckT;
02613   }
02614 
02615   T = new (*this) ParenType(InnerType, Canon);
02616   Types.push_back(T);
02617   ParenTypes.InsertNode(T, InsertPos);
02618   return QualType(T, 0);
02619 }
02620 
02621 QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
02622                                           NestedNameSpecifier *NNS,
02623                                           const IdentifierInfo *Name,
02624                                           QualType Canon) const {
02625   assert(NNS->isDependent() && "nested-name-specifier must be dependent");
02626 
02627   if (Canon.isNull()) {
02628     NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
02629     ElaboratedTypeKeyword CanonKeyword = Keyword;
02630     if (Keyword == ETK_None)
02631       CanonKeyword = ETK_Typename;
02632     
02633     if (CanonNNS != NNS || CanonKeyword != Keyword)
02634       Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
02635   }
02636 
02637   llvm::FoldingSetNodeID ID;
02638   DependentNameType::Profile(ID, Keyword, NNS, Name);
02639 
02640   void *InsertPos = 0;
02641   DependentNameType *T
02642     = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
02643   if (T)
02644     return QualType(T, 0);
02645 
02646   T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
02647   Types.push_back(T);
02648   DependentNameTypes.InsertNode(T, InsertPos);
02649   return QualType(T, 0);
02650 }
02651 
02652 QualType
02653 ASTContext::getDependentTemplateSpecializationType(
02654                                  ElaboratedTypeKeyword Keyword,
02655                                  NestedNameSpecifier *NNS,
02656                                  const IdentifierInfo *Name,
02657                                  const TemplateArgumentListInfo &Args) const {
02658   // TODO: avoid this copy
02659   SmallVector<TemplateArgument, 16> ArgCopy;
02660   for (unsigned I = 0, E = Args.size(); I != E; ++I)
02661     ArgCopy.push_back(Args[I].getArgument());
02662   return getDependentTemplateSpecializationType(Keyword, NNS, Name,
02663                                                 ArgCopy.size(),
02664                                                 ArgCopy.data());
02665 }
02666 
02667 QualType
02668 ASTContext::getDependentTemplateSpecializationType(
02669                                  ElaboratedTypeKeyword Keyword,
02670                                  NestedNameSpecifier *NNS,
02671                                  const IdentifierInfo *Name,
02672                                  unsigned NumArgs,
02673                                  const TemplateArgument *Args) const {
02674   assert((!NNS || NNS->isDependent()) && 
02675          "nested-name-specifier must be dependent");
02676 
02677   llvm::FoldingSetNodeID ID;
02678   DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
02679                                                Name, NumArgs, Args);
02680 
02681   void *InsertPos = 0;
02682   DependentTemplateSpecializationType *T
02683     = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
02684   if (T)
02685     return QualType(T, 0);
02686 
02687   NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
02688 
02689   ElaboratedTypeKeyword CanonKeyword = Keyword;
02690   if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
02691 
02692   bool AnyNonCanonArgs = false;
02693   SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
02694   for (unsigned I = 0; I != NumArgs; ++I) {
02695     CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
02696     if (!CanonArgs[I].structurallyEquals(Args[I]))
02697       AnyNonCanonArgs = true;
02698   }
02699 
02700   QualType Canon;
02701   if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
02702     Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
02703                                                    Name, NumArgs,
02704                                                    CanonArgs.data());
02705 
02706     // Find the insert position again.
02707     DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
02708   }
02709 
02710   void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
02711                         sizeof(TemplateArgument) * NumArgs),
02712                        TypeAlignment);
02713   T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
02714                                                     Name, NumArgs, Args, Canon);
02715   Types.push_back(T);
02716   DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
02717   return QualType(T, 0);
02718 }
02719 
02720 QualType ASTContext::getPackExpansionType(QualType Pattern,
02721                                       llvm::Optional<unsigned> NumExpansions) {
02722   llvm::FoldingSetNodeID ID;
02723   PackExpansionType::Profile(ID, Pattern, NumExpansions);
02724 
02725   assert(Pattern->containsUnexpandedParameterPack() &&
02726          "Pack expansions must expand one or more parameter packs");
02727   void *InsertPos = 0;
02728   PackExpansionType *T
02729     = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
02730   if (T)
02731     return QualType(T, 0);
02732 
02733   QualType Canon;
02734   if (!Pattern.isCanonical()) {
02735     Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
02736 
02737     // Find the insert position again.
02738     PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
02739   }
02740 
02741   T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
02742   Types.push_back(T);
02743   PackExpansionTypes.InsertNode(T, InsertPos);
02744   return QualType(T, 0);  
02745 }
02746 
02747 /// CmpProtocolNames - Comparison predicate for sorting protocols
02748 /// alphabetically.
02749 static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
02750                             const ObjCProtocolDecl *RHS) {
02751   return LHS->getDeclName() < RHS->getDeclName();
02752 }
02753 
02754 static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
02755                                 unsigned NumProtocols) {
02756   if (NumProtocols == 0) return true;
02757 
02758   if (Protocols[0]->getCanonicalDecl() != Protocols[0])
02759     return false;
02760   
02761   for (unsigned i = 1; i != NumProtocols; ++i)
02762     if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
02763         Protocols[i]->getCanonicalDecl() != Protocols[i])
02764       return false;
02765   return true;
02766 }
02767 
02768 static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
02769                                    unsigned &NumProtocols) {
02770   ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
02771 
02772   // Sort protocols, keyed by name.
02773   std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
02774 
02775   // Canonicalize.
02776   for (unsigned I = 0, N = NumProtocols; I != N; ++I)
02777     Protocols[I] = Protocols[I]->getCanonicalDecl();
02778   
02779   // Remove duplicates.
02780   ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
02781   NumProtocols = ProtocolsEnd-Protocols;
02782 }
02783 
02784 QualType ASTContext::getObjCObjectType(QualType BaseType,
02785                                        ObjCProtocolDecl * const *Protocols,
02786                                        unsigned NumProtocols) const {
02787   // If the base type is an interface and there aren't any protocols
02788   // to add, then the interface type will do just fine.
02789   if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
02790     return BaseType;
02791 
02792   // Look in the folding set for an existing type.
02793   llvm::FoldingSetNodeID ID;
02794   ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
02795   void *InsertPos = 0;
02796   if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
02797     return QualType(QT, 0);
02798 
02799   // Build the canonical type, which has the canonical base type and
02800   // a sorted-and-uniqued list of protocols.
02801   QualType Canonical;
02802   bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
02803   if (!ProtocolsSorted || !BaseType.isCanonical()) {
02804     if (!ProtocolsSorted) {
02805       SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
02806                                                      Protocols + NumProtocols);
02807       unsigned UniqueCount = NumProtocols;
02808 
02809       SortAndUniqueProtocols(&Sorted[0], UniqueCount);
02810       Canonical = getObjCObjectType(getCanonicalType(BaseType),
02811                                     &Sorted[0], UniqueCount);
02812     } else {
02813       Canonical = getObjCObjectType(getCanonicalType(BaseType),
02814                                     Protocols, NumProtocols);
02815     }
02816 
02817     // Regenerate InsertPos.
02818     ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
02819   }
02820 
02821   unsigned Size = sizeof(ObjCObjectTypeImpl);
02822   Size += NumProtocols * sizeof(ObjCProtocolDecl *);
02823   void *Mem = Allocate(Size, TypeAlignment);
02824   ObjCObjectTypeImpl *T =
02825     new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
02826 
02827   Types.push_back(T);
02828   ObjCObjectTypes.InsertNode(T, InsertPos);
02829   return QualType(T, 0);
02830 }
02831 
02832 /// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
02833 /// the given object type.
02834 QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
02835   llvm::FoldingSetNodeID ID;
02836   ObjCObjectPointerType::Profile(ID, ObjectT);
02837 
02838   void *InsertPos = 0;
02839   if (ObjCObjectPointerType *QT =
02840               ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
02841     return QualType(QT, 0);
02842 
02843   // Find the canonical object type.
02844   QualType Canonical;
02845   if (!ObjectT.isCanonical()) {
02846     Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
02847 
02848     // Regenerate InsertPos.
02849     ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
02850   }
02851 
02852   // No match.
02853   void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
02854   ObjCObjectPointerType *QType =
02855     new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
02856 
02857   Types.push_back(QType);
02858   ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
02859   return QualType(QType, 0);
02860 }
02861 
02862 /// getObjCInterfaceType - Return the unique reference to the type for the
02863 /// specified ObjC interface decl. The list of protocols is optional.
02864 QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
02865                                           ObjCInterfaceDecl *PrevDecl) const {
02866   if (Decl->TypeForDecl)
02867     return QualType(Decl->TypeForDecl, 0);
02868 
02869   if (PrevDecl) {
02870     assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
02871     Decl->TypeForDecl = PrevDecl->TypeForDecl;
02872     return QualType(PrevDecl->TypeForDecl, 0);
02873   }
02874 
02875   // Prefer the definition, if there is one.
02876   if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
02877     Decl = Def;
02878   
02879   void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
02880   ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
02881   Decl->TypeForDecl = T;
02882   Types.push_back(T);
02883   return QualType(T, 0);
02884 }
02885 
02886 /// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
02887 /// TypeOfExprType AST's (since expression's are never shared). For example,
02888 /// multiple declarations that refer to "typeof(x)" all contain different
02889 /// DeclRefExpr's. This doesn't effect the type checker, since it operates
02890 /// on canonical type's (which are always unique).
02891 QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
02892   TypeOfExprType *toe;
02893   if (tofExpr->isTypeDependent()) {
02894     llvm::FoldingSetNodeID ID;
02895     DependentTypeOfExprType::Profile(ID, *this, tofExpr);
02896 
02897     void *InsertPos = 0;
02898     DependentTypeOfExprType *Canon
02899       = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
02900     if (Canon) {
02901       // We already have a "canonical" version of an identical, dependent
02902       // typeof(expr) type. Use that as our canonical type.
02903       toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
02904                                           QualType((TypeOfExprType*)Canon, 0));
02905     } else {
02906       // Build a new, canonical typeof(expr) type.
02907       Canon
02908         = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
02909       DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
02910       toe = Canon;
02911     }
02912   } else {
02913     QualType Canonical = getCanonicalType(tofExpr->getType());
02914     toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
02915   }
02916   Types.push_back(toe);
02917   return QualType(toe, 0);
02918 }
02919 
02920 /// getTypeOfType -  Unlike many "get<Type>" functions, we don't unique
02921 /// TypeOfType AST's. The only motivation to unique these nodes would be
02922 /// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
02923 /// an issue. This doesn't effect the type checker, since it operates
02924 /// on canonical type's (which are always unique).
02925 QualType ASTContext::getTypeOfType(QualType tofType) const {
02926   QualType Canonical = getCanonicalType(tofType);
02927   TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
02928   Types.push_back(tot);
02929   return QualType(tot, 0);
02930 }
02931 
02932 
02933 /// getDecltypeType -  Unlike many "get<Type>" functions, we don't unique
02934 /// DecltypeType AST's. The only motivation to unique these nodes would be
02935 /// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
02936 /// an issue. This doesn't effect the type checker, since it operates
02937 /// on canonical types (which are always unique).
02938 QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
02939   DecltypeType *dt;
02940   
02941   // C++0x [temp.type]p2:
02942   //   If an expression e involves a template parameter, decltype(e) denotes a
02943   //   unique dependent type. Two such decltype-specifiers refer to the same 
02944   //   type only if their expressions are equivalent (14.5.6.1). 
02945   if (e->isInstantiationDependent()) {
02946     llvm::FoldingSetNodeID ID;
02947     DependentDecltypeType::Profile(ID, *this, e);
02948 
02949     void *InsertPos = 0;
02950     DependentDecltypeType *Canon
02951       = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
02952     if (Canon) {
02953       // We already have a "canonical" version of an equivalent, dependent
02954       // decltype type. Use that as our canonical type.
02955       dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
02956                                        QualType((DecltypeType*)Canon, 0));
02957     } else {
02958       // Build a new, canonical typeof(expr) type.
02959       Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
02960       DependentDecltypeTypes.InsertNode(Canon, InsertPos);
02961       dt = Canon;
02962     }
02963   } else {
02964     dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType, 
02965                                       getCanonicalType(UnderlyingType));
02966   }
02967   Types.push_back(dt);
02968   return QualType(dt, 0);
02969 }
02970 
02971 /// getUnaryTransformationType - We don't unique these, since the memory
02972 /// savings are minimal and these are rare.
02973 QualType ASTContext::getUnaryTransformType(QualType BaseType,
02974                                            QualType UnderlyingType,
02975                                            UnaryTransformType::UTTKind Kind)
02976     const {
02977   UnaryTransformType *Ty =
02978     new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType, 
02979                                                    Kind,
02980                                  UnderlyingType->isDependentType() ?
02981                                  QualType() : getCanonicalType(UnderlyingType));
02982   Types.push_back(Ty);
02983   return QualType(Ty, 0);
02984 }
02985 
02986 /// getAutoType - We only unique auto types after they've been deduced.
02987 QualType ASTContext::getAutoType(QualType DeducedType) const {
02988   void *InsertPos = 0;
02989   if (!DeducedType.isNull()) {
02990     // Look in the folding set for an existing type.
02991     llvm::FoldingSetNodeID ID;
02992     AutoType::Profile(ID, DeducedType);
02993     if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
02994       return QualType(AT, 0);
02995   }
02996 
02997   AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
02998   Types.push_back(AT);
02999   if (InsertPos)
03000     AutoTypes.InsertNode(AT, InsertPos);
03001   return QualType(AT, 0);
03002 }
03003 
03004 /// getAtomicType - Return the uniqued reference to the atomic type for
03005 /// the given value type.
03006 QualType ASTContext::getAtomicType(QualType T) const {
03007   // Unique pointers, to guarantee there is only one pointer of a particular
03008   // structure.
03009   llvm::FoldingSetNodeID ID;
03010   AtomicType::Profile(ID, T);
03011 
03012   void *InsertPos = 0;
03013   if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
03014     return QualType(AT, 0);
03015 
03016   // If the atomic value type isn't canonical, this won't be a canonical type
03017   // either, so fill in the canonical type field.
03018   QualType Canonical;
03019   if (!T.isCanonical()) {
03020     Canonical = getAtomicType(getCanonicalType(T));
03021 
03022     // Get the new insert position for the node we care about.
03023     AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
03024     assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
03025   }
03026   AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
03027   Types.push_back(New);
03028   AtomicTypes.InsertNode(New, InsertPos);
03029   return QualType(New, 0);
03030 }
03031 
03032 /// getAutoDeductType - Get type pattern for deducing against 'auto'.
03033 QualType ASTContext::getAutoDeductType() const {
03034   if (AutoDeductTy.isNull())
03035     AutoDeductTy = getAutoType(QualType());
03036   assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
03037   return AutoDeductTy;
03038 }
03039 
03040 /// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
03041 QualType ASTContext::getAutoRRefDeductType() const {
03042   if (AutoRRefDeductTy.isNull())
03043     AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
03044   assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
03045   return AutoRRefDeductTy;
03046 }
03047 
03048 /// getTagDeclType - Return the unique reference to the type for the
03049 /// specified TagDecl (struct/union/class/enum) decl.
03050 QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
03051   assert (Decl);
03052   // FIXME: What is the design on getTagDeclType when it requires casting
03053   // away const?  mutable?
03054   return getTypeDeclType(const_cast<TagDecl*>(Decl));
03055 }
03056 
03057 /// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
03058 /// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
03059 /// needs to agree with the definition in <stddef.h>.
03060 CanQualType ASTContext::getSizeType() const {
03061   return getFromTargetType(Target->getSizeType());
03062 }
03063 
03064 /// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
03065 CanQualType ASTContext::getIntMaxType() const {
03066   return getFromTargetType(Target->getIntMaxType());
03067 }
03068 
03069 /// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
03070 CanQualType ASTContext::getUIntMaxType() const {
03071   return getFromTargetType(Target->getUIntMaxType());
03072 }
03073 
03074 /// getSignedWCharType - Return the type of "signed wchar_t".
03075 /// Used when in C++, as a GCC extension.
03076 QualType ASTContext::getSignedWCharType() const {
03077   // FIXME: derive from "Target" ?
03078   return WCharTy;
03079 }
03080 
03081 /// getUnsignedWCharType - Return the type of "unsigned wchar_t".
03082 /// Used when in C++, as a GCC extension.
03083 QualType ASTContext::getUnsignedWCharType() const {
03084   // FIXME: derive from "Target" ?
03085   return UnsignedIntTy;
03086 }
03087 
03088 /// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
03089 /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
03090 QualType ASTContext::getPointerDiffType() const {
03091   return getFromTargetType(Target->getPtrDiffType(0));
03092 }
03093 
03094 //===----------------------------------------------------------------------===//
03095 //                              Type Operators
03096 //===----------------------------------------------------------------------===//
03097 
03098 CanQualType ASTContext::getCanonicalParamType(QualType T) const {
03099   // Push qualifiers into arrays, and then discard any remaining
03100   // qualifiers.
03101   T = getCanonicalType(T);
03102   T = getVariableArrayDecayedType(T);
03103   const Type *Ty = T.getTypePtr();
03104   QualType Result;
03105   if (isa<ArrayType>(Ty)) {
03106     Result = getArrayDecayedType(QualType(Ty,0));
03107   } else if (isa<FunctionType>(Ty)) {
03108     Result = getPointerType(QualType(Ty, 0));
03109   } else {
03110     Result = QualType(Ty, 0);
03111   }
03112 
03113   return CanQualType::CreateUnsafe(Result);
03114 }
03115 
03116 QualType ASTContext::getUnqualifiedArrayType(QualType type,
03117                                              Qualifiers &quals) {
03118   SplitQualType splitType = type.getSplitUnqualifiedType();
03119 
03120   // FIXME: getSplitUnqualifiedType() actually walks all the way to
03121   // the unqualified desugared type and then drops it on the floor.
03122   // We then have to strip that sugar back off with
03123   // getUnqualifiedDesugaredType(), which is silly.
03124   const ArrayType *AT =
03125     dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
03126 
03127   // If we don't have an array, just use the results in splitType.
03128   if (!AT) {
03129     quals = splitType.Quals;
03130     return QualType(splitType.Ty, 0);
03131   }
03132 
03133   // Otherwise, recurse on the array's element type.
03134   QualType elementType = AT->getElementType();
03135   QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
03136 
03137   // If that didn't change the element type, AT has no qualifiers, so we
03138   // can just use the results in splitType.
03139   if (elementType == unqualElementType) {
03140     assert(quals.empty()); // from the recursive call
03141     quals = splitType.Quals;
03142     return QualType(splitType.Ty, 0);
03143   }
03144 
03145   // Otherwise, add in the qualifiers from the outermost type, then
03146   // build the type back up.
03147   quals.addConsistentQualifiers(splitType.Quals);
03148 
03149   if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
03150     return getConstantArrayType(unqualElementType, CAT->getSize(),
03151                                 CAT->getSizeModifier(), 0);
03152   }
03153 
03154   if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
03155     return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
03156   }
03157 
03158   if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
03159     return getVariableArrayType(unqualElementType,
03160                                 VAT->getSizeExpr(),
03161                                 VAT->getSizeModifier(),
03162                                 VAT->getIndexTypeCVRQualifiers(),
03163                                 VAT->getBracketsRange());
03164   }
03165 
03166   const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
03167   return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
03168                                     DSAT->getSizeModifier(), 0,
03169                                     SourceRange());
03170 }
03171 
03172 /// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types  that
03173 /// may be similar (C++ 4.4), replaces T1 and T2 with the type that
03174 /// they point to and return true. If T1 and T2 aren't pointer types
03175 /// or pointer-to-member types, or if they are not similar at this
03176 /// level, returns false and leaves T1 and T2 unchanged. Top-level
03177 /// qualifiers on T1 and T2 are ignored. This function will typically
03178 /// be called in a loop that successively "unwraps" pointer and
03179 /// pointer-to-member types to compare them at each level.
03180 bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
03181   const PointerType *T1PtrType = T1->getAs<PointerType>(),
03182                     *T2PtrType = T2->getAs<PointerType>();
03183   if (T1PtrType && T2PtrType) {
03184     T1 = T1PtrType->getPointeeType();
03185     T2 = T2PtrType->getPointeeType();
03186     return true;
03187   }
03188   
03189   const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
03190                           *T2MPType = T2->getAs<MemberPointerType>();
03191   if (T1MPType && T2MPType && 
03192       hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0), 
03193                              QualType(T2MPType->getClass(), 0))) {
03194     T1 = T1MPType->getPointeeType();
03195     T2 = T2MPType->getPointeeType();
03196     return true;
03197   }
03198   
03199   if (getLangOpts().ObjC1) {
03200     const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
03201                                 *T2OPType = T2->getAs<ObjCObjectPointerType>();
03202     if (T1OPType && T2OPType) {
03203       T1 = T1OPType->getPointeeType();
03204       T2 = T2OPType->getPointeeType();
03205       return true;
03206     }
03207   }
03208   
03209   // FIXME: Block pointers, too?
03210   
03211   return false;
03212 }
03213 
03214 DeclarationNameInfo
03215 ASTContext::getNameForTemplate(TemplateName Name,
03216                                SourceLocation NameLoc) const {
03217   switch (Name.getKind()) {
03218   case TemplateName::QualifiedTemplate:
03219   case TemplateName::Template:
03220     // DNInfo work in progress: CHECKME: what about DNLoc?
03221     return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
03222                                NameLoc);
03223 
03224   case TemplateName::OverloadedTemplate: {
03225     OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
03226     // DNInfo work in progress: CHECKME: what about DNLoc?
03227     return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
03228   }
03229 
03230   case TemplateName::DependentTemplate: {
03231     DependentTemplateName *DTN = Name.getAsDependentTemplateName();
03232     DeclarationName DName;
03233     if (DTN->isIdentifier()) {
03234       DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
03235       return DeclarationNameInfo(DName, NameLoc);
03236     } else {
03237       DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
03238       // DNInfo work in progress: FIXME: source locations?
03239       DeclarationNameLoc DNLoc;
03240       DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
03241       DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
03242       return DeclarationNameInfo(DName, NameLoc, DNLoc);
03243     }
03244   }
03245 
03246   case TemplateName::SubstTemplateTemplateParm: {
03247     SubstTemplateTemplateParmStorage *subst
03248       = Name.getAsSubstTemplateTemplateParm();
03249     return DeclarationNameInfo(subst->getParameter()->getDeclName(),
03250                                NameLoc);
03251   }
03252 
03253   case TemplateName::SubstTemplateTemplateParmPack: {
03254     SubstTemplateTemplateParmPackStorage *subst
03255       = Name.getAsSubstTemplateTemplateParmPack();
03256     return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
03257                                NameLoc);
03258   }
03259   }
03260 
03261   llvm_unreachable("bad template name kind!");
03262 }
03263 
03264 TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
03265   switch (Name.getKind()) {
03266   case TemplateName::QualifiedTemplate:
03267   case TemplateName::Template: {
03268     TemplateDecl *Template = Name.getAsTemplateDecl();
03269     if (TemplateTemplateParmDecl *TTP 
03270           = dyn_cast<TemplateTemplateParmDecl>(Template))
03271       Template = getCanonicalTemplateTemplateParmDecl(TTP);
03272   
03273     // The canonical template name is the canonical template declaration.
03274     return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
03275   }
03276 
03277   case TemplateName::OverloadedTemplate:
03278     llvm_unreachable("cannot canonicalize overloaded template");
03279 
03280   case TemplateName::DependentTemplate: {
03281     DependentTemplateName *DTN = Name.getAsDependentTemplateName();
03282     assert(DTN && "Non-dependent template names must refer to template decls.");
03283     return DTN->CanonicalTemplateName;
03284   }
03285 
03286   case TemplateName::SubstTemplateTemplateParm: {
03287     SubstTemplateTemplateParmStorage *subst
03288       = Name.getAsSubstTemplateTemplateParm();
03289     return getCanonicalTemplateName(subst->getReplacement());
03290   }
03291 
03292   case TemplateName::SubstTemplateTemplateParmPack: {
03293     SubstTemplateTemplateParmPackStorage *subst
03294                                   = Name.getAsSubstTemplateTemplateParmPack();
03295     TemplateTemplateParmDecl *canonParameter
03296       = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
03297     TemplateArgument canonArgPack
03298       = getCanonicalTemplateArgument(subst->getArgumentPack());
03299     return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
03300   }
03301   }
03302 
03303   llvm_unreachable("bad template name!");
03304 }
03305 
03306 bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
03307   X = getCanonicalTemplateName(X);
03308   Y = getCanonicalTemplateName(Y);
03309   return X.getAsVoidPointer() == Y.getAsVoidPointer();
03310 }
03311 
03312 TemplateArgument
03313 ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
03314   switch (Arg.getKind()) {
03315     case TemplateArgument::Null:
03316       return Arg;
03317 
03318     case TemplateArgument::Expression:
03319       return Arg;
03320 
03321     case TemplateArgument::Declaration: {
03322       if (Decl *D = Arg.getAsDecl())
03323           return TemplateArgument(D->getCanonicalDecl());
03324       return TemplateArgument((Decl*)0);
03325     }
03326 
03327     case TemplateArgument::Template:
03328       return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
03329 
03330     case TemplateArgument::TemplateExpansion:
03331       return TemplateArgument(getCanonicalTemplateName(
03332                                          Arg.getAsTemplateOrTemplatePattern()),
03333                               Arg.getNumTemplateExpansions());
03334 
03335     case TemplateArgument::Integral:
03336       return TemplateArgument(*Arg.getAsIntegral(),
03337                               getCanonicalType(Arg.getIntegralType()));
03338 
03339     case TemplateArgument::Type:
03340       return TemplateArgument(getCanonicalType(Arg.getAsType()));
03341 
03342     case TemplateArgument::Pack: {
03343       if (Arg.pack_size() == 0)
03344         return Arg;
03345       
03346       TemplateArgument *CanonArgs
03347         = new (*this) TemplateArgument[Arg.pack_size()];
03348       unsigned Idx = 0;
03349       for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
03350                                         AEnd = Arg.pack_end();
03351            A != AEnd; (void)++A, ++Idx)
03352         CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
03353 
03354       return TemplateArgument(CanonArgs, Arg.pack_size());
03355     }
03356   }
03357 
03358   // Silence GCC warning
03359   llvm_unreachable("Unhandled template argument kind");
03360 }
03361 
03362 NestedNameSpecifier *
03363 ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
03364   if (!NNS)
03365     return 0;
03366 
03367   switch (NNS->getKind()) {
03368   case NestedNameSpecifier::Identifier:
03369     // Canonicalize the prefix but keep the identifier the same.
03370     return NestedNameSpecifier::Create(*this,
03371                          getCanonicalNestedNameSpecifier(NNS->getPrefix()),
03372                                        NNS->getAsIdentifier());
03373 
03374   case NestedNameSpecifier::Namespace:
03375     // A namespace is canonical; build a nested-name-specifier with
03376     // this namespace and no prefix.
03377     return NestedNameSpecifier::Create(*this, 0, 
03378                                  NNS->getAsNamespace()->getOriginalNamespace());
03379 
03380   case NestedNameSpecifier::NamespaceAlias:
03381     // A namespace is canonical; build a nested-name-specifier with
03382     // this namespace and no prefix.
03383     return NestedNameSpecifier::Create(*this, 0, 
03384                                     NNS->getAsNamespaceAlias()->getNamespace()
03385                                                       ->getOriginalNamespace());
03386 
03387   case NestedNameSpecifier::TypeSpec:
03388   case NestedNameSpecifier::TypeSpecWithTemplate: {
03389     QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
03390     
03391     // If we have some kind of dependent-named type (e.g., "typename T::type"),
03392     // break it apart into its prefix and identifier, then reconsititute those
03393     // as the canonical nested-name-specifier. This is required to canonicalize
03394     // a dependent nested-name-specifier involving typedefs of dependent-name
03395     // types, e.g.,
03396     //   typedef typename T::type T1;
03397     //   typedef typename T1::type T2;
03398     if (const DependentNameType *DNT = T->getAs<DependentNameType>())
03399       return NestedNameSpecifier::Create(*this, DNT->getQualifier(), 
03400                            const_cast<IdentifierInfo *>(DNT->getIdentifier()));
03401 
03402     // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
03403     // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
03404     // first place?
03405     return NestedNameSpecifier::Create(*this, 0, false,
03406                                        const_cast<Type*>(T.getTypePtr()));
03407   }
03408 
03409   case NestedNameSpecifier::Global:
03410     // The global specifier is canonical and unique.
03411     return NNS;
03412   }
03413 
03414   llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
03415 }
03416 
03417 
03418 const ArrayType *ASTContext::getAsArrayType(QualType T) const {
03419   // Handle the non-qualified case efficiently.
03420   if (!T.hasLocalQualifiers()) {
03421     // Handle the common positive case fast.
03422     if (const ArrayType *AT = dyn_cast<ArrayType>(T))
03423       return AT;
03424   }
03425 
03426   // Handle the common negative case fast.
03427   if (!isa<ArrayType>(T.getCanonicalType()))
03428     return 0;
03429 
03430   // Apply any qualifiers from the array type to the element type.  This
03431   // implements C99 6.7.3p8: "If the specification of an array type includes
03432   // any type qualifiers, the element type is so qualified, not the array type."
03433 
03434   // If we get here, we either have type qualifiers on the type, or we have
03435   // sugar such as a typedef in the way.  If we have type qualifiers on the type
03436   // we must propagate them down into the element type.
03437 
03438   SplitQualType split = T.getSplitDesugaredType();
03439   Qualifiers qs = split.Quals;
03440 
03441   // If we have a simple case, just return now.
03442   const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
03443   if (ATy == 0 || qs.empty())
03444     return ATy;
03445 
03446   // Otherwise, we have an array and we have qualifiers on it.  Push the
03447   // qualifiers into the array element type and return a new array type.
03448   QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
03449 
03450   if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
03451     return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
03452                                                 CAT->getSizeModifier(),
03453                                            CAT->getIndexTypeCVRQualifiers()));
03454   if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
03455     return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
03456                                                   IAT->getSizeModifier(),
03457                                            IAT->getIndexTypeCVRQualifiers()));
03458 
03459   if (const DependentSizedArrayType *DSAT
03460         = dyn_cast<DependentSizedArrayType>(ATy))
03461     return cast<ArrayType>(
03462                      getDependentSizedArrayType(NewEltTy,
03463                                                 DSAT->getSizeExpr(),
03464                                                 DSAT->getSizeModifier(),
03465                                               DSAT->getIndexTypeCVRQualifiers(),
03466                                                 DSAT->getBracketsRange()));
03467 
03468   const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
03469   return cast<ArrayType>(getVariableArrayType(NewEltTy,
03470                                               VAT->getSizeExpr(),
03471                                               VAT->getSizeModifier(),
03472                                               VAT->getIndexTypeCVRQualifiers(),
03473                                               VAT->getBracketsRange()));
03474 }
03475 
03476 QualType ASTContext::getAdjustedParameterType(QualType T) {
03477   // C99 6.7.5.3p7:
03478   //   A declaration of a parameter as "array of type" shall be
03479   //   adjusted to "qualified pointer to type", where the type
03480   //   qualifiers (if any) are those specified within the [ and ] of
03481   //   the array type derivation.
03482   if (T->isArrayType())
03483     return getArrayDecayedType(T);
03484   
03485   // C99 6.7.5.3p8:
03486   //   A declaration of a parameter as "function returning type"
03487   //   shall be adjusted to "pointer to function returning type", as
03488   //   in 6.3.2.1.
03489   if (T->isFunctionType())
03490     return getPointerType(T);
03491   
03492   return T;  
03493 }
03494 
03495 QualType ASTContext::getSignatureParameterType(QualType T) {
03496   T = getVariableArrayDecayedType(T);
03497   T = getAdjustedParameterType(T);
03498   return T.getUnqualifiedType();
03499 }
03500 
03501 /// getArrayDecayedType - Return the properly qualified result of decaying the
03502 /// specified array type to a pointer.  This operation is non-trivial when
03503 /// handling typedefs etc.  The canonical type of "T" must be an array type,
03504 /// this returns a pointer to a properly qualified element of the array.
03505 ///
03506 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
03507 QualType ASTContext::getArrayDecayedType(QualType Ty) const {
03508   // Get the element type with 'getAsArrayType' so that we don't lose any
03509   // typedefs in the element type of the array.  This also handles propagation
03510   // of type qualifiers from the array type into the element type if present
03511   // (C99 6.7.3p8).
03512   const ArrayType *PrettyArrayType = getAsArrayType(Ty);
03513   assert(PrettyArrayType && "Not an array type!");
03514 
03515   QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
03516 
03517   // int x[restrict 4] ->  int *restrict
03518   return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
03519 }
03520 
03521 QualType ASTContext::getBaseElementType(const ArrayType *array) const {
03522   return getBaseElementType(array->getElementType());
03523 }
03524 
03525 QualType ASTContext::getBaseElementType(QualType type) const {
03526   Qualifiers qs;
03527   while (true) {
03528     SplitQualType split = type.getSplitDesugaredType();
03529     const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
03530     if (!array) break;
03531 
03532     type = array->getElementType();
03533     qs.addConsistentQualifiers(split.Quals);
03534   }
03535 
03536   return getQualifiedType(type, qs);
03537 }
03538 
03539 /// getConstantArrayElementCount - Returns number of constant array elements.
03540 uint64_t
03541 ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA)  const {
03542   uint64_t ElementCount = 1;
03543   do {
03544     ElementCount *= CA->getSize().getZExtValue();
03545     CA = dyn_cast<ConstantArrayType>(CA->getElementType());
03546   } while (CA);
03547   return ElementCount;
03548 }
03549 
03550 /// getFloatingRank - Return a relative rank for floating point types.
03551 /// This routine will assert if passed a built-in type that isn't a float.
03552 static FloatingRank getFloatingRank(QualType T) {
03553   if (const ComplexType *CT = T->getAs<ComplexType>())
03554     return getFloatingRank(CT->getElementType());
03555 
03556   assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
03557   switch (T->getAs<BuiltinType>()->getKind()) {
03558   default: llvm_unreachable("getFloatingRank(): not a floating type");
03559   case BuiltinType::Half:       return HalfRank;
03560   case BuiltinType::Float:      return FloatRank;
03561   case BuiltinType::Double:     return DoubleRank;
03562   case BuiltinType::LongDouble: return LongDoubleRank;
03563   }
03564 }
03565 
03566 /// getFloatingTypeOfSizeWithinDomain - Returns a real floating
03567 /// point or a complex type (based on typeDomain/typeSize).
03568 /// 'typeDomain' is a real floating point or complex type.
03569 /// 'typeSize' is a real floating point or complex type.
03570 QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
03571                                                        QualType Domain) const {
03572   FloatingRank EltRank = getFloatingRank(Size);
03573   if (Domain->isComplexType()) {
03574     switch (EltRank) {
03575     case HalfRank: llvm_unreachable("Complex half is not supported");
03576     case FloatRank:      return FloatComplexTy;
03577     case DoubleRank:     return DoubleComplexTy;
03578     case LongDoubleRank: return LongDoubleComplexTy;
03579     }
03580   }
03581 
03582   assert(Domain->isRealFloatingType() && "Unknown domain!");
03583   switch (EltRank) {
03584   case HalfRank: llvm_unreachable("Half ranks are not valid here");
03585   case FloatRank:      return FloatTy;
03586   case DoubleRank:     return DoubleTy;
03587   case LongDoubleRank: return LongDoubleTy;
03588   }
03589   llvm_unreachable("getFloatingRank(): illegal value for rank");
03590 }
03591 
03592 /// getFloatingTypeOrder - Compare the rank of the two specified floating
03593 /// point types, ignoring the domain of the type (i.e. 'double' ==
03594 /// '_Complex double').  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
03595 /// LHS < RHS, return -1.
03596 int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
03597   FloatingRank LHSR = getFloatingRank(LHS);
03598   FloatingRank RHSR = getFloatingRank(RHS);
03599 
03600   if (LHSR == RHSR)
03601     return 0;
03602   if (LHSR > RHSR)
03603     return 1;
03604   return -1;
03605 }
03606 
03607 /// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
03608 /// routine will assert if passed a built-in type that isn't an integer or enum,
03609 /// or if it is not canonicalized.
03610 unsigned ASTContext::getIntegerRank(const Type *T) const {
03611   assert(T->isCanonicalUnqualified() && "T should be canonicalized");
03612 
03613   switch (cast<BuiltinType>(T)->getKind()) {
03614   default: llvm_unreachable("getIntegerRank(): not a built-in integer");
03615   case BuiltinType::Bool:
03616     return 1 + (getIntWidth(BoolTy) << 3);
03617   case BuiltinType::Char_S:
03618   case BuiltinType::Char_U:
03619   case BuiltinType::SChar:
03620   case BuiltinType::UChar:
03621     return 2 + (getIntWidth(CharTy) << 3);
03622   case BuiltinType::Short:
03623   case BuiltinType::UShort:
03624     return 3 + (getIntWidth(ShortTy) << 3);
03625   case BuiltinType::Int:
03626   case BuiltinType::UInt:
03627     return 4 + (getIntWidth(IntTy) << 3);
03628   case BuiltinType::Long:
03629   case BuiltinType::ULong:
03630     return 5 + (getIntWidth(LongTy) << 3);
03631   case BuiltinType::LongLong:
03632   case BuiltinType::ULongLong:
03633     return 6 + (getIntWidth(LongLongTy) << 3);
03634   case BuiltinType::Int128:
03635   case BuiltinType::UInt128:
03636     return 7 + (getIntWidth(Int128Ty) << 3);
03637   }
03638 }
03639 
03640 /// \brief Whether this is a promotable bitfield reference according
03641 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
03642 ///
03643 /// \returns the type this bit-field will promote to, or NULL if no
03644 /// promotion occurs.
03645 QualType ASTContext::isPromotableBitField(Expr *E) const {
03646   if (E->isTypeDependent() || E->isValueDependent())
03647     return QualType();
03648   
03649   FieldDecl *Field = E->getBitField();
03650   if (!Field)
03651     return QualType();
03652 
03653   QualType FT = Field->getType();
03654 
03655   uint64_t BitWidth = Field->getBitWidthValue(*this);
03656   uint64_t IntSize = getTypeSize(IntTy);
03657   // GCC extension compatibility: if the bit-field size is less than or equal
03658   // to the size of int, it gets promoted no matter what its type is.
03659   // For instance, unsigned long bf : 4 gets promoted to signed int.
03660   if (BitWidth < IntSize)
03661     return IntTy;
03662 
03663   if (BitWidth == IntSize)
03664     return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
03665 
03666   // Types bigger than int are not subject to promotions, and therefore act
03667   // like the base type.
03668   // FIXME: This doesn't quite match what gcc does, but what gcc does here
03669   // is ridiculous.
03670   return QualType();
03671 }
03672 
03673 /// getPromotedIntegerType - Returns the type that Promotable will
03674 /// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
03675 /// integer type.
03676 QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
03677   assert(!Promotable.isNull());
03678   assert(Promotable->isPromotableIntegerType());
03679   if (const EnumType *ET = Promotable->getAs<EnumType>())
03680     return ET->getDecl()->getPromotionType();
03681 
03682   if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
03683     // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
03684     // (3.9.1) can be converted to a prvalue of the first of the following
03685     // types that can represent all the values of its underlying type:
03686     // int, unsigned int, long int, unsigned long int, long long int, or
03687     // unsigned long long int [...]
03688     // FIXME: Is there some better way to compute this?
03689     if (BT->getKind() == BuiltinType::WChar_S ||
03690         BT->getKind() == BuiltinType::WChar_U ||
03691         BT->getKind() == BuiltinType::Char16 ||
03692         BT->getKind() == BuiltinType::Char32) {
03693       bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
03694       uint64_t FromSize = getTypeSize(BT);
03695       QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
03696                                   LongLongTy, UnsignedLongLongTy };
03697       for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
03698         uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
03699         if (FromSize < ToSize ||
03700             (FromSize == ToSize &&
03701              FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
03702           return PromoteTypes[Idx];
03703       }
03704       llvm_unreachable("char type should fit into long long");
03705     }
03706   }
03707 
03708   // At this point, we should have a signed or unsigned integer type.
03709   if (Promotable->isSignedIntegerType())
03710     return IntTy;
03711   uint64_t PromotableSize = getTypeSize(Promotable);
03712   uint64_t IntSize = getTypeSize(IntTy);
03713   assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
03714   return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
03715 }
03716 
03717 /// \brief Recurses in pointer/array types until it finds an objc retainable
03718 /// type and returns its ownership.
03719 Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
03720   while (!T.isNull()) {
03721     if (T.getObjCLifetime() != Qualifiers::OCL_None)
03722       return T.getObjCLifetime();
03723     if (T->isArrayType())
03724       T = getBaseElementType(T);
03725     else if (const PointerType *PT = T->getAs<PointerType>())
03726       T = PT->getPointeeType();
03727     else if (const ReferenceType *RT = T->getAs<ReferenceType>())
03728       T = RT->getPointeeType();
03729     else
03730       break;
03731   }
03732 
03733   return Qualifiers::OCL_None;
03734 }
03735 
03736 /// getIntegerTypeOrder - Returns the highest ranked integer type:
03737 /// C99 6.3.1.8p1.  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
03738 /// LHS < RHS, return -1.
03739 int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
03740   const Type *LHSC = getCanonicalType(LHS).getTypePtr();
03741   const Type *RHSC = getCanonicalType(RHS).getTypePtr();
03742   if (LHSC == RHSC) return 0;
03743 
03744   bool LHSUnsigned = LHSC->isUnsignedIntegerType();
03745   bool RHSUnsigned = RHSC->isUnsignedIntegerType();
03746 
03747   unsigned LHSRank = getIntegerRank(LHSC);
03748   unsigned RHSRank = getIntegerRank(RHSC);
03749 
03750   if (LHSUnsigned == RHSUnsigned) {  // Both signed or both unsigned.
03751     if (LHSRank == RHSRank) return 0;
03752     return LHSRank > RHSRank ? 1 : -1;
03753   }
03754 
03755   // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
03756   if (LHSUnsigned) {
03757     // If the unsigned [LHS] type is larger, return it.
03758     if (LHSRank >= RHSRank)
03759       return 1;
03760 
03761     // If the signed type can represent all values of the unsigned type, it
03762     // wins.  Because we are dealing with 2's complement and types that are
03763     // powers of two larger than each other, this is always safe.
03764     return -1;
03765   }
03766 
03767   // If the unsigned [RHS] type is larger, return it.
03768   if (RHSRank >= LHSRank)
03769     return -1;
03770 
03771   // If the signed type can represent all values of the unsigned type, it
03772   // wins.  Because we are dealing with 2's complement and types that are
03773   // powers of two larger than each other, this is always safe.
03774   return 1;
03775 }
03776 
03777 static RecordDecl *
03778 CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
03779                  DeclContext *DC, IdentifierInfo *Id) {
03780   SourceLocation Loc;
03781   if (Ctx.getLangOpts().CPlusPlus)
03782     return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
03783   else
03784     return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
03785 }
03786 
03787 // getCFConstantStringType - Return the type used for constant CFStrings.
03788 QualType ASTContext::getCFConstantStringType() const {
03789   if (!CFConstantStringTypeDecl) {
03790     CFConstantStringTypeDecl =
03791       CreateRecordDecl(*this, TTK_Struct, TUDecl,
03792                        &Idents.get("NSConstantString"));
03793     CFConstantStringTypeDecl->startDefinition();
03794 
03795     QualType FieldTypes[4];
03796 
03797     // const int *isa;
03798     FieldTypes[0] = getPointerType(IntTy.withConst());
03799     // int flags;
03800     FieldTypes[1] = IntTy;
03801     // const char *str;
03802     FieldTypes[2] = getPointerType(CharTy.withConst());
03803     // long length;
03804     FieldTypes[3] = LongTy;
03805 
03806     // Create fields
03807     for (unsigned i = 0; i < 4; ++i) {
03808       FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
03809                                            SourceLocation(),
03810                                            SourceLocation(), 0,
03811                                            FieldTypes[i], /*TInfo=*/0,
03812                                            /*BitWidth=*/0,
03813                                            /*Mutable=*/false,
03814                                            /*HasInit=*/false);
03815       Field->setAccess(AS_public);
03816       CFConstantStringTypeDecl->addDecl(Field);
03817     }
03818 
03819     CFConstantStringTypeDecl->completeDefinition();
03820   }
03821 
03822   return getTagDeclType(CFConstantStringTypeDecl);
03823 }
03824 
03825 void ASTContext::setCFConstantStringType(QualType T) {
03826   const RecordType *Rec = T->getAs<RecordType>();
03827   assert(Rec && "Invalid CFConstantStringType");
03828   CFConstantStringTypeDecl = Rec->getDecl();
03829 }
03830 
03831 QualType ASTContext::getBlockDescriptorType() const {
03832   if (BlockDescriptorType)
03833     return getTagDeclType(BlockDescriptorType);
03834 
03835   RecordDecl *T;
03836   // FIXME: Needs the FlagAppleBlock bit.
03837   T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
03838                        &Idents.get("__block_descriptor"));
03839   T->startDefinition();
03840   
03841   QualType FieldTypes[] = {
03842     UnsignedLongTy,
03843     UnsignedLongTy,
03844   };
03845 
03846   const char *FieldNames[] = {
03847     "reserved",
03848     "Size"
03849   };
03850 
03851   for (size_t i = 0; i < 2; ++i) {
03852     FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
03853                                          SourceLocation(),
03854                                          &Idents.get(FieldNames[i]),
03855                                          FieldTypes[i], /*TInfo=*/0,
03856                                          /*BitWidth=*/0,
03857                                          /*Mutable=*/false,
03858                                          /*HasInit=*/false);
03859     Field->setAccess(AS_public);
03860     T->addDecl(Field);
03861   }
03862 
03863   T->completeDefinition();
03864 
03865   BlockDescriptorType = T;
03866 
03867   return getTagDeclType(BlockDescriptorType);
03868 }
03869 
03870 QualType ASTContext::getBlockDescriptorExtendedType() const {
03871   if (BlockDescriptorExtendedType)
03872     return getTagDeclType(BlockDescriptorExtendedType);
03873 
03874   RecordDecl *T;
03875   // FIXME: Needs the FlagAppleBlock bit.
03876   T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
03877                        &Idents.get("__block_descriptor_withcopydispose"));
03878   T->startDefinition();
03879   
03880   QualType FieldTypes[] = {
03881     UnsignedLongTy,
03882     UnsignedLongTy,
03883     getPointerType(VoidPtrTy),
03884     getPointerType(VoidPtrTy)
03885   };
03886 
03887   const char *FieldNames[] = {
03888     "reserved",
03889     "Size",
03890     "CopyFuncPtr",
03891     "DestroyFuncPtr"
03892   };
03893 
03894   for (size_t i = 0; i < 4; ++i) {
03895     FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
03896                                          SourceLocation(),
03897                                          &Idents.get(FieldNames[i]),
03898                                          FieldTypes[i], /*TInfo=*/0,
03899                                          /*BitWidth=*/0,
03900                                          /*Mutable=*/false,
03901                                          /*HasInit=*/false);
03902     Field->setAccess(AS_public);
03903     T->addDecl(Field);
03904   }
03905 
03906   T->completeDefinition();
03907 
03908   BlockDescriptorExtendedType = T;
03909 
03910   return getTagDeclType(BlockDescriptorExtendedType);
03911 }
03912 
03913 bool ASTContext::BlockRequiresCopying(QualType Ty) const {
03914   if (Ty->isObjCRetainableType())
03915     return true;
03916   if (getLangOpts().CPlusPlus) {
03917     if (const RecordType *RT = Ty->getAs<RecordType>()) {
03918       CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
03919       return RD->hasConstCopyConstructor();
03920       
03921     }
03922   }
03923   return false;
03924 }
03925 
03926 QualType
03927 ASTContext::BuildByRefType(StringRef DeclName, QualType Ty) const {
03928   //  type = struct __Block_byref_1_X {
03929   //    void *__isa;
03930   //    struct __Block_byref_1_X *__forwarding;
03931   //    unsigned int __flags;
03932   //    unsigned int __size;
03933   //    void *__copy_helper;            // as needed
03934   //    void *__destroy_help            // as needed
03935   //    int X;
03936   //  } *
03937 
03938   bool HasCopyAndDispose = BlockRequiresCopying(Ty);
03939 
03940   // FIXME: Move up
03941   SmallString<36> Name;
03942   llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
03943                                   ++UniqueBlockByRefTypeID << '_' << DeclName;
03944   RecordDecl *T;
03945   T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
03946   T->startDefinition();
03947   QualType Int32Ty = IntTy;
03948   assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
03949   QualType FieldTypes[] = {
03950     getPointerType(VoidPtrTy),
03951     getPointerType(getTagDeclType(T)),
03952     Int32Ty,
03953     Int32Ty,
03954     getPointerType(VoidPtrTy),
03955     getPointerType(VoidPtrTy),
03956     Ty
03957   };
03958 
03959   StringRef FieldNames[] = {
03960     "__isa",
03961     "__forwarding",
03962     "__flags",
03963     "__size",
03964     "__copy_helper",
03965     "__destroy_helper",
03966     DeclName,
03967   };
03968 
03969   for (size_t i = 0; i < 7; ++i) {
03970     if (!HasCopyAndDispose && i >=4 && i <= 5)
03971       continue;
03972     FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
03973                                          SourceLocation(),
03974                                          &Idents.get(FieldNames[i]),
03975                                          FieldTypes[i], /*TInfo=*/0,
03976                                          /*BitWidth=*/0, /*Mutable=*/false,
03977                                          /*HasInit=*/false);
03978     Field->setAccess(AS_public);
03979     T->addDecl(Field);
03980   }
03981 
03982   T->completeDefinition();
03983 
03984   return getPointerType(getTagDeclType(T));
03985 }
03986 
03987 TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
03988   if (!ObjCInstanceTypeDecl)
03989     ObjCInstanceTypeDecl = TypedefDecl::Create(*this, 
03990                                                getTranslationUnitDecl(),
03991                                                SourceLocation(), 
03992                                                SourceLocation(),
03993                                                &Idents.get("instancetype"), 
03994                                      getTrivialTypeSourceInfo(getObjCIdType()));
03995   return ObjCInstanceTypeDecl;
03996 }
03997 
03998 // This returns true if a type has been typedefed to BOOL:
03999 // typedef <type> BOOL;
04000 static bool isTypeTypedefedAsBOOL(QualType T) {
04001   if (const TypedefType *TT = dyn_cast<TypedefType>(T))
04002     if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
04003       return II->isStr("BOOL");
04004 
04005   return false;
04006 }
04007 
04008 /// getObjCEncodingTypeSize returns size of type for objective-c encoding
04009 /// purpose.
04010 CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
04011   if (!type->isIncompleteArrayType() && type->isIncompleteType())
04012     return CharUnits::Zero();
04013   
04014   CharUnits sz = getTypeSizeInChars(type);
04015 
04016   // Make all integer and enum types at least as large as an int
04017   if (sz.isPositive() && type->isIntegralOrEnumerationType())
04018     sz = std::max(sz, getTypeSizeInChars(IntTy));
04019   // Treat arrays as pointers, since that's how they're passed in.
04020   else if (type->isArrayType())
04021     sz = getTypeSizeInChars(VoidPtrTy);
04022   return sz;
04023 }
04024 
04025 static inline 
04026 std::string charUnitsToString(const CharUnits &CU) {
04027   return llvm::itostr(CU.getQuantity());
04028 }
04029 
04030 /// getObjCEncodingForBlock - Return the encoded type for this block
04031 /// declaration.
04032 std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
04033   std::string S;
04034 
04035   const BlockDecl *Decl = Expr->getBlockDecl();
04036   QualType BlockTy =
04037       Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
04038   // Encode result type.
04039   getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
04040   // Compute size of all parameters.
04041   // Start with computing size of a pointer in number of bytes.
04042   // FIXME: There might(should) be a better way of doing this computation!
04043   SourceLocation Loc;
04044   CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
04045   CharUnits ParmOffset = PtrSize;
04046   for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
04047        E = Decl->param_end(); PI != E; ++PI) {
04048     QualType PType = (*PI)->getType();
04049     CharUnits sz = getObjCEncodingTypeSize(PType);
04050     assert (sz.isPositive() && "BlockExpr - Incomplete param type");
04051     ParmOffset += sz;
04052   }
04053   // Size of the argument frame
04054   S += charUnitsToString(ParmOffset);
04055   // Block pointer and offset.
04056   S += "@?0";
04057   
04058   // Argument types.
04059   ParmOffset = PtrSize;
04060   for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
04061        Decl->param_end(); PI != E; ++PI) {
04062     ParmVarDecl *PVDecl = *PI;
04063     QualType PType = PVDecl->getOriginalType(); 
04064     if (const ArrayType *AT =
04065           dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
04066       // Use array's original type only if it has known number of
04067       // elements.
04068       if (!isa<ConstantArrayType>(AT))
04069         PType = PVDecl->getType();
04070     } else if (PType->isFunctionType())
04071       PType = PVDecl->getType();
04072     getObjCEncodingForType(PType, S);
04073     S += charUnitsToString(ParmOffset);
04074     ParmOffset += getObjCEncodingTypeSize(PType);
04075   }
04076 
04077   return S;
04078 }
04079 
04080 bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
04081                                                 std::string& S) {
04082   // Encode result type.
04083   getObjCEncodingForType(Decl->getResultType(), S);
04084   CharUnits ParmOffset;
04085   // Compute size of all parameters.
04086   for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
04087        E = Decl->param_end(); PI != E; ++PI) {
04088     QualType PType = (*PI)->getType();
04089     CharUnits sz = getObjCEncodingTypeSize(PType);
04090     if (sz.isZero())
04091       return true;
04092     
04093     assert (sz.isPositive() && 
04094         "getObjCEncodingForFunctionDecl - Incomplete param type");
04095     ParmOffset += sz;
04096   }
04097   S += charUnitsToString(ParmOffset);
04098   ParmOffset = CharUnits::Zero();
04099 
04100   // Argument types.
04101   for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
04102        E = Decl->param_end(); PI != E; ++PI) {
04103     ParmVarDecl *PVDecl = *PI;
04104     QualType PType = PVDecl->getOriginalType();
04105     if (const ArrayType *AT =
04106           dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
04107       // Use array's original type only if it has known number of
04108       // elements.
04109       if (!isa<ConstantArrayType>(AT))
04110         PType = PVDecl->getType();
04111     } else if (PType->isFunctionType())
04112       PType = PVDecl->getType();
04113     getObjCEncodingForType(PType, S);
04114     S += charUnitsToString(ParmOffset);
04115     ParmOffset += getObjCEncodingTypeSize(PType);
04116   }
04117   
04118   return false;
04119 }
04120 
04121 /// getObjCEncodingForMethodParameter - Return the encoded type for a single
04122 /// method parameter or return type. If Extended, include class names and 
04123 /// block object types.
04124 void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
04125                                                    QualType T, std::string& S,
04126                                                    bool Extended) const {
04127   // Encode type qualifer, 'in', 'inout', etc. for the parameter.
04128   getObjCEncodingForTypeQualifier(QT, S);
04129   // Encode parameter type.
04130   getObjCEncodingForTypeImpl(T, S, true, true, 0,
04131                              true     /*OutermostType*/,
04132                              false    /*EncodingProperty*/, 
04133                              false    /*StructField*/, 
04134                              Extended /*EncodeBlockParameters*/, 
04135                              Extended /*EncodeClassNames*/);
04136 }
04137 
04138 /// getObjCEncodingForMethodDecl - Return the encoded type for this method
04139 /// declaration.
04140 bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
04141                                               std::string& S, 
04142                                               bool Extended) const {
04143   // FIXME: This is not very efficient.
04144   // Encode return type.
04145   getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(), 
04146                                     Decl->getResultType(), S, Extended);
04147   // Compute size of all parameters.
04148   // Start with computing size of a pointer in number of bytes.
04149   // FIXME: There might(should) be a better way of doing this computation!
04150   SourceLocation Loc;
04151   CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
04152   // The first two arguments (self and _cmd) are pointers; account for
04153   // their size.
04154   CharUnits ParmOffset = 2 * PtrSize;
04155   for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
04156        E = Decl->sel_param_end(); PI != E; ++PI) {
04157     QualType PType = (*PI)->getType();
04158     CharUnits sz = getObjCEncodingTypeSize(PType);
04159     if (sz.isZero())
04160       return true;
04161     
04162     assert (sz.isPositive() && 
04163         "getObjCEncodingForMethodDecl - Incomplete param type");
04164     ParmOffset += sz;
04165   }
04166   S += charUnitsToString(ParmOffset);
04167   S += "@0:";
04168   S += charUnitsToString(PtrSize);
04169 
04170   // Argument types.
04171   ParmOffset = 2 * PtrSize;
04172   for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
04173        E = Decl->sel_param_end(); PI != E; ++PI) {
04174     const ParmVarDecl *PVDecl = *PI;
04175     QualType PType = PVDecl->getOriginalType();
04176     if (const ArrayType *AT =
04177           dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
04178       // Use array's original type only if it has known number of
04179       // elements.
04180       if (!isa<ConstantArrayType>(AT))
04181         PType = PVDecl->getType();
04182     } else if (PType->isFunctionType())
04183       PType = PVDecl->getType();
04184     getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(), 
04185                                       PType, S, Extended);
04186     S += charUnitsToString(ParmOffset);
04187     ParmOffset += getObjCEncodingTypeSize(PType);
04188   }
04189   
04190   return false;
04191 }
04192 
04193 /// getObjCEncodingForPropertyDecl - Return the encoded type for this
04194 /// property declaration. If non-NULL, Container must be either an
04195 /// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
04196 /// NULL when getting encodings for protocol properties.
04197 /// Property attributes are stored as a comma-delimited C string. The simple
04198 /// attributes readonly and bycopy are encoded as single characters. The
04199 /// parametrized attributes, getter=name, setter=name, and ivar=name, are
04200 /// encoded as single characters, followed by an identifier. Property types
04201 /// are also encoded as a parametrized attribute. The characters used to encode
04202 /// these attributes are defined by the following enumeration:
04203 /// @code
04204 /// enum PropertyAttributes {
04205 /// kPropertyReadOnly = 'R',   // property is read-only.
04206 /// kPropertyBycopy = 'C',     // property is a copy of the value last assigned
04207 /// kPropertyByref = '&',  // property is a reference to the value last assigned
04208 /// kPropertyDynamic = 'D',    // property is dynamic
04209 /// kPropertyGetter = 'G',     // followed by getter selector name
04210 /// kPropertySetter = 'S',     // followed by setter selector name
04211 /// kPropertyInstanceVariable = 'V'  // followed by instance variable  name
04212 /// kPropertyType = 'T'              // followed by old-style type encoding.
04213 /// kPropertyWeak = 'W'              // 'weak' property
04214 /// kPropertyStrong = 'P'            // property GC'able
04215 /// kPropertyNonAtomic = 'N'         // property non-atomic
04216 /// };
04217 /// @endcode
04218 void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
04219                                                 const Decl *Container,
04220                                                 std::string& S) const {
04221   // Collect information from the property implementation decl(s).
04222   bool Dynamic = false;
04223   ObjCPropertyImplDecl *SynthesizePID = 0;
04224 
04225   // FIXME: Duplicated code due to poor abstraction.
04226   if (Container) {
04227     if (const ObjCCategoryImplDecl *CID =
04228         dyn_cast<ObjCCategoryImplDecl>(Container)) {
04229       for (ObjCCategoryImplDecl::propimpl_iterator
04230              i = CID->propimpl_begin(), e = CID->propimpl_end();
04231            i != e; ++i) {
04232         ObjCPropertyImplDecl *PID = &*i;
04233         if (PID->getPropertyDecl() == PD) {
04234           if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
04235             Dynamic = true;
04236           } else {
04237             SynthesizePID = PID;
04238           }
04239         }
04240       }
04241     } else {
04242       const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
04243       for (ObjCCategoryImplDecl::propimpl_iterator
04244              i = OID->propimpl_begin(), e = OID->propimpl_end();
04245            i != e; ++i) {
04246         ObjCPropertyImplDecl *PID = &*i;
04247         if (PID->getPropertyDecl() == PD) {
04248           if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
04249             Dynamic = true;
04250           } else {
04251             SynthesizePID = PID;
04252           }
04253         }
04254       }
04255     }
04256   }
04257 
04258   // FIXME: This is not very efficient.
04259   S = "T";
04260 
04261   // Encode result type.
04262   // GCC has some special rules regarding encoding of properties which
04263   // closely resembles encoding of ivars.
04264   getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
04265                              true /* outermost type */,
04266                              true /* encoding for property */);
04267 
04268   if (PD->isReadOnly()) {
04269     S += ",R";
04270   } else {
04271     switch (PD->getSetterKind()) {
04272     case ObjCPropertyDecl::Assign: break;
04273     case ObjCPropertyDecl::Copy:   S += ",C"; break;
04274     case ObjCPropertyDecl::Retain: S += ",&"; break;
04275     case ObjCPropertyDecl::Weak:   S += ",W"; break;
04276     }
04277   }
04278 
04279   // It really isn't clear at all what this means, since properties
04280   // are "dynamic by default".
04281   if (Dynamic)
04282     S += ",D";
04283 
04284   if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
04285     S += ",N";
04286 
04287   if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
04288     S += ",G";
04289     S += PD->getGetterName().getAsString();
04290   }
04291 
04292   if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
04293     S += ",S";
04294     S += PD->getSetterName().getAsString();
04295   }
04296 
04297   if (SynthesizePID) {
04298     const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
04299     S += ",V";
04300     S += OID->getNameAsString();
04301   }
04302 
04303   // FIXME: OBJCGC: weak & strong
04304 }
04305 
04306 /// getLegacyIntegralTypeEncoding -
04307 /// Another legacy compatibility encoding: 32-bit longs are encoded as
04308 /// 'l' or 'L' , but not always.  For typedefs, we need to use
04309 /// 'i' or 'I' instead if encoding a struct field, or a pointer!
04310 ///
04311 void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
04312   if (isa<TypedefType>(PointeeTy.getTypePtr())) {
04313     if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
04314       if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
04315         PointeeTy = UnsignedIntTy;
04316       else
04317         if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
04318           PointeeTy = IntTy;
04319     }
04320   }
04321 }
04322 
04323 void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
04324                                         const FieldDecl *Field) const {
04325   // We follow the behavior of gcc, expanding structures which are
04326   // directly pointed to, and expanding embedded structures. Note that
04327   // these rules are sufficient to prevent recursive encoding of the
04328   // same type.
04329   getObjCEncodingForTypeImpl(T, S, true, true, Field,
04330                              true /* outermost type */);
04331 }
04332 
04333 static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
04334     switch (T->getAs<BuiltinType>()->getKind()) {
04335     default: llvm_unreachable("Unhandled builtin type kind");
04336     case BuiltinType::Void:       return 'v';
04337     case BuiltinType::Bool:       return 'B';
04338     case BuiltinType::Char_U:
04339     case BuiltinType::UChar:      return 'C';
04340     case BuiltinType::UShort:     return 'S';
04341     case BuiltinType::UInt:       return 'I';
04342     case BuiltinType::ULong:
04343         return C->getIntWidth(T) == 32 ? 'L' : 'Q';
04344     case BuiltinType::UInt128:    return 'T';
04345     case BuiltinType::ULongLong:  return 'Q';
04346     case BuiltinType::Char_S:
04347     case BuiltinType::SChar:      return 'c';
04348     case BuiltinType::Short:      return 's';
04349     case BuiltinType::WChar_S:
04350     case BuiltinType::WChar_U:
04351     case BuiltinType::Int:        return 'i';
04352     case BuiltinType::Long:
04353       return C->getIntWidth(T) == 32 ? 'l' : 'q';
04354     case BuiltinType::LongLong:   return 'q';
04355     case BuiltinType::Int128:     return 't';
04356     case BuiltinType::Float:      return 'f';
04357     case BuiltinType::Double:     return 'd';
04358     case BuiltinType::LongDouble: return 'D';
04359     }
04360 }
04361 
04362 static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
04363   EnumDecl *Enum = ET->getDecl();
04364   
04365   // The encoding of an non-fixed enum type is always 'i', regardless of size.
04366   if (!Enum->isFixed())
04367     return 'i';
04368   
04369   // The encoding of a fixed enum type matches its fixed underlying type.
04370   return ObjCEncodingForPrimitiveKind(C, Enum->getIntegerType());
04371 }
04372 
04373 static void EncodeBitField(const ASTContext *Ctx, std::string& S,
04374                            QualType T, const FieldDecl *FD) {
04375   assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
04376   S += 'b';
04377   // The NeXT runtime encodes bit fields as b followed by the number of bits.
04378   // The GNU runtime requires more information; bitfields are encoded as b,
04379   // then the offset (in bits) of the first element, then the type of the
04380   // bitfield, then the size in bits.  For example, in this structure:
04381   //
04382   // struct
04383   // {
04384   //    int integer;
04385   //    int flags:2;
04386   // };
04387   // On a 32-bit system, the encoding for flags would be b2 for the NeXT
04388   // runtime, but b32i2 for the GNU runtime.  The reason for this extra
04389   // information is not especially sensible, but we're stuck with it for
04390   // compatibility with GCC, although providing it breaks anything that
04391   // actually uses runtime introspection and wants to work on both runtimes...
04392   if (!Ctx->getLangOpts().NeXTRuntime) {
04393     const RecordDecl *RD = FD->getParent();
04394     const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
04395     S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
04396     if (const EnumType *ET = T->getAs<EnumType>())
04397       S += ObjCEncodingForEnumType(Ctx, ET);
04398     else
04399       S += ObjCEncodingForPrimitiveKind(Ctx, T);
04400   }
04401   S += llvm::utostr(FD->getBitWidthValue(*Ctx));
04402 }
04403 
04404 // FIXME: Use SmallString for accumulating string.
04405 void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
04406                                             bool ExpandPointedToStructures,
04407                                             bool ExpandStructures,
04408                                             const FieldDecl *FD,
04409                                             bool OutermostType,
04410                                             bool EncodingProperty,
04411                                             bool StructField,
04412                                             bool EncodeBlockParameters,
04413                                             bool EncodeClassNames) const {
04414   if (T->getAs<BuiltinType>()) {
04415     if (FD && FD->isBitField())
04416       return EncodeBitField(this, S, T, FD);
04417     S += ObjCEncodingForPrimitiveKind(this, T);
04418     return;
04419   }
04420 
04421   if (const ComplexType *CT = T->getAs<ComplexType>()) {
04422     S += 'j';
04423     getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
04424                                false);
04425     return;
04426   }
04427   
04428   // encoding for pointer or r3eference types.
04429   QualType PointeeTy;
04430   if (const PointerType *PT = T->getAs<PointerType>()) {
04431     if (PT->isObjCSelType()) {
04432       S += ':';
04433       return;
04434     }
04435     PointeeTy = PT->getPointeeType();
04436   }
04437   else if (const ReferenceType *RT = T->getAs<ReferenceType>())
04438     PointeeTy = RT->getPointeeType();
04439   if (!PointeeTy.isNull()) {
04440     bool isReadOnly = false;
04441     // For historical/compatibility reasons, the read-only qualifier of the
04442     // pointee gets emitted _before_ the '^'.  The read-only qualifier of
04443     // the pointer itself gets ignored, _unless_ we are looking at a typedef!
04444     // Also, do not emit the 'r' for anything but the outermost type!
04445     if (isa<TypedefType>(T.getTypePtr())) {
04446       if (OutermostType && T.isConstQualified()) {
04447         isReadOnly = true;
04448         S += 'r';
04449       }
04450     } else if (OutermostType) {
04451       QualType P = PointeeTy;
04452       while (P->getAs<PointerType>())
04453         P = P->getAs<PointerType>()->getPointeeType();
04454       if (P.isConstQualified()) {
04455         isReadOnly = true;
04456         S += 'r';
04457       }
04458     }
04459     if (isReadOnly) {
04460       // Another legacy compatibility encoding. Some ObjC qualifier and type
04461       // combinations need to be rearranged.
04462       // Rewrite "in const" from "nr" to "rn"
04463       if (StringRef(S).endswith("nr"))
04464         S.replace(S.end()-2, S.end(), "rn");
04465     }
04466 
04467     if (PointeeTy->isCharType()) {
04468       // char pointer types should be encoded as '*' unless it is a
04469       // type that has been typedef'd to 'BOOL'.
04470       if (!isTypeTypedefedAsBOOL(PointeeTy)) {
04471         S += '*';
04472         return;
04473       }
04474     } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
04475       // GCC binary compat: Need to convert "struct objc_class *" to "#".
04476       if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
04477         S += '#';
04478         return;
04479       }
04480       // GCC binary compat: Need to convert "struct objc_object *" to "@".
04481       if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
04482         S += '@';
04483         return;
04484       }
04485       // fall through...
04486     }
04487     S += '^';
04488     getLegacyIntegralTypeEncoding(PointeeTy);
04489 
04490     getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
04491                                NULL);
04492     return;
04493   }
04494   
04495   if (const ArrayType *AT =
04496       // Ignore type qualifiers etc.
04497         dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
04498     if (isa<IncompleteArrayType>(AT) && !StructField) {
04499       // Incomplete arrays are encoded as a pointer to the array element.
04500       S += '^';
04501 
04502       getObjCEncodingForTypeImpl(AT->getElementType(), S,
04503                                  false, ExpandStructures, FD);
04504     } else {
04505       S += '[';
04506 
04507       if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
04508         if (getTypeSize(CAT->getElementType()) == 0)
04509           S += '0';
04510         else
04511           S += llvm::utostr(CAT->getSize().getZExtValue());
04512       } else {
04513         //Variable length arrays are encoded as a regular array with 0 elements.
04514         assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
04515                "Unknown array type!");
04516         S += '0';
04517       }
04518 
04519       getObjCEncodingForTypeImpl(AT->getElementType(), S,
04520                                  false, ExpandStructures, FD);
04521       S += ']';
04522     }
04523     return;
04524   }
04525 
04526   if (T->getAs<FunctionType>()) {
04527     S += '?';
04528     return;
04529   }
04530 
04531   if (const RecordType *RTy = T->getAs<RecordType>()) {
04532     RecordDecl *RDecl = RTy->getDecl();
04533     S += RDecl->isUnion() ? '(' : '{';
04534     // Anonymous structures print as '?'
04535     if (const IdentifierInfo *II = RDecl->getIdentifier()) {
04536       S += II->getName();
04537       if (ClassTemplateSpecializationDecl *Spec
04538           = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
04539         const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
04540         std::string TemplateArgsStr
04541           = TemplateSpecializationType::PrintTemplateArgumentList(
04542                                             TemplateArgs.data(),
04543                                             TemplateArgs.size(),
04544                                             (*this).getPrintingPolicy());
04545 
04546         S += TemplateArgsStr;
04547       }
04548     } else {
04549       S += '?';
04550     }
04551     if (ExpandStructures) {
04552       S += '=';
04553       if (!RDecl->isUnion()) {
04554         getObjCEncodingForStructureImpl(RDecl, S, FD);
04555       } else {
04556         for (RecordDecl::field_iterator Field = RDecl->field_begin(),
04557                                      FieldEnd = RDecl->field_end();
04558              Field != FieldEnd; ++Field) {
04559           if (FD) {
04560             S += '"';
04561             S += Field->getNameAsString();
04562             S += '"';
04563           }
04564 
04565           // Special case bit-fields.
04566           if (Field->isBitField()) {
04567             getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
04568                                        &*Field);
04569           } else {
04570             QualType qt = Field->getType();
04571             getLegacyIntegralTypeEncoding(qt);
04572             getObjCEncodingForTypeImpl(qt, S, false, true,
04573                                        FD, /*OutermostType*/false,
04574                                        /*EncodingProperty*/false,
04575                                        /*StructField*/true);
04576           }
04577         }
04578       }
04579     }
04580     S += RDecl->isUnion() ? ')' : '}';
04581     return;
04582   }
04583   
04584   if (const EnumType *ET = T->getAs<EnumType>()) {
04585     if (FD && FD->isBitField())
04586       EncodeBitField(this, S, T, FD);
04587     else
04588       S += ObjCEncodingForEnumType(this, ET);
04589     return;
04590   }
04591 
04592   if (const BlockPointerType *BT = T->getAs<BlockPointerType>()) {
04593     S += "@?"; // Unlike a pointer-to-function, which is "^?".
04594     if (EncodeBlockParameters) {
04595       const FunctionType *FT = BT->getPointeeType()->getAs<FunctionType>();
04596       
04597       S += '<';
04598       // Block return type
04599       getObjCEncodingForTypeImpl(FT->getResultType(), S, 
04600                                  ExpandPointedToStructures, ExpandStructures, 
04601                                  FD, 
04602                                  false /* OutermostType */, 
04603                                  EncodingProperty, 
04604                                  false /* StructField */, 
04605                                  EncodeBlockParameters, 
04606                                  EncodeClassNames);
04607       // Block self
04608       S += "@?";
04609       // Block parameters
04610       if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
04611         for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
04612                E = FPT->arg_type_end(); I && (I != E); ++I) {
04613           getObjCEncodingForTypeImpl(*I, S, 
04614                                      ExpandPointedToStructures, 
04615                                      ExpandStructures, 
04616                                      FD, 
04617                                      false /* OutermostType */, 
04618                                      EncodingProperty, 
04619                                      false /* StructField */, 
04620                                      EncodeBlockParameters, 
04621                                      EncodeClassNames);
04622         }
04623       }
04624       S += '>';
04625     }
04626     return;
04627   }
04628 
04629   // Ignore protocol qualifiers when mangling at this level.
04630   if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
04631     T = OT->getBaseType();
04632 
04633   if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
04634     // @encode(class_name)
04635     ObjCInterfaceDecl *OI = OIT->getDecl();
04636     S += '{';
04637     const IdentifierInfo *II = OI->getIdentifier();
04638     S += II->getName();
04639     S += '=';
04640     SmallVector<const ObjCIvarDecl*, 32> Ivars;
04641     DeepCollectObjCIvars(OI, true, Ivars);
04642     for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
04643       const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
04644       if (Field->isBitField())
04645         getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
04646       else
04647         getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
04648     }
04649     S += '}';
04650     return;
04651   }
04652 
04653   if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
04654     if (OPT->isObjCIdType()) {
04655       S += '@';
04656       return;
04657     }
04658 
04659     if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
04660       // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
04661       // Since this is a binary compatibility issue, need to consult with runtime
04662       // folks. Fortunately, this is a *very* obsure construct.
04663       S += '#';
04664       return;
04665     }
04666 
04667     if (OPT->isObjCQualifiedIdType()) {
04668       getObjCEncodingForTypeImpl(getObjCIdType(), S,
04669                                  ExpandPointedToStructures,
04670                                  ExpandStructures, FD);
04671       if (FD || EncodingProperty || EncodeClassNames) {
04672         // Note that we do extended encoding of protocol qualifer list
04673         // Only when doing ivar or property encoding.
04674         S += '"';
04675         for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
04676              E = OPT->qual_end(); I != E; ++I) {
04677           S += '<';
04678           S += (*I)->getNameAsString();
04679           S += '>';
04680         }
04681         S += '"';
04682       }
04683       return;
04684     }
04685 
04686     QualType PointeeTy = OPT->getPointeeType();
04687     if (!EncodingProperty &&
04688         isa<TypedefType>(PointeeTy.getTypePtr())) {
04689       // Another historical/compatibility reason.
04690       // We encode the underlying type which comes out as
04691       // {...};
04692       S += '^';
04693       getObjCEncodingForTypeImpl(PointeeTy, S,
04694                                  false, ExpandPointedToStructures,
04695                                  NULL);
04696       return;
04697     }
04698 
04699     S += '@';
04700     if (OPT->getInterfaceDecl() && 
04701         (FD || EncodingProperty || EncodeClassNames)) {
04702       S += '"';
04703       S += OPT->getInterfaceDecl()->getIdentifier()->getName();
04704       for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
04705            E = OPT->qual_end(); I != E; ++I) {
04706         S += '<';
04707         S += (*I)->getNameAsString();
04708         S += '>';
04709       }
04710       S += '"';
04711     }
04712     return;
04713   }
04714 
04715   // gcc just blithely ignores member pointers.
04716   // TODO: maybe there should be a mangling for these
04717   if (T->getAs<MemberPointerType>())
04718     return;
04719   
04720   if (T->isVectorType()) {
04721     // This matches gcc's encoding, even though technically it is
04722     // insufficient.
04723     // FIXME. We should do a better job than gcc.
04724     return;
04725   }
04726   
04727   llvm_unreachable("@encode for type not implemented!");
04728 }
04729 
04730 void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
04731                                                  std::string &S,
04732                                                  const FieldDecl *FD,
04733                                                  bool includeVBases) const {
04734   assert(RDecl && "Expected non-null RecordDecl");
04735   assert(!RDecl->isUnion() && "Should not be called for unions");
04736   if (!RDecl->getDefinition())
04737     return;
04738 
04739   CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
04740   std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
04741   const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
04742 
04743   if (CXXRec) {
04744     for (CXXRecordDecl::base_class_iterator
04745            BI = CXXRec->bases_begin(),
04746            BE = CXXRec->bases_end(); BI != BE; ++BI) {
04747       if (!BI->isVirtual()) {
04748         CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
04749         if (base->isEmpty())
04750           continue;
04751         uint64_t offs = layout.getBaseClassOffsetInBits(base);
04752         FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
04753                                   std::make_pair(offs, base));
04754       }
04755     }
04756   }
04757   
04758   unsigned i = 0;
04759   for (RecordDecl::field_iterator Field = RDecl->field_begin(),
04760                                FieldEnd = RDecl->field_end();
04761        Field != FieldEnd; ++Field, ++i) {
04762     uint64_t offs = layout.getFieldOffset(i);
04763     FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
04764                               std::make_pair(offs, &*Field));
04765   }
04766 
04767   if (CXXRec && includeVBases) {
04768     for (CXXRecordDecl::base_class_iterator
04769            BI = CXXRec->vbases_begin(),
04770            BE = CXXRec->vbases_end(); BI != BE; ++BI) {
04771       CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
04772       if (base->isEmpty())
04773         continue;
04774       uint64_t offs = layout.getVBaseClassOffsetInBits(base);
04775       if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
04776         FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
04777                                   std::make_pair(offs, base));
04778     }
04779   }
04780 
04781   CharUnits size;
04782   if (CXXRec) {
04783     size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
04784   } else {
04785     size = layout.getSize();
04786   }
04787 
04788   uint64_t CurOffs = 0;
04789   std::multimap<uint64_t, NamedDecl *>::iterator
04790     CurLayObj = FieldOrBaseOffsets.begin();
04791 
04792   if (CXXRec && CXXRec->isDynamicClass() &&
04793       (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
04794     if (FD) {
04795       S += "\"_vptr$";
04796       std::string recname = CXXRec->getNameAsString();
04797       if (recname.empty()) recname = "?";
04798       S += recname;
04799       S += '"';
04800     }
04801     S += "^^?";
04802     CurOffs += getTypeSize(VoidPtrTy);
04803   }
04804 
04805   if (!RDecl->hasFlexibleArrayMember()) {
04806     // Mark the end of the structure.
04807     uint64_t offs = toBits(size);
04808     FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
04809                               std::make_pair(offs, (NamedDecl*)0));
04810   }
04811 
04812   for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
04813     assert(CurOffs <= CurLayObj->first);
04814 
04815     if (CurOffs < CurLayObj->first) {
04816       uint64_t padding = CurLayObj->first - CurOffs; 
04817       // FIXME: There doesn't seem to be a way to indicate in the encoding that
04818       // packing/alignment of members is different that normal, in which case
04819       // the encoding will be out-of-sync with the real layout.
04820       // If the runtime switches to just consider the size of types without
04821       // taking into account alignment, we could make padding explicit in the
04822       // encoding (e.g. using arrays of chars). The encoding strings would be
04823       // longer then though.
04824       CurOffs += padding;
04825     }
04826 
04827     NamedDecl *dcl = CurLayObj->second;
04828     if (dcl == 0)
04829       break; // reached end of structure.
04830 
04831     if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
04832       // We expand the bases without their virtual bases since those are going
04833       // in the initial structure. Note that this differs from gcc which
04834       // expands virtual bases each time one is encountered in the hierarchy,
04835       // making the encoding type bigger than it really is.
04836       getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
04837       assert(!base->isEmpty());
04838       CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
04839     } else {
04840       FieldDecl *field = cast<FieldDecl>(dcl);
04841       if (FD) {
04842         S += '"';
04843         S += field->getNameAsString();
04844         S += '"';
04845       }
04846 
04847       if (field->isBitField()) {
04848         EncodeBitField(this, S, field->getType(), field);
04849         CurOffs += field->getBitWidthValue(*this);
04850       } else {
04851         QualType qt = field->getType();
04852         getLegacyIntegralTypeEncoding(qt);
04853         getObjCEncodingForTypeImpl(qt, S, false, true, FD,
04854                                    /*OutermostType*/false,
04855                                    /*EncodingProperty*/false,
04856                                    /*StructField*/true);
04857         CurOffs += getTypeSize(field->getType());
04858       }
04859     }
04860   }
04861 }
04862 
04863 void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
04864                                                  std::string& S) const {
04865   if (QT & Decl::OBJC_TQ_In)
04866     S += 'n';
04867   if (QT & Decl::OBJC_TQ_Inout)
04868     S += 'N';
04869   if (QT & Decl::OBJC_TQ_Out)
04870     S += 'o';
04871   if (QT & Decl::OBJC_TQ_Bycopy)
04872     S += 'O';
04873   if (QT & Decl::OBJC_TQ_Byref)
04874     S += 'R';
04875   if (QT & Decl::OBJC_TQ_Oneway)
04876     S += 'V';
04877 }
04878 
04879 void ASTContext::setBuiltinVaListType(QualType T) {
04880   assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
04881 
04882   BuiltinVaListType = T;
04883 }
04884 
04885 TypedefDecl *ASTContext::getObjCIdDecl() const {
04886   if (!ObjCIdDecl) {
04887     QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
04888     T = getObjCObjectPointerType(T);
04889     TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
04890     ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
04891                                      getTranslationUnitDecl(),
04892                                      SourceLocation(), SourceLocation(),
04893                                      &Idents.get("id"), IdInfo);
04894   }
04895   
04896   return ObjCIdDecl;
04897 }
04898 
04899 TypedefDecl *ASTContext::getObjCSelDecl() const {
04900   if (!ObjCSelDecl) {
04901     QualType SelT = getPointerType(ObjCBuiltinSelTy);
04902     TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
04903     ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
04904                                       getTranslationUnitDecl(),
04905                                       SourceLocation(), SourceLocation(),
04906                                       &Idents.get("SEL"), SelInfo);
04907   }
04908   return ObjCSelDecl;
04909 }
04910 
04911 TypedefDecl *ASTContext::getObjCClassDecl() const {
04912   if (!ObjCClassDecl) {
04913     QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
04914     T = getObjCObjectPointerType(T);
04915     TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
04916     ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
04917                                         getTranslationUnitDecl(),
04918                                         SourceLocation(), SourceLocation(),
04919                                         &Idents.get("Class"), ClassInfo);
04920   }
04921   
04922   return ObjCClassDecl;
04923 }
04924 
04925 ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
04926   if (!ObjCProtocolClassDecl) {
04927     ObjCProtocolClassDecl 
04928       = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(), 
04929                                   SourceLocation(),
04930                                   &Idents.get("Protocol"),
04931                                   /*PrevDecl=*/0,
04932                                   SourceLocation(), true);    
04933   }
04934   
04935   return ObjCProtocolClassDecl;
04936 }
04937 
04938 void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
04939   assert(ObjCConstantStringType.isNull() &&
04940          "'NSConstantString' type already set!");
04941 
04942   ObjCConstantStringType = getObjCInterfaceType(Decl);
04943 }
04944 
04945 /// \brief Retrieve the template name that corresponds to a non-empty
04946 /// lookup.
04947 TemplateName
04948 ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
04949                                       UnresolvedSetIterator End) const {
04950   unsigned size = End - Begin;
04951   assert(size > 1 && "set is not overloaded!");
04952 
04953   void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
04954                           size * sizeof(FunctionTemplateDecl*));
04955   OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
04956 
04957   NamedDecl **Storage = OT->getStorage();
04958   for (UnresolvedSetIterator I = Begin; I != End; ++I) {
04959     NamedDecl *D = *I;
04960     assert(isa<FunctionTemplateDecl>(D) ||
04961            (isa<UsingShadowDecl>(D) &&
04962             isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
04963     *Storage++ = D;
04964   }
04965 
04966   return TemplateName(OT);
04967 }
04968 
04969 /// \brief Retrieve the template name that represents a qualified
04970 /// template name such as \c std::vector.
04971 TemplateName
04972 ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
04973                                      bool TemplateKeyword,
04974                                      TemplateDecl *Template) const {
04975   assert(NNS && "Missing nested-name-specifier in qualified template name");
04976   
04977   // FIXME: Canonicalization?
04978   llvm::FoldingSetNodeID ID;
04979   QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
04980 
04981   void *InsertPos = 0;
04982   QualifiedTemplateName *QTN =
04983     QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
04984   if (!QTN) {
04985     QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
04986     QualifiedTemplateNames.InsertNode(QTN, InsertPos);
04987   }
04988 
04989   return TemplateName(QTN);
04990 }
04991 
04992 /// \brief Retrieve the template name that represents a dependent
04993 /// template name such as \c MetaFun::template apply.
04994 TemplateName
04995 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
04996                                      const IdentifierInfo *Name) const {
04997   assert((!NNS || NNS->isDependent()) &&
04998          "Nested name specifier must be dependent");
04999 
05000   llvm::FoldingSetNodeID ID;
05001   DependentTemplateName::Profile(ID, NNS, Name);
05002 
05003   void *InsertPos = 0;
05004   DependentTemplateName *QTN =
05005     DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
05006 
05007   if (QTN)
05008     return TemplateName(QTN);
05009 
05010   NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
05011   if (CanonNNS == NNS) {
05012     QTN = new (*this,4) DependentTemplateName(NNS, Name);
05013   } else {
05014     TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
05015     QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
05016     DependentTemplateName *CheckQTN =
05017       DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
05018     assert(!CheckQTN && "Dependent type name canonicalization broken");
05019     (void)CheckQTN;
05020   }
05021 
05022   DependentTemplateNames.InsertNode(QTN, InsertPos);
05023   return TemplateName(QTN);
05024 }
05025 
05026 /// \brief Retrieve the template name that represents a dependent
05027 /// template name such as \c MetaFun::template operator+.
05028 TemplateName 
05029 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
05030                                      OverloadedOperatorKind Operator) const {
05031   assert((!NNS || NNS->isDependent()) &&
05032          "Nested name specifier must be dependent");
05033   
05034   llvm::FoldingSetNodeID ID;
05035   DependentTemplateName::Profile(ID, NNS, Operator);
05036   
05037   void *InsertPos = 0;
05038   DependentTemplateName *QTN
05039     = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
05040   
05041   if (QTN)
05042     return TemplateName(QTN);
05043   
05044   NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
05045   if (CanonNNS == NNS) {
05046     QTN = new (*this,4) DependentTemplateName(NNS, Operator);
05047   } else {
05048     TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
05049     QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
05050     
05051     DependentTemplateName *CheckQTN
05052       = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
05053     assert(!CheckQTN && "Dependent template name canonicalization broken");
05054     (void)CheckQTN;
05055   }
05056   
05057   DependentTemplateNames.InsertNode(QTN, InsertPos);
05058   return TemplateName(QTN);
05059 }
05060 
05061 TemplateName 
05062 ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
05063                                          TemplateName replacement) const {
05064   llvm::FoldingSetNodeID ID;
05065   SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
05066   
05067   void *insertPos = 0;
05068   SubstTemplateTemplateParmStorage *subst
05069     = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
05070   
05071   if (!subst) {
05072     subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
05073     SubstTemplateTemplateParms.InsertNode(subst, insertPos);
05074   }
05075 
05076   return TemplateName(subst);
05077 }
05078 
05079 TemplateName 
05080 ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
05081                                        const TemplateArgument &ArgPack) const {
05082   ASTContext &Self = const_cast<ASTContext &>(*this);
05083   llvm::FoldingSetNodeID ID;
05084   SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
05085   
05086   void *InsertPos = 0;
05087   SubstTemplateTemplateParmPackStorage *Subst
05088     = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
05089   
05090   if (!Subst) {
05091     Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param, 
05092                                                            ArgPack.pack_size(),
05093                                                          ArgPack.pack_begin());
05094     SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
05095   }
05096 
05097   return TemplateName(Subst);
05098 }
05099 
05100 /// getFromTargetType - Given one of the integer types provided by
05101 /// TargetInfo, produce the corresponding type. The unsigned @p Type
05102 /// is actually a value of type @c TargetInfo::IntType.
05103 CanQualType ASTContext::getFromTargetType(unsigned Type) const {
05104   switch (Type) {
05105   case TargetInfo::NoInt: return CanQualType();
05106   case TargetInfo::SignedShort: return ShortTy;
05107   case TargetInfo::UnsignedShort: return UnsignedShortTy;
05108   case TargetInfo::SignedInt: return IntTy;
05109   case TargetInfo::UnsignedInt: return UnsignedIntTy;
05110   case TargetInfo::SignedLong: return LongTy;
05111   case TargetInfo::UnsignedLong: return UnsignedLongTy;
05112   case TargetInfo::SignedLongLong: return LongLongTy;
05113   case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
05114   }
05115 
05116   llvm_unreachable("Unhandled TargetInfo::IntType value");
05117 }
05118 
05119 //===----------------------------------------------------------------------===//
05120 //                        Type Predicates.
05121 //===----------------------------------------------------------------------===//
05122 
05123 /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
05124 /// garbage collection attribute.
05125 ///
05126 Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
05127   if (getLangOpts().getGC() == LangOptions::NonGC)
05128     return Qualifiers::GCNone;
05129 
05130   assert(getLangOpts().ObjC1);
05131   Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
05132 
05133   // Default behaviour under objective-C's gc is for ObjC pointers
05134   // (or pointers to them) be treated as though they were declared
05135   // as __strong.
05136   if (GCAttrs == Qualifiers::GCNone) {
05137     if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
05138       return Qualifiers::Strong;
05139     else if (Ty->isPointerType())
05140       return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
05141   } else {
05142     // It's not valid to set GC attributes on anything that isn't a
05143     // pointer.
05144 #ifndef NDEBUG
05145     QualType CT = Ty->getCanonicalTypeInternal();
05146     while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
05147       CT = AT->getElementType();
05148     assert(CT->isAnyPointerType() || CT->isBlockPointerType());
05149 #endif
05150   }
05151   return GCAttrs;
05152 }
05153 
05154 //===----------------------------------------------------------------------===//
05155 //                        Type Compatibility Testing
05156 //===----------------------------------------------------------------------===//
05157 
05158 /// areCompatVectorTypes - Return true if the two specified vector types are
05159 /// compatible.
05160 static bool areCompatVectorTypes(const VectorType *LHS,
05161                                  const VectorType *RHS) {
05162   assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
05163   return LHS->getElementType() == RHS->getElementType() &&
05164          LHS->getNumElements() == RHS->getNumElements();
05165 }
05166 
05167 bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
05168                                           QualType SecondVec) {
05169   assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
05170   assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
05171 
05172   if (hasSameUnqualifiedType(FirstVec, SecondVec))
05173     return true;
05174 
05175   // Treat Neon vector types and most AltiVec vector types as if they are the
05176   // equivalent GCC vector types.
05177   const VectorType *First = FirstVec->getAs<VectorType>();
05178   const VectorType *Second = SecondVec->getAs<VectorType>();
05179   if (First->getNumElements() == Second->getNumElements() &&
05180       hasSameType(First->getElementType(), Second->getElementType()) &&
05181       First->getVectorKind() != VectorType::AltiVecPixel &&
05182       First->getVectorKind() != VectorType::AltiVecBool &&
05183       Second->getVectorKind() != VectorType::AltiVecPixel &&
05184       Second->getVectorKind() != VectorType::AltiVecBool)
05185     return true;
05186 
05187   return false;
05188 }
05189 
05190 //===----------------------------------------------------------------------===//
05191 // ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
05192 //===----------------------------------------------------------------------===//
05193 
05194 /// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
05195 /// inheritance hierarchy of 'rProto'.
05196 bool
05197 ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
05198                                            ObjCProtocolDecl *rProto) const {
05199   if (declaresSameEntity(lProto, rProto))
05200     return true;
05201   for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
05202        E = rProto->protocol_end(); PI != E; ++PI)
05203     if (ProtocolCompatibleWithProtocol(lProto, *PI))
05204       return true;
05205   return false;
05206 }
05207 
05208 /// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
05209 /// return true if lhs's protocols conform to rhs's protocol; false
05210 /// otherwise.
05211 bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
05212   if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
05213     return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
05214   return false;
05215 }
05216 
05217 /// ObjCQualifiedClassTypesAreCompatible - compare  Class<p,...> and
05218 /// Class<p1, ...>.
05219 bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs, 
05220                                                       QualType rhs) {
05221   const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
05222   const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
05223   assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
05224   
05225   for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
05226        E = lhsQID->qual_end(); I != E; ++I) {
05227     bool match = false;
05228     ObjCProtocolDecl *lhsProto = *I;
05229     for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
05230          E = rhsOPT->qual_end(); J != E; ++J) {
05231       ObjCProtocolDecl *rhsProto = *J;
05232       if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
05233         match = true;
05234         break;
05235       }
05236     }
05237     if (!match)
05238       return false;
05239   }
05240   return true;
05241 }
05242 
05243 /// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
05244 /// ObjCQualifiedIDType.
05245 bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
05246                                                    bool compare) {
05247   // Allow id<P..> and an 'id' or void* type in all cases.
05248   if (lhs->isVoidPointerType() ||
05249       lhs->isObjCIdType() || lhs->isObjCClassType())
05250     return true;
05251   else if (rhs->isVoidPointerType() ||
05252            rhs->isObjCIdType() || rhs->isObjCClassType())
05253     return true;
05254 
05255   if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
05256     const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
05257 
05258     if (!rhsOPT) return false;
05259 
05260     if (rhsOPT->qual_empty()) {
05261       // If the RHS is a unqualified interface pointer "NSString*",
05262       // make sure we check the class hierarchy.
05263       if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
05264         for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
05265              E = lhsQID->qual_end(); I != E; ++I) {
05266           // when comparing an id<P> on lhs with a static type on rhs,
05267           // see if static class implements all of id's protocols, directly or
05268           // through its super class and categories.
05269           if (!rhsID->ClassImplementsProtocol(*I, true))
05270             return false;
05271         }
05272       }
05273       // If there are no qualifiers and no interface, we have an 'id'.
05274       return true;
05275     }
05276     // Both the right and left sides have qualifiers.
05277     for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
05278          E = lhsQID->qual_end(); I != E; ++I) {
05279       ObjCProtocolDecl *lhsProto = *I;
05280       bool match = false;
05281 
05282       // when comparing an id<P> on lhs with a static type on rhs,
05283       // see if static class implements all of id's protocols, directly or
05284       // through its super class and categories.
05285       for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
05286            E = rhsOPT->qual_end(); J != E; ++J) {
05287         ObjCProtocolDecl *rhsProto = *J;
05288         if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
05289             (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
05290           match = true;
05291           break;
05292         }
05293       }
05294       // If the RHS is a qualified interface pointer "NSString<P>*",
05295       // make sure we check the class hierarchy.
05296       if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
05297         for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
05298              E = lhsQID->qual_end(); I != E; ++I) {
05299           // when comparing an id<P> on lhs with a static type on rhs,
05300           // see if static class implements all of id's protocols, directly or
05301           // through its super class and categories.
05302           if (rhsID->ClassImplementsProtocol(*I, true)) {
05303             match = true;
05304             break;
05305           }
05306         }
05307       }
05308       if (!match)
05309         return false;
05310     }
05311 
05312     return true;
05313   }
05314 
05315   const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
05316   assert(rhsQID && "One of the LHS/RHS should be id<x>");
05317 
05318   if (const ObjCObjectPointerType *lhsOPT =
05319         lhs->getAsObjCInterfacePointerType()) {
05320     // If both the right and left sides have qualifiers.
05321     for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
05322          E = lhsOPT->qual_end(); I != E; ++I) {
05323       ObjCProtocolDecl *lhsProto = *I;
05324       bool match = false;
05325 
05326       // when comparing an id<P> on rhs with a static type on lhs,
05327       // see if static class implements all of id's protocols, directly or
05328       // through its super class and categories.
05329       // First, lhs protocols in the qualifier list must be found, direct
05330       // or indirect in rhs's qualifier list or it is a mismatch.
05331       for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
05332            E = rhsQID->qual_end(); J != E; ++J) {
05333         ObjCProtocolDecl *rhsProto = *J;
05334         if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
05335             (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
05336           match = true;
05337           break;
05338         }
05339       }
05340       if (!match)
05341         return false;
05342     }
05343     
05344     // Static class's protocols, or its super class or category protocols
05345     // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
05346     if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
05347       llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
05348       CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
05349       // This is rather dubious but matches gcc's behavior. If lhs has
05350       // no type qualifier and its class has no static protocol(s)
05351       // assume that it is mismatch.
05352       if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
05353         return false;
05354       for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
05355            LHSInheritedProtocols.begin(),
05356            E = LHSInheritedProtocols.end(); I != E; ++I) {
05357         bool match = false;
05358         ObjCProtocolDecl *lhsProto = (*I);
05359         for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
05360              E = rhsQID->qual_end(); J != E; ++J) {
05361           ObjCProtocolDecl *rhsProto = *J;
05362           if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
05363               (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
05364             match = true;
05365             break;
05366           }
05367         }
05368         if (!match)
05369           return false;
05370       }
05371     }
05372     return true;
05373   }
05374   return false;
05375 }
05376 
05377 /// canAssignObjCInterfaces - Return true if the two interface types are
05378 /// compatible for assignment from RHS to LHS.  This handles validation of any
05379 /// protocol qualifiers on the LHS or RHS.
05380 ///
05381 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
05382                                          const ObjCObjectPointerType *RHSOPT) {
05383   const ObjCObjectType* LHS = LHSOPT->getObjectType();
05384   const ObjCObjectType* RHS = RHSOPT->getObjectType();
05385 
05386   // If either type represents the built-in 'id' or 'Class' types, return true.
05387   if (LHS->isObjCUnqualifiedIdOrClass() ||
05388       RHS->isObjCUnqualifiedIdOrClass())
05389     return true;
05390 
05391   if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
05392     return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
05393                                              QualType(RHSOPT,0),
05394                                              false);
05395   
05396   if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
05397     return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
05398                                                 QualType(RHSOPT,0));
05399   
05400   // If we have 2 user-defined types, fall into that path.
05401   if (LHS->getInterface() && RHS->getInterface())
05402     return canAssignObjCInterfaces(LHS, RHS);
05403 
05404   return false;
05405 }
05406 
05407 /// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
05408 /// for providing type-safety for objective-c pointers used to pass/return 
05409 /// arguments in block literals. When passed as arguments, passing 'A*' where
05410 /// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
05411 /// not OK. For the return type, the opposite is not OK.
05412 bool ASTContext::canAssignObjCInterfacesInBlockPointer(
05413                                          const ObjCObjectPointerType *LHSOPT,
05414                                          const ObjCObjectPointerType *RHSOPT,
05415                                          bool BlockReturnType) {
05416   if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
05417     return true;
05418   
05419   if (LHSOPT->isObjCBuiltinType()) {
05420     return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
05421   }
05422   
05423   if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
05424     return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
05425                                              QualType(RHSOPT,0),
05426                                              false);
05427   
05428   const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
05429   const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
05430   if (LHS && RHS)  { // We have 2 user-defined types.
05431     if (LHS != RHS) {
05432       if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
05433         return BlockReturnType;
05434       if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
05435         return !BlockReturnType;
05436     }
05437     else
05438       return true;
05439   }
05440   return false;
05441 }
05442 
05443 /// getIntersectionOfProtocols - This routine finds the intersection of set
05444 /// of protocols inherited from two distinct objective-c pointer objects.
05445 /// It is used to build composite qualifier list of the composite type of
05446 /// the conditional expression involving two objective-c pointer objects.
05447 static 
05448 void getIntersectionOfProtocols(ASTContext &Context,
05449                                 const ObjCObjectPointerType *LHSOPT,
05450                                 const ObjCObjectPointerType *RHSOPT,
05451       SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
05452   
05453   const ObjCObjectType* LHS = LHSOPT->getObjectType();
05454   const ObjCObjectType* RHS = RHSOPT->getObjectType();
05455   assert(LHS->getInterface() && "LHS must have an interface base");
05456   assert(RHS->getInterface() && "RHS must have an interface base");
05457   
05458   llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
05459   unsigned LHSNumProtocols = LHS->getNumProtocols();
05460   if (LHSNumProtocols > 0)
05461     InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
05462   else {
05463     llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
05464     Context.CollectInheritedProtocols(LHS->getInterface(),
05465                                       LHSInheritedProtocols);
05466     InheritedProtocolSet.insert(LHSInheritedProtocols.begin(), 
05467                                 LHSInheritedProtocols.end());
05468   }
05469   
05470   unsigned RHSNumProtocols = RHS->getNumProtocols();
05471   if (RHSNumProtocols > 0) {
05472     ObjCProtocolDecl **RHSProtocols =
05473       const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
05474     for (unsigned i = 0; i < RHSNumProtocols; ++i)
05475       if (InheritedProtocolSet.count(RHSProtocols[i]))
05476         IntersectionOfProtocols.push_back(RHSProtocols[i]);
05477   } else {
05478     llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
05479     Context.CollectInheritedProtocols(RHS->getInterface(),
05480                                       RHSInheritedProtocols);
05481     for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I = 
05482          RHSInheritedProtocols.begin(),
05483          E = RHSInheritedProtocols.end(); I != E; ++I) 
05484       if (InheritedProtocolSet.count((*I)))
05485         IntersectionOfProtocols.push_back((*I));
05486   }
05487 }
05488 
05489 /// areCommonBaseCompatible - Returns common base class of the two classes if
05490 /// one found. Note that this is O'2 algorithm. But it will be called as the
05491 /// last type comparison in a ?-exp of ObjC pointer types before a 
05492 /// warning is issued. So, its invokation is extremely rare.
05493 QualType ASTContext::areCommonBaseCompatible(
05494                                           const ObjCObjectPointerType *Lptr,
05495                                           const ObjCObjectPointerType *Rptr) {
05496   const ObjCObjectType *LHS = Lptr->getObjectType();
05497   const ObjCObjectType *RHS = Rptr->getObjectType();
05498   const ObjCInterfaceDecl* LDecl = LHS->getInterface();
05499   const ObjCInterfaceDecl* RDecl = RHS->getInterface();
05500   if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
05501     return QualType();
05502   
05503   do {
05504     LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
05505     if (canAssignObjCInterfaces(LHS, RHS)) {
05506       SmallVector<ObjCProtocolDecl *, 8> Protocols;
05507       getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
05508 
05509       QualType Result = QualType(LHS, 0);
05510       if (!Protocols.empty())
05511         Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
05512       Result = getObjCObjectPointerType(Result);
05513       return Result;
05514     }
05515   } while ((LDecl = LDecl->getSuperClass()));
05516     
05517   return QualType();
05518 }
05519 
05520 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
05521                                          const ObjCObjectType *RHS) {
05522   assert(LHS->getInterface() && "LHS is not an interface type");
05523   assert(RHS->getInterface() && "RHS is not an interface type");
05524 
05525   // Verify that the base decls are compatible: the RHS must be a subclass of
05526   // the LHS.
05527   if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
05528     return false;
05529 
05530   // RHS must have a superset of the protocols in the LHS.  If the LHS is not
05531   // protocol qualified at all, then we are good.
05532   if (LHS->getNumProtocols() == 0)
05533     return true;
05534 
05535   // Okay, we know the LHS has protocol qualifiers.  If the RHS doesn't, 
05536   // more detailed analysis is required.
05537   if (RHS->getNumProtocols() == 0) {
05538     // OK, if LHS is a superclass of RHS *and*
05539     // this superclass is assignment compatible with LHS.
05540     // false otherwise.
05541     bool IsSuperClass = 
05542       LHS->getInterface()->isSuperClassOf(RHS->getInterface());
05543     if (IsSuperClass) {
05544       // OK if conversion of LHS to SuperClass results in narrowing of types
05545       // ; i.e., SuperClass may implement at least one of the protocols
05546       // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
05547       // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
05548       llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
05549       CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
05550       // If super class has no protocols, it is not a match.
05551       if (SuperClassInheritedProtocols.empty())
05552         return false;
05553       
05554       for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
05555            LHSPE = LHS->qual_end();
05556            LHSPI != LHSPE; LHSPI++) {
05557         bool SuperImplementsProtocol = false;
05558         ObjCProtocolDecl *LHSProto = (*LHSPI);
05559         
05560         for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
05561              SuperClassInheritedProtocols.begin(),
05562              E = SuperClassInheritedProtocols.end(); I != E; ++I) {
05563           ObjCProtocolDecl *SuperClassProto = (*I);
05564           if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
05565             SuperImplementsProtocol = true;
05566             break;
05567           }
05568         }
05569         if (!SuperImplementsProtocol)
05570           return false;
05571       }
05572       return true;
05573     }
05574     return false;
05575   }
05576 
05577   for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
05578                                      LHSPE = LHS->qual_end();
05579        LHSPI != LHSPE; LHSPI++) {
05580     bool RHSImplementsProtocol = false;
05581 
05582     // If the RHS doesn't implement the protocol on the left, the types
05583     // are incompatible.
05584     for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
05585                                        RHSPE = RHS->qual_end();
05586          RHSPI != RHSPE; RHSPI++) {
05587       if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
05588         RHSImplementsProtocol = true;
05589         break;
05590       }
05591     }
05592     // FIXME: For better diagnostics, consider passing back the protocol name.
05593     if (!RHSImplementsProtocol)
05594       return false;
05595   }
05596   // The RHS implements all protocols listed on the LHS.
05597   return true;
05598 }
05599 
05600 bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
05601   // get the "pointed to" types
05602   const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
05603   const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
05604 
05605   if (!LHSOPT || !RHSOPT)
05606     return false;
05607 
05608   return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
05609          canAssignObjCInterfaces(RHSOPT, LHSOPT);
05610 }
05611 
05612 bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
05613   return canAssignObjCInterfaces(
05614                 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
05615                 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
05616 }
05617 
05618 /// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
05619 /// both shall have the identically qualified version of a compatible type.
05620 /// C99 6.2.7p1: Two types have compatible types if their types are the
05621 /// same. See 6.7.[2,3,5] for additional rules.
05622 bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
05623                                     bool CompareUnqualified) {
05624   if (getLangOpts().CPlusPlus)
05625     return hasSameType(LHS, RHS);
05626   
05627   return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
05628 }
05629 
05630 bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
05631   return typesAreCompatible(LHS, RHS);
05632 }
05633 
05634 bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
05635   return !mergeTypes(LHS, RHS, true).isNull();
05636 }
05637 
05638 /// mergeTransparentUnionType - if T is a transparent union type and a member
05639 /// of T is compatible with SubType, return the merged type, else return
05640 /// QualType()
05641 QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
05642                                                bool OfBlockPointer,
05643                                                bool Unqualified) {
05644   if (const RecordType *UT = T->getAsUnionType()) {
05645     RecordDecl *UD = UT->getDecl();
05646     if (UD->hasAttr<TransparentUnionAttr>()) {
05647       for (RecordDecl::field_iterator it = UD->field_begin(),
05648            itend = UD->field_end(); it != itend; ++it) {
05649         QualType ET = it->getType().getUnqualifiedType();
05650         QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
05651         if (!MT.isNull())
05652           return MT;
05653       }
05654     }
05655   }
05656 
05657   return QualType();
05658 }
05659 
05660 /// mergeFunctionArgumentTypes - merge two types which appear as function
05661 /// argument types
05662 QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs, 
05663                                                 bool OfBlockPointer,
05664                                                 bool Unqualified) {
05665   // GNU extension: two types are compatible if they appear as a function
05666   // argument, one of the types is a transparent union type and the other
05667   // type is compatible with a union member
05668   QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
05669                                               Unqualified);
05670   if (!lmerge.isNull())
05671     return lmerge;
05672 
05673   QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
05674                                               Unqualified);
05675   if (!rmerge.isNull())
05676     return rmerge;
05677 
05678   return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
05679 }
05680 
05681 QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs, 
05682                                         bool OfBlockPointer,
05683                                         bool Unqualified) {
05684   const FunctionType *lbase = lhs->getAs<FunctionType>();
05685   const FunctionType *rbase = rhs->getAs<FunctionType>();
05686   const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
05687   const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
05688   bool allLTypes = true;
05689   bool allRTypes = true;
05690 
05691   // Check return type
05692   QualType retType;
05693   if (OfBlockPointer) {
05694     QualType RHS = rbase->getResultType();
05695     QualType LHS = lbase->getResultType();
05696     bool UnqualifiedResult = Unqualified;
05697     if (!UnqualifiedResult)
05698       UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
05699     retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
05700   }
05701   else
05702     retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
05703                          Unqualified);
05704   if (retType.isNull()) return QualType();
05705   
05706   if (Unqualified)
05707     retType = retType.getUnqualifiedType();
05708 
05709   CanQualType LRetType = getCanonicalType(lbase->getResultType());
05710   CanQualType RRetType = getCanonicalType(rbase->getResultType());
05711   if (Unqualified) {
05712     LRetType = LRetType.getUnqualifiedType();
05713     RRetType = RRetType.getUnqualifiedType();
05714   }
05715   
05716   if (getCanonicalType(retType) != LRetType)
05717     allLTypes = false;
05718   if (getCanonicalType(retType) != RRetType)
05719     allRTypes = false;
05720 
05721   // FIXME: double check this
05722   // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
05723   //                           rbase->getRegParmAttr() != 0 &&
05724   //                           lbase->getRegParmAttr() != rbase->getRegParmAttr()?
05725   FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
05726   FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
05727 
05728   // Compatible functions must have compatible calling conventions
05729   if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
05730     return QualType();
05731 
05732   // Regparm is part of the calling convention.
05733   if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
05734     return QualType();
05735   if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
05736     return QualType();
05737 
05738   if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
05739     return QualType();
05740 
05741   // functypes which return are preferred over those that do not.
05742   if (lbaseInfo.getNoReturn() && !rbaseInfo.getNoReturn())
05743     allLTypes = false;
05744   else if (!lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn())
05745     allRTypes = false;
05746   // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
05747   bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
05748 
05749   FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
05750 
05751   if (lproto && rproto) { // two C99 style function prototypes
05752     assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
05753            "C++ shouldn't be here");
05754     unsigned lproto_nargs = lproto->getNumArgs();
05755     unsigned rproto_nargs = rproto->getNumArgs();
05756 
05757     // Compatible functions must have the same number of arguments
05758     if (lproto_nargs != rproto_nargs)
05759       return QualType();
05760 
05761     // Variadic and non-variadic functions aren't compatible
05762     if (lproto->isVariadic() != rproto->isVariadic())
05763       return QualType();
05764 
05765     if (lproto->getTypeQuals() != rproto->getTypeQuals())
05766       return QualType();
05767 
05768     if (LangOpts.ObjCAutoRefCount &&
05769         !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
05770       return QualType();
05771       
05772     // Check argument compatibility
05773     SmallVector<QualType, 10> types;
05774     for (unsigned i = 0; i < lproto_nargs; i++) {
05775       QualType largtype = lproto->getArgType(i).getUnqualifiedType();
05776       QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
05777       QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
05778                                                     OfBlockPointer,
05779                                                     Unqualified);
05780       if (argtype.isNull()) return QualType();
05781       
05782       if (Unqualified)
05783         argtype = argtype.getUnqualifiedType();
05784       
05785       types.push_back(argtype);
05786       if (Unqualified) {
05787         largtype = largtype.getUnqualifiedType();
05788         rargtype = rargtype.getUnqualifiedType();
05789       }
05790       
05791       if (getCanonicalType(argtype) != getCanonicalType(largtype))
05792         allLTypes = false;
05793       if (getCanonicalType(argtype) != getCanonicalType(rargtype))
05794         allRTypes = false;
05795     }
05796       
05797     if (allLTypes) return lhs;
05798     if (allRTypes) return rhs;
05799 
05800     FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
05801     EPI.ExtInfo = einfo;
05802     return getFunctionType(retType, types.begin(), types.size(), EPI);
05803   }
05804 
05805   if (lproto) allRTypes = false;
05806   if (rproto) allLTypes = false;
05807 
05808   const FunctionProtoType *proto = lproto ? lproto : rproto;
05809   if (proto) {
05810     assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
05811     if (proto->isVariadic()) return QualType();
05812     // Check that the types are compatible with the types that
05813     // would result from default argument promotions (C99 6.7.5.3p15).
05814     // The only types actually affected are promotable integer
05815     // types and floats, which would be passed as a different
05816     // type depending on whether the prototype is visible.
05817     unsigned proto_nargs = proto->getNumArgs();
05818     for (unsigned i = 0; i < proto_nargs; ++i) {
05819       QualType argTy = proto->getArgType(i);
05820       
05821       // Look at the promotion type of enum types, since that is the type used
05822       // to pass enum values.
05823       if (const EnumType *Enum = argTy->getAs<EnumType>())
05824         argTy = Enum->getDecl()->getPromotionType();
05825       
05826       if (argTy->isPromotableIntegerType() ||
05827           getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
05828         return QualType();
05829     }
05830 
05831     if (allLTypes) return lhs;
05832     if (allRTypes) return rhs;
05833 
05834     FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
05835     EPI.ExtInfo = einfo;
05836     return getFunctionType(retType, proto->arg_type_begin(),
05837                            proto->getNumArgs(), EPI);
05838   }
05839 
05840   if (allLTypes) return lhs;
05841   if (allRTypes) return rhs;
05842   return getFunctionNoProtoType(retType, einfo);
05843 }
05844 
05845 QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, 
05846                                 bool OfBlockPointer,
05847                                 bool Unqualified, bool BlockReturnType) {
05848   // C++ [expr]: If an expression initially has the type "reference to T", the
05849   // type is adjusted to "T" prior to any further analysis, the expression
05850   // designates the object or function denoted by the reference, and the
05851   // expression is an lvalue unless the reference is an rvalue reference and
05852   // the expression is a function call (possibly inside parentheses).
05853   assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
05854   assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
05855 
05856   if (Unqualified) {
05857     LHS = LHS.getUnqualifiedType();
05858     RHS = RHS.getUnqualifiedType();
05859   }
05860   
05861   QualType LHSCan = getCanonicalType(LHS),
05862            RHSCan = getCanonicalType(RHS);
05863 
05864   // If two types are identical, they are compatible.
05865   if (LHSCan == RHSCan)
05866     return LHS;
05867 
05868   // If the qualifiers are different, the types aren't compatible... mostly.
05869   Qualifiers LQuals = LHSCan.getLocalQualifiers();
05870   Qualifiers RQuals = RHSCan.getLocalQualifiers();
05871   if (LQuals != RQuals) {
05872     // If any of these qualifiers are different, we have a type
05873     // mismatch.
05874     if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
05875         LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
05876         LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
05877       return QualType();
05878 
05879     // Exactly one GC qualifier difference is allowed: __strong is
05880     // okay if the other type has no GC qualifier but is an Objective
05881     // C object pointer (i.e. implicitly strong by default).  We fix
05882     // this by pretending that the unqualified type was actually
05883     // qualified __strong.
05884     Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
05885     Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
05886     assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
05887 
05888     if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
05889       return QualType();
05890 
05891     if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
05892       return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
05893     }
05894     if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
05895       return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
05896     }
05897     return QualType();
05898   }
05899 
05900   // Okay, qualifiers are equal.
05901 
05902   Type::TypeClass LHSClass = LHSCan->getTypeClass();
05903   Type::TypeClass RHSClass = RHSCan->getTypeClass();
05904 
05905   // We want to consider the two function types to be the same for these
05906   // comparisons, just force one to the other.
05907   if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
05908   if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
05909 
05910   // Same as above for arrays
05911   if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
05912     LHSClass = Type::ConstantArray;
05913   if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
05914     RHSClass = Type::ConstantArray;
05915 
05916   // ObjCInterfaces are just specialized ObjCObjects.
05917   if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
05918   if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
05919 
05920   // Canonicalize ExtVector -> Vector.
05921   if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
05922   if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
05923 
05924   // If the canonical type classes don't match.
05925   if (LHSClass != RHSClass) {
05926     // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
05927     // a signed integer type, or an unsigned integer type.
05928     // Compatibility is based on the underlying type, not the promotion
05929     // type.
05930     if (const EnumType* ETy = LHS->getAs<EnumType>()) {
05931       QualType TINT = ETy->getDecl()->getIntegerType();
05932       if (!TINT.isNull() && hasSameType(TINT, RHSCan.getUnqualifiedType()))
05933         return RHS;
05934     }
05935     if (const EnumType* ETy = RHS->getAs<EnumType>()) {
05936       QualType TINT = ETy->getDecl()->getIntegerType();
05937       if (!TINT.isNull() && hasSameType(TINT, LHSCan.getUnqualifiedType()))
05938         return LHS;
05939     }
05940     // allow block pointer type to match an 'id' type.
05941     if (OfBlockPointer && !BlockReturnType) {
05942        if (LHS->isObjCIdType() && RHS->isBlockPointerType())
05943          return LHS;
05944       if (RHS->isObjCIdType() && LHS->isBlockPointerType())
05945         return RHS;
05946     }
05947     
05948     return QualType();
05949   }
05950 
05951   // The canonical type classes match.
05952   switch (LHSClass) {
05953 #define TYPE(Class, Base)
05954 #define ABSTRACT_TYPE(Class, Base)
05955 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
05956 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
05957 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
05958 #include "clang/AST/TypeNodes.def"
05959     llvm_unreachable("Non-canonical and dependent types shouldn't get here");
05960 
05961   case Type::LValueReference:
05962   case Type::RValueReference:
05963   case Type::MemberPointer:
05964     llvm_unreachable("C++ should never be in mergeTypes");
05965 
05966   case Type::ObjCInterface:
05967   case Type::IncompleteArray:
05968   case Type::VariableArray:
05969   case Type::FunctionProto:
05970   case Type::ExtVector:
05971     llvm_unreachable("Types are eliminated above");
05972 
05973   case Type::Pointer:
05974   {
05975     // Merge two pointer types, while trying to preserve typedef info
05976     QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
05977     QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
05978     if (Unqualified) {
05979       LHSPointee = LHSPointee.getUnqualifiedType();
05980       RHSPointee = RHSPointee.getUnqualifiedType();
05981     }
05982     QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false, 
05983                                      Unqualified);
05984     if (ResultType.isNull()) return QualType();
05985     if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
05986       return LHS;
05987     if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
05988       return RHS;
05989     return getPointerType(ResultType);
05990   }
05991   case Type::BlockPointer:
05992   {
05993     // Merge two block pointer types, while trying to preserve typedef info
05994     QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
05995     QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
05996     if (Unqualified) {
05997       LHSPointee = LHSPointee.getUnqualifiedType();
05998       RHSPointee = RHSPointee.getUnqualifiedType();
05999     }
06000     QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
06001                                      Unqualified);
06002     if (ResultType.isNull()) return QualType();
06003     if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
06004       return LHS;
06005     if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
06006       return RHS;
06007     return getBlockPointerType(ResultType);
06008   }
06009   case Type::Atomic:
06010   {
06011     // Merge two pointer types, while trying to preserve typedef info
06012     QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
06013     QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
06014     if (Unqualified) {
06015       LHSValue = LHSValue.getUnqualifiedType();
06016       RHSValue = RHSValue.getUnqualifiedType();
06017     }
06018     QualType ResultType = mergeTypes(LHSValue, RHSValue, false, 
06019                                      Unqualified);
06020     if (ResultType.isNull()) return QualType();
06021     if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
06022       return LHS;
06023     if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
06024       return RHS;
06025     return getAtomicType(ResultType);
06026   }
06027   case Type::ConstantArray:
06028   {
06029     const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
06030     const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
06031     if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
06032       return QualType();
06033 
06034     QualType LHSElem = getAsArrayType(LHS)->getElementType();
06035     QualType RHSElem = getAsArrayType(RHS)->getElementType();
06036     if (Unqualified) {
06037       LHSElem = LHSElem.getUnqualifiedType();
06038       RHSElem = RHSElem.getUnqualifiedType();
06039     }
06040     
06041     QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
06042     if (ResultType.isNull()) return QualType();
06043     if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
06044       return LHS;
06045     if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
06046       return RHS;
06047     if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
06048                                           ArrayType::ArraySizeModifier(), 0);
06049     if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
06050                                           ArrayType::ArraySizeModifier(), 0);
06051     const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
06052     const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
06053     if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
06054       return LHS;
06055     if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
06056       return RHS;
06057     if (LVAT) {
06058       // FIXME: This isn't correct! But tricky to implement because
06059       // the array's size has to be the size of LHS, but the type
06060       // has to be different.
06061       return LHS;
06062     }
06063     if (RVAT) {
06064       // FIXME: This isn't correct! But tricky to implement because
06065       // the array's size has to be the size of RHS, but the type
06066       // has to be different.
06067       return RHS;
06068     }
06069     if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
06070     if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
06071     return getIncompleteArrayType(ResultType,
06072                                   ArrayType::ArraySizeModifier(), 0);
06073   }
06074   case Type::FunctionNoProto:
06075     return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
06076   case Type::Record:
06077   case Type::Enum:
06078     return QualType();
06079   case Type::Builtin:
06080     // Only exactly equal builtin types are compatible, which is tested above.
06081     return QualType();
06082   case Type::Complex:
06083     // Distinct complex types are incompatible.
06084     return QualType();
06085   case Type::Vector:
06086     // FIXME: The merged type should be an ExtVector!
06087     if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
06088                              RHSCan->getAs<VectorType>()))
06089       return LHS;
06090     return QualType();
06091   case Type::ObjCObject: {
06092     // Check if the types are assignment compatible.
06093     // FIXME: This should be type compatibility, e.g. whether
06094     // "LHS x; RHS x;" at global scope is legal.
06095     const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
06096     const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
06097     if (canAssignObjCInterfaces(LHSIface, RHSIface))
06098       return LHS;
06099 
06100     return QualType();
06101   }
06102   case Type::ObjCObjectPointer: {
06103     if (OfBlockPointer) {
06104       if (canAssignObjCInterfacesInBlockPointer(
06105                                           LHS->getAs<ObjCObjectPointerType>(),
06106                                           RHS->getAs<ObjCObjectPointerType>(),
06107                                           BlockReturnType))
06108         return LHS;
06109       return QualType();
06110     }
06111     if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
06112                                 RHS->getAs<ObjCObjectPointerType>()))
06113       return LHS;
06114 
06115     return QualType();
06116   }
06117   }
06118 
06119   llvm_unreachable("Invalid Type::Class!");
06120 }
06121 
06122 bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
06123                    const FunctionProtoType *FromFunctionType,
06124                    const FunctionProtoType *ToFunctionType) {
06125   if (FromFunctionType->hasAnyConsumedArgs() != 
06126       ToFunctionType->hasAnyConsumedArgs())
06127     return false;
06128   FunctionProtoType::ExtProtoInfo FromEPI = 
06129     FromFunctionType->getExtProtoInfo();
06130   FunctionProtoType::ExtProtoInfo ToEPI = 
06131     ToFunctionType->getExtProtoInfo();
06132   if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
06133     for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
06134          ArgIdx != NumArgs; ++ArgIdx)  {
06135       if (FromEPI.ConsumedArguments[ArgIdx] != 
06136           ToEPI.ConsumedArguments[ArgIdx])
06137         return false;
06138     }
06139   return true;
06140 }
06141 
06142 /// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
06143 /// 'RHS' attributes and returns the merged version; including for function
06144 /// return types.
06145 QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
06146   QualType LHSCan = getCanonicalType(LHS),
06147   RHSCan = getCanonicalType(RHS);
06148   // If two types are identical, they are compatible.
06149   if (LHSCan == RHSCan)
06150     return LHS;
06151   if (RHSCan->isFunctionType()) {
06152     if (!LHSCan->isFunctionType())
06153       return QualType();
06154     QualType OldReturnType = 
06155       cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
06156     QualType NewReturnType =
06157       cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
06158     QualType ResReturnType = 
06159       mergeObjCGCQualifiers(NewReturnType, OldReturnType);
06160     if (ResReturnType.isNull())
06161       return QualType();
06162     if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
06163       // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
06164       // In either case, use OldReturnType to build the new function type.
06165       const FunctionType *F = LHS->getAs<FunctionType>();
06166       if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
06167         FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
06168         EPI.ExtInfo = getFunctionExtInfo(LHS);
06169         QualType ResultType
06170           = getFunctionType(OldReturnType, FPT->arg_type_begin(),
06171                             FPT->getNumArgs(), EPI);
06172         return ResultType;
06173       }
06174     }
06175     return QualType();
06176   }
06177   
06178   // If the qualifiers are different, the types can still be merged.
06179   Qualifiers LQuals = LHSCan.getLocalQualifiers();
06180   Qualifiers RQuals = RHSCan.getLocalQualifiers();
06181   if (LQuals != RQuals) {
06182     // If any of these qualifiers are different, we have a type mismatch.
06183     if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
06184         LQuals.getAddressSpace() != RQuals.getAddressSpace())
06185       return QualType();
06186     
06187     // Exactly one GC qualifier difference is allowed: __strong is
06188     // okay if the other type has no GC qualifier but is an Objective
06189     // C object pointer (i.e. implicitly strong by default).  We fix
06190     // this by pretending that the unqualified type was actually
06191     // qualified __strong.
06192     Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
06193     Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
06194     assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
06195     
06196     if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
06197       return QualType();
06198     
06199     if (GC_L == Qualifiers::Strong)
06200       return LHS;
06201     if (GC_R == Qualifiers::Strong)
06202       return RHS;
06203     return QualType();
06204   }
06205   
06206   if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
06207     QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
06208     QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
06209     QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
06210     if (ResQT == LHSBaseQT)
06211       return LHS;
06212     if (ResQT == RHSBaseQT)
06213       return RHS;
06214   }
06215   return QualType();
06216 }
06217 
06218 //===----------------------------------------------------------------------===//
06219 //                         Integer Predicates
06220 //===----------------------------------------------------------------------===//
06221 
06222 unsigned ASTContext::getIntWidth(QualType T) const {
06223   if (const EnumType *ET = dyn_cast<EnumType>(T))
06224     T = ET->getDecl()->getIntegerType();
06225   if (T->isBooleanType())
06226     return 1;
06227   // For builtin types, just use the standard type sizing method
06228   return (unsigned)getTypeSize(T);
06229 }
06230 
06231 QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
06232   assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
06233   
06234   // Turn <4 x signed int> -> <4 x unsigned int>
06235   if (const VectorType *VTy = T->getAs<VectorType>())
06236     return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
06237                          VTy->getNumElements(), VTy->getVectorKind());
06238 
06239   // For enums, we return the unsigned version of the base type.
06240   if (const EnumType *ETy = T->getAs<EnumType>())
06241     T = ETy->getDecl()->getIntegerType();
06242   
06243   const BuiltinType *BTy = T->getAs<BuiltinType>();
06244   assert(BTy && "Unexpected signed integer type");
06245   switch (BTy->getKind()) {
06246   case BuiltinType::Char_S:
06247   case BuiltinType::SChar:
06248     return UnsignedCharTy;
06249   case BuiltinType::Short:
06250     return UnsignedShortTy;
06251   case BuiltinType::Int:
06252     return UnsignedIntTy;
06253   case BuiltinType::Long:
06254     return UnsignedLongTy;
06255   case BuiltinType::LongLong:
06256     return UnsignedLongLongTy;
06257   case BuiltinType::Int128:
06258     return UnsignedInt128Ty;
06259   default:
06260     llvm_unreachable("Unexpected signed integer type");
06261   }
06262 }
06263 
06264 ASTMutationListener::~ASTMutationListener() { }
06265 
06266 
06267 //===----------------------------------------------------------------------===//
06268 //                          Builtin Type Computation
06269 //===----------------------------------------------------------------------===//
06270 
06271 /// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
06272 /// pointer over the consumed characters.  This returns the resultant type.  If
06273 /// AllowTypeModifiers is false then modifier like * are not parsed, just basic
06274 /// types.  This allows "v2i*" to be parsed as a pointer to a v2i instead of
06275 /// a vector of "i*".
06276 ///
06277 /// RequiresICE is filled in on return to indicate whether the value is required
06278 /// to be an Integer Constant Expression.
06279 static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
06280                                   ASTContext::GetBuiltinTypeError &Error,
06281                                   bool &RequiresICE,
06282                                   bool AllowTypeModifiers) {
06283   // Modifiers.
06284   int HowLong = 0;
06285   bool Signed = false, Unsigned = false;
06286   RequiresICE = false;
06287   
06288   // Read the prefixed modifiers first.
06289   bool Done = false;
06290   while (!Done) {
06291     switch (*Str++) {
06292     default: Done = true; --Str; break;
06293     case 'I':
06294       RequiresICE = true;
06295       break;
06296     case 'S':
06297       assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
06298       assert(!Signed && "Can't use 'S' modifier multiple times!");
06299       Signed = true;
06300       break;
06301     case 'U':
06302       assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
06303       assert(!Unsigned && "Can't use 'S' modifier multiple times!");
06304       Unsigned = true;
06305       break;
06306     case 'L':
06307       assert(HowLong <= 2 && "Can't have LLLL modifier");
06308       ++HowLong;
06309       break;
06310     }
06311   }
06312 
06313   QualType Type;
06314 
06315   // Read the base type.
06316   switch (*Str++) {
06317   default: llvm_unreachable("Unknown builtin type letter!");
06318   case 'v':
06319     assert(HowLong == 0 && !Signed && !Unsigned &&
06320            "Bad modifiers used with 'v'!");
06321     Type = Context.VoidTy;
06322     break;
06323   case 'f':
06324     assert(HowLong == 0 && !Signed && !Unsigned &&
06325            "Bad modifiers used with 'f'!");
06326     Type = Context.FloatTy;
06327     break;
06328   case 'd':
06329     assert(HowLong < 2 && !Signed && !Unsigned &&
06330            "Bad modifiers used with 'd'!");
06331     if (HowLong)
06332       Type = Context.LongDoubleTy;
06333     else
06334       Type = Context.DoubleTy;
06335     break;
06336   case 's':
06337     assert(HowLong == 0 && "Bad modifiers used with 's'!");
06338     if (Unsigned)
06339       Type = Context.UnsignedShortTy;
06340     else
06341       Type = Context.ShortTy;
06342     break;
06343   case 'i':
06344     if (HowLong == 3)
06345       Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
06346     else if (HowLong == 2)
06347       Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
06348     else if (HowLong == 1)
06349       Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
06350     else
06351       Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
06352     break;
06353   case 'c':
06354     assert(HowLong == 0 && "Bad modifiers used with 'c'!");
06355     if (Signed)
06356       Type = Context.SignedCharTy;
06357     else if (Unsigned)
06358       Type = Context.UnsignedCharTy;
06359     else
06360       Type = Context.CharTy;
06361     break;
06362   case 'b': // boolean
06363     assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
06364     Type = Context.BoolTy;
06365     break;
06366   case 'z':  // size_t.
06367     assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
06368     Type = Context.getSizeType();
06369     break;
06370   case 'F':
06371     Type = Context.getCFConstantStringType();
06372     break;
06373   case 'G':
06374     Type = Context.getObjCIdType();
06375     break;
06376   case 'H':
06377     Type = Context.getObjCSelType();
06378     break;
06379   case 'a':
06380     Type = Context.getBuiltinVaListType();
06381     assert(!Type.isNull() && "builtin va list type not initialized!");
06382     break;
06383   case 'A':
06384     // This is a "reference" to a va_list; however, what exactly
06385     // this means depends on how va_list is defined. There are two
06386     // different kinds of va_list: ones passed by value, and ones
06387     // passed by reference.  An example of a by-value va_list is
06388     // x86, where va_list is a char*. An example of by-ref va_list
06389     // is x86-64, where va_list is a __va_list_tag[1]. For x86,
06390     // we want this argument to be a char*&; for x86-64, we want
06391     // it to be a __va_list_tag*.
06392     Type = Context.getBuiltinVaListType();
06393     assert(!Type.isNull() && "builtin va list type not initialized!");
06394     if (Type->isArrayType())
06395       Type = Context.getArrayDecayedType(Type);
06396     else
06397       Type = Context.getLValueReferenceType(Type);
06398     break;
06399   case 'V': {
06400     char *End;
06401     unsigned NumElements = strtoul(Str, &End, 10);
06402     assert(End != Str && "Missing vector size");
06403     Str = End;
06404 
06405     QualType ElementType = DecodeTypeFromStr(Str, Context, Error, 
06406                                              RequiresICE, false);
06407     assert(!RequiresICE && "Can't require vector ICE");
06408     
06409     // TODO: No way to make AltiVec vectors in builtins yet.
06410     Type = Context.getVectorType(ElementType, NumElements,
06411                                  VectorType::GenericVector);
06412     break;
06413   }
06414   case 'X': {
06415     QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
06416                                              false);
06417     assert(!RequiresICE && "Can't require complex ICE");
06418     Type = Context.getComplexType(ElementType);
06419     break;
06420   }  
06421   case 'Y' : {
06422     Type = Context.getPointerDiffType();
06423     break;
06424   }
06425   case 'P':
06426     Type = Context.getFILEType();
06427     if (Type.isNull()) {
06428       Error = ASTContext::GE_Missing_stdio;
06429       return QualType();
06430     }
06431     break;
06432   case 'J':
06433     if (Signed)
06434       Type = Context.getsigjmp_bufType();
06435     else
06436       Type = Context.getjmp_bufType();
06437 
06438     if (Type.isNull()) {
06439       Error = ASTContext::GE_Missing_setjmp;
06440       return QualType();
06441     }
06442     break;
06443   case 'K':
06444     assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
06445     Type = Context.getucontext_tType();
06446 
06447     if (Type.isNull()) {
06448       Error = ASTContext::GE_Missing_ucontext;
06449       return QualType();
06450     }
06451     break;
06452   }
06453 
06454   // If there are modifiers and if we're allowed to parse them, go for it.
06455   Done = !AllowTypeModifiers;
06456   while (!Done) {
06457     switch (char c = *Str++) {
06458     default: Done = true; --Str; break;
06459     case '*':
06460     case '&': {
06461       // Both pointers and references can have their pointee types
06462       // qualified with an address space.
06463       char *End;
06464       unsigned AddrSpace = strtoul(Str, &End, 10);
06465       if (End != Str && AddrSpace != 0) {
06466         Type = Context.getAddrSpaceQualType(Type, AddrSpace);
06467         Str = End;
06468       }
06469       if (c == '*')
06470         Type = Context.getPointerType(Type);
06471       else
06472         Type = Context.getLValueReferenceType(Type);
06473       break;
06474     }
06475     // FIXME: There's no way to have a built-in with an rvalue ref arg.
06476     case 'C':
06477       Type = Type.withConst();
06478       break;
06479     case 'D':
06480       Type = Context.getVolatileType(Type);
06481       break;
06482     case 'R':
06483       Type = Type.withRestrict();
06484       break;
06485     }
06486   }
06487   
06488   assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
06489          "Integer constant 'I' type must be an integer"); 
06490 
06491   return Type;
06492 }
06493 
06494 /// GetBuiltinType - Return the type for the specified builtin.
06495 QualType ASTContext::GetBuiltinType(unsigned Id,
06496                                     GetBuiltinTypeError &Error,
06497                                     unsigned *IntegerConstantArgs) const {
06498   const char *TypeStr = BuiltinInfo.GetTypeString(Id);
06499 
06500   SmallVector<QualType, 8> ArgTypes;
06501 
06502   bool RequiresICE = false;
06503   Error = GE_None;
06504   QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
06505                                        RequiresICE, true);
06506   if (Error != GE_None)
06507     return QualType();
06508   
06509   assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
06510   
06511   while (TypeStr[0] && TypeStr[0] != '.') {
06512     QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
06513     if (Error != GE_None)
06514       return QualType();
06515 
06516     // If this argument is required to be an IntegerConstantExpression and the
06517     // caller cares, fill in the bitmask we return.
06518     if (RequiresICE && IntegerConstantArgs)
06519       *IntegerConstantArgs |= 1 << ArgTypes.size();
06520     
06521     // Do array -> pointer decay.  The builtin should use the decayed type.
06522     if (Ty->isArrayType())
06523       Ty = getArrayDecayedType(Ty);
06524 
06525     ArgTypes.push_back(Ty);
06526   }
06527 
06528   assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
06529          "'.' should only occur at end of builtin type list!");
06530 
06531   FunctionType::ExtInfo EI;
06532   if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
06533 
06534   bool Variadic = (TypeStr[0] == '.');
06535 
06536   // We really shouldn't be making a no-proto type here, especially in C++.
06537   if (ArgTypes.empty() && Variadic)
06538     return getFunctionNoProtoType(ResType, EI);
06539 
06540   FunctionProtoType::ExtProtoInfo EPI;
06541   EPI.ExtInfo = EI;
06542   EPI.Variadic = Variadic;
06543 
06544   return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
06545 }
06546 
06547 GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
06548   GVALinkage External = GVA_StrongExternal;
06549 
06550   Linkage L = FD->getLinkage();
06551   switch (L) {
06552   case NoLinkage:
06553   case InternalLinkage:
06554   case UniqueExternalLinkage:
06555     return GVA_Internal;
06556     
06557   case ExternalLinkage:
06558     switch (FD->getTemplateSpecializationKind()) {
06559     case TSK_Undeclared:
06560     case TSK_ExplicitSpecialization:
06561       External = GVA_StrongExternal;
06562       break;
06563 
06564     case TSK_ExplicitInstantiationDefinition:
06565       return GVA_ExplicitTemplateInstantiation;
06566 
06567     case TSK_ExplicitInstantiationDeclaration:
06568     case TSK_ImplicitInstantiation:
06569       External = GVA_TemplateInstantiation;
06570       break;
06571     }
06572   }
06573 
06574   if (!FD->isInlined())
06575     return External;
06576     
06577   if (!getLangOpts().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
06578     // GNU or C99 inline semantics. Determine whether this symbol should be
06579     // externally visible.
06580     if (FD->isInlineDefinitionExternallyVisible())
06581       return External;
06582 
06583     // C99 inline semantics, where the symbol is not externally visible.
06584     return GVA_C99Inline;
06585   }
06586 
06587   // C++0x [temp.explicit]p9:
06588   //   [ Note: The intent is that an inline function that is the subject of 
06589   //   an explicit instantiation declaration will still be implicitly 
06590   //   instantiated when used so that the body can be considered for 
06591   //   inlining, but that no out-of-line copy of the inline function would be
06592   //   generated in the translation unit. -- end note ]
06593   if (FD->getTemplateSpecializationKind() 
06594                                        == TSK_ExplicitInstantiationDeclaration)
06595     return GVA_C99Inline;
06596 
06597   return GVA_CXXInline;
06598 }
06599 
06600 GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
06601   // If this is a static data member, compute the kind of template
06602   // specialization. Otherwise, this variable is not part of a
06603   // template.
06604   TemplateSpecializationKind TSK = TSK_Undeclared;
06605   if (VD->isStaticDataMember())
06606     TSK = VD->getTemplateSpecializationKind();
06607 
06608   Linkage L = VD->getLinkage();
06609   if (L == ExternalLinkage && getLangOpts().CPlusPlus &&
06610       VD->getType()->getLinkage() == UniqueExternalLinkage)
06611     L = UniqueExternalLinkage;
06612 
06613   switch (L) {
06614   case NoLinkage:
06615   case InternalLinkage:
06616   case UniqueExternalLinkage:
06617     return GVA_Internal;
06618 
06619   case ExternalLinkage:
06620     switch (TSK) {
06621     case TSK_Undeclared:
06622     case TSK_ExplicitSpecialization:
06623       return GVA_StrongExternal;
06624 
06625     case TSK_ExplicitInstantiationDeclaration:
06626       llvm_unreachable("Variable should not be instantiated");
06627       // Fall through to treat this like any other instantiation.
06628         
06629     case TSK_ExplicitInstantiationDefinition:
06630       return GVA_ExplicitTemplateInstantiation;
06631 
06632     case TSK_ImplicitInstantiation:
06633       return GVA_TemplateInstantiation;      
06634     }
06635   }
06636 
06637   llvm_unreachable("Invalid Linkage!");
06638 }
06639 
06640 bool ASTContext::DeclMustBeEmitted(const Decl *D) {
06641   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
06642     if (!VD->isFileVarDecl())
06643       return false;
06644   } else if (!isa<FunctionDecl>(D))
06645     return false;
06646 
06647   // Weak references don't produce any output by themselves.
06648   if (D->hasAttr<WeakRefAttr>())
06649     return false;
06650 
06651   // Aliases and used decls are required.
06652   if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
06653     return true;
06654 
06655   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
06656     // Forward declarations aren't required.
06657     if (!FD->doesThisDeclarationHaveABody())
06658       return FD->doesDeclarationForceExternallyVisibleDefinition();
06659 
06660     // Constructors and destructors are required.
06661     if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
06662       return true;
06663     
06664     // The key function for a class is required.
06665     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
06666       const CXXRecordDecl *RD = MD->getParent();
06667       if (MD->isOutOfLine() && RD->isDynamicClass()) {
06668         const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
06669         if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
06670           return true;
06671       }
06672     }
06673 
06674     GVALinkage Linkage = GetGVALinkageForFunction(FD);
06675 
06676     // static, static inline, always_inline, and extern inline functions can
06677     // always be deferred.  Normal inline functions can be deferred in C99/C++.
06678     // Implicit template instantiations can also be deferred in C++.
06679     if (Linkage == GVA_Internal  || Linkage == GVA_C99Inline ||
06680         Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
06681       return false;
06682     return true;
06683   }
06684   
06685   const VarDecl *VD = cast<VarDecl>(D);
06686   assert(VD->isFileVarDecl() && "Expected file scoped var");
06687 
06688   if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
06689     return false;
06690 
06691   // Structs that have non-trivial constructors or destructors are required.
06692 
06693   // FIXME: Handle references.
06694   // FIXME: Be more selective about which constructors we care about.
06695   if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
06696     if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
06697       if (RD->hasDefinition() && !(RD->hasTrivialDefaultConstructor() &&
06698                                    RD->hasTrivialCopyConstructor() &&
06699                                    RD->hasTrivialMoveConstructor() &&
06700                                    RD->hasTrivialDestructor()))
06701         return true;
06702     }
06703   }
06704 
06705   GVALinkage L = GetGVALinkageForVariable(VD);
06706   if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
06707     if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
06708       return false;
06709   }
06710 
06711   return true;
06712 }
06713 
06714 CallingConv ASTContext::getDefaultMethodCallConv() {
06715   // Pass through to the C++ ABI object
06716   return ABI->getDefaultMethodCallConv();
06717 }
06718 
06719 bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
06720   // Pass through to the C++ ABI object
06721   return ABI->isNearlyEmpty(RD);
06722 }
06723 
06724 MangleContext *ASTContext::createMangleContext() {
06725   switch (Target->getCXXABI()) {
06726   case CXXABI_ARM:
06727   case CXXABI_Itanium:
06728     return createItaniumMangleContext(*this, getDiagnostics());
06729   case CXXABI_Microsoft:
06730     return createMicrosoftMangleContext(*this, getDiagnostics());
06731   }
06732   llvm_unreachable("Unsupported ABI");
06733 }
06734 
06735 CXXABI::~CXXABI() {}
06736 
06737 size_t ASTContext::getSideTableAllocatedMemory() const {
06738   return ASTRecordLayouts.getMemorySize()
06739     + llvm::capacity_in_bytes(ObjCLayouts)
06740     + llvm::capacity_in_bytes(KeyFunctions)
06741     + llvm::capacity_in_bytes(ObjCImpls)
06742     + llvm::capacity_in_bytes(BlockVarCopyInits)
06743     + llvm::capacity_in_bytes(DeclAttrs)
06744     + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
06745     + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
06746     + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
06747     + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
06748     + llvm::capacity_in_bytes(OverriddenMethods)
06749     + llvm::capacity_in_bytes(Types)
06750     + llvm::capacity_in_bytes(VariableArrayTypes)
06751     + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
06752 }
06753 
06754 unsigned ASTContext::getLambdaManglingNumber(CXXMethodDecl *CallOperator) {
06755   CXXRecordDecl *Lambda = CallOperator->getParent();
06756   return LambdaMangleContexts[Lambda->getDeclContext()]
06757            .getManglingNumber(CallOperator);
06758 }
06759 
06760 
06761 void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
06762   ParamIndices[D] = index;
06763 }
06764 
06765 unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
06766   ParameterIndexTable::const_iterator I = ParamIndices.find(D);
06767   assert(I != ParamIndices.end() && 
06768          "ParmIndices lacks entry set by ParmVarDecl");
06769   return I->second;
06770 }