1 //===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements the ASTContext interface.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/CharUnits.h"
16 #include "clang/AST/DeclCXX.h"
17 #include "clang/AST/DeclObjC.h"
18 #include "clang/AST/DeclTemplate.h"
19 #include "clang/AST/TypeLoc.h"
20 #include "clang/AST/Expr.h"
21 #include "clang/AST/ExprCXX.h"
22 #include "clang/AST/ExternalASTSource.h"
23 #include "clang/AST/ASTMutationListener.h"
24 #include "clang/AST/RecordLayout.h"
25 #include "clang/AST/Mangle.h"
26 #include "clang/Basic/Builtins.h"
27 #include "clang/Basic/SourceManager.h"
28 #include "clang/Basic/TargetInfo.h"
29 #include "llvm/ADT/SmallString.h"
30 #include "llvm/ADT/StringExtras.h"
31 #include "llvm/Support/MathExtras.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/Support/Capacity.h"
34 #include "CXXABI.h"
35 #include <map>
36 
37 using namespace clang;
38 
39 unsigned ASTContext::NumImplicitDefaultConstructors;
40 unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
41 unsigned ASTContext::NumImplicitCopyConstructors;
42 unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
43 unsigned ASTContext::NumImplicitMoveConstructors;
44 unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
45 unsigned ASTContext::NumImplicitCopyAssignmentOperators;
46 unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
47 unsigned ASTContext::NumImplicitMoveAssignmentOperators;
48 unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
49 unsigned ASTContext::NumImplicitDestructors;
50 unsigned ASTContext::NumImplicitDestructorsDeclared;
51 
52 enum FloatingRank {
53   HalfRank, FloatRank, DoubleRank, LongDoubleRank
54 };
55 
56 void
57 ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
58                                                TemplateTemplateParmDecl *Parm) {
59   ID.AddInteger(Parm->getDepth());
60   ID.AddInteger(Parm->getPosition());
61   ID.AddBoolean(Parm->isParameterPack());
62 
63   TemplateParameterList *Params = Parm->getTemplateParameters();
64   ID.AddInteger(Params->size());
65   for (TemplateParameterList::const_iterator P = Params->begin(),
66                                           PEnd = Params->end();
67        P != PEnd; ++P) {
68     if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
69       ID.AddInteger(0);
70       ID.AddBoolean(TTP->isParameterPack());
71       continue;
72     }
73 
74     if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
75       ID.AddInteger(1);
76       ID.AddBoolean(NTTP->isParameterPack());
77       ID.AddPointer(NTTP->getType().getAsOpaquePtr());
78       if (NTTP->isExpandedParameterPack()) {
79         ID.AddBoolean(true);
80         ID.AddInteger(NTTP->getNumExpansionTypes());
81         for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I)
82           ID.AddPointer(NTTP->getExpansionType(I).getAsOpaquePtr());
83       } else
84         ID.AddBoolean(false);
85       continue;
86     }
87 
88     TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
89     ID.AddInteger(2);
90     Profile(ID, TTP);
91   }
92 }
93 
94 TemplateTemplateParmDecl *
95 ASTContext::getCanonicalTemplateTemplateParmDecl(
96                                           TemplateTemplateParmDecl *TTP) const {
97   // Check if we already have a canonical template template parameter.
98   llvm::FoldingSetNodeID ID;
99   CanonicalTemplateTemplateParm::Profile(ID, TTP);
100   void *InsertPos = 0;
101   CanonicalTemplateTemplateParm *Canonical
102     = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
103   if (Canonical)
104     return Canonical->getParam();
105 
106   // Build a canonical template parameter list.
107   TemplateParameterList *Params = TTP->getTemplateParameters();
108   SmallVector<NamedDecl *, 4> CanonParams;
109   CanonParams.reserve(Params->size());
110   for (TemplateParameterList::const_iterator P = Params->begin(),
111                                           PEnd = Params->end();
112        P != PEnd; ++P) {
113     if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
114       CanonParams.push_back(
115                   TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
116                                                SourceLocation(),
117                                                SourceLocation(),
118                                                TTP->getDepth(),
119                                                TTP->getIndex(), 0, false,
120                                                TTP->isParameterPack()));
121     else if (NonTypeTemplateParmDecl *NTTP
122              = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
123       QualType T = getCanonicalType(NTTP->getType());
124       TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
125       NonTypeTemplateParmDecl *Param;
126       if (NTTP->isExpandedParameterPack()) {
127         SmallVector<QualType, 2> ExpandedTypes;
128         SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
129         for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
130           ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
131           ExpandedTInfos.push_back(
132                                 getTrivialTypeSourceInfo(ExpandedTypes.back()));
133         }
134 
135         Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
136                                                 SourceLocation(),
137                                                 SourceLocation(),
138                                                 NTTP->getDepth(),
139                                                 NTTP->getPosition(), 0,
140                                                 T,
141                                                 TInfo,
142                                                 ExpandedTypes.data(),
143                                                 ExpandedTypes.size(),
144                                                 ExpandedTInfos.data());
145       } else {
146         Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
147                                                 SourceLocation(),
148                                                 SourceLocation(),
149                                                 NTTP->getDepth(),
150                                                 NTTP->getPosition(), 0,
151                                                 T,
152                                                 NTTP->isParameterPack(),
153                                                 TInfo);
154       }
155       CanonParams.push_back(Param);
156 
157     } else
158       CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
159                                            cast<TemplateTemplateParmDecl>(*P)));
160   }
161 
162   TemplateTemplateParmDecl *CanonTTP
163     = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
164                                        SourceLocation(), TTP->getDepth(),
165                                        TTP->getPosition(),
166                                        TTP->isParameterPack(),
167                                        0,
168                          TemplateParameterList::Create(*this, SourceLocation(),
169                                                        SourceLocation(),
170                                                        CanonParams.data(),
171                                                        CanonParams.size(),
172                                                        SourceLocation()));
173 
174   // Get the new insert position for the node we care about.
175   Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
176   assert(Canonical == 0 && "Shouldn't be in the map!");
177   (void)Canonical;
178 
179   // Create the canonical template template parameter entry.
180   Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
181   CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
182   return CanonTTP;
183 }
184 
185 CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
186   if (!LangOpts.CPlusPlus) return 0;
187 
188   switch (T.getCXXABI()) {
189   case CXXABI_ARM:
190     return CreateARMCXXABI(*this);
191   case CXXABI_Itanium:
192     return CreateItaniumCXXABI(*this);
193   case CXXABI_Microsoft:
194     return CreateMicrosoftCXXABI(*this);
195   }
196   llvm_unreachable("Invalid CXXABI type!");
197 }
198 
199 static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
200                                              const LangOptions &LOpts) {
201   if (LOpts.FakeAddressSpaceMap) {
202     // The fake address space map must have a distinct entry for each
203     // language-specific address space.
204     static const unsigned FakeAddrSpaceMap[] = {
205       1, // opencl_global
206       2, // opencl_local
207       3  // opencl_constant
208     };
209     return &FakeAddrSpaceMap;
210   } else {
211     return &T.getAddressSpaceMap();
212   }
213 }
214 
215 ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
216                        const TargetInfo *t,
217                        IdentifierTable &idents, SelectorTable &sels,
218                        Builtin::Context &builtins,
219                        unsigned size_reserve,
220                        bool DelayInitialization)
221   : FunctionProtoTypes(this_()),
222     TemplateSpecializationTypes(this_()),
223     DependentTemplateSpecializationTypes(this_()),
224     SubstTemplateTemplateParmPacks(this_()),
225     GlobalNestedNameSpecifier(0),
226     Int128Decl(0), UInt128Decl(0),
227     ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
228     CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
229     FILEDecl(0),
230     jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
231     BlockDescriptorType(0), BlockDescriptorExtendedType(0),
232     cudaConfigureCallDecl(0),
233     NullTypeSourceInfo(QualType()),
234     FirstLocalImport(), LastLocalImport(),
235     SourceMgr(SM), LangOpts(LOpts),
236     AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
237     Idents(idents), Selectors(sels),
238     BuiltinInfo(builtins),
239     DeclarationNames(*this),
240     ExternalSource(0), Listener(0),
241     LastSDM(0, 0),
242     UniqueBlockByRefTypeID(0)
243 {
244   if (size_reserve > 0) Types.reserve(size_reserve);
245   TUDecl = TranslationUnitDecl::Create(*this);
246 
247   if (!DelayInitialization) {
248     assert(t && "No target supplied for ASTContext initialization");
249     InitBuiltinTypes(*t);
250   }
251 }
252 
253 ASTContext::~ASTContext() {
254   // Release the DenseMaps associated with DeclContext objects.
255   // FIXME: Is this the ideal solution?
256   ReleaseDeclContextMaps();
257 
258   // Call all of the deallocation functions.
259   for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
260     Deallocations[I].first(Deallocations[I].second);
261 
262   // Release all of the memory associated with overridden C++ methods.
263   for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator
264          OM = OverriddenMethods.begin(), OMEnd = OverriddenMethods.end();
265        OM != OMEnd; ++OM)
266     OM->second.Destroy();
267 
268   // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
269   // because they can contain DenseMaps.
270   for (llvm::DenseMap<const ObjCContainerDecl*,
271        const ASTRecordLayout*>::iterator
272        I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
273     // Increment in loop to prevent using deallocated memory.
274     if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
275       R->Destroy(*this);
276 
277   for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
278        I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
279     // Increment in loop to prevent using deallocated memory.
280     if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
281       R->Destroy(*this);
282   }
283 
284   for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
285                                                     AEnd = DeclAttrs.end();
286        A != AEnd; ++A)
287     A->second->~AttrVec();
288 }
289 
290 void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
291   Deallocations.push_back(std::make_pair(Callback, Data));
292 }
293 
294 void
295 ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
296   ExternalSource.reset(Source.take());
297 }
298 
299 void ASTContext::PrintStats() const {
300   llvm::errs() << "\n*** AST Context Stats:\n";
301   llvm::errs() << "  " << Types.size() << " types total.\n";
302 
303   unsigned counts[] = {
304 #define TYPE(Name, Parent) 0,
305 #define ABSTRACT_TYPE(Name, Parent)
306 #include "clang/AST/TypeNodes.def"
307     0 // Extra
308   };
309 
310   for (unsigned i = 0, e = Types.size(); i != e; ++i) {
311     Type *T = Types[i];
312     counts[(unsigned)T->getTypeClass()]++;
313   }
314 
315   unsigned Idx = 0;
316   unsigned TotalBytes = 0;
317 #define TYPE(Name, Parent)                                              \
318   if (counts[Idx])                                                      \
319     llvm::errs() << "    " << counts[Idx] << " " << #Name               \
320                  << " types\n";                                         \
321   TotalBytes += counts[Idx] * sizeof(Name##Type);                       \
322   ++Idx;
323 #define ABSTRACT_TYPE(Name, Parent)
324 #include "clang/AST/TypeNodes.def"
325 
326   llvm::errs() << "Total bytes = " << TotalBytes << "\n";
327 
328   // Implicit special member functions.
329   llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
330                << NumImplicitDefaultConstructors
331                << " implicit default constructors created\n";
332   llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
333                << NumImplicitCopyConstructors
334                << " implicit copy constructors created\n";
335   if (getLangOptions().CPlusPlus)
336     llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
337                  << NumImplicitMoveConstructors
338                  << " implicit move constructors created\n";
339   llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
340                << NumImplicitCopyAssignmentOperators
341                << " implicit copy assignment operators created\n";
342   if (getLangOptions().CPlusPlus)
343     llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
344                  << NumImplicitMoveAssignmentOperators
345                  << " implicit move assignment operators created\n";
346   llvm::errs() << NumImplicitDestructorsDeclared << "/"
347                << NumImplicitDestructors
348                << " implicit destructors created\n";
349 
350   if (ExternalSource.get()) {
351     llvm::errs() << "\n";
352     ExternalSource->PrintStats();
353   }
354 
355   BumpAlloc.PrintStats();
356 }
357 
358 TypedefDecl *ASTContext::getInt128Decl() const {
359   if (!Int128Decl) {
360     TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
361     Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
362                                      getTranslationUnitDecl(),
363                                      SourceLocation(),
364                                      SourceLocation(),
365                                      &Idents.get("__int128_t"),
366                                      TInfo);
367   }
368 
369   return Int128Decl;
370 }
371 
372 TypedefDecl *ASTContext::getUInt128Decl() const {
373   if (!UInt128Decl) {
374     TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
375     UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
376                                      getTranslationUnitDecl(),
377                                      SourceLocation(),
378                                      SourceLocation(),
379                                      &Idents.get("__uint128_t"),
380                                      TInfo);
381   }
382 
383   return UInt128Decl;
384 }
385 
386 void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
387   BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
388   R = CanQualType::CreateUnsafe(QualType(Ty, 0));
389   Types.push_back(Ty);
390 }
391 
392 void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
393   assert((!this->Target || this->Target == &Target) &&
394          "Incorrect target reinitialization");
395   assert(VoidTy.isNull() && "Context reinitialized?");
396 
397   this->Target = &Target;
398 
399   ABI.reset(createCXXABI(Target));
400   AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
401 
402   // C99 6.2.5p19.
403   InitBuiltinType(VoidTy,              BuiltinType::Void);
404 
405   // C99 6.2.5p2.
406   InitBuiltinType(BoolTy,              BuiltinType::Bool);
407   // C99 6.2.5p3.
408   if (LangOpts.CharIsSigned)
409     InitBuiltinType(CharTy,            BuiltinType::Char_S);
410   else
411     InitBuiltinType(CharTy,            BuiltinType::Char_U);
412   // C99 6.2.5p4.
413   InitBuiltinType(SignedCharTy,        BuiltinType::SChar);
414   InitBuiltinType(ShortTy,             BuiltinType::Short);
415   InitBuiltinType(IntTy,               BuiltinType::Int);
416   InitBuiltinType(LongTy,              BuiltinType::Long);
417   InitBuiltinType(LongLongTy,          BuiltinType::LongLong);
418 
419   // C99 6.2.5p6.
420   InitBuiltinType(UnsignedCharTy,      BuiltinType::UChar);
421   InitBuiltinType(UnsignedShortTy,     BuiltinType::UShort);
422   InitBuiltinType(UnsignedIntTy,       BuiltinType::UInt);
423   InitBuiltinType(UnsignedLongTy,      BuiltinType::ULong);
424   InitBuiltinType(UnsignedLongLongTy,  BuiltinType::ULongLong);
425 
426   // C99 6.2.5p10.
427   InitBuiltinType(FloatTy,             BuiltinType::Float);
428   InitBuiltinType(DoubleTy,            BuiltinType::Double);
429   InitBuiltinType(LongDoubleTy,        BuiltinType::LongDouble);
430 
431   // GNU extension, 128-bit integers.
432   InitBuiltinType(Int128Ty,            BuiltinType::Int128);
433   InitBuiltinType(UnsignedInt128Ty,    BuiltinType::UInt128);
434 
435   if (LangOpts.CPlusPlus) { // C++ 3.9.1p5
436     if (TargetInfo::isTypeSigned(Target.getWCharType()))
437       InitBuiltinType(WCharTy,           BuiltinType::WChar_S);
438     else  // -fshort-wchar makes wchar_t be unsigned.
439       InitBuiltinType(WCharTy,           BuiltinType::WChar_U);
440   } else // C99
441     WCharTy = getFromTargetType(Target.getWCharType());
442 
443   if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
444     InitBuiltinType(Char16Ty,           BuiltinType::Char16);
445   else // C99
446     Char16Ty = getFromTargetType(Target.getChar16Type());
447 
448   if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
449     InitBuiltinType(Char32Ty,           BuiltinType::Char32);
450   else // C99
451     Char32Ty = getFromTargetType(Target.getChar32Type());
452 
453   // Placeholder type for type-dependent expressions whose type is
454   // completely unknown. No code should ever check a type against
455   // DependentTy and users should never see it; however, it is here to
456   // help diagnose failures to properly check for type-dependent
457   // expressions.
458   InitBuiltinType(DependentTy,         BuiltinType::Dependent);
459 
460   // Placeholder type for functions.
461   InitBuiltinType(OverloadTy,          BuiltinType::Overload);
462 
463   // Placeholder type for bound members.
464   InitBuiltinType(BoundMemberTy,       BuiltinType::BoundMember);
465 
466   // Placeholder type for pseudo-objects.
467   InitBuiltinType(PseudoObjectTy,      BuiltinType::PseudoObject);
468 
469   // "any" type; useful for debugger-like clients.
470   InitBuiltinType(UnknownAnyTy,        BuiltinType::UnknownAny);
471 
472   // Placeholder type for unbridged ARC casts.
473   InitBuiltinType(ARCUnbridgedCastTy,  BuiltinType::ARCUnbridgedCast);
474 
475   // C99 6.2.5p11.
476   FloatComplexTy      = getComplexType(FloatTy);
477   DoubleComplexTy     = getComplexType(DoubleTy);
478   LongDoubleComplexTy = getComplexType(LongDoubleTy);
479 
480   BuiltinVaListType = QualType();
481 
482   // Builtin types for 'id', 'Class', and 'SEL'.
483   InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
484   InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
485   InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
486 
487   ObjCConstantStringType = QualType();
488 
489   // void * type
490   VoidPtrTy = getPointerType(VoidTy);
491 
492   // nullptr type (C++0x 2.14.7)
493   InitBuiltinType(NullPtrTy,           BuiltinType::NullPtr);
494 
495   // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
496   InitBuiltinType(HalfTy, BuiltinType::Half);
497 }
498 
499 DiagnosticsEngine &ASTContext::getDiagnostics() const {
500   return SourceMgr.getDiagnostics();
501 }
502 
503 AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
504   AttrVec *&Result = DeclAttrs[D];
505   if (!Result) {
506     void *Mem = Allocate(sizeof(AttrVec));
507     Result = new (Mem) AttrVec;
508   }
509 
510   return *Result;
511 }
512 
513 /// \brief Erase the attributes corresponding to the given declaration.
514 void ASTContext::eraseDeclAttrs(const Decl *D) {
515   llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
516   if (Pos != DeclAttrs.end()) {
517     Pos->second->~AttrVec();
518     DeclAttrs.erase(Pos);
519   }
520 }
521 
522 MemberSpecializationInfo *
523 ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
524   assert(Var->isStaticDataMember() && "Not a static data member");
525   llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
526     = InstantiatedFromStaticDataMember.find(Var);
527   if (Pos == InstantiatedFromStaticDataMember.end())
528     return 0;
529 
530   return Pos->second;
531 }
532 
533 void
534 ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
535                                                 TemplateSpecializationKind TSK,
536                                           SourceLocation PointOfInstantiation) {
537   assert(Inst->isStaticDataMember() && "Not a static data member");
538   assert(Tmpl->isStaticDataMember() && "Not a static data member");
539   assert(!InstantiatedFromStaticDataMember[Inst] &&
540          "Already noted what static data member was instantiated from");
541   InstantiatedFromStaticDataMember[Inst]
542     = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
543 }
544 
545 FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
546                                                      const FunctionDecl *FD){
547   assert(FD && "Specialization is 0");
548   llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
549     = ClassScopeSpecializationPattern.find(FD);
550   if (Pos == ClassScopeSpecializationPattern.end())
551     return 0;
552 
553   return Pos->second;
554 }
555 
556 void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
557                                         FunctionDecl *Pattern) {
558   assert(FD && "Specialization is 0");
559   assert(Pattern && "Class scope specialization pattern is 0");
560   ClassScopeSpecializationPattern[FD] = Pattern;
561 }
562 
563 NamedDecl *
564 ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
565   llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
566     = InstantiatedFromUsingDecl.find(UUD);
567   if (Pos == InstantiatedFromUsingDecl.end())
568     return 0;
569 
570   return Pos->second;
571 }
572 
573 void
574 ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
575   assert((isa<UsingDecl>(Pattern) ||
576           isa<UnresolvedUsingValueDecl>(Pattern) ||
577           isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
578          "pattern decl is not a using decl");
579   assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
580   InstantiatedFromUsingDecl[Inst] = Pattern;
581 }
582 
583 UsingShadowDecl *
584 ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
585   llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
586     = InstantiatedFromUsingShadowDecl.find(Inst);
587   if (Pos == InstantiatedFromUsingShadowDecl.end())
588     return 0;
589 
590   return Pos->second;
591 }
592 
593 void
594 ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
595                                                UsingShadowDecl *Pattern) {
596   assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
597   InstantiatedFromUsingShadowDecl[Inst] = Pattern;
598 }
599 
600 FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
601   llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
602     = InstantiatedFromUnnamedFieldDecl.find(Field);
603   if (Pos == InstantiatedFromUnnamedFieldDecl.end())
604     return 0;
605 
606   return Pos->second;
607 }
608 
609 void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
610                                                      FieldDecl *Tmpl) {
611   assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
612   assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
613   assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
614          "Already noted what unnamed field was instantiated from");
615 
616   InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
617 }
618 
619 bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
620                                     const FieldDecl *LastFD) const {
621   return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
622           FD->getBitWidthValue(*this) == 0);
623 }
624 
625 bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
626                                              const FieldDecl *LastFD) const {
627   return (FD->isBitField() && LastFD && LastFD->isBitField() &&
628           FD->getBitWidthValue(*this) == 0 &&
629           LastFD->getBitWidthValue(*this) != 0);
630 }
631 
632 bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
633                                          const FieldDecl *LastFD) const {
634   return (FD->isBitField() && LastFD && LastFD->isBitField() &&
635           FD->getBitWidthValue(*this) &&
636           LastFD->getBitWidthValue(*this));
637 }
638 
639 bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
640                                          const FieldDecl *LastFD) const {
641   return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
642           LastFD->getBitWidthValue(*this));
643 }
644 
645 bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
646                                              const FieldDecl *LastFD) const {
647   return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
648           FD->getBitWidthValue(*this));
649 }
650 
651 ASTContext::overridden_cxx_method_iterator
652 ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
653   llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
654     = OverriddenMethods.find(Method);
655   if (Pos == OverriddenMethods.end())
656     return 0;
657 
658   return Pos->second.begin();
659 }
660 
661 ASTContext::overridden_cxx_method_iterator
662 ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
663   llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
664     = OverriddenMethods.find(Method);
665   if (Pos == OverriddenMethods.end())
666     return 0;
667 
668   return Pos->second.end();
669 }
670 
671 unsigned
672 ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
673   llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
674     = OverriddenMethods.find(Method);
675   if (Pos == OverriddenMethods.end())
676     return 0;
677 
678   return Pos->second.size();
679 }
680 
681 void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
682                                      const CXXMethodDecl *Overridden) {
683   OverriddenMethods[Method].push_back(Overridden);
684 }
685 
686 void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
687   assert(!Import->NextLocalImport && "Import declaration already in the chain");
688   assert(!Import->isFromASTFile() && "Non-local import declaration");
689   if (!FirstLocalImport) {
690     FirstLocalImport = Import;
691     LastLocalImport = Import;
692     return;
693   }
694 
695   LastLocalImport->NextLocalImport = Import;
696   LastLocalImport = Import;
697 }
698 
699 //===----------------------------------------------------------------------===//
700 //                         Type Sizing and Analysis
701 //===----------------------------------------------------------------------===//
702 
703 /// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
704 /// scalar floating point type.
705 const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
706   const BuiltinType *BT = T->getAs<BuiltinType>();
707   assert(BT && "Not a floating point type!");
708   switch (BT->getKind()) {
709   default: llvm_unreachable("Not a floating point type!");
710   case BuiltinType::Half:       return Target->getHalfFormat();
711   case BuiltinType::Float:      return Target->getFloatFormat();
712   case BuiltinType::Double:     return Target->getDoubleFormat();
713   case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
714   }
715 }
716 
717 /// getDeclAlign - Return a conservative estimate of the alignment of the
718 /// specified decl.  Note that bitfields do not have a valid alignment, so
719 /// this method will assert on them.
720 /// If @p RefAsPointee, references are treated like their underlying type
721 /// (for alignof), else they're treated like pointers (for CodeGen).
722 CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
723   unsigned Align = Target->getCharWidth();
724 
725   bool UseAlignAttrOnly = false;
726   if (unsigned AlignFromAttr = D->getMaxAlignment()) {
727     Align = AlignFromAttr;
728 
729     // __attribute__((aligned)) can increase or decrease alignment
730     // *except* on a struct or struct member, where it only increases
731     // alignment unless 'packed' is also specified.
732     //
733     // It is an error for alignas to decrease alignment, so we can
734     // ignore that possibility;  Sema should diagnose it.
735     if (isa<FieldDecl>(D)) {
736       UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
737         cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
738     } else {
739       UseAlignAttrOnly = true;
740     }
741   }
742   else if (isa<FieldDecl>(D))
743       UseAlignAttrOnly =
744         D->hasAttr<PackedAttr>() ||
745         cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
746 
747   // If we're using the align attribute only, just ignore everything
748   // else about the declaration and its type.
749   if (UseAlignAttrOnly) {
750     // do nothing
751 
752   } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
753     QualType T = VD->getType();
754     if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
755       if (RefAsPointee)
756         T = RT->getPointeeType();
757       else
758         T = getPointerType(RT->getPointeeType());
759     }
760     if (!T->isIncompleteType() && !T->isFunctionType()) {
761       // Adjust alignments of declarations with array type by the
762       // large-array alignment on the target.
763       unsigned MinWidth = Target->getLargeArrayMinWidth();
764       const ArrayType *arrayType;
765       if (MinWidth && (arrayType = getAsArrayType(T))) {
766         if (isa<VariableArrayType>(arrayType))
767           Align = std::max(Align, Target->getLargeArrayAlign());
768         else if (isa<ConstantArrayType>(arrayType) &&
769                  MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
770           Align = std::max(Align, Target->getLargeArrayAlign());
771 
772         // Walk through any array types while we're at it.
773         T = getBaseElementType(arrayType);
774       }
775       Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
776     }
777 
778     // Fields can be subject to extra alignment constraints, like if
779     // the field is packed, the struct is packed, or the struct has a
780     // a max-field-alignment constraint (#pragma pack).  So calculate
781     // the actual alignment of the field within the struct, and then
782     // (as we're expected to) constrain that by the alignment of the type.
783     if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
784       // So calculate the alignment of the field.
785       const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
786 
787       // Start with the record's overall alignment.
788       unsigned fieldAlign = toBits(layout.getAlignment());
789 
790       // Use the GCD of that and the offset within the record.
791       uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
792       if (offset > 0) {
793         // Alignment is always a power of 2, so the GCD will be a power of 2,
794         // which means we get to do this crazy thing instead of Euclid's.
795         uint64_t lowBitOfOffset = offset & (~offset + 1);
796         if (lowBitOfOffset < fieldAlign)
797           fieldAlign = static_cast<unsigned>(lowBitOfOffset);
798       }
799 
800       Align = std::min(Align, fieldAlign);
801     }
802   }
803 
804   return toCharUnitsFromBits(Align);
805 }
806 
807 std::pair<CharUnits, CharUnits>
808 ASTContext::getTypeInfoInChars(const Type *T) const {
809   std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
810   return std::make_pair(toCharUnitsFromBits(Info.first),
811                         toCharUnitsFromBits(Info.second));
812 }
813 
814 std::pair<CharUnits, CharUnits>
815 ASTContext::getTypeInfoInChars(QualType T) const {
816   return getTypeInfoInChars(T.getTypePtr());
817 }
818 
819 /// getTypeSize - Return the size of the specified type, in bits.  This method
820 /// does not work on incomplete types.
821 ///
822 /// FIXME: Pointers into different addr spaces could have different sizes and
823 /// alignment requirements: getPointerInfo should take an AddrSpace, this
824 /// should take a QualType, &c.
825 std::pair<uint64_t, unsigned>
826 ASTContext::getTypeInfo(const Type *T) const {
827   uint64_t Width=0;
828   unsigned Align=8;
829   switch (T->getTypeClass()) {
830 #define TYPE(Class, Base)
831 #define ABSTRACT_TYPE(Class, Base)
832 #define NON_CANONICAL_TYPE(Class, Base)
833 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
834 #include "clang/AST/TypeNodes.def"
835     llvm_unreachable("Should not see dependent types");
836 
837   case Type::FunctionNoProto:
838   case Type::FunctionProto:
839     // GCC extension: alignof(function) = 32 bits
840     Width = 0;
841     Align = 32;
842     break;
843 
844   case Type::IncompleteArray:
845   case Type::VariableArray:
846     Width = 0;
847     Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
848     break;
849 
850   case Type::ConstantArray: {
851     const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
852 
853     std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
854     uint64_t Size = CAT->getSize().getZExtValue();
855     assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) && "Overflow in array type bit size evaluation");
856     Width = EltInfo.first*Size;
857     Align = EltInfo.second;
858     Width = llvm::RoundUpToAlignment(Width, Align);
859     break;
860   }
861   case Type::ExtVector:
862   case Type::Vector: {
863     const VectorType *VT = cast<VectorType>(T);
864     std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
865     Width = EltInfo.first*VT->getNumElements();
866     Align = Width;
867     // If the alignment is not a power of 2, round up to the next power of 2.
868     // This happens for non-power-of-2 length vectors.
869     if (Align & (Align-1)) {
870       Align = llvm::NextPowerOf2(Align);
871       Width = llvm::RoundUpToAlignment(Width, Align);
872     }
873     break;
874   }
875 
876   case Type::Builtin:
877     switch (cast<BuiltinType>(T)->getKind()) {
878     default: llvm_unreachable("Unknown builtin type!");
879     case BuiltinType::Void:
880       // GCC extension: alignof(void) = 8 bits.
881       Width = 0;
882       Align = 8;
883       break;
884 
885     case BuiltinType::Bool:
886       Width = Target->getBoolWidth();
887       Align = Target->getBoolAlign();
888       break;
889     case BuiltinType::Char_S:
890     case BuiltinType::Char_U:
891     case BuiltinType::UChar:
892     case BuiltinType::SChar:
893       Width = Target->getCharWidth();
894       Align = Target->getCharAlign();
895       break;
896     case BuiltinType::WChar_S:
897     case BuiltinType::WChar_U:
898       Width = Target->getWCharWidth();
899       Align = Target->getWCharAlign();
900       break;
901     case BuiltinType::Char16:
902       Width = Target->getChar16Width();
903       Align = Target->getChar16Align();
904       break;
905     case BuiltinType::Char32:
906       Width = Target->getChar32Width();
907       Align = Target->getChar32Align();
908       break;
909     case BuiltinType::UShort:
910     case BuiltinType::Short:
911       Width = Target->getShortWidth();
912       Align = Target->getShortAlign();
913       break;
914     case BuiltinType::UInt:
915     case BuiltinType::Int:
916       Width = Target->getIntWidth();
917       Align = Target->getIntAlign();
918       break;
919     case BuiltinType::ULong:
920     case BuiltinType::Long:
921       Width = Target->getLongWidth();
922       Align = Target->getLongAlign();
923       break;
924     case BuiltinType::ULongLong:
925     case BuiltinType::LongLong:
926       Width = Target->getLongLongWidth();
927       Align = Target->getLongLongAlign();
928       break;
929     case BuiltinType::Int128:
930     case BuiltinType::UInt128:
931       Width = 128;
932       Align = 128; // int128_t is 128-bit aligned on all targets.
933       break;
934     case BuiltinType::Half:
935       Width = Target->getHalfWidth();
936       Align = Target->getHalfAlign();
937       break;
938     case BuiltinType::Float:
939       Width = Target->getFloatWidth();
940       Align = Target->getFloatAlign();
941       break;
942     case BuiltinType::Double:
943       Width = Target->getDoubleWidth();
944       Align = Target->getDoubleAlign();
945       break;
946     case BuiltinType::LongDouble:
947       Width = Target->getLongDoubleWidth();
948       Align = Target->getLongDoubleAlign();
949       break;
950     case BuiltinType::NullPtr:
951       Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
952       Align = Target->getPointerAlign(0); //   == sizeof(void*)
953       break;
954     case BuiltinType::ObjCId:
955     case BuiltinType::ObjCClass:
956     case BuiltinType::ObjCSel:
957       Width = Target->getPointerWidth(0);
958       Align = Target->getPointerAlign(0);
959       break;
960     }
961     break;
962   case Type::ObjCObjectPointer:
963     Width = Target->getPointerWidth(0);
964     Align = Target->getPointerAlign(0);
965     break;
966   case Type::BlockPointer: {
967     unsigned AS = getTargetAddressSpace(
968         cast<BlockPointerType>(T)->getPointeeType());
969     Width = Target->getPointerWidth(AS);
970     Align = Target->getPointerAlign(AS);
971     break;
972   }
973   case Type::LValueReference:
974   case Type::RValueReference: {
975     // alignof and sizeof should never enter this code path here, so we go
976     // the pointer route.
977     unsigned AS = getTargetAddressSpace(
978         cast<ReferenceType>(T)->getPointeeType());
979     Width = Target->getPointerWidth(AS);
980     Align = Target->getPointerAlign(AS);
981     break;
982   }
983   case Type::Pointer: {
984     unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
985     Width = Target->getPointerWidth(AS);
986     Align = Target->getPointerAlign(AS);
987     break;
988   }
989   case Type::MemberPointer: {
990     const MemberPointerType *MPT = cast<MemberPointerType>(T);
991     std::pair<uint64_t, unsigned> PtrDiffInfo =
992       getTypeInfo(getPointerDiffType());
993     Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
994     Align = PtrDiffInfo.second;
995     break;
996   }
997   case Type::Complex: {
998     // Complex types have the same alignment as their elements, but twice the
999     // size.
1000     std::pair<uint64_t, unsigned> EltInfo =
1001       getTypeInfo(cast<ComplexType>(T)->getElementType());
1002     Width = EltInfo.first*2;
1003     Align = EltInfo.second;
1004     break;
1005   }
1006   case Type::ObjCObject:
1007     return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
1008   case Type::ObjCInterface: {
1009     const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
1010     const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
1011     Width = toBits(Layout.getSize());
1012     Align = toBits(Layout.getAlignment());
1013     break;
1014   }
1015   case Type::Record:
1016   case Type::Enum: {
1017     const TagType *TT = cast<TagType>(T);
1018 
1019     if (TT->getDecl()->isInvalidDecl()) {
1020       Width = 8;
1021       Align = 8;
1022       break;
1023     }
1024 
1025     if (const EnumType *ET = dyn_cast<EnumType>(TT))
1026       return getTypeInfo(ET->getDecl()->getIntegerType());
1027 
1028     const RecordType *RT = cast<RecordType>(TT);
1029     const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
1030     Width = toBits(Layout.getSize());
1031     Align = toBits(Layout.getAlignment());
1032     break;
1033   }
1034 
1035   case Type::SubstTemplateTypeParm:
1036     return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1037                        getReplacementType().getTypePtr());
1038 
1039   case Type::Auto: {
1040     const AutoType *A = cast<AutoType>(T);
1041     assert(A->isDeduced() && "Cannot request the size of a dependent type");
1042     return getTypeInfo(A->getDeducedType().getTypePtr());
1043   }
1044 
1045   case Type::Paren:
1046     return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1047 
1048   case Type::Typedef: {
1049     const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
1050     std::pair<uint64_t, unsigned> Info
1051       = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
1052     // If the typedef has an aligned attribute on it, it overrides any computed
1053     // alignment we have.  This violates the GCC documentation (which says that
1054     // attribute(aligned) can only round up) but matches its implementation.
1055     if (unsigned AttrAlign = Typedef->getMaxAlignment())
1056       Align = AttrAlign;
1057     else
1058       Align = Info.second;
1059     Width = Info.first;
1060     break;
1061   }
1062 
1063   case Type::TypeOfExpr:
1064     return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1065                          .getTypePtr());
1066 
1067   case Type::TypeOf:
1068     return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1069 
1070   case Type::Decltype:
1071     return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1072                         .getTypePtr());
1073 
1074   case Type::UnaryTransform:
1075     return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1076 
1077   case Type::Elaborated:
1078     return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
1079 
1080   case Type::Attributed:
1081     return getTypeInfo(
1082                   cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1083 
1084   case Type::TemplateSpecialization: {
1085     assert(getCanonicalType(T) != T &&
1086            "Cannot request the size of a dependent type");
1087     const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1088     // A type alias template specialization may refer to a typedef with the
1089     // aligned attribute on it.
1090     if (TST->isTypeAlias())
1091       return getTypeInfo(TST->getAliasedType().getTypePtr());
1092     else
1093       return getTypeInfo(getCanonicalType(T));
1094   }
1095 
1096   case Type::Atomic: {
1097     std::pair<uint64_t, unsigned> Info
1098       = getTypeInfo(cast<AtomicType>(T)->getValueType());
1099     Width = Info.first;
1100     Align = Info.second;
1101     if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth() &&
1102         llvm::isPowerOf2_64(Width)) {
1103       // We can potentially perform lock-free atomic operations for this
1104       // type; promote the alignment appropriately.
1105       // FIXME: We could potentially promote the width here as well...
1106       // is that worthwhile?  (Non-struct atomic types generally have
1107       // power-of-two size anyway, but structs might not.  Requires a bit
1108       // of implementation work to make sure we zero out the extra bits.)
1109       Align = static_cast<unsigned>(Width);
1110     }
1111   }
1112 
1113   }
1114 
1115   assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
1116   return std::make_pair(Width, Align);
1117 }
1118 
1119 /// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1120 CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1121   return CharUnits::fromQuantity(BitSize / getCharWidth());
1122 }
1123 
1124 /// toBits - Convert a size in characters to a size in characters.
1125 int64_t ASTContext::toBits(CharUnits CharSize) const {
1126   return CharSize.getQuantity() * getCharWidth();
1127 }
1128 
1129 /// getTypeSizeInChars - Return the size of the specified type, in characters.
1130 /// This method does not work on incomplete types.
1131 CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
1132   return toCharUnitsFromBits(getTypeSize(T));
1133 }
1134 CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
1135   return toCharUnitsFromBits(getTypeSize(T));
1136 }
1137 
1138 /// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
1139 /// characters. This method does not work on incomplete types.
1140 CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
1141   return toCharUnitsFromBits(getTypeAlign(T));
1142 }
1143 CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
1144   return toCharUnitsFromBits(getTypeAlign(T));
1145 }
1146 
1147 /// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1148 /// type for the current target in bits.  This can be different than the ABI
1149 /// alignment in cases where it is beneficial for performance to overalign
1150 /// a data type.
1151 unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
1152   unsigned ABIAlign = getTypeAlign(T);
1153 
1154   // Double and long long should be naturally aligned if possible.
1155   if (const ComplexType* CT = T->getAs<ComplexType>())
1156     T = CT->getElementType().getTypePtr();
1157   if (T->isSpecificBuiltinType(BuiltinType::Double) ||
1158       T->isSpecificBuiltinType(BuiltinType::LongLong))
1159     return std::max(ABIAlign, (unsigned)getTypeSize(T));
1160 
1161   return ABIAlign;
1162 }
1163 
1164 /// DeepCollectObjCIvars -
1165 /// This routine first collects all declared, but not synthesized, ivars in
1166 /// super class and then collects all ivars, including those synthesized for
1167 /// current class. This routine is used for implementation of current class
1168 /// when all ivars, declared and synthesized are known.
1169 ///
1170 void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1171                                       bool leafClass,
1172                             SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
1173   if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1174     DeepCollectObjCIvars(SuperClass, false, Ivars);
1175   if (!leafClass) {
1176     for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1177          E = OI->ivar_end(); I != E; ++I)
1178       Ivars.push_back(*I);
1179   } else {
1180     ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
1181     for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
1182          Iv= Iv->getNextIvar())
1183       Ivars.push_back(Iv);
1184   }
1185 }
1186 
1187 /// CollectInheritedProtocols - Collect all protocols in current class and
1188 /// those inherited by it.
1189 void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
1190                           llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
1191   if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
1192     // We can use protocol_iterator here instead of
1193     // all_referenced_protocol_iterator since we are walking all categories.
1194     for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1195          PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
1196       ObjCProtocolDecl *Proto = (*P);
1197       Protocols.insert(Proto->getCanonicalDecl());
1198       for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1199            PE = Proto->protocol_end(); P != PE; ++P) {
1200         Protocols.insert((*P)->getCanonicalDecl());
1201         CollectInheritedProtocols(*P, Protocols);
1202       }
1203     }
1204 
1205     // Categories of this Interface.
1206     for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1207          CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1208       CollectInheritedProtocols(CDeclChain, Protocols);
1209     if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1210       while (SD) {
1211         CollectInheritedProtocols(SD, Protocols);
1212         SD = SD->getSuperClass();
1213       }
1214   } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
1215     for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
1216          PE = OC->protocol_end(); P != PE; ++P) {
1217       ObjCProtocolDecl *Proto = (*P);
1218       Protocols.insert(Proto->getCanonicalDecl());
1219       for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1220            PE = Proto->protocol_end(); P != PE; ++P)
1221         CollectInheritedProtocols(*P, Protocols);
1222     }
1223   } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
1224     for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1225          PE = OP->protocol_end(); P != PE; ++P) {
1226       ObjCProtocolDecl *Proto = (*P);
1227       Protocols.insert(Proto->getCanonicalDecl());
1228       for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1229            PE = Proto->protocol_end(); P != PE; ++P)
1230         CollectInheritedProtocols(*P, Protocols);
1231     }
1232   }
1233 }
1234 
1235 unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
1236   unsigned count = 0;
1237   // Count ivars declared in class extension.
1238   for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1239        CDecl = CDecl->getNextClassExtension())
1240     count += CDecl->ivar_size();
1241 
1242   // Count ivar defined in this class's implementation.  This
1243   // includes synthesized ivars.
1244   if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
1245     count += ImplDecl->ivar_size();
1246 
1247   return count;
1248 }
1249 
1250 /// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1251 ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1252   llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1253     I = ObjCImpls.find(D);
1254   if (I != ObjCImpls.end())
1255     return cast<ObjCImplementationDecl>(I->second);
1256   return 0;
1257 }
1258 /// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1259 ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1260   llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1261     I = ObjCImpls.find(D);
1262   if (I != ObjCImpls.end())
1263     return cast<ObjCCategoryImplDecl>(I->second);
1264   return 0;
1265 }
1266 
1267 /// \brief Set the implementation of ObjCInterfaceDecl.
1268 void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1269                            ObjCImplementationDecl *ImplD) {
1270   assert(IFaceD && ImplD && "Passed null params");
1271   ObjCImpls[IFaceD] = ImplD;
1272 }
1273 /// \brief Set the implementation of ObjCCategoryDecl.
1274 void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1275                            ObjCCategoryImplDecl *ImplD) {
1276   assert(CatD && ImplD && "Passed null params");
1277   ObjCImpls[CatD] = ImplD;
1278 }
1279 
1280 ObjCInterfaceDecl *ASTContext::getObjContainingInterface(NamedDecl *ND) const {
1281   if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
1282     return ID;
1283   if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
1284     return CD->getClassInterface();
1285   if (ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
1286     return IMD->getClassInterface();
1287 
1288   return 0;
1289 }
1290 
1291 /// \brief Get the copy initialization expression of VarDecl,or NULL if
1292 /// none exists.
1293 Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
1294   assert(VD && "Passed null params");
1295   assert(VD->hasAttr<BlocksAttr>() &&
1296          "getBlockVarCopyInits - not __block var");
1297   llvm::DenseMap<const VarDecl*, Expr*>::iterator
1298     I = BlockVarCopyInits.find(VD);
1299   return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1300 }
1301 
1302 /// \brief Set the copy inialization expression of a block var decl.
1303 void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1304   assert(VD && Init && "Passed null params");
1305   assert(VD->hasAttr<BlocksAttr>() &&
1306          "setBlockVarCopyInits - not __block var");
1307   BlockVarCopyInits[VD] = Init;
1308 }
1309 
1310 /// \brief Allocate an uninitialized TypeSourceInfo.
1311 ///
1312 /// The caller should initialize the memory held by TypeSourceInfo using
1313 /// the TypeLoc wrappers.
1314 ///
1315 /// \param T the type that will be the basis for type source info. This type
1316 /// should refer to how the declarator was written in source code, not to
1317 /// what type semantic analysis resolved the declarator to.
1318 TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
1319                                                  unsigned DataSize) const {
1320   if (!DataSize)
1321     DataSize = TypeLoc::getFullDataSizeForType(T);
1322   else
1323     assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
1324            "incorrect data size provided to CreateTypeSourceInfo!");
1325 
1326   TypeSourceInfo *TInfo =
1327     (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1328   new (TInfo) TypeSourceInfo(T);
1329   return TInfo;
1330 }
1331 
1332 TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
1333                                                      SourceLocation L) const {
1334   TypeSourceInfo *DI = CreateTypeSourceInfo(T);
1335   DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
1336   return DI;
1337 }
1338 
1339 const ASTRecordLayout &
1340 ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
1341   return getObjCLayout(D, 0);
1342 }
1343 
1344 const ASTRecordLayout &
1345 ASTContext::getASTObjCImplementationLayout(
1346                                         const ObjCImplementationDecl *D) const {
1347   return getObjCLayout(D->getClassInterface(), D);
1348 }
1349 
1350 //===----------------------------------------------------------------------===//
1351 //                   Type creation/memoization methods
1352 //===----------------------------------------------------------------------===//
1353 
1354 QualType
1355 ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1356   unsigned fastQuals = quals.getFastQualifiers();
1357   quals.removeFastQualifiers();
1358 
1359   // Check if we've already instantiated this type.
1360   llvm::FoldingSetNodeID ID;
1361   ExtQuals::Profile(ID, baseType, quals);
1362   void *insertPos = 0;
1363   if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1364     assert(eq->getQualifiers() == quals);
1365     return QualType(eq, fastQuals);
1366   }
1367 
1368   // If the base type is not canonical, make the appropriate canonical type.
1369   QualType canon;
1370   if (!baseType->isCanonicalUnqualified()) {
1371     SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
1372     canonSplit.second.addConsistentQualifiers(quals);
1373     canon = getExtQualType(canonSplit.first, canonSplit.second);
1374 
1375     // Re-find the insert position.
1376     (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1377   }
1378 
1379   ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1380   ExtQualNodes.InsertNode(eq, insertPos);
1381   return QualType(eq, fastQuals);
1382 }
1383 
1384 QualType
1385 ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
1386   QualType CanT = getCanonicalType(T);
1387   if (CanT.getAddressSpace() == AddressSpace)
1388     return T;
1389 
1390   // If we are composing extended qualifiers together, merge together
1391   // into one ExtQuals node.
1392   QualifierCollector Quals;
1393   const Type *TypeNode = Quals.strip(T);
1394 
1395   // If this type already has an address space specified, it cannot get
1396   // another one.
1397   assert(!Quals.hasAddressSpace() &&
1398          "Type cannot be in multiple addr spaces!");
1399   Quals.addAddressSpace(AddressSpace);
1400 
1401   return getExtQualType(TypeNode, Quals);
1402 }
1403 
1404 QualType ASTContext::getObjCGCQualType(QualType T,
1405                                        Qualifiers::GC GCAttr) const {
1406   QualType CanT = getCanonicalType(T);
1407   if (CanT.getObjCGCAttr() == GCAttr)
1408     return T;
1409 
1410   if (const PointerType *ptr = T->getAs<PointerType>()) {
1411     QualType Pointee = ptr->getPointeeType();
1412     if (Pointee->isAnyPointerType()) {
1413       QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1414       return getPointerType(ResultType);
1415     }
1416   }
1417 
1418   // If we are composing extended qualifiers together, merge together
1419   // into one ExtQuals node.
1420   QualifierCollector Quals;
1421   const Type *TypeNode = Quals.strip(T);
1422 
1423   // If this type already has an ObjCGC specified, it cannot get
1424   // another one.
1425   assert(!Quals.hasObjCGCAttr() &&
1426          "Type cannot have multiple ObjCGCs!");
1427   Quals.addObjCGCAttr(GCAttr);
1428 
1429   return getExtQualType(TypeNode, Quals);
1430 }
1431 
1432 const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1433                                                    FunctionType::ExtInfo Info) {
1434   if (T->getExtInfo() == Info)
1435     return T;
1436 
1437   QualType Result;
1438   if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1439     Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1440   } else {
1441     const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1442     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1443     EPI.ExtInfo = Info;
1444     Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1445                              FPT->getNumArgs(), EPI);
1446   }
1447 
1448   return cast<FunctionType>(Result.getTypePtr());
1449 }
1450 
1451 /// getComplexType - Return the uniqued reference to the type for a complex
1452 /// number with the specified element type.
1453 QualType ASTContext::getComplexType(QualType T) const {
1454   // Unique pointers, to guarantee there is only one pointer of a particular
1455   // structure.
1456   llvm::FoldingSetNodeID ID;
1457   ComplexType::Profile(ID, T);
1458 
1459   void *InsertPos = 0;
1460   if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1461     return QualType(CT, 0);
1462 
1463   // If the pointee type isn't canonical, this won't be a canonical type either,
1464   // so fill in the canonical type field.
1465   QualType Canonical;
1466   if (!T.isCanonical()) {
1467     Canonical = getComplexType(getCanonicalType(T));
1468 
1469     // Get the new insert position for the node we care about.
1470     ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
1471     assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
1472   }
1473   ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
1474   Types.push_back(New);
1475   ComplexTypes.InsertNode(New, InsertPos);
1476   return QualType(New, 0);
1477 }
1478 
1479 /// getPointerType - Return the uniqued reference to the type for a pointer to
1480 /// the specified type.
1481 QualType ASTContext::getPointerType(QualType T) const {
1482   // Unique pointers, to guarantee there is only one pointer of a particular
1483   // structure.
1484   llvm::FoldingSetNodeID ID;
1485   PointerType::Profile(ID, T);
1486 
1487   void *InsertPos = 0;
1488   if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1489     return QualType(PT, 0);
1490 
1491   // If the pointee type isn't canonical, this won't be a canonical type either,
1492   // so fill in the canonical type field.
1493   QualType Canonical;
1494   if (!T.isCanonical()) {
1495     Canonical = getPointerType(getCanonicalType(T));
1496 
1497     // Get the new insert position for the node we care about.
1498     PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1499     assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
1500   }
1501   PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
1502   Types.push_back(New);
1503   PointerTypes.InsertNode(New, InsertPos);
1504   return QualType(New, 0);
1505 }
1506 
1507 /// getBlockPointerType - Return the uniqued reference to the type for
1508 /// a pointer to the specified block.
1509 QualType ASTContext::getBlockPointerType(QualType T) const {
1510   assert(T->isFunctionType() && "block of function types only");
1511   // Unique pointers, to guarantee there is only one block of a particular
1512   // structure.
1513   llvm::FoldingSetNodeID ID;
1514   BlockPointerType::Profile(ID, T);
1515 
1516   void *InsertPos = 0;
1517   if (BlockPointerType *PT =
1518         BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1519     return QualType(PT, 0);
1520 
1521   // If the block pointee type isn't canonical, this won't be a canonical
1522   // type either so fill in the canonical type field.
1523   QualType Canonical;
1524   if (!T.isCanonical()) {
1525     Canonical = getBlockPointerType(getCanonicalType(T));
1526 
1527     // Get the new insert position for the node we care about.
1528     BlockPointerType *NewIP =
1529       BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1530     assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
1531   }
1532   BlockPointerType *New
1533     = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
1534   Types.push_back(New);
1535   BlockPointerTypes.InsertNode(New, InsertPos);
1536   return QualType(New, 0);
1537 }
1538 
1539 /// getLValueReferenceType - Return the uniqued reference to the type for an
1540 /// lvalue reference to the specified type.
1541 QualType
1542 ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
1543   assert(getCanonicalType(T) != OverloadTy &&
1544          "Unresolved overloaded function type");
1545 
1546   // Unique pointers, to guarantee there is only one pointer of a particular
1547   // structure.
1548   llvm::FoldingSetNodeID ID;
1549   ReferenceType::Profile(ID, T, SpelledAsLValue);
1550 
1551   void *InsertPos = 0;
1552   if (LValueReferenceType *RT =
1553         LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1554     return QualType(RT, 0);
1555 
1556   const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1557 
1558   // If the referencee type isn't canonical, this won't be a canonical type
1559   // either, so fill in the canonical type field.
1560   QualType Canonical;
1561   if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1562     QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1563     Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
1564 
1565     // Get the new insert position for the node we care about.
1566     LValueReferenceType *NewIP =
1567       LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1568     assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
1569   }
1570 
1571   LValueReferenceType *New
1572     = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1573                                                      SpelledAsLValue);
1574   Types.push_back(New);
1575   LValueReferenceTypes.InsertNode(New, InsertPos);
1576 
1577   return QualType(New, 0);
1578 }
1579 
1580 /// getRValueReferenceType - Return the uniqued reference to the type for an
1581 /// rvalue reference to the specified type.
1582 QualType ASTContext::getRValueReferenceType(QualType T) const {
1583   // Unique pointers, to guarantee there is only one pointer of a particular
1584   // structure.
1585   llvm::FoldingSetNodeID ID;
1586   ReferenceType::Profile(ID, T, false);
1587 
1588   void *InsertPos = 0;
1589   if (RValueReferenceType *RT =
1590         RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1591     return QualType(RT, 0);
1592 
1593   const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1594 
1595   // If the referencee type isn't canonical, this won't be a canonical type
1596   // either, so fill in the canonical type field.
1597   QualType Canonical;
1598   if (InnerRef || !T.isCanonical()) {
1599     QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1600     Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
1601 
1602     // Get the new insert position for the node we care about.
1603     RValueReferenceType *NewIP =
1604       RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1605     assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
1606   }
1607 
1608   RValueReferenceType *New
1609     = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
1610   Types.push_back(New);
1611   RValueReferenceTypes.InsertNode(New, InsertPos);
1612   return QualType(New, 0);
1613 }
1614 
1615 /// getMemberPointerType - Return the uniqued reference to the type for a
1616 /// member pointer to the specified type, in the specified class.
1617 QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
1618   // Unique pointers, to guarantee there is only one pointer of a particular
1619   // structure.
1620   llvm::FoldingSetNodeID ID;
1621   MemberPointerType::Profile(ID, T, Cls);
1622 
1623   void *InsertPos = 0;
1624   if (MemberPointerType *PT =
1625       MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1626     return QualType(PT, 0);
1627 
1628   // If the pointee or class type isn't canonical, this won't be a canonical
1629   // type either, so fill in the canonical type field.
1630   QualType Canonical;
1631   if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
1632     Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1633 
1634     // Get the new insert position for the node we care about.
1635     MemberPointerType *NewIP =
1636       MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1637     assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
1638   }
1639   MemberPointerType *New
1640     = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
1641   Types.push_back(New);
1642   MemberPointerTypes.InsertNode(New, InsertPos);
1643   return QualType(New, 0);
1644 }
1645 
1646 /// getConstantArrayType - Return the unique reference to the type for an
1647 /// array of the specified element type.
1648 QualType ASTContext::getConstantArrayType(QualType EltTy,
1649                                           const llvm::APInt &ArySizeIn,
1650                                           ArrayType::ArraySizeModifier ASM,
1651                                           unsigned IndexTypeQuals) const {
1652   assert((EltTy->isDependentType() ||
1653           EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
1654          "Constant array of VLAs is illegal!");
1655 
1656   // Convert the array size into a canonical width matching the pointer size for
1657   // the target.
1658   llvm::APInt ArySize(ArySizeIn);
1659   ArySize =
1660     ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
1661 
1662   llvm::FoldingSetNodeID ID;
1663   ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
1664 
1665   void *InsertPos = 0;
1666   if (ConstantArrayType *ATP =
1667       ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1668     return QualType(ATP, 0);
1669 
1670   // If the element type isn't canonical or has qualifiers, this won't
1671   // be a canonical type either, so fill in the canonical type field.
1672   QualType Canon;
1673   if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1674     SplitQualType canonSplit = getCanonicalType(EltTy).split();
1675     Canon = getConstantArrayType(QualType(canonSplit.first, 0), ArySize,
1676                                  ASM, IndexTypeQuals);
1677     Canon = getQualifiedType(Canon, canonSplit.second);
1678 
1679     // Get the new insert position for the node we care about.
1680     ConstantArrayType *NewIP =
1681       ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1682     assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
1683   }
1684 
1685   ConstantArrayType *New = new(*this,TypeAlignment)
1686     ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
1687   ConstantArrayTypes.InsertNode(New, InsertPos);
1688   Types.push_back(New);
1689   return QualType(New, 0);
1690 }
1691 
1692 /// getVariableArrayDecayedType - Turns the given type, which may be
1693 /// variably-modified, into the corresponding type with all the known
1694 /// sizes replaced with [*].
1695 QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
1696   // Vastly most common case.
1697   if (!type->isVariablyModifiedType()) return type;
1698 
1699   QualType result;
1700 
1701   SplitQualType split = type.getSplitDesugaredType();
1702   const Type *ty = split.first;
1703   switch (ty->getTypeClass()) {
1704 #define TYPE(Class, Base)
1705 #define ABSTRACT_TYPE(Class, Base)
1706 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1707 #include "clang/AST/TypeNodes.def"
1708     llvm_unreachable("didn't desugar past all non-canonical types?");
1709 
1710   // These types should never be variably-modified.
1711   case Type::Builtin:
1712   case Type::Complex:
1713   case Type::Vector:
1714   case Type::ExtVector:
1715   case Type::DependentSizedExtVector:
1716   case Type::ObjCObject:
1717   case Type::ObjCInterface:
1718   case Type::ObjCObjectPointer:
1719   case Type::Record:
1720   case Type::Enum:
1721   case Type::UnresolvedUsing:
1722   case Type::TypeOfExpr:
1723   case Type::TypeOf:
1724   case Type::Decltype:
1725   case Type::UnaryTransform:
1726   case Type::DependentName:
1727   case Type::InjectedClassName:
1728   case Type::TemplateSpecialization:
1729   case Type::DependentTemplateSpecialization:
1730   case Type::TemplateTypeParm:
1731   case Type::SubstTemplateTypeParmPack:
1732   case Type::Auto:
1733   case Type::PackExpansion:
1734     llvm_unreachable("type should never be variably-modified");
1735 
1736   // These types can be variably-modified but should never need to
1737   // further decay.
1738   case Type::FunctionNoProto:
1739   case Type::FunctionProto:
1740   case Type::BlockPointer:
1741   case Type::MemberPointer:
1742     return type;
1743 
1744   // These types can be variably-modified.  All these modifications
1745   // preserve structure except as noted by comments.
1746   // TODO: if we ever care about optimizing VLAs, there are no-op
1747   // optimizations available here.
1748   case Type::Pointer:
1749     result = getPointerType(getVariableArrayDecayedType(
1750                               cast<PointerType>(ty)->getPointeeType()));
1751     break;
1752 
1753   case Type::LValueReference: {
1754     const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
1755     result = getLValueReferenceType(
1756                  getVariableArrayDecayedType(lv->getPointeeType()),
1757                                     lv->isSpelledAsLValue());
1758     break;
1759   }
1760 
1761   case Type::RValueReference: {
1762     const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
1763     result = getRValueReferenceType(
1764                  getVariableArrayDecayedType(lv->getPointeeType()));
1765     break;
1766   }
1767 
1768   case Type::Atomic: {
1769     const AtomicType *at = cast<AtomicType>(ty);
1770     result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
1771     break;
1772   }
1773 
1774   case Type::ConstantArray: {
1775     const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
1776     result = getConstantArrayType(
1777                  getVariableArrayDecayedType(cat->getElementType()),
1778                                   cat->getSize(),
1779                                   cat->getSizeModifier(),
1780                                   cat->getIndexTypeCVRQualifiers());
1781     break;
1782   }
1783 
1784   case Type::DependentSizedArray: {
1785     const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
1786     result = getDependentSizedArrayType(
1787                  getVariableArrayDecayedType(dat->getElementType()),
1788                                         dat->getSizeExpr(),
1789                                         dat->getSizeModifier(),
1790                                         dat->getIndexTypeCVRQualifiers(),
1791                                         dat->getBracketsRange());
1792     break;
1793   }
1794 
1795   // Turn incomplete types into [*] types.
1796   case Type::IncompleteArray: {
1797     const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
1798     result = getVariableArrayType(
1799                  getVariableArrayDecayedType(iat->getElementType()),
1800                                   /*size*/ 0,
1801                                   ArrayType::Normal,
1802                                   iat->getIndexTypeCVRQualifiers(),
1803                                   SourceRange());
1804     break;
1805   }
1806 
1807   // Turn VLA types into [*] types.
1808   case Type::VariableArray: {
1809     const VariableArrayType *vat = cast<VariableArrayType>(ty);
1810     result = getVariableArrayType(
1811                  getVariableArrayDecayedType(vat->getElementType()),
1812                                   /*size*/ 0,
1813                                   ArrayType::Star,
1814                                   vat->getIndexTypeCVRQualifiers(),
1815                                   vat->getBracketsRange());
1816     break;
1817   }
1818   }
1819 
1820   // Apply the top-level qualifiers from the original.
1821   return getQualifiedType(result, split.second);
1822 }
1823 
1824 /// getVariableArrayType - Returns a non-unique reference to the type for a
1825 /// variable array of the specified element type.
1826 QualType ASTContext::getVariableArrayType(QualType EltTy,
1827                                           Expr *NumElts,
1828                                           ArrayType::ArraySizeModifier ASM,
1829                                           unsigned IndexTypeQuals,
1830                                           SourceRange Brackets) const {
1831   // Since we don't unique expressions, it isn't possible to unique VLA's
1832   // that have an expression provided for their size.
1833   QualType Canon;
1834 
1835   // Be sure to pull qualifiers off the element type.
1836   if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1837     SplitQualType canonSplit = getCanonicalType(EltTy).split();
1838     Canon = getVariableArrayType(QualType(canonSplit.first, 0), NumElts, ASM,
1839                                  IndexTypeQuals, Brackets);
1840     Canon = getQualifiedType(Canon, canonSplit.second);
1841   }
1842 
1843   VariableArrayType *New = new(*this, TypeAlignment)
1844     VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
1845 
1846   VariableArrayTypes.push_back(New);
1847   Types.push_back(New);
1848   return QualType(New, 0);
1849 }
1850 
1851 /// getDependentSizedArrayType - Returns a non-unique reference to
1852 /// the type for a dependently-sized array of the specified element
1853 /// type.
1854 QualType ASTContext::getDependentSizedArrayType(QualType elementType,
1855                                                 Expr *numElements,
1856                                                 ArrayType::ArraySizeModifier ASM,
1857                                                 unsigned elementTypeQuals,
1858                                                 SourceRange brackets) const {
1859   assert((!numElements || numElements->isTypeDependent() ||
1860           numElements->isValueDependent()) &&
1861          "Size must be type- or value-dependent!");
1862 
1863   // Dependently-sized array types that do not have a specified number
1864   // of elements will have their sizes deduced from a dependent
1865   // initializer.  We do no canonicalization here at all, which is okay
1866   // because they can't be used in most locations.
1867   if (!numElements) {
1868     DependentSizedArrayType *newType
1869       = new (*this, TypeAlignment)
1870           DependentSizedArrayType(*this, elementType, QualType(),
1871                                   numElements, ASM, elementTypeQuals,
1872                                   brackets);
1873     Types.push_back(newType);
1874     return QualType(newType, 0);
1875   }
1876 
1877   // Otherwise, we actually build a new type every time, but we
1878   // also build a canonical type.
1879 
1880   SplitQualType canonElementType = getCanonicalType(elementType).split();
1881 
1882   void *insertPos = 0;
1883   llvm::FoldingSetNodeID ID;
1884   DependentSizedArrayType::Profile(ID, *this,
1885                                    QualType(canonElementType.first, 0),
1886                                    ASM, elementTypeQuals, numElements);
1887 
1888   // Look for an existing type with these properties.
1889   DependentSizedArrayType *canonTy =
1890     DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
1891 
1892   // If we don't have one, build one.
1893   if (!canonTy) {
1894     canonTy = new (*this, TypeAlignment)
1895       DependentSizedArrayType(*this, QualType(canonElementType.first, 0),
1896                               QualType(), numElements, ASM, elementTypeQuals,
1897                               brackets);
1898     DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
1899     Types.push_back(canonTy);
1900   }
1901 
1902   // Apply qualifiers from the element type to the array.
1903   QualType canon = getQualifiedType(QualType(canonTy,0),
1904                                     canonElementType.second);
1905 
1906   // If we didn't need extra canonicalization for the element type,
1907   // then just use that as our result.
1908   if (QualType(canonElementType.first, 0) == elementType)
1909     return canon;
1910 
1911   // Otherwise, we need to build a type which follows the spelling
1912   // of the element type.
1913   DependentSizedArrayType *sugaredType
1914     = new (*this, TypeAlignment)
1915         DependentSizedArrayType(*this, elementType, canon, numElements,
1916                                 ASM, elementTypeQuals, brackets);
1917   Types.push_back(sugaredType);
1918   return QualType(sugaredType, 0);
1919 }
1920 
1921 QualType ASTContext::getIncompleteArrayType(QualType elementType,
1922                                             ArrayType::ArraySizeModifier ASM,
1923                                             unsigned elementTypeQuals) const {
1924   llvm::FoldingSetNodeID ID;
1925   IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
1926 
1927   void *insertPos = 0;
1928   if (IncompleteArrayType *iat =
1929        IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
1930     return QualType(iat, 0);
1931 
1932   // If the element type isn't canonical, this won't be a canonical type
1933   // either, so fill in the canonical type field.  We also have to pull
1934   // qualifiers off the element type.
1935   QualType canon;
1936 
1937   if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
1938     SplitQualType canonSplit = getCanonicalType(elementType).split();
1939     canon = getIncompleteArrayType(QualType(canonSplit.first, 0),
1940                                    ASM, elementTypeQuals);
1941     canon = getQualifiedType(canon, canonSplit.second);
1942 
1943     // Get the new insert position for the node we care about.
1944     IncompleteArrayType *existing =
1945       IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
1946     assert(!existing && "Shouldn't be in the map!"); (void) existing;
1947   }
1948 
1949   IncompleteArrayType *newType = new (*this, TypeAlignment)
1950     IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
1951 
1952   IncompleteArrayTypes.InsertNode(newType, insertPos);
1953   Types.push_back(newType);
1954   return QualType(newType, 0);
1955 }
1956 
1957 /// getVectorType - Return the unique reference to a vector type of
1958 /// the specified element type and size. VectorType must be a built-in type.
1959 QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
1960                                    VectorType::VectorKind VecKind) const {
1961   assert(vecType->isBuiltinType());
1962 
1963   // Check if we've already instantiated a vector of this type.
1964   llvm::FoldingSetNodeID ID;
1965   VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
1966 
1967   void *InsertPos = 0;
1968   if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1969     return QualType(VTP, 0);
1970 
1971   // If the element type isn't canonical, this won't be a canonical type either,
1972   // so fill in the canonical type field.
1973   QualType Canonical;
1974   if (!vecType.isCanonical()) {
1975     Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
1976 
1977     // Get the new insert position for the node we care about.
1978     VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1979     assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
1980   }
1981   VectorType *New = new (*this, TypeAlignment)
1982     VectorType(vecType, NumElts, Canonical, VecKind);
1983   VectorTypes.InsertNode(New, InsertPos);
1984   Types.push_back(New);
1985   return QualType(New, 0);
1986 }
1987 
1988 /// getExtVectorType - Return the unique reference to an extended vector type of
1989 /// the specified element type and size. VectorType must be a built-in type.
1990 QualType
1991 ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
1992   assert(vecType->isBuiltinType() || vecType->isDependentType());
1993 
1994   // Check if we've already instantiated a vector of this type.
1995   llvm::FoldingSetNodeID ID;
1996   VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
1997                       VectorType::GenericVector);
1998   void *InsertPos = 0;
1999   if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2000     return QualType(VTP, 0);
2001 
2002   // If the element type isn't canonical, this won't be a canonical type either,
2003   // so fill in the canonical type field.
2004   QualType Canonical;
2005   if (!vecType.isCanonical()) {
2006     Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
2007 
2008     // Get the new insert position for the node we care about.
2009     VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2010     assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2011   }
2012   ExtVectorType *New = new (*this, TypeAlignment)
2013     ExtVectorType(vecType, NumElts, Canonical);
2014   VectorTypes.InsertNode(New, InsertPos);
2015   Types.push_back(New);
2016   return QualType(New, 0);
2017 }
2018 
2019 QualType
2020 ASTContext::getDependentSizedExtVectorType(QualType vecType,
2021                                            Expr *SizeExpr,
2022                                            SourceLocation AttrLoc) const {
2023   llvm::FoldingSetNodeID ID;
2024   DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
2025                                        SizeExpr);
2026 
2027   void *InsertPos = 0;
2028   DependentSizedExtVectorType *Canon
2029     = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2030   DependentSizedExtVectorType *New;
2031   if (Canon) {
2032     // We already have a canonical version of this array type; use it as
2033     // the canonical type for a newly-built type.
2034     New = new (*this, TypeAlignment)
2035       DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2036                                   SizeExpr, AttrLoc);
2037   } else {
2038     QualType CanonVecTy = getCanonicalType(vecType);
2039     if (CanonVecTy == vecType) {
2040       New = new (*this, TypeAlignment)
2041         DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2042                                     AttrLoc);
2043 
2044       DependentSizedExtVectorType *CanonCheck
2045         = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2046       assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2047       (void)CanonCheck;
2048       DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2049     } else {
2050       QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2051                                                       SourceLocation());
2052       New = new (*this, TypeAlignment)
2053         DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
2054     }
2055   }
2056 
2057   Types.push_back(New);
2058   return QualType(New, 0);
2059 }
2060 
2061 /// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
2062 ///
2063 QualType
2064 ASTContext::getFunctionNoProtoType(QualType ResultTy,
2065                                    const FunctionType::ExtInfo &Info) const {
2066   const CallingConv DefaultCC = Info.getCC();
2067   const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2068                                CC_X86StdCall : DefaultCC;
2069   // Unique functions, to guarantee there is only one function of a particular
2070   // structure.
2071   llvm::FoldingSetNodeID ID;
2072   FunctionNoProtoType::Profile(ID, ResultTy, Info);
2073 
2074   void *InsertPos = 0;
2075   if (FunctionNoProtoType *FT =
2076         FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
2077     return QualType(FT, 0);
2078 
2079   QualType Canonical;
2080   if (!ResultTy.isCanonical() ||
2081       getCanonicalCallConv(CallConv) != CallConv) {
2082     Canonical =
2083       getFunctionNoProtoType(getCanonicalType(ResultTy),
2084                      Info.withCallingConv(getCanonicalCallConv(CallConv)));
2085 
2086     // Get the new insert position for the node we care about.
2087     FunctionNoProtoType *NewIP =
2088       FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
2089     assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2090   }
2091 
2092   FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
2093   FunctionNoProtoType *New = new (*this, TypeAlignment)
2094     FunctionNoProtoType(ResultTy, Canonical, newInfo);
2095   Types.push_back(New);
2096   FunctionNoProtoTypes.InsertNode(New, InsertPos);
2097   return QualType(New, 0);
2098 }
2099 
2100 /// getFunctionType - Return a normal function type with a typed argument
2101 /// list.  isVariadic indicates whether the argument list includes '...'.
2102 QualType
2103 ASTContext::getFunctionType(QualType ResultTy,
2104                             const QualType *ArgArray, unsigned NumArgs,
2105                             const FunctionProtoType::ExtProtoInfo &EPI) const {
2106   // Unique functions, to guarantee there is only one function of a particular
2107   // structure.
2108   llvm::FoldingSetNodeID ID;
2109   FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
2110 
2111   void *InsertPos = 0;
2112   if (FunctionProtoType *FTP =
2113         FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
2114     return QualType(FTP, 0);
2115 
2116   // Determine whether the type being created is already canonical or not.
2117   bool isCanonical= EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical();
2118   for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
2119     if (!ArgArray[i].isCanonicalAsParam())
2120       isCanonical = false;
2121 
2122   const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2123   const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2124                                CC_X86StdCall : DefaultCC;
2125 
2126   // If this type isn't canonical, get the canonical version of it.
2127   // The exception spec is not part of the canonical type.
2128   QualType Canonical;
2129   if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
2130     SmallVector<QualType, 16> CanonicalArgs;
2131     CanonicalArgs.reserve(NumArgs);
2132     for (unsigned i = 0; i != NumArgs; ++i)
2133       CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
2134 
2135     FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
2136     CanonicalEPI.ExceptionSpecType = EST_None;
2137     CanonicalEPI.NumExceptions = 0;
2138     CanonicalEPI.ExtInfo
2139       = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2140 
2141     Canonical = getFunctionType(getCanonicalType(ResultTy),
2142                                 CanonicalArgs.data(), NumArgs,
2143                                 CanonicalEPI);
2144 
2145     // Get the new insert position for the node we care about.
2146     FunctionProtoType *NewIP =
2147       FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
2148     assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2149   }
2150 
2151   // FunctionProtoType objects are allocated with extra bytes after
2152   // them for three variable size arrays at the end:
2153   //  - parameter types
2154   //  - exception types
2155   //  - consumed-arguments flags
2156   // Instead of the exception types, there could be a noexcept
2157   // expression.
2158   size_t Size = sizeof(FunctionProtoType) +
2159                 NumArgs * sizeof(QualType);
2160   if (EPI.ExceptionSpecType == EST_Dynamic)
2161     Size += EPI.NumExceptions * sizeof(QualType);
2162   else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
2163     Size += sizeof(Expr*);
2164   }
2165   if (EPI.ConsumedArguments)
2166     Size += NumArgs * sizeof(bool);
2167 
2168   FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
2169   FunctionProtoType::ExtProtoInfo newEPI = EPI;
2170   newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
2171   new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
2172   Types.push_back(FTP);
2173   FunctionProtoTypes.InsertNode(FTP, InsertPos);
2174   return QualType(FTP, 0);
2175 }
2176 
2177 #ifndef NDEBUG
2178 static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2179   if (!isa<CXXRecordDecl>(D)) return false;
2180   const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2181   if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2182     return true;
2183   if (RD->getDescribedClassTemplate() &&
2184       !isa<ClassTemplateSpecializationDecl>(RD))
2185     return true;
2186   return false;
2187 }
2188 #endif
2189 
2190 /// getInjectedClassNameType - Return the unique reference to the
2191 /// injected class name type for the specified templated declaration.
2192 QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
2193                                               QualType TST) const {
2194   assert(NeedsInjectedClassNameType(Decl));
2195   if (Decl->TypeForDecl) {
2196     assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2197   } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
2198     assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2199     Decl->TypeForDecl = PrevDecl->TypeForDecl;
2200     assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2201   } else {
2202     Type *newType =
2203       new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
2204     Decl->TypeForDecl = newType;
2205     Types.push_back(newType);
2206   }
2207   return QualType(Decl->TypeForDecl, 0);
2208 }
2209 
2210 /// getTypeDeclType - Return the unique reference to the type for the
2211 /// specified type declaration.
2212 QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
2213   assert(Decl && "Passed null for Decl param");
2214   assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
2215 
2216   if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
2217     return getTypedefType(Typedef);
2218 
2219   assert(!isa<TemplateTypeParmDecl>(Decl) &&
2220          "Template type parameter types are always available.");
2221 
2222   if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
2223     assert(!Record->getPreviousDecl() &&
2224            "struct/union has previous declaration");
2225     assert(!NeedsInjectedClassNameType(Record));
2226     return getRecordType(Record);
2227   } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
2228     assert(!Enum->getPreviousDecl() &&
2229            "enum has previous declaration");
2230     return getEnumType(Enum);
2231   } else if (const UnresolvedUsingTypenameDecl *Using =
2232                dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
2233     Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2234     Decl->TypeForDecl = newType;
2235     Types.push_back(newType);
2236   } else
2237     llvm_unreachable("TypeDecl without a type?");
2238 
2239   return QualType(Decl->TypeForDecl, 0);
2240 }
2241 
2242 /// getTypedefType - Return the unique reference to the type for the
2243 /// specified typedef name decl.
2244 QualType
2245 ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2246                            QualType Canonical) const {
2247   if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2248 
2249   if (Canonical.isNull())
2250     Canonical = getCanonicalType(Decl->getUnderlyingType());
2251   TypedefType *newType = new(*this, TypeAlignment)
2252     TypedefType(Type::Typedef, Decl, Canonical);
2253   Decl->TypeForDecl = newType;
2254   Types.push_back(newType);
2255   return QualType(newType, 0);
2256 }
2257 
2258 QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
2259   if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2260 
2261   if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
2262     if (PrevDecl->TypeForDecl)
2263       return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2264 
2265   RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2266   Decl->TypeForDecl = newType;
2267   Types.push_back(newType);
2268   return QualType(newType, 0);
2269 }
2270 
2271 QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
2272   if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2273 
2274   if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
2275     if (PrevDecl->TypeForDecl)
2276       return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2277 
2278   EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2279   Decl->TypeForDecl = newType;
2280   Types.push_back(newType);
2281   return QualType(newType, 0);
2282 }
2283 
2284 QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2285                                        QualType modifiedType,
2286                                        QualType equivalentType) {
2287   llvm::FoldingSetNodeID id;
2288   AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2289 
2290   void *insertPos = 0;
2291   AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2292   if (type) return QualType(type, 0);
2293 
2294   QualType canon = getCanonicalType(equivalentType);
2295   type = new (*this, TypeAlignment)
2296            AttributedType(canon, attrKind, modifiedType, equivalentType);
2297 
2298   Types.push_back(type);
2299   AttributedTypes.InsertNode(type, insertPos);
2300 
2301   return QualType(type, 0);
2302 }
2303 
2304 
2305 /// \brief Retrieve a substitution-result type.
2306 QualType
2307 ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
2308                                          QualType Replacement) const {
2309   assert(Replacement.isCanonical()
2310          && "replacement types must always be canonical");
2311 
2312   llvm::FoldingSetNodeID ID;
2313   SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2314   void *InsertPos = 0;
2315   SubstTemplateTypeParmType *SubstParm
2316     = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2317 
2318   if (!SubstParm) {
2319     SubstParm = new (*this, TypeAlignment)
2320       SubstTemplateTypeParmType(Parm, Replacement);
2321     Types.push_back(SubstParm);
2322     SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2323   }
2324 
2325   return QualType(SubstParm, 0);
2326 }
2327 
2328 /// \brief Retrieve a
2329 QualType ASTContext::getSubstTemplateTypeParmPackType(
2330                                           const TemplateTypeParmType *Parm,
2331                                               const TemplateArgument &ArgPack) {
2332 #ifndef NDEBUG
2333   for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2334                                     PEnd = ArgPack.pack_end();
2335        P != PEnd; ++P) {
2336     assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2337     assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2338   }
2339 #endif
2340 
2341   llvm::FoldingSetNodeID ID;
2342   SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2343   void *InsertPos = 0;
2344   if (SubstTemplateTypeParmPackType *SubstParm
2345         = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2346     return QualType(SubstParm, 0);
2347 
2348   QualType Canon;
2349   if (!Parm->isCanonicalUnqualified()) {
2350     Canon = getCanonicalType(QualType(Parm, 0));
2351     Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2352                                              ArgPack);
2353     SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2354   }
2355 
2356   SubstTemplateTypeParmPackType *SubstParm
2357     = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2358                                                                ArgPack);
2359   Types.push_back(SubstParm);
2360   SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2361   return QualType(SubstParm, 0);
2362 }
2363 
2364 /// \brief Retrieve the template type parameter type for a template
2365 /// parameter or parameter pack with the given depth, index, and (optionally)
2366 /// name.
2367 QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
2368                                              bool ParameterPack,
2369                                              TemplateTypeParmDecl *TTPDecl) const {
2370   llvm::FoldingSetNodeID ID;
2371   TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
2372   void *InsertPos = 0;
2373   TemplateTypeParmType *TypeParm
2374     = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2375 
2376   if (TypeParm)
2377     return QualType(TypeParm, 0);
2378 
2379   if (TTPDecl) {
2380     QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
2381     TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
2382 
2383     TemplateTypeParmType *TypeCheck
2384       = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2385     assert(!TypeCheck && "Template type parameter canonical type broken");
2386     (void)TypeCheck;
2387   } else
2388     TypeParm = new (*this, TypeAlignment)
2389       TemplateTypeParmType(Depth, Index, ParameterPack);
2390 
2391   Types.push_back(TypeParm);
2392   TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2393 
2394   return QualType(TypeParm, 0);
2395 }
2396 
2397 TypeSourceInfo *
2398 ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2399                                               SourceLocation NameLoc,
2400                                         const TemplateArgumentListInfo &Args,
2401                                               QualType Underlying) const {
2402   assert(!Name.getAsDependentTemplateName() &&
2403          "No dependent template names here!");
2404   QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
2405 
2406   TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2407   TemplateSpecializationTypeLoc TL
2408     = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
2409   TL.setTemplateNameLoc(NameLoc);
2410   TL.setLAngleLoc(Args.getLAngleLoc());
2411   TL.setRAngleLoc(Args.getRAngleLoc());
2412   for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2413     TL.setArgLocInfo(i, Args[i].getLocInfo());
2414   return DI;
2415 }
2416 
2417 QualType
2418 ASTContext::getTemplateSpecializationType(TemplateName Template,
2419                                           const TemplateArgumentListInfo &Args,
2420                                           QualType Underlying) const {
2421   assert(!Template.getAsDependentTemplateName() &&
2422          "No dependent template names here!");
2423 
2424   unsigned NumArgs = Args.size();
2425 
2426   SmallVector<TemplateArgument, 4> ArgVec;
2427   ArgVec.reserve(NumArgs);
2428   for (unsigned i = 0; i != NumArgs; ++i)
2429     ArgVec.push_back(Args[i].getArgument());
2430 
2431   return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
2432                                        Underlying);
2433 }
2434 
2435 QualType
2436 ASTContext::getTemplateSpecializationType(TemplateName Template,
2437                                           const TemplateArgument *Args,
2438                                           unsigned NumArgs,
2439                                           QualType Underlying) const {
2440   assert(!Template.getAsDependentTemplateName() &&
2441          "No dependent template names here!");
2442   // Look through qualified template names.
2443   if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2444     Template = TemplateName(QTN->getTemplateDecl());
2445 
2446   bool isTypeAlias =
2447     Template.getAsTemplateDecl() &&
2448     isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
2449 
2450   QualType CanonType;
2451   if (!Underlying.isNull())
2452     CanonType = getCanonicalType(Underlying);
2453   else {
2454     assert(!isTypeAlias &&
2455            "Underlying type for template alias must be computed by caller");
2456     CanonType = getCanonicalTemplateSpecializationType(Template, Args,
2457                                                        NumArgs);
2458   }
2459 
2460   // Allocate the (non-canonical) template specialization type, but don't
2461   // try to unique it: these types typically have location information that
2462   // we don't unique and don't want to lose.
2463   void *Mem = Allocate(sizeof(TemplateSpecializationType) +
2464                        sizeof(TemplateArgument) * NumArgs +
2465                        (isTypeAlias ? sizeof(QualType) : 0),
2466                        TypeAlignment);
2467   TemplateSpecializationType *Spec
2468     = new (Mem) TemplateSpecializationType(Template,
2469                                            Args, NumArgs,
2470                                            CanonType,
2471                                          isTypeAlias ? Underlying : QualType());
2472 
2473   Types.push_back(Spec);
2474   return QualType(Spec, 0);
2475 }
2476 
2477 QualType
2478 ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2479                                                    const TemplateArgument *Args,
2480                                                    unsigned NumArgs) const {
2481   assert(!Template.getAsDependentTemplateName() &&
2482          "No dependent template names here!");
2483   assert((!Template.getAsTemplateDecl() ||
2484           !isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) &&
2485          "Underlying type for template alias must be computed by caller");
2486 
2487   // Look through qualified template names.
2488   if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2489     Template = TemplateName(QTN->getTemplateDecl());
2490 
2491   // Build the canonical template specialization type.
2492   TemplateName CanonTemplate = getCanonicalTemplateName(Template);
2493   SmallVector<TemplateArgument, 4> CanonArgs;
2494   CanonArgs.reserve(NumArgs);
2495   for (unsigned I = 0; I != NumArgs; ++I)
2496     CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2497 
2498   // Determine whether this canonical template specialization type already
2499   // exists.
2500   llvm::FoldingSetNodeID ID;
2501   TemplateSpecializationType::Profile(ID, CanonTemplate,
2502                                       CanonArgs.data(), NumArgs, *this);
2503 
2504   void *InsertPos = 0;
2505   TemplateSpecializationType *Spec
2506     = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2507 
2508   if (!Spec) {
2509     // Allocate a new canonical template specialization type.
2510     void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2511                           sizeof(TemplateArgument) * NumArgs),
2512                          TypeAlignment);
2513     Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2514                                                 CanonArgs.data(), NumArgs,
2515                                                 QualType(), QualType());
2516     Types.push_back(Spec);
2517     TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2518   }
2519 
2520   assert(Spec->isDependentType() &&
2521          "Non-dependent template-id type must have a canonical type");
2522   return QualType(Spec, 0);
2523 }
2524 
2525 QualType
2526 ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2527                               NestedNameSpecifier *NNS,
2528                               QualType NamedType) const {
2529   llvm::FoldingSetNodeID ID;
2530   ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
2531 
2532   void *InsertPos = 0;
2533   ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2534   if (T)
2535     return QualType(T, 0);
2536 
2537   QualType Canon = NamedType;
2538   if (!Canon.isCanonical()) {
2539     Canon = getCanonicalType(NamedType);
2540     ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2541     assert(!CheckT && "Elaborated canonical type broken");
2542     (void)CheckT;
2543   }
2544 
2545   T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
2546   Types.push_back(T);
2547   ElaboratedTypes.InsertNode(T, InsertPos);
2548   return QualType(T, 0);
2549 }
2550 
2551 QualType
2552 ASTContext::getParenType(QualType InnerType) const {
2553   llvm::FoldingSetNodeID ID;
2554   ParenType::Profile(ID, InnerType);
2555 
2556   void *InsertPos = 0;
2557   ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2558   if (T)
2559     return QualType(T, 0);
2560 
2561   QualType Canon = InnerType;
2562   if (!Canon.isCanonical()) {
2563     Canon = getCanonicalType(InnerType);
2564     ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2565     assert(!CheckT && "Paren canonical type broken");
2566     (void)CheckT;
2567   }
2568 
2569   T = new (*this) ParenType(InnerType, Canon);
2570   Types.push_back(T);
2571   ParenTypes.InsertNode(T, InsertPos);
2572   return QualType(T, 0);
2573 }
2574 
2575 QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2576                                           NestedNameSpecifier *NNS,
2577                                           const IdentifierInfo *Name,
2578                                           QualType Canon) const {
2579   assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2580 
2581   if (Canon.isNull()) {
2582     NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
2583     ElaboratedTypeKeyword CanonKeyword = Keyword;
2584     if (Keyword == ETK_None)
2585       CanonKeyword = ETK_Typename;
2586 
2587     if (CanonNNS != NNS || CanonKeyword != Keyword)
2588       Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
2589   }
2590 
2591   llvm::FoldingSetNodeID ID;
2592   DependentNameType::Profile(ID, Keyword, NNS, Name);
2593 
2594   void *InsertPos = 0;
2595   DependentNameType *T
2596     = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
2597   if (T)
2598     return QualType(T, 0);
2599 
2600   T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
2601   Types.push_back(T);
2602   DependentNameTypes.InsertNode(T, InsertPos);
2603   return QualType(T, 0);
2604 }
2605 
2606 QualType
2607 ASTContext::getDependentTemplateSpecializationType(
2608                                  ElaboratedTypeKeyword Keyword,
2609                                  NestedNameSpecifier *NNS,
2610                                  const IdentifierInfo *Name,
2611                                  const TemplateArgumentListInfo &Args) const {
2612   // TODO: avoid this copy
2613   SmallVector<TemplateArgument, 16> ArgCopy;
2614   for (unsigned I = 0, E = Args.size(); I != E; ++I)
2615     ArgCopy.push_back(Args[I].getArgument());
2616   return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2617                                                 ArgCopy.size(),
2618                                                 ArgCopy.data());
2619 }
2620 
2621 QualType
2622 ASTContext::getDependentTemplateSpecializationType(
2623                                  ElaboratedTypeKeyword Keyword,
2624                                  NestedNameSpecifier *NNS,
2625                                  const IdentifierInfo *Name,
2626                                  unsigned NumArgs,
2627                                  const TemplateArgument *Args) const {
2628   assert((!NNS || NNS->isDependent()) &&
2629          "nested-name-specifier must be dependent");
2630 
2631   llvm::FoldingSetNodeID ID;
2632   DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2633                                                Name, NumArgs, Args);
2634 
2635   void *InsertPos = 0;
2636   DependentTemplateSpecializationType *T
2637     = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2638   if (T)
2639     return QualType(T, 0);
2640 
2641   NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
2642 
2643   ElaboratedTypeKeyword CanonKeyword = Keyword;
2644   if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2645 
2646   bool AnyNonCanonArgs = false;
2647   SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
2648   for (unsigned I = 0; I != NumArgs; ++I) {
2649     CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2650     if (!CanonArgs[I].structurallyEquals(Args[I]))
2651       AnyNonCanonArgs = true;
2652   }
2653 
2654   QualType Canon;
2655   if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2656     Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2657                                                    Name, NumArgs,
2658                                                    CanonArgs.data());
2659 
2660     // Find the insert position again.
2661     DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2662   }
2663 
2664   void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2665                         sizeof(TemplateArgument) * NumArgs),
2666                        TypeAlignment);
2667   T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
2668                                                     Name, NumArgs, Args, Canon);
2669   Types.push_back(T);
2670   DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
2671   return QualType(T, 0);
2672 }
2673 
2674 QualType ASTContext::getPackExpansionType(QualType Pattern,
2675                                       llvm::Optional<unsigned> NumExpansions) {
2676   llvm::FoldingSetNodeID ID;
2677   PackExpansionType::Profile(ID, Pattern, NumExpansions);
2678 
2679   assert(Pattern->containsUnexpandedParameterPack() &&
2680          "Pack expansions must expand one or more parameter packs");
2681   void *InsertPos = 0;
2682   PackExpansionType *T
2683     = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2684   if (T)
2685     return QualType(T, 0);
2686 
2687   QualType Canon;
2688   if (!Pattern.isCanonical()) {
2689     Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
2690 
2691     // Find the insert position again.
2692     PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2693   }
2694 
2695   T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
2696   Types.push_back(T);
2697   PackExpansionTypes.InsertNode(T, InsertPos);
2698   return QualType(T, 0);
2699 }
2700 
2701 /// CmpProtocolNames - Comparison predicate for sorting protocols
2702 /// alphabetically.
2703 static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2704                             const ObjCProtocolDecl *RHS) {
2705   return LHS->getDeclName() < RHS->getDeclName();
2706 }
2707 
2708 static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
2709                                 unsigned NumProtocols) {
2710   if (NumProtocols == 0) return true;
2711 
2712   if (Protocols[0]->getCanonicalDecl() != Protocols[0])
2713     return false;
2714 
2715   for (unsigned i = 1; i != NumProtocols; ++i)
2716     if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
2717         Protocols[i]->getCanonicalDecl() != Protocols[i])
2718       return false;
2719   return true;
2720 }
2721 
2722 static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
2723                                    unsigned &NumProtocols) {
2724   ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
2725 
2726   // Sort protocols, keyed by name.
2727   std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2728 
2729   // Canonicalize.
2730   for (unsigned I = 0, N = NumProtocols; I != N; ++I)
2731     Protocols[I] = Protocols[I]->getCanonicalDecl();
2732 
2733   // Remove duplicates.
2734   ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2735   NumProtocols = ProtocolsEnd-Protocols;
2736 }
2737 
2738 QualType ASTContext::getObjCObjectType(QualType BaseType,
2739                                        ObjCProtocolDecl * const *Protocols,
2740                                        unsigned NumProtocols) const {
2741   // If the base type is an interface and there aren't any protocols
2742   // to add, then the interface type will do just fine.
2743   if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2744     return BaseType;
2745 
2746   // Look in the folding set for an existing type.
2747   llvm::FoldingSetNodeID ID;
2748   ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
2749   void *InsertPos = 0;
2750   if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2751     return QualType(QT, 0);
2752 
2753   // Build the canonical type, which has the canonical base type and
2754   // a sorted-and-uniqued list of protocols.
2755   QualType Canonical;
2756   bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2757   if (!ProtocolsSorted || !BaseType.isCanonical()) {
2758     if (!ProtocolsSorted) {
2759       SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
2760                                                      Protocols + NumProtocols);
2761       unsigned UniqueCount = NumProtocols;
2762 
2763       SortAndUniqueProtocols(&Sorted[0], UniqueCount);
2764       Canonical = getObjCObjectType(getCanonicalType(BaseType),
2765                                     &Sorted[0], UniqueCount);
2766     } else {
2767       Canonical = getObjCObjectType(getCanonicalType(BaseType),
2768                                     Protocols, NumProtocols);
2769     }
2770 
2771     // Regenerate InsertPos.
2772     ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2773   }
2774 
2775   unsigned Size = sizeof(ObjCObjectTypeImpl);
2776   Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2777   void *Mem = Allocate(Size, TypeAlignment);
2778   ObjCObjectTypeImpl *T =
2779     new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2780 
2781   Types.push_back(T);
2782   ObjCObjectTypes.InsertNode(T, InsertPos);
2783   return QualType(T, 0);
2784 }
2785 
2786 /// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2787 /// the given object type.
2788 QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
2789   llvm::FoldingSetNodeID ID;
2790   ObjCObjectPointerType::Profile(ID, ObjectT);
2791 
2792   void *InsertPos = 0;
2793   if (ObjCObjectPointerType *QT =
2794               ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2795     return QualType(QT, 0);
2796 
2797   // Find the canonical object type.
2798   QualType Canonical;
2799   if (!ObjectT.isCanonical()) {
2800     Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2801 
2802     // Regenerate InsertPos.
2803     ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2804   }
2805 
2806   // No match.
2807   void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2808   ObjCObjectPointerType *QType =
2809     new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
2810 
2811   Types.push_back(QType);
2812   ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
2813   return QualType(QType, 0);
2814 }
2815 
2816 /// getObjCInterfaceType - Return the unique reference to the type for the
2817 /// specified ObjC interface decl. The list of protocols is optional.
2818 QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
2819                                           ObjCInterfaceDecl *PrevDecl) const {
2820   if (Decl->TypeForDecl)
2821     return QualType(Decl->TypeForDecl, 0);
2822 
2823   if (PrevDecl) {
2824     assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
2825     Decl->TypeForDecl = PrevDecl->TypeForDecl;
2826     return QualType(PrevDecl->TypeForDecl, 0);
2827   }
2828 
2829   // Prefer the definition, if there is one.
2830   if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
2831     Decl = Def;
2832 
2833   void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2834   ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2835   Decl->TypeForDecl = T;
2836   Types.push_back(T);
2837   return QualType(T, 0);
2838 }
2839 
2840 /// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2841 /// TypeOfExprType AST's (since expression's are never shared). For example,
2842 /// multiple declarations that refer to "typeof(x)" all contain different
2843 /// DeclRefExpr's. This doesn't effect the type checker, since it operates
2844 /// on canonical type's (which are always unique).
2845 QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
2846   TypeOfExprType *toe;
2847   if (tofExpr->isTypeDependent()) {
2848     llvm::FoldingSetNodeID ID;
2849     DependentTypeOfExprType::Profile(ID, *this, tofExpr);
2850 
2851     void *InsertPos = 0;
2852     DependentTypeOfExprType *Canon
2853       = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2854     if (Canon) {
2855       // We already have a "canonical" version of an identical, dependent
2856       // typeof(expr) type. Use that as our canonical type.
2857       toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
2858                                           QualType((TypeOfExprType*)Canon, 0));
2859     } else {
2860       // Build a new, canonical typeof(expr) type.
2861       Canon
2862         = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
2863       DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2864       toe = Canon;
2865     }
2866   } else {
2867     QualType Canonical = getCanonicalType(tofExpr->getType());
2868     toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
2869   }
2870   Types.push_back(toe);
2871   return QualType(toe, 0);
2872 }
2873 
2874 /// getTypeOfType -  Unlike many "get<Type>" functions, we don't unique
2875 /// TypeOfType AST's. The only motivation to unique these nodes would be
2876 /// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
2877 /// an issue. This doesn't effect the type checker, since it operates
2878 /// on canonical type's (which are always unique).
2879 QualType ASTContext::getTypeOfType(QualType tofType) const {
2880   QualType Canonical = getCanonicalType(tofType);
2881   TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
2882   Types.push_back(tot);
2883   return QualType(tot, 0);
2884 }
2885 
2886 /// getDecltypeForExpr - Given an expr, will return the decltype for that
2887 /// expression, according to the rules in C++0x [dcl.type.simple]p4
2888 static QualType getDecltypeForExpr(const Expr *e, const ASTContext &Context) {
2889   if (e->isTypeDependent())
2890     return Context.DependentTy;
2891 
2892   // If e is an id expression or a class member access, decltype(e) is defined
2893   // as the type of the entity named by e.
2894   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2895     if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2896       return VD->getType();
2897   }
2898   if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2899     if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2900       return FD->getType();
2901   }
2902   // If e is a function call or an invocation of an overloaded operator,
2903   // (parentheses around e are ignored), decltype(e) is defined as the
2904   // return type of that function.
2905   if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2906     return CE->getCallReturnType();
2907 
2908   QualType T = e->getType();
2909 
2910   // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
2911   // defined as T&, otherwise decltype(e) is defined as T.
2912   if (e->isLValue())
2913     T = Context.getLValueReferenceType(T);
2914 
2915   return T;
2916 }
2917 
2918 /// getDecltypeType -  Unlike many "get<Type>" functions, we don't unique
2919 /// DecltypeType AST's. The only motivation to unique these nodes would be
2920 /// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
2921 /// an issue. This doesn't effect the type checker, since it operates
2922 /// on canonical types (which are always unique).
2923 QualType ASTContext::getDecltypeType(Expr *e) const {
2924   DecltypeType *dt;
2925 
2926   // C++0x [temp.type]p2:
2927   //   If an expression e involves a template parameter, decltype(e) denotes a
2928   //   unique dependent type. Two such decltype-specifiers refer to the same
2929   //   type only if their expressions are equivalent (14.5.6.1).
2930   if (e->isInstantiationDependent()) {
2931     llvm::FoldingSetNodeID ID;
2932     DependentDecltypeType::Profile(ID, *this, e);
2933 
2934     void *InsertPos = 0;
2935     DependentDecltypeType *Canon
2936       = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2937     if (Canon) {
2938       // We already have a "canonical" version of an equivalent, dependent
2939       // decltype type. Use that as our canonical type.
2940       dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
2941                                        QualType((DecltypeType*)Canon, 0));
2942     } else {
2943       // Build a new, canonical typeof(expr) type.
2944       Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
2945       DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2946       dt = Canon;
2947     }
2948   } else {
2949     QualType T = getDecltypeForExpr(e, *this);
2950     dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
2951   }
2952   Types.push_back(dt);
2953   return QualType(dt, 0);
2954 }
2955 
2956 /// getUnaryTransformationType - We don't unique these, since the memory
2957 /// savings are minimal and these are rare.
2958 QualType ASTContext::getUnaryTransformType(QualType BaseType,
2959                                            QualType UnderlyingType,
2960                                            UnaryTransformType::UTTKind Kind)
2961     const {
2962   UnaryTransformType *Ty =
2963     new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
2964                                                    Kind,
2965                                  UnderlyingType->isDependentType() ?
2966                                     QualType() : UnderlyingType);
2967   Types.push_back(Ty);
2968   return QualType(Ty, 0);
2969 }
2970 
2971 /// getAutoType - We only unique auto types after they've been deduced.
2972 QualType ASTContext::getAutoType(QualType DeducedType) const {
2973   void *InsertPos = 0;
2974   if (!DeducedType.isNull()) {
2975     // Look in the folding set for an existing type.
2976     llvm::FoldingSetNodeID ID;
2977     AutoType::Profile(ID, DeducedType);
2978     if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
2979       return QualType(AT, 0);
2980   }
2981 
2982   AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
2983   Types.push_back(AT);
2984   if (InsertPos)
2985     AutoTypes.InsertNode(AT, InsertPos);
2986   return QualType(AT, 0);
2987 }
2988 
2989 /// getAtomicType - Return the uniqued reference to the atomic type for
2990 /// the given value type.
2991 QualType ASTContext::getAtomicType(QualType T) const {
2992   // Unique pointers, to guarantee there is only one pointer of a particular
2993   // structure.
2994   llvm::FoldingSetNodeID ID;
2995   AtomicType::Profile(ID, T);
2996 
2997   void *InsertPos = 0;
2998   if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
2999     return QualType(AT, 0);
3000 
3001   // If the atomic value type isn't canonical, this won't be a canonical type
3002   // either, so fill in the canonical type field.
3003   QualType Canonical;
3004   if (!T.isCanonical()) {
3005     Canonical = getAtomicType(getCanonicalType(T));
3006 
3007     // Get the new insert position for the node we care about.
3008     AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3009     assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3010   }
3011   AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3012   Types.push_back(New);
3013   AtomicTypes.InsertNode(New, InsertPos);
3014   return QualType(New, 0);
3015 }
3016 
3017 /// getAutoDeductType - Get type pattern for deducing against 'auto'.
3018 QualType ASTContext::getAutoDeductType() const {
3019   if (AutoDeductTy.isNull())
3020     AutoDeductTy = getAutoType(QualType());
3021   assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
3022   return AutoDeductTy;
3023 }
3024 
3025 /// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3026 QualType ASTContext::getAutoRRefDeductType() const {
3027   if (AutoRRefDeductTy.isNull())
3028     AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3029   assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3030   return AutoRRefDeductTy;
3031 }
3032 
3033 /// getTagDeclType - Return the unique reference to the type for the
3034 /// specified TagDecl (struct/union/class/enum) decl.
3035 QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
3036   assert (Decl);
3037   // FIXME: What is the design on getTagDeclType when it requires casting
3038   // away const?  mutable?
3039   return getTypeDeclType(const_cast<TagDecl*>(Decl));
3040 }
3041 
3042 /// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3043 /// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3044 /// needs to agree with the definition in <stddef.h>.
3045 CanQualType ASTContext::getSizeType() const {
3046   return getFromTargetType(Target->getSizeType());
3047 }
3048 
3049 /// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3050 CanQualType ASTContext::getIntMaxType() const {
3051   return getFromTargetType(Target->getIntMaxType());
3052 }
3053 
3054 /// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3055 CanQualType ASTContext::getUIntMaxType() const {
3056   return getFromTargetType(Target->getUIntMaxType());
3057 }
3058 
3059 /// getSignedWCharType - Return the type of "signed wchar_t".
3060 /// Used when in C++, as a GCC extension.
3061 QualType ASTContext::getSignedWCharType() const {
3062   // FIXME: derive from "Target" ?
3063   return WCharTy;
3064 }
3065 
3066 /// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3067 /// Used when in C++, as a GCC extension.
3068 QualType ASTContext::getUnsignedWCharType() const {
3069   // FIXME: derive from "Target" ?
3070   return UnsignedIntTy;
3071 }
3072 
3073 /// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
3074 /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3075 QualType ASTContext::getPointerDiffType() const {
3076   return getFromTargetType(Target->getPtrDiffType(0));
3077 }
3078 
3079 //===----------------------------------------------------------------------===//
3080 //                              Type Operators
3081 //===----------------------------------------------------------------------===//
3082 
3083 CanQualType ASTContext::getCanonicalParamType(QualType T) const {
3084   // Push qualifiers into arrays, and then discard any remaining
3085   // qualifiers.
3086   T = getCanonicalType(T);
3087   T = getVariableArrayDecayedType(T);
3088   const Type *Ty = T.getTypePtr();
3089   QualType Result;
3090   if (isa<ArrayType>(Ty)) {
3091     Result = getArrayDecayedType(QualType(Ty,0));
3092   } else if (isa<FunctionType>(Ty)) {
3093     Result = getPointerType(QualType(Ty, 0));
3094   } else {
3095     Result = QualType(Ty, 0);
3096   }
3097 
3098   return CanQualType::CreateUnsafe(Result);
3099 }
3100 
3101 QualType ASTContext::getUnqualifiedArrayType(QualType type,
3102                                              Qualifiers &quals) {
3103   SplitQualType splitType = type.getSplitUnqualifiedType();
3104 
3105   // FIXME: getSplitUnqualifiedType() actually walks all the way to
3106   // the unqualified desugared type and then drops it on the floor.
3107   // We then have to strip that sugar back off with
3108   // getUnqualifiedDesugaredType(), which is silly.
3109   const ArrayType *AT =
3110     dyn_cast<ArrayType>(splitType.first->getUnqualifiedDesugaredType());
3111 
3112   // If we don't have an array, just use the results in splitType.
3113   if (!AT) {
3114     quals = splitType.second;
3115     return QualType(splitType.first, 0);
3116   }
3117 
3118   // Otherwise, recurse on the array's element type.
3119   QualType elementType = AT->getElementType();
3120   QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3121 
3122   // If that didn't change the element type, AT has no qualifiers, so we
3123   // can just use the results in splitType.
3124   if (elementType == unqualElementType) {
3125     assert(quals.empty()); // from the recursive call
3126     quals = splitType.second;
3127     return QualType(splitType.first, 0);
3128   }
3129 
3130   // Otherwise, add in the qualifiers from the outermost type, then
3131   // build the type back up.
3132   quals.addConsistentQualifiers(splitType.second);
3133 
3134   if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
3135     return getConstantArrayType(unqualElementType, CAT->getSize(),
3136                                 CAT->getSizeModifier(), 0);
3137   }
3138 
3139   if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
3140     return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
3141   }
3142 
3143   if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
3144     return getVariableArrayType(unqualElementType,
3145                                 VAT->getSizeExpr(),
3146                                 VAT->getSizeModifier(),
3147                                 VAT->getIndexTypeCVRQualifiers(),
3148                                 VAT->getBracketsRange());
3149   }
3150 
3151   const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
3152   return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
3153                                     DSAT->getSizeModifier(), 0,
3154                                     SourceRange());
3155 }
3156 
3157 /// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types  that
3158 /// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3159 /// they point to and return true. If T1 and T2 aren't pointer types
3160 /// or pointer-to-member types, or if they are not similar at this
3161 /// level, returns false and leaves T1 and T2 unchanged. Top-level
3162 /// qualifiers on T1 and T2 are ignored. This function will typically
3163 /// be called in a loop that successively "unwraps" pointer and
3164 /// pointer-to-member types to compare them at each level.
3165 bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3166   const PointerType *T1PtrType = T1->getAs<PointerType>(),
3167                     *T2PtrType = T2->getAs<PointerType>();
3168   if (T1PtrType && T2PtrType) {
3169     T1 = T1PtrType->getPointeeType();
3170     T2 = T2PtrType->getPointeeType();
3171     return true;
3172   }
3173 
3174   const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3175                           *T2MPType = T2->getAs<MemberPointerType>();
3176   if (T1MPType && T2MPType &&
3177       hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3178                              QualType(T2MPType->getClass(), 0))) {
3179     T1 = T1MPType->getPointeeType();
3180     T2 = T2MPType->getPointeeType();
3181     return true;
3182   }
3183 
3184   if (getLangOptions().ObjC1) {
3185     const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3186                                 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3187     if (T1OPType && T2OPType) {
3188       T1 = T1OPType->getPointeeType();
3189       T2 = T2OPType->getPointeeType();
3190       return true;
3191     }
3192   }
3193 
3194   // FIXME: Block pointers, too?
3195 
3196   return false;
3197 }
3198 
3199 DeclarationNameInfo
3200 ASTContext::getNameForTemplate(TemplateName Name,
3201                                SourceLocation NameLoc) const {
3202   switch (Name.getKind()) {
3203   case TemplateName::QualifiedTemplate:
3204   case TemplateName::Template:
3205     // DNInfo work in progress: CHECKME: what about DNLoc?
3206     return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3207                                NameLoc);
3208 
3209   case TemplateName::OverloadedTemplate: {
3210     OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3211     // DNInfo work in progress: CHECKME: what about DNLoc?
3212     return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3213   }
3214 
3215   case TemplateName::DependentTemplate: {
3216     DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3217     DeclarationName DName;
3218     if (DTN->isIdentifier()) {
3219       DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3220       return DeclarationNameInfo(DName, NameLoc);
3221     } else {
3222       DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3223       // DNInfo work in progress: FIXME: source locations?
3224       DeclarationNameLoc DNLoc;
3225       DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3226       DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3227       return DeclarationNameInfo(DName, NameLoc, DNLoc);
3228     }
3229   }
3230 
3231   case TemplateName::SubstTemplateTemplateParm: {
3232     SubstTemplateTemplateParmStorage *subst
3233       = Name.getAsSubstTemplateTemplateParm();
3234     return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3235                                NameLoc);
3236   }
3237 
3238   case TemplateName::SubstTemplateTemplateParmPack: {
3239     SubstTemplateTemplateParmPackStorage *subst
3240       = Name.getAsSubstTemplateTemplateParmPack();
3241     return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3242                                NameLoc);
3243   }
3244   }
3245 
3246   llvm_unreachable("bad template name kind!");
3247 }
3248 
3249 TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
3250   switch (Name.getKind()) {
3251   case TemplateName::QualifiedTemplate:
3252   case TemplateName::Template: {
3253     TemplateDecl *Template = Name.getAsTemplateDecl();
3254     if (TemplateTemplateParmDecl *TTP
3255           = dyn_cast<TemplateTemplateParmDecl>(Template))
3256       Template = getCanonicalTemplateTemplateParmDecl(TTP);
3257 
3258     // The canonical template name is the canonical template declaration.
3259     return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
3260   }
3261 
3262   case TemplateName::OverloadedTemplate:
3263     llvm_unreachable("cannot canonicalize overloaded template");
3264 
3265   case TemplateName::DependentTemplate: {
3266     DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3267     assert(DTN && "Non-dependent template names must refer to template decls.");
3268     return DTN->CanonicalTemplateName;
3269   }
3270 
3271   case TemplateName::SubstTemplateTemplateParm: {
3272     SubstTemplateTemplateParmStorage *subst
3273       = Name.getAsSubstTemplateTemplateParm();
3274     return getCanonicalTemplateName(subst->getReplacement());
3275   }
3276 
3277   case TemplateName::SubstTemplateTemplateParmPack: {
3278     SubstTemplateTemplateParmPackStorage *subst
3279                                   = Name.getAsSubstTemplateTemplateParmPack();
3280     TemplateTemplateParmDecl *canonParameter
3281       = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3282     TemplateArgument canonArgPack
3283       = getCanonicalTemplateArgument(subst->getArgumentPack());
3284     return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3285   }
3286   }
3287 
3288   llvm_unreachable("bad template name!");
3289 }
3290 
3291 bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3292   X = getCanonicalTemplateName(X);
3293   Y = getCanonicalTemplateName(Y);
3294   return X.getAsVoidPointer() == Y.getAsVoidPointer();
3295 }
3296 
3297 TemplateArgument
3298 ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
3299   switch (Arg.getKind()) {
3300     case TemplateArgument::Null:
3301       return Arg;
3302 
3303     case TemplateArgument::Expression:
3304       return Arg;
3305 
3306     case TemplateArgument::Declaration:
3307       return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
3308 
3309     case TemplateArgument::Template:
3310       return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
3311 
3312     case TemplateArgument::TemplateExpansion:
3313       return TemplateArgument(getCanonicalTemplateName(
3314                                          Arg.getAsTemplateOrTemplatePattern()),
3315                               Arg.getNumTemplateExpansions());
3316 
3317     case TemplateArgument::Integral:
3318       return TemplateArgument(*Arg.getAsIntegral(),
3319                               getCanonicalType(Arg.getIntegralType()));
3320 
3321     case TemplateArgument::Type:
3322       return TemplateArgument(getCanonicalType(Arg.getAsType()));
3323 
3324     case TemplateArgument::Pack: {
3325       if (Arg.pack_size() == 0)
3326         return Arg;
3327 
3328       TemplateArgument *CanonArgs
3329         = new (*this) TemplateArgument[Arg.pack_size()];
3330       unsigned Idx = 0;
3331       for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
3332                                         AEnd = Arg.pack_end();
3333            A != AEnd; (void)++A, ++Idx)
3334         CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
3335 
3336       return TemplateArgument(CanonArgs, Arg.pack_size());
3337     }
3338   }
3339 
3340   // Silence GCC warning
3341   llvm_unreachable("Unhandled template argument kind");
3342 }
3343 
3344 NestedNameSpecifier *
3345 ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
3346   if (!NNS)
3347     return 0;
3348 
3349   switch (NNS->getKind()) {
3350   case NestedNameSpecifier::Identifier:
3351     // Canonicalize the prefix but keep the identifier the same.
3352     return NestedNameSpecifier::Create(*this,
3353                          getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3354                                        NNS->getAsIdentifier());
3355 
3356   case NestedNameSpecifier::Namespace:
3357     // A namespace is canonical; build a nested-name-specifier with
3358     // this namespace and no prefix.
3359     return NestedNameSpecifier::Create(*this, 0,
3360                                  NNS->getAsNamespace()->getOriginalNamespace());
3361 
3362   case NestedNameSpecifier::NamespaceAlias:
3363     // A namespace is canonical; build a nested-name-specifier with
3364     // this namespace and no prefix.
3365     return NestedNameSpecifier::Create(*this, 0,
3366                                     NNS->getAsNamespaceAlias()->getNamespace()
3367                                                       ->getOriginalNamespace());
3368 
3369   case NestedNameSpecifier::TypeSpec:
3370   case NestedNameSpecifier::TypeSpecWithTemplate: {
3371     QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
3372 
3373     // If we have some kind of dependent-named type (e.g., "typename T::type"),
3374     // break it apart into its prefix and identifier, then reconsititute those
3375     // as the canonical nested-name-specifier. This is required to canonicalize
3376     // a dependent nested-name-specifier involving typedefs of dependent-name
3377     // types, e.g.,
3378     //   typedef typename T::type T1;
3379     //   typedef typename T1::type T2;
3380     if (const DependentNameType *DNT = T->getAs<DependentNameType>()) {
3381       NestedNameSpecifier *Prefix
3382         = getCanonicalNestedNameSpecifier(DNT->getQualifier());
3383       return NestedNameSpecifier::Create(*this, Prefix,
3384                            const_cast<IdentifierInfo *>(DNT->getIdentifier()));
3385     }
3386 
3387     // Do the same thing as above, but with dependent-named specializations.
3388     if (const DependentTemplateSpecializationType *DTST
3389           = T->getAs<DependentTemplateSpecializationType>()) {
3390       NestedNameSpecifier *Prefix
3391         = getCanonicalNestedNameSpecifier(DTST->getQualifier());
3392 
3393       T = getDependentTemplateSpecializationType(DTST->getKeyword(),
3394                                                  Prefix, DTST->getIdentifier(),
3395                                                  DTST->getNumArgs(),
3396                                                  DTST->getArgs());
3397       T = getCanonicalType(T);
3398     }
3399 
3400     return NestedNameSpecifier::Create(*this, 0, false,
3401                                        const_cast<Type*>(T.getTypePtr()));
3402   }
3403 
3404   case NestedNameSpecifier::Global:
3405     // The global specifier is canonical and unique.
3406     return NNS;
3407   }
3408 
3409   llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
3410 }
3411 
3412 
3413 const ArrayType *ASTContext::getAsArrayType(QualType T) const {
3414   // Handle the non-qualified case efficiently.
3415   if (!T.hasLocalQualifiers()) {
3416     // Handle the common positive case fast.
3417     if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3418       return AT;
3419   }
3420 
3421   // Handle the common negative case fast.
3422   if (!isa<ArrayType>(T.getCanonicalType()))
3423     return 0;
3424 
3425   // Apply any qualifiers from the array type to the element type.  This
3426   // implements C99 6.7.3p8: "If the specification of an array type includes
3427   // any type qualifiers, the element type is so qualified, not the array type."
3428 
3429   // If we get here, we either have type qualifiers on the type, or we have
3430   // sugar such as a typedef in the way.  If we have type qualifiers on the type
3431   // we must propagate them down into the element type.
3432 
3433   SplitQualType split = T.getSplitDesugaredType();
3434   Qualifiers qs = split.second;
3435 
3436   // If we have a simple case, just return now.
3437   const ArrayType *ATy = dyn_cast<ArrayType>(split.first);
3438   if (ATy == 0 || qs.empty())
3439     return ATy;
3440 
3441   // Otherwise, we have an array and we have qualifiers on it.  Push the
3442   // qualifiers into the array element type and return a new array type.
3443   QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
3444 
3445   if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3446     return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3447                                                 CAT->getSizeModifier(),
3448                                            CAT->getIndexTypeCVRQualifiers()));
3449   if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3450     return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3451                                                   IAT->getSizeModifier(),
3452                                            IAT->getIndexTypeCVRQualifiers()));
3453 
3454   if (const DependentSizedArrayType *DSAT
3455         = dyn_cast<DependentSizedArrayType>(ATy))
3456     return cast<ArrayType>(
3457                      getDependentSizedArrayType(NewEltTy,
3458                                                 DSAT->getSizeExpr(),
3459                                                 DSAT->getSizeModifier(),
3460                                               DSAT->getIndexTypeCVRQualifiers(),
3461                                                 DSAT->getBracketsRange()));
3462 
3463   const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
3464   return cast<ArrayType>(getVariableArrayType(NewEltTy,
3465                                               VAT->getSizeExpr(),
3466                                               VAT->getSizeModifier(),
3467                                               VAT->getIndexTypeCVRQualifiers(),
3468                                               VAT->getBracketsRange()));
3469 }
3470 
3471 QualType ASTContext::getAdjustedParameterType(QualType T) {
3472   // C99 6.7.5.3p7:
3473   //   A declaration of a parameter as "array of type" shall be
3474   //   adjusted to "qualified pointer to type", where the type
3475   //   qualifiers (if any) are those specified within the [ and ] of
3476   //   the array type derivation.
3477   if (T->isArrayType())
3478     return getArrayDecayedType(T);
3479 
3480   // C99 6.7.5.3p8:
3481   //   A declaration of a parameter as "function returning type"
3482   //   shall be adjusted to "pointer to function returning type", as
3483   //   in 6.3.2.1.
3484   if (T->isFunctionType())
3485     return getPointerType(T);
3486 
3487   return T;
3488 }
3489 
3490 QualType ASTContext::getSignatureParameterType(QualType T) {
3491   T = getVariableArrayDecayedType(T);
3492   T = getAdjustedParameterType(T);
3493   return T.getUnqualifiedType();
3494 }
3495 
3496 /// getArrayDecayedType - Return the properly qualified result of decaying the
3497 /// specified array type to a pointer.  This operation is non-trivial when
3498 /// handling typedefs etc.  The canonical type of "T" must be an array type,
3499 /// this returns a pointer to a properly qualified element of the array.
3500 ///
3501 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
3502 QualType ASTContext::getArrayDecayedType(QualType Ty) const {
3503   // Get the element type with 'getAsArrayType' so that we don't lose any
3504   // typedefs in the element type of the array.  This also handles propagation
3505   // of type qualifiers from the array type into the element type if present
3506   // (C99 6.7.3p8).
3507   const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3508   assert(PrettyArrayType && "Not an array type!");
3509 
3510   QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
3511 
3512   // int x[restrict 4] ->  int *restrict
3513   return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
3514 }
3515 
3516 QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3517   return getBaseElementType(array->getElementType());
3518 }
3519 
3520 QualType ASTContext::getBaseElementType(QualType type) const {
3521   Qualifiers qs;
3522   while (true) {
3523     SplitQualType split = type.getSplitDesugaredType();
3524     const ArrayType *array = split.first->getAsArrayTypeUnsafe();
3525     if (!array) break;
3526 
3527     type = array->getElementType();
3528     qs.addConsistentQualifiers(split.second);
3529   }
3530 
3531   return getQualifiedType(type, qs);
3532 }
3533 
3534 /// getConstantArrayElementCount - Returns number of constant array elements.
3535 uint64_t
3536 ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA)  const {
3537   uint64_t ElementCount = 1;
3538   do {
3539     ElementCount *= CA->getSize().getZExtValue();
3540     CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3541   } while (CA);
3542   return ElementCount;
3543 }
3544 
3545 /// getFloatingRank - Return a relative rank for floating point types.
3546 /// This routine will assert if passed a built-in type that isn't a float.
3547 static FloatingRank getFloatingRank(QualType T) {
3548   if (const ComplexType *CT = T->getAs<ComplexType>())
3549     return getFloatingRank(CT->getElementType());
3550 
3551   assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3552   switch (T->getAs<BuiltinType>()->getKind()) {
3553   default: llvm_unreachable("getFloatingRank(): not a floating type");
3554   case BuiltinType::Half:       return HalfRank;
3555   case BuiltinType::Float:      return FloatRank;
3556   case BuiltinType::Double:     return DoubleRank;
3557   case BuiltinType::LongDouble: return LongDoubleRank;
3558   }
3559 }
3560 
3561 /// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3562 /// point or a complex type (based on typeDomain/typeSize).
3563 /// 'typeDomain' is a real floating point or complex type.
3564 /// 'typeSize' is a real floating point or complex type.
3565 QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3566                                                        QualType Domain) const {
3567   FloatingRank EltRank = getFloatingRank(Size);
3568   if (Domain->isComplexType()) {
3569     switch (EltRank) {
3570     case HalfRank: llvm_unreachable("Complex half is not supported");
3571     case FloatRank:      return FloatComplexTy;
3572     case DoubleRank:     return DoubleComplexTy;
3573     case LongDoubleRank: return LongDoubleComplexTy;
3574     }
3575   }
3576 
3577   assert(Domain->isRealFloatingType() && "Unknown domain!");
3578   switch (EltRank) {
3579   case HalfRank: llvm_unreachable("Half ranks are not valid here");
3580   case FloatRank:      return FloatTy;
3581   case DoubleRank:     return DoubleTy;
3582   case LongDoubleRank: return LongDoubleTy;
3583   }
3584   llvm_unreachable("getFloatingRank(): illegal value for rank");
3585 }
3586 
3587 /// getFloatingTypeOrder - Compare the rank of the two specified floating
3588 /// point types, ignoring the domain of the type (i.e. 'double' ==
3589 /// '_Complex double').  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
3590 /// LHS < RHS, return -1.
3591 int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
3592   FloatingRank LHSR = getFloatingRank(LHS);
3593   FloatingRank RHSR = getFloatingRank(RHS);
3594 
3595   if (LHSR == RHSR)
3596     return 0;
3597   if (LHSR > RHSR)
3598     return 1;
3599   return -1;
3600 }
3601 
3602 /// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3603 /// routine will assert if passed a built-in type that isn't an integer or enum,
3604 /// or if it is not canonicalized.
3605 unsigned ASTContext::getIntegerRank(const Type *T) const {
3606   assert(T->isCanonicalUnqualified() && "T should be canonicalized");
3607 
3608   switch (cast<BuiltinType>(T)->getKind()) {
3609   default: llvm_unreachable("getIntegerRank(): not a built-in integer");
3610   case BuiltinType::Bool:
3611     return 1 + (getIntWidth(BoolTy) << 3);
3612   case BuiltinType::Char_S:
3613   case BuiltinType::Char_U:
3614   case BuiltinType::SChar:
3615   case BuiltinType::UChar:
3616     return 2 + (getIntWidth(CharTy) << 3);
3617   case BuiltinType::Short:
3618   case BuiltinType::UShort:
3619     return 3 + (getIntWidth(ShortTy) << 3);
3620   case BuiltinType::Int:
3621   case BuiltinType::UInt:
3622     return 4 + (getIntWidth(IntTy) << 3);
3623   case BuiltinType::Long:
3624   case BuiltinType::ULong:
3625     return 5 + (getIntWidth(LongTy) << 3);
3626   case BuiltinType::LongLong:
3627   case BuiltinType::ULongLong:
3628     return 6 + (getIntWidth(LongLongTy) << 3);
3629   case BuiltinType::Int128:
3630   case BuiltinType::UInt128:
3631     return 7 + (getIntWidth(Int128Ty) << 3);
3632   }
3633 }
3634 
3635 /// \brief Whether this is a promotable bitfield reference according
3636 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3637 ///
3638 /// \returns the type this bit-field will promote to, or NULL if no
3639 /// promotion occurs.
3640 QualType ASTContext::isPromotableBitField(Expr *E) const {
3641   if (E->isTypeDependent() || E->isValueDependent())
3642     return QualType();
3643 
3644   FieldDecl *Field = E->getBitField();
3645   if (!Field)
3646     return QualType();
3647 
3648   QualType FT = Field->getType();
3649 
3650   uint64_t BitWidth = Field->getBitWidthValue(*this);
3651   uint64_t IntSize = getTypeSize(IntTy);
3652   // GCC extension compatibility: if the bit-field size is less than or equal
3653   // to the size of int, it gets promoted no matter what its type is.
3654   // For instance, unsigned long bf : 4 gets promoted to signed int.
3655   if (BitWidth < IntSize)
3656     return IntTy;
3657 
3658   if (BitWidth == IntSize)
3659     return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3660 
3661   // Types bigger than int are not subject to promotions, and therefore act
3662   // like the base type.
3663   // FIXME: This doesn't quite match what gcc does, but what gcc does here
3664   // is ridiculous.
3665   return QualType();
3666 }
3667 
3668 /// getPromotedIntegerType - Returns the type that Promotable will
3669 /// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3670 /// integer type.
3671 QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
3672   assert(!Promotable.isNull());
3673   assert(Promotable->isPromotableIntegerType());
3674   if (const EnumType *ET = Promotable->getAs<EnumType>())
3675     return ET->getDecl()->getPromotionType();
3676 
3677   if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
3678     // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
3679     // (3.9.1) can be converted to a prvalue of the first of the following
3680     // types that can represent all the values of its underlying type:
3681     // int, unsigned int, long int, unsigned long int, long long int, or
3682     // unsigned long long int [...]
3683     // FIXME: Is there some better way to compute this?
3684     if (BT->getKind() == BuiltinType::WChar_S ||
3685         BT->getKind() == BuiltinType::WChar_U ||
3686         BT->getKind() == BuiltinType::Char16 ||
3687         BT->getKind() == BuiltinType::Char32) {
3688       bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
3689       uint64_t FromSize = getTypeSize(BT);
3690       QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
3691                                   LongLongTy, UnsignedLongLongTy };
3692       for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
3693         uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
3694         if (FromSize < ToSize ||
3695             (FromSize == ToSize &&
3696              FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
3697           return PromoteTypes[Idx];
3698       }
3699       llvm_unreachable("char type should fit into long long");
3700     }
3701   }
3702 
3703   // At this point, we should have a signed or unsigned integer type.
3704   if (Promotable->isSignedIntegerType())
3705     return IntTy;
3706   uint64_t PromotableSize = getTypeSize(Promotable);
3707   uint64_t IntSize = getTypeSize(IntTy);
3708   assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3709   return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3710 }
3711 
3712 /// \brief Recurses in pointer/array types until it finds an objc retainable
3713 /// type and returns its ownership.
3714 Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
3715   while (!T.isNull()) {
3716     if (T.getObjCLifetime() != Qualifiers::OCL_None)
3717       return T.getObjCLifetime();
3718     if (T->isArrayType())
3719       T = getBaseElementType(T);
3720     else if (const PointerType *PT = T->getAs<PointerType>())
3721       T = PT->getPointeeType();
3722     else if (const ReferenceType *RT = T->getAs<ReferenceType>())
3723       T = RT->getPointeeType();
3724     else
3725       break;
3726   }
3727 
3728   return Qualifiers::OCL_None;
3729 }
3730 
3731 /// getIntegerTypeOrder - Returns the highest ranked integer type:
3732 /// C99 6.3.1.8p1.  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
3733 /// LHS < RHS, return -1.
3734 int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
3735   const Type *LHSC = getCanonicalType(LHS).getTypePtr();
3736   const Type *RHSC = getCanonicalType(RHS).getTypePtr();
3737   if (LHSC == RHSC) return 0;
3738 
3739   bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3740   bool RHSUnsigned = RHSC->isUnsignedIntegerType();
3741 
3742   unsigned LHSRank = getIntegerRank(LHSC);
3743   unsigned RHSRank = getIntegerRank(RHSC);
3744 
3745   if (LHSUnsigned == RHSUnsigned) {  // Both signed or both unsigned.
3746     if (LHSRank == RHSRank) return 0;
3747     return LHSRank > RHSRank ? 1 : -1;
3748   }
3749 
3750   // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3751   if (LHSUnsigned) {
3752     // If the unsigned [LHS] type is larger, return it.
3753     if (LHSRank >= RHSRank)
3754       return 1;
3755 
3756     // If the signed type can represent all values of the unsigned type, it
3757     // wins.  Because we are dealing with 2's complement and types that are
3758     // powers of two larger than each other, this is always safe.
3759     return -1;
3760   }
3761 
3762   // If the unsigned [RHS] type is larger, return it.
3763   if (RHSRank >= LHSRank)
3764     return -1;
3765 
3766   // If the signed type can represent all values of the unsigned type, it
3767   // wins.  Because we are dealing with 2's complement and types that are
3768   // powers of two larger than each other, this is always safe.
3769   return 1;
3770 }
3771 
3772 static RecordDecl *
3773 CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
3774                  DeclContext *DC, IdentifierInfo *Id) {
3775   SourceLocation Loc;
3776   if (Ctx.getLangOptions().CPlusPlus)
3777     return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
3778   else
3779     return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
3780 }
3781 
3782 // getCFConstantStringType - Return the type used for constant CFStrings.
3783 QualType ASTContext::getCFConstantStringType() const {
3784   if (!CFConstantStringTypeDecl) {
3785     CFConstantStringTypeDecl =
3786       CreateRecordDecl(*this, TTK_Struct, TUDecl,
3787                        &Idents.get("NSConstantString"));
3788     CFConstantStringTypeDecl->startDefinition();
3789 
3790     QualType FieldTypes[4];
3791 
3792     // const int *isa;
3793     FieldTypes[0] = getPointerType(IntTy.withConst());
3794     // int flags;
3795     FieldTypes[1] = IntTy;
3796     // const char *str;
3797     FieldTypes[2] = getPointerType(CharTy.withConst());
3798     // long length;
3799     FieldTypes[3] = LongTy;
3800 
3801     // Create fields
3802     for (unsigned i = 0; i < 4; ++i) {
3803       FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
3804                                            SourceLocation(),
3805                                            SourceLocation(), 0,
3806                                            FieldTypes[i], /*TInfo=*/0,
3807                                            /*BitWidth=*/0,
3808                                            /*Mutable=*/false,
3809                                            /*HasInit=*/false);
3810       Field->setAccess(AS_public);
3811       CFConstantStringTypeDecl->addDecl(Field);
3812     }
3813 
3814     CFConstantStringTypeDecl->completeDefinition();
3815   }
3816 
3817   return getTagDeclType(CFConstantStringTypeDecl);
3818 }
3819 
3820 void ASTContext::setCFConstantStringType(QualType T) {
3821   const RecordType *Rec = T->getAs<RecordType>();
3822   assert(Rec && "Invalid CFConstantStringType");
3823   CFConstantStringTypeDecl = Rec->getDecl();
3824 }
3825 
3826 QualType ASTContext::getBlockDescriptorType() const {
3827   if (BlockDescriptorType)
3828     return getTagDeclType(BlockDescriptorType);
3829 
3830   RecordDecl *T;
3831   // FIXME: Needs the FlagAppleBlock bit.
3832   T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
3833                        &Idents.get("__block_descriptor"));
3834   T->startDefinition();
3835 
3836   QualType FieldTypes[] = {
3837     UnsignedLongTy,
3838     UnsignedLongTy,
3839   };
3840 
3841   const char *FieldNames[] = {
3842     "reserved",
3843     "Size"
3844   };
3845 
3846   for (size_t i = 0; i < 2; ++i) {
3847     FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3848                                          SourceLocation(),
3849                                          &Idents.get(FieldNames[i]),
3850                                          FieldTypes[i], /*TInfo=*/0,
3851                                          /*BitWidth=*/0,
3852                                          /*Mutable=*/false,
3853                                          /*HasInit=*/false);
3854     Field->setAccess(AS_public);
3855     T->addDecl(Field);
3856   }
3857 
3858   T->completeDefinition();
3859 
3860   BlockDescriptorType = T;
3861 
3862   return getTagDeclType(BlockDescriptorType);
3863 }
3864 
3865 QualType ASTContext::getBlockDescriptorExtendedType() const {
3866   if (BlockDescriptorExtendedType)
3867     return getTagDeclType(BlockDescriptorExtendedType);
3868 
3869   RecordDecl *T;
3870   // FIXME: Needs the FlagAppleBlock bit.
3871   T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
3872                        &Idents.get("__block_descriptor_withcopydispose"));
3873   T->startDefinition();
3874 
3875   QualType FieldTypes[] = {
3876     UnsignedLongTy,
3877     UnsignedLongTy,
3878     getPointerType(VoidPtrTy),
3879     getPointerType(VoidPtrTy)
3880   };
3881 
3882   const char *FieldNames[] = {
3883     "reserved",
3884     "Size",
3885     "CopyFuncPtr",
3886     "DestroyFuncPtr"
3887   };
3888 
3889   for (size_t i = 0; i < 4; ++i) {
3890     FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3891                                          SourceLocation(),
3892                                          &Idents.get(FieldNames[i]),
3893                                          FieldTypes[i], /*TInfo=*/0,
3894                                          /*BitWidth=*/0,
3895                                          /*Mutable=*/false,
3896                                          /*HasInit=*/false);
3897     Field->setAccess(AS_public);
3898     T->addDecl(Field);
3899   }
3900 
3901   T->completeDefinition();
3902 
3903   BlockDescriptorExtendedType = T;
3904 
3905   return getTagDeclType(BlockDescriptorExtendedType);
3906 }
3907 
3908 bool ASTContext::BlockRequiresCopying(QualType Ty) const {
3909   if (Ty->isObjCRetainableType())
3910     return true;
3911   if (getLangOptions().CPlusPlus) {
3912     if (const RecordType *RT = Ty->getAs<RecordType>()) {
3913       CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3914       return RD->hasConstCopyConstructor();
3915 
3916     }
3917   }
3918   return false;
3919 }
3920 
3921 QualType
3922 ASTContext::BuildByRefType(StringRef DeclName, QualType Ty) const {
3923   //  type = struct __Block_byref_1_X {
3924   //    void *__isa;
3925   //    struct __Block_byref_1_X *__forwarding;
3926   //    unsigned int __flags;
3927   //    unsigned int __size;
3928   //    void *__copy_helper;            // as needed
3929   //    void *__destroy_help            // as needed
3930   //    int X;
3931   //  } *
3932 
3933   bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3934 
3935   // FIXME: Move up
3936   llvm::SmallString<36> Name;
3937   llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3938                                   ++UniqueBlockByRefTypeID << '_' << DeclName;
3939   RecordDecl *T;
3940   T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
3941   T->startDefinition();
3942   QualType Int32Ty = IntTy;
3943   assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3944   QualType FieldTypes[] = {
3945     getPointerType(VoidPtrTy),
3946     getPointerType(getTagDeclType(T)),
3947     Int32Ty,
3948     Int32Ty,
3949     getPointerType(VoidPtrTy),
3950     getPointerType(VoidPtrTy),
3951     Ty
3952   };
3953 
3954   StringRef FieldNames[] = {
3955     "__isa",
3956     "__forwarding",
3957     "__flags",
3958     "__size",
3959     "__copy_helper",
3960     "__destroy_helper",
3961     DeclName,
3962   };
3963 
3964   for (size_t i = 0; i < 7; ++i) {
3965     if (!HasCopyAndDispose && i >=4 && i <= 5)
3966       continue;
3967     FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3968                                          SourceLocation(),
3969                                          &Idents.get(FieldNames[i]),
3970                                          FieldTypes[i], /*TInfo=*/0,
3971                                          /*BitWidth=*/0, /*Mutable=*/false,
3972                                          /*HasInit=*/false);
3973     Field->setAccess(AS_public);
3974     T->addDecl(Field);
3975   }
3976 
3977   T->completeDefinition();
3978 
3979   return getPointerType(getTagDeclType(T));
3980 }
3981 
3982 TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
3983   if (!ObjCInstanceTypeDecl)
3984     ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
3985                                                getTranslationUnitDecl(),
3986                                                SourceLocation(),
3987                                                SourceLocation(),
3988                                                &Idents.get("instancetype"),
3989                                      getTrivialTypeSourceInfo(getObjCIdType()));
3990   return ObjCInstanceTypeDecl;
3991 }
3992 
3993 // This returns true if a type has been typedefed to BOOL:
3994 // typedef <type> BOOL;
3995 static bool isTypeTypedefedAsBOOL(QualType T) {
3996   if (const TypedefType *TT = dyn_cast<TypedefType>(T))
3997     if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3998       return II->isStr("BOOL");
3999 
4000   return false;
4001 }
4002 
4003 /// getObjCEncodingTypeSize returns size of type for objective-c encoding
4004 /// purpose.
4005 CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
4006   if (!type->isIncompleteArrayType() && type->isIncompleteType())
4007     return CharUnits::Zero();
4008 
4009   CharUnits sz = getTypeSizeInChars(type);
4010 
4011   // Make all integer and enum types at least as large as an int
4012   if (sz.isPositive() && type->isIntegralOrEnumerationType())
4013     sz = std::max(sz, getTypeSizeInChars(IntTy));
4014   // Treat arrays as pointers, since that's how they're passed in.
4015   else if (type->isArrayType())
4016     sz = getTypeSizeInChars(VoidPtrTy);
4017   return sz;
4018 }
4019 
4020 static inline
4021 std::string charUnitsToString(const CharUnits &CU) {
4022   return llvm::itostr(CU.getQuantity());
4023 }
4024 
4025 /// getObjCEncodingForBlock - Return the encoded type for this block
4026 /// declaration.
4027 std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4028   std::string S;
4029 
4030   const BlockDecl *Decl = Expr->getBlockDecl();
4031   QualType BlockTy =
4032       Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4033   // Encode result type.
4034   getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
4035   // Compute size of all parameters.
4036   // Start with computing size of a pointer in number of bytes.
4037   // FIXME: There might(should) be a better way of doing this computation!
4038   SourceLocation Loc;
4039   CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4040   CharUnits ParmOffset = PtrSize;
4041   for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
4042        E = Decl->param_end(); PI != E; ++PI) {
4043     QualType PType = (*PI)->getType();
4044     CharUnits sz = getObjCEncodingTypeSize(PType);
4045     assert (sz.isPositive() && "BlockExpr - Incomplete param type");
4046     ParmOffset += sz;
4047   }
4048   // Size of the argument frame
4049   S += charUnitsToString(ParmOffset);
4050   // Block pointer and offset.
4051   S += "@?0";
4052 
4053   // Argument types.
4054   ParmOffset = PtrSize;
4055   for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4056        Decl->param_end(); PI != E; ++PI) {
4057     ParmVarDecl *PVDecl = *PI;
4058     QualType PType = PVDecl->getOriginalType();
4059     if (const ArrayType *AT =
4060           dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4061       // Use array's original type only if it has known number of
4062       // elements.
4063       if (!isa<ConstantArrayType>(AT))
4064         PType = PVDecl->getType();
4065     } else if (PType->isFunctionType())
4066       PType = PVDecl->getType();
4067     getObjCEncodingForType(PType, S);
4068     S += charUnitsToString(ParmOffset);
4069     ParmOffset += getObjCEncodingTypeSize(PType);
4070   }
4071 
4072   return S;
4073 }
4074 
4075 bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
4076                                                 std::string& S) {
4077   // Encode result type.
4078   getObjCEncodingForType(Decl->getResultType(), S);
4079   CharUnits ParmOffset;
4080   // Compute size of all parameters.
4081   for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4082        E = Decl->param_end(); PI != E; ++PI) {
4083     QualType PType = (*PI)->getType();
4084     CharUnits sz = getObjCEncodingTypeSize(PType);
4085     if (sz.isZero())
4086       return true;
4087 
4088     assert (sz.isPositive() &&
4089         "getObjCEncodingForFunctionDecl - Incomplete param type");
4090     ParmOffset += sz;
4091   }
4092   S += charUnitsToString(ParmOffset);
4093   ParmOffset = CharUnits::Zero();
4094 
4095   // Argument types.
4096   for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4097        E = Decl->param_end(); PI != E; ++PI) {
4098     ParmVarDecl *PVDecl = *PI;
4099     QualType PType = PVDecl->getOriginalType();
4100     if (const ArrayType *AT =
4101           dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4102       // Use array's original type only if it has known number of
4103       // elements.
4104       if (!isa<ConstantArrayType>(AT))
4105         PType = PVDecl->getType();
4106     } else if (PType->isFunctionType())
4107       PType = PVDecl->getType();
4108     getObjCEncodingForType(PType, S);
4109     S += charUnitsToString(ParmOffset);
4110     ParmOffset += getObjCEncodingTypeSize(PType);
4111   }
4112 
4113   return false;
4114 }
4115 
4116 /// getObjCEncodingForMethodParameter - Return the encoded type for a single
4117 /// method parameter or return type. If Extended, include class names and
4118 /// block object types.
4119 void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4120                                                    QualType T, std::string& S,
4121                                                    bool Extended) const {
4122   // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4123   getObjCEncodingForTypeQualifier(QT, S);
4124   // Encode parameter type.
4125   getObjCEncodingForTypeImpl(T, S, true, true, 0,
4126                              true     /*OutermostType*/,
4127                              false    /*EncodingProperty*/,
4128                              false    /*StructField*/,
4129                              Extended /*EncodeBlockParameters*/,
4130                              Extended /*EncodeClassNames*/);
4131 }
4132 
4133 /// getObjCEncodingForMethodDecl - Return the encoded type for this method
4134 /// declaration.
4135 bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
4136                                               std::string& S,
4137                                               bool Extended) const {
4138   // FIXME: This is not very efficient.
4139   // Encode return type.
4140   getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4141                                     Decl->getResultType(), S, Extended);
4142   // Compute size of all parameters.
4143   // Start with computing size of a pointer in number of bytes.
4144   // FIXME: There might(should) be a better way of doing this computation!
4145   SourceLocation Loc;
4146   CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4147   // The first two arguments (self and _cmd) are pointers; account for
4148   // their size.
4149   CharUnits ParmOffset = 2 * PtrSize;
4150   for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
4151        E = Decl->sel_param_end(); PI != E; ++PI) {
4152     QualType PType = (*PI)->getType();
4153     CharUnits sz = getObjCEncodingTypeSize(PType);
4154     if (sz.isZero())
4155       return true;
4156 
4157     assert (sz.isPositive() &&
4158         "getObjCEncodingForMethodDecl - Incomplete param type");
4159     ParmOffset += sz;
4160   }
4161   S += charUnitsToString(ParmOffset);
4162   S += "@0:";
4163   S += charUnitsToString(PtrSize);
4164 
4165   // Argument types.
4166   ParmOffset = 2 * PtrSize;
4167   for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
4168        E = Decl->sel_param_end(); PI != E; ++PI) {
4169     const ParmVarDecl *PVDecl = *PI;
4170     QualType PType = PVDecl->getOriginalType();
4171     if (const ArrayType *AT =
4172           dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4173       // Use array's original type only if it has known number of
4174       // elements.
4175       if (!isa<ConstantArrayType>(AT))
4176         PType = PVDecl->getType();
4177     } else if (PType->isFunctionType())
4178       PType = PVDecl->getType();
4179     getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4180                                       PType, S, Extended);
4181     S += charUnitsToString(ParmOffset);
4182     ParmOffset += getObjCEncodingTypeSize(PType);
4183   }
4184 
4185   return false;
4186 }
4187 
4188 /// getObjCEncodingForPropertyDecl - Return the encoded type for this
4189 /// property declaration. If non-NULL, Container must be either an
4190 /// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4191 /// NULL when getting encodings for protocol properties.
4192 /// Property attributes are stored as a comma-delimited C string. The simple
4193 /// attributes readonly and bycopy are encoded as single characters. The
4194 /// parametrized attributes, getter=name, setter=name, and ivar=name, are
4195 /// encoded as single characters, followed by an identifier. Property types
4196 /// are also encoded as a parametrized attribute. The characters used to encode
4197 /// these attributes are defined by the following enumeration:
4198 /// @code
4199 /// enum PropertyAttributes {
4200 /// kPropertyReadOnly = 'R',   // property is read-only.
4201 /// kPropertyBycopy = 'C',     // property is a copy of the value last assigned
4202 /// kPropertyByref = '&',  // property is a reference to the value last assigned
4203 /// kPropertyDynamic = 'D',    // property is dynamic
4204 /// kPropertyGetter = 'G',     // followed by getter selector name
4205 /// kPropertySetter = 'S',     // followed by setter selector name
4206 /// kPropertyInstanceVariable = 'V'  // followed by instance variable  name
4207 /// kPropertyType = 't'              // followed by old-style type encoding.
4208 /// kPropertyWeak = 'W'              // 'weak' property
4209 /// kPropertyStrong = 'P'            // property GC'able
4210 /// kPropertyNonAtomic = 'N'         // property non-atomic
4211 /// };
4212 /// @endcode
4213 void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
4214                                                 const Decl *Container,
4215                                                 std::string& S) const {
4216   // Collect information from the property implementation decl(s).
4217   bool Dynamic = false;
4218   ObjCPropertyImplDecl *SynthesizePID = 0;
4219 
4220   // FIXME: Duplicated code due to poor abstraction.
4221   if (Container) {
4222     if (const ObjCCategoryImplDecl *CID =
4223         dyn_cast<ObjCCategoryImplDecl>(Container)) {
4224       for (ObjCCategoryImplDecl::propimpl_iterator
4225              i = CID->propimpl_begin(), e = CID->propimpl_end();
4226            i != e; ++i) {
4227         ObjCPropertyImplDecl *PID = *i;
4228         if (PID->getPropertyDecl() == PD) {
4229           if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4230             Dynamic = true;
4231           } else {
4232             SynthesizePID = PID;
4233           }
4234         }
4235       }
4236     } else {
4237       const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
4238       for (ObjCCategoryImplDecl::propimpl_iterator
4239              i = OID->propimpl_begin(), e = OID->propimpl_end();
4240            i != e; ++i) {
4241         ObjCPropertyImplDecl *PID = *i;
4242         if (PID->getPropertyDecl() == PD) {
4243           if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4244             Dynamic = true;
4245           } else {
4246             SynthesizePID = PID;
4247           }
4248         }
4249       }
4250     }
4251   }
4252 
4253   // FIXME: This is not very efficient.
4254   S = "T";
4255 
4256   // Encode result type.
4257   // GCC has some special rules regarding encoding of properties which
4258   // closely resembles encoding of ivars.
4259   getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
4260                              true /* outermost type */,
4261                              true /* encoding for property */);
4262 
4263   if (PD->isReadOnly()) {
4264     S += ",R";
4265   } else {
4266     switch (PD->getSetterKind()) {
4267     case ObjCPropertyDecl::Assign: break;
4268     case ObjCPropertyDecl::Copy:   S += ",C"; break;
4269     case ObjCPropertyDecl::Retain: S += ",&"; break;
4270     case ObjCPropertyDecl::Weak:   S += ",W"; break;
4271     }
4272   }
4273 
4274   // It really isn't clear at all what this means, since properties
4275   // are "dynamic by default".
4276   if (Dynamic)
4277     S += ",D";
4278 
4279   if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4280     S += ",N";
4281 
4282   if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4283     S += ",G";
4284     S += PD->getGetterName().getAsString();
4285   }
4286 
4287   if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4288     S += ",S";
4289     S += PD->getSetterName().getAsString();
4290   }
4291 
4292   if (SynthesizePID) {
4293     const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4294     S += ",V";
4295     S += OID->getNameAsString();
4296   }
4297 
4298   // FIXME: OBJCGC: weak & strong
4299 }
4300 
4301 /// getLegacyIntegralTypeEncoding -
4302 /// Another legacy compatibility encoding: 32-bit longs are encoded as
4303 /// 'l' or 'L' , but not always.  For typedefs, we need to use
4304 /// 'i' or 'I' instead if encoding a struct field, or a pointer!
4305 ///
4306 void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
4307   if (isa<TypedefType>(PointeeTy.getTypePtr())) {
4308     if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
4309       if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
4310         PointeeTy = UnsignedIntTy;
4311       else
4312         if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
4313           PointeeTy = IntTy;
4314     }
4315   }
4316 }
4317 
4318 void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
4319                                         const FieldDecl *Field) const {
4320   // We follow the behavior of gcc, expanding structures which are
4321   // directly pointed to, and expanding embedded structures. Note that
4322   // these rules are sufficient to prevent recursive encoding of the
4323   // same type.
4324   getObjCEncodingForTypeImpl(T, S, true, true, Field,
4325                              true /* outermost type */);
4326 }
4327 
4328 static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
4329     switch (T->getAs<BuiltinType>()->getKind()) {
4330     default: llvm_unreachable("Unhandled builtin type kind");
4331     case BuiltinType::Void:       return 'v';
4332     case BuiltinType::Bool:       return 'B';
4333     case BuiltinType::Char_U:
4334     case BuiltinType::UChar:      return 'C';
4335     case BuiltinType::UShort:     return 'S';
4336     case BuiltinType::UInt:       return 'I';
4337     case BuiltinType::ULong:
4338         return C->getIntWidth(T) == 32 ? 'L' : 'Q';
4339     case BuiltinType::UInt128:    return 'T';
4340     case BuiltinType::ULongLong:  return 'Q';
4341     case BuiltinType::Char_S:
4342     case BuiltinType::SChar:      return 'c';
4343     case BuiltinType::Short:      return 's';
4344     case BuiltinType::WChar_S:
4345     case BuiltinType::WChar_U:
4346     case BuiltinType::Int:        return 'i';
4347     case BuiltinType::Long:
4348       return C->getIntWidth(T) == 32 ? 'l' : 'q';
4349     case BuiltinType::LongLong:   return 'q';
4350     case BuiltinType::Int128:     return 't';
4351     case BuiltinType::Float:      return 'f';
4352     case BuiltinType::Double:     return 'd';
4353     case BuiltinType::LongDouble: return 'D';
4354     }
4355 }
4356 
4357 static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
4358   EnumDecl *Enum = ET->getDecl();
4359 
4360   // The encoding of an non-fixed enum type is always 'i', regardless of size.
4361   if (!Enum->isFixed())
4362     return 'i';
4363 
4364   // The encoding of a fixed enum type matches its fixed underlying type.
4365   return ObjCEncodingForPrimitiveKind(C, Enum->getIntegerType());
4366 }
4367 
4368 static void EncodeBitField(const ASTContext *Ctx, std::string& S,
4369                            QualType T, const FieldDecl *FD) {
4370   assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
4371   S += 'b';
4372   // The NeXT runtime encodes bit fields as b followed by the number of bits.
4373   // The GNU runtime requires more information; bitfields are encoded as b,
4374   // then the offset (in bits) of the first element, then the type of the
4375   // bitfield, then the size in bits.  For example, in this structure:
4376   //
4377   // struct
4378   // {
4379   //    int integer;
4380   //    int flags:2;
4381   // };
4382   // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4383   // runtime, but b32i2 for the GNU runtime.  The reason for this extra
4384   // information is not especially sensible, but we're stuck with it for
4385   // compatibility with GCC, although providing it breaks anything that
4386   // actually uses runtime introspection and wants to work on both runtimes...
4387   if (!Ctx->getLangOptions().NeXTRuntime) {
4388     const RecordDecl *RD = FD->getParent();
4389     const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
4390     S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
4391     if (const EnumType *ET = T->getAs<EnumType>())
4392       S += ObjCEncodingForEnumType(Ctx, ET);
4393     else
4394       S += ObjCEncodingForPrimitiveKind(Ctx, T);
4395   }
4396   S += llvm::utostr(FD->getBitWidthValue(*Ctx));
4397 }
4398 
4399 // FIXME: Use SmallString for accumulating string.
4400 void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4401                                             bool ExpandPointedToStructures,
4402                                             bool ExpandStructures,
4403                                             const FieldDecl *FD,
4404                                             bool OutermostType,
4405                                             bool EncodingProperty,
4406                                             bool StructField,
4407                                             bool EncodeBlockParameters,
4408                                             bool EncodeClassNames) const {
4409   if (T->getAs<BuiltinType>()) {
4410     if (FD && FD->isBitField())
4411       return EncodeBitField(this, S, T, FD);
4412     S += ObjCEncodingForPrimitiveKind(this, T);
4413     return;
4414   }
4415 
4416   if (const ComplexType *CT = T->getAs<ComplexType>()) {
4417     S += 'j';
4418     getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
4419                                false);
4420     return;
4421   }
4422 
4423   // encoding for pointer or r3eference types.
4424   QualType PointeeTy;
4425   if (const PointerType *PT = T->getAs<PointerType>()) {
4426     if (PT->isObjCSelType()) {
4427       S += ':';
4428       return;
4429     }
4430     PointeeTy = PT->getPointeeType();
4431   }
4432   else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4433     PointeeTy = RT->getPointeeType();
4434   if (!PointeeTy.isNull()) {
4435     bool isReadOnly = false;
4436     // For historical/compatibility reasons, the read-only qualifier of the
4437     // pointee gets emitted _before_ the '^'.  The read-only qualifier of
4438     // the pointer itself gets ignored, _unless_ we are looking at a typedef!
4439     // Also, do not emit the 'r' for anything but the outermost type!
4440     if (isa<TypedefType>(T.getTypePtr())) {
4441       if (OutermostType && T.isConstQualified()) {
4442         isReadOnly = true;
4443         S += 'r';
4444       }
4445     } else if (OutermostType) {
4446       QualType P = PointeeTy;
4447       while (P->getAs<PointerType>())
4448         P = P->getAs<PointerType>()->getPointeeType();
4449       if (P.isConstQualified()) {
4450         isReadOnly = true;
4451         S += 'r';
4452       }
4453     }
4454     if (isReadOnly) {
4455       // Another legacy compatibility encoding. Some ObjC qualifier and type
4456       // combinations need to be rearranged.
4457       // Rewrite "in const" from "nr" to "rn"
4458       if (StringRef(S).endswith("nr"))
4459         S.replace(S.end()-2, S.end(), "rn");
4460     }
4461 
4462     if (PointeeTy->isCharType()) {
4463       // char pointer types should be encoded as '*' unless it is a
4464       // type that has been typedef'd to 'BOOL'.
4465       if (!isTypeTypedefedAsBOOL(PointeeTy)) {
4466         S += '*';
4467         return;
4468       }
4469     } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
4470       // GCC binary compat: Need to convert "struct objc_class *" to "#".
4471       if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4472         S += '#';
4473         return;
4474       }
4475       // GCC binary compat: Need to convert "struct objc_object *" to "@".
4476       if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4477         S += '@';
4478         return;
4479       }
4480       // fall through...
4481     }
4482     S += '^';
4483     getLegacyIntegralTypeEncoding(PointeeTy);
4484 
4485     getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
4486                                NULL);
4487     return;
4488   }
4489 
4490   if (const ArrayType *AT =
4491       // Ignore type qualifiers etc.
4492         dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
4493     if (isa<IncompleteArrayType>(AT) && !StructField) {
4494       // Incomplete arrays are encoded as a pointer to the array element.
4495       S += '^';
4496 
4497       getObjCEncodingForTypeImpl(AT->getElementType(), S,
4498                                  false, ExpandStructures, FD);
4499     } else {
4500       S += '[';
4501 
4502       if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4503         if (getTypeSize(CAT->getElementType()) == 0)
4504           S += '0';
4505         else
4506           S += llvm::utostr(CAT->getSize().getZExtValue());
4507       } else {
4508         //Variable length arrays are encoded as a regular array with 0 elements.
4509         assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
4510                "Unknown array type!");
4511         S += '0';
4512       }
4513 
4514       getObjCEncodingForTypeImpl(AT->getElementType(), S,
4515                                  false, ExpandStructures, FD);
4516       S += ']';
4517     }
4518     return;
4519   }
4520 
4521   if (T->getAs<FunctionType>()) {
4522     S += '?';
4523     return;
4524   }
4525 
4526   if (const RecordType *RTy = T->getAs<RecordType>()) {
4527     RecordDecl *RDecl = RTy->getDecl();
4528     S += RDecl->isUnion() ? '(' : '{';
4529     // Anonymous structures print as '?'
4530     if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4531       S += II->getName();
4532       if (ClassTemplateSpecializationDecl *Spec
4533           = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4534         const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4535         std::string TemplateArgsStr
4536           = TemplateSpecializationType::PrintTemplateArgumentList(
4537                                             TemplateArgs.data(),
4538                                             TemplateArgs.size(),
4539                                             (*this).getPrintingPolicy());
4540 
4541         S += TemplateArgsStr;
4542       }
4543     } else {
4544       S += '?';
4545     }
4546     if (ExpandStructures) {
4547       S += '=';
4548       if (!RDecl->isUnion()) {
4549         getObjCEncodingForStructureImpl(RDecl, S, FD);
4550       } else {
4551         for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4552                                      FieldEnd = RDecl->field_end();
4553              Field != FieldEnd; ++Field) {
4554           if (FD) {
4555             S += '"';
4556             S += Field->getNameAsString();
4557             S += '"';
4558           }
4559 
4560           // Special case bit-fields.
4561           if (Field->isBitField()) {
4562             getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
4563                                        (*Field));
4564           } else {
4565             QualType qt = Field->getType();
4566             getLegacyIntegralTypeEncoding(qt);
4567             getObjCEncodingForTypeImpl(qt, S, false, true,
4568                                        FD, /*OutermostType*/false,
4569                                        /*EncodingProperty*/false,
4570                                        /*StructField*/true);
4571           }
4572         }
4573       }
4574     }
4575     S += RDecl->isUnion() ? ')' : '}';
4576     return;
4577   }
4578 
4579   if (const EnumType *ET = T->getAs<EnumType>()) {
4580     if (FD && FD->isBitField())
4581       EncodeBitField(this, S, T, FD);
4582     else
4583       S += ObjCEncodingForEnumType(this, ET);
4584     return;
4585   }
4586 
4587   if (const BlockPointerType *BT = T->getAs<BlockPointerType>()) {
4588     S += "@?"; // Unlike a pointer-to-function, which is "^?".
4589     if (EncodeBlockParameters) {
4590       const FunctionType *FT = BT->getPointeeType()->getAs<FunctionType>();
4591 
4592       S += '<';
4593       // Block return type
4594       getObjCEncodingForTypeImpl(FT->getResultType(), S,
4595                                  ExpandPointedToStructures, ExpandStructures,
4596                                  FD,
4597                                  false /* OutermostType */,
4598                                  EncodingProperty,
4599                                  false /* StructField */,
4600                                  EncodeBlockParameters,
4601                                  EncodeClassNames);
4602       // Block self
4603       S += "@?";
4604       // Block parameters
4605       if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
4606         for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
4607                E = FPT->arg_type_end(); I && (I != E); ++I) {
4608           getObjCEncodingForTypeImpl(*I, S,
4609                                      ExpandPointedToStructures,
4610                                      ExpandStructures,
4611                                      FD,
4612                                      false /* OutermostType */,
4613                                      EncodingProperty,
4614                                      false /* StructField */,
4615                                      EncodeBlockParameters,
4616                                      EncodeClassNames);
4617         }
4618       }
4619       S += '>';
4620     }
4621     return;
4622   }
4623 
4624   // Ignore protocol qualifiers when mangling at this level.
4625   if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4626     T = OT->getBaseType();
4627 
4628   if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
4629     // @encode(class_name)
4630     ObjCInterfaceDecl *OI = OIT->getDecl();
4631     S += '{';
4632     const IdentifierInfo *II = OI->getIdentifier();
4633     S += II->getName();
4634     S += '=';
4635     SmallVector<const ObjCIvarDecl*, 32> Ivars;
4636     DeepCollectObjCIvars(OI, true, Ivars);
4637     for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
4638       const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
4639       if (Field->isBitField())
4640         getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
4641       else
4642         getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
4643     }
4644     S += '}';
4645     return;
4646   }
4647 
4648   if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
4649     if (OPT->isObjCIdType()) {
4650       S += '@';
4651       return;
4652     }
4653 
4654     if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4655       // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4656       // Since this is a binary compatibility issue, need to consult with runtime
4657       // folks. Fortunately, this is a *very* obsure construct.
4658       S += '#';
4659       return;
4660     }
4661 
4662     if (OPT->isObjCQualifiedIdType()) {
4663       getObjCEncodingForTypeImpl(getObjCIdType(), S,
4664                                  ExpandPointedToStructures,
4665                                  ExpandStructures, FD);
4666       if (FD || EncodingProperty || EncodeClassNames) {
4667         // Note that we do extended encoding of protocol qualifer list
4668         // Only when doing ivar or property encoding.
4669         S += '"';
4670         for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4671              E = OPT->qual_end(); I != E; ++I) {
4672           S += '<';
4673           S += (*I)->getNameAsString();
4674           S += '>';
4675         }
4676         S += '"';
4677       }
4678       return;
4679     }
4680 
4681     QualType PointeeTy = OPT->getPointeeType();
4682     if (!EncodingProperty &&
4683         isa<TypedefType>(PointeeTy.getTypePtr())) {
4684       // Another historical/compatibility reason.
4685       // We encode the underlying type which comes out as
4686       // {...};
4687       S += '^';
4688       getObjCEncodingForTypeImpl(PointeeTy, S,
4689                                  false, ExpandPointedToStructures,
4690                                  NULL);
4691       return;
4692     }
4693 
4694     S += '@';
4695     if (OPT->getInterfaceDecl() &&
4696         (FD || EncodingProperty || EncodeClassNames)) {
4697       S += '"';
4698       S += OPT->getInterfaceDecl()->getIdentifier()->getName();
4699       for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4700            E = OPT->qual_end(); I != E; ++I) {
4701         S += '<';
4702         S += (*I)->getNameAsString();
4703         S += '>';
4704       }
4705       S += '"';
4706     }
4707     return;
4708   }
4709 
4710   // gcc just blithely ignores member pointers.
4711   // TODO: maybe there should be a mangling for these
4712   if (T->getAs<MemberPointerType>())
4713     return;
4714 
4715   if (T->isVectorType()) {
4716     // This matches gcc's encoding, even though technically it is
4717     // insufficient.
4718     // FIXME. We should do a better job than gcc.
4719     return;
4720   }
4721 
4722   llvm_unreachable("@encode for type not implemented!");
4723 }
4724 
4725 void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
4726                                                  std::string &S,
4727                                                  const FieldDecl *FD,
4728                                                  bool includeVBases) const {
4729   assert(RDecl && "Expected non-null RecordDecl");
4730   assert(!RDecl->isUnion() && "Should not be called for unions");
4731   if (!RDecl->getDefinition())
4732     return;
4733 
4734   CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
4735   std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
4736   const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
4737 
4738   if (CXXRec) {
4739     for (CXXRecordDecl::base_class_iterator
4740            BI = CXXRec->bases_begin(),
4741            BE = CXXRec->bases_end(); BI != BE; ++BI) {
4742       if (!BI->isVirtual()) {
4743         CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
4744         if (base->isEmpty())
4745           continue;
4746         uint64_t offs = layout.getBaseClassOffsetInBits(base);
4747         FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4748                                   std::make_pair(offs, base));
4749       }
4750     }
4751   }
4752 
4753   unsigned i = 0;
4754   for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4755                                FieldEnd = RDecl->field_end();
4756        Field != FieldEnd; ++Field, ++i) {
4757     uint64_t offs = layout.getFieldOffset(i);
4758     FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4759                               std::make_pair(offs, *Field));
4760   }
4761 
4762   if (CXXRec && includeVBases) {
4763     for (CXXRecordDecl::base_class_iterator
4764            BI = CXXRec->vbases_begin(),
4765            BE = CXXRec->vbases_end(); BI != BE; ++BI) {
4766       CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
4767       if (base->isEmpty())
4768         continue;
4769       uint64_t offs = layout.getVBaseClassOffsetInBits(base);
4770       if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
4771         FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
4772                                   std::make_pair(offs, base));
4773     }
4774   }
4775 
4776   CharUnits size;
4777   if (CXXRec) {
4778     size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
4779   } else {
4780     size = layout.getSize();
4781   }
4782 
4783   uint64_t CurOffs = 0;
4784   std::multimap<uint64_t, NamedDecl *>::iterator
4785     CurLayObj = FieldOrBaseOffsets.begin();
4786 
4787   if ((CurLayObj != FieldOrBaseOffsets.end() && CurLayObj->first != 0) ||
4788       (CurLayObj == FieldOrBaseOffsets.end() &&
4789          CXXRec && CXXRec->isDynamicClass())) {
4790     assert(CXXRec && CXXRec->isDynamicClass() &&
4791            "Offset 0 was empty but no VTable ?");
4792     if (FD) {
4793       S += "\"_vptr$";
4794       std::string recname = CXXRec->getNameAsString();
4795       if (recname.empty()) recname = "?";
4796       S += recname;
4797       S += '"';
4798     }
4799     S += "^^?";
4800     CurOffs += getTypeSize(VoidPtrTy);
4801   }
4802 
4803   if (!RDecl->hasFlexibleArrayMember()) {
4804     // Mark the end of the structure.
4805     uint64_t offs = toBits(size);
4806     FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4807                               std::make_pair(offs, (NamedDecl*)0));
4808   }
4809 
4810   for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
4811     assert(CurOffs <= CurLayObj->first);
4812 
4813     if (CurOffs < CurLayObj->first) {
4814       uint64_t padding = CurLayObj->first - CurOffs;
4815       // FIXME: There doesn't seem to be a way to indicate in the encoding that
4816       // packing/alignment of members is different that normal, in which case
4817       // the encoding will be out-of-sync with the real layout.
4818       // If the runtime switches to just consider the size of types without
4819       // taking into account alignment, we could make padding explicit in the
4820       // encoding (e.g. using arrays of chars). The encoding strings would be
4821       // longer then though.
4822       CurOffs += padding;
4823     }
4824 
4825     NamedDecl *dcl = CurLayObj->second;
4826     if (dcl == 0)
4827       break; // reached end of structure.
4828 
4829     if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
4830       // We expand the bases without their virtual bases since those are going
4831       // in the initial structure. Note that this differs from gcc which
4832       // expands virtual bases each time one is encountered in the hierarchy,
4833       // making the encoding type bigger than it really is.
4834       getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
4835       assert(!base->isEmpty());
4836       CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
4837     } else {
4838       FieldDecl *field = cast<FieldDecl>(dcl);
4839       if (FD) {
4840         S += '"';
4841         S += field->getNameAsString();
4842         S += '"';
4843       }
4844 
4845       if (field->isBitField()) {
4846         EncodeBitField(this, S, field->getType(), field);
4847         CurOffs += field->getBitWidthValue(*this);
4848       } else {
4849         QualType qt = field->getType();
4850         getLegacyIntegralTypeEncoding(qt);
4851         getObjCEncodingForTypeImpl(qt, S, false, true, FD,
4852                                    /*OutermostType*/false,
4853                                    /*EncodingProperty*/false,
4854                                    /*StructField*/true);
4855         CurOffs += getTypeSize(field->getType());
4856       }
4857     }
4858   }
4859 }
4860 
4861 void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
4862                                                  std::string& S) const {
4863   if (QT & Decl::OBJC_TQ_In)
4864     S += 'n';
4865   if (QT & Decl::OBJC_TQ_Inout)
4866     S += 'N';
4867   if (QT & Decl::OBJC_TQ_Out)
4868     S += 'o';
4869   if (QT & Decl::OBJC_TQ_Bycopy)
4870     S += 'O';
4871   if (QT & Decl::OBJC_TQ_Byref)
4872     S += 'R';
4873   if (QT & Decl::OBJC_TQ_Oneway)
4874     S += 'V';
4875 }
4876 
4877 void ASTContext::setBuiltinVaListType(QualType T) {
4878   assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
4879 
4880   BuiltinVaListType = T;
4881 }
4882 
4883 TypedefDecl *ASTContext::getObjCIdDecl() const {
4884   if (!ObjCIdDecl) {
4885     QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
4886     T = getObjCObjectPointerType(T);
4887     TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
4888     ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4889                                      getTranslationUnitDecl(),
4890                                      SourceLocation(), SourceLocation(),
4891                                      &Idents.get("id"), IdInfo);
4892   }
4893 
4894   return ObjCIdDecl;
4895 }
4896 
4897 TypedefDecl *ASTContext::getObjCSelDecl() const {
4898   if (!ObjCSelDecl) {
4899     QualType SelT = getPointerType(ObjCBuiltinSelTy);
4900     TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
4901     ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4902                                       getTranslationUnitDecl(),
4903                                       SourceLocation(), SourceLocation(),
4904                                       &Idents.get("SEL"), SelInfo);
4905   }
4906   return ObjCSelDecl;
4907 }
4908 
4909 TypedefDecl *ASTContext::getObjCClassDecl() const {
4910   if (!ObjCClassDecl) {
4911     QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
4912     T = getObjCObjectPointerType(T);
4913     TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
4914     ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4915                                         getTranslationUnitDecl(),
4916                                         SourceLocation(), SourceLocation(),
4917                                         &Idents.get("Class"), ClassInfo);
4918   }
4919 
4920   return ObjCClassDecl;
4921 }
4922 
4923 ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
4924   if (!ObjCProtocolClassDecl) {
4925     ObjCProtocolClassDecl
4926       = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
4927                                   SourceLocation(),
4928                                   &Idents.get("Protocol"),
4929                                   /*PrevDecl=*/0,
4930                                   SourceLocation(), true);
4931   }
4932 
4933   return ObjCProtocolClassDecl;
4934 }
4935 
4936 void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
4937   assert(ObjCConstantStringType.isNull() &&
4938          "'NSConstantString' type already set!");
4939 
4940   ObjCConstantStringType = getObjCInterfaceType(Decl);
4941 }
4942 
4943 /// \brief Retrieve the template name that corresponds to a non-empty
4944 /// lookup.
4945 TemplateName
4946 ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
4947                                       UnresolvedSetIterator End) const {
4948   unsigned size = End - Begin;
4949   assert(size > 1 && "set is not overloaded!");
4950 
4951   void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
4952                           size * sizeof(FunctionTemplateDecl*));
4953   OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
4954 
4955   NamedDecl **Storage = OT->getStorage();
4956   for (UnresolvedSetIterator I = Begin; I != End; ++I) {
4957     NamedDecl *D = *I;
4958     assert(isa<FunctionTemplateDecl>(D) ||
4959            (isa<UsingShadowDecl>(D) &&
4960             isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4961     *Storage++ = D;
4962   }
4963 
4964   return TemplateName(OT);
4965 }
4966 
4967 /// \brief Retrieve the template name that represents a qualified
4968 /// template name such as \c std::vector.
4969 TemplateName
4970 ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
4971                                      bool TemplateKeyword,
4972                                      TemplateDecl *Template) const {
4973   assert(NNS && "Missing nested-name-specifier in qualified template name");
4974 
4975   // FIXME: Canonicalization?
4976   llvm::FoldingSetNodeID ID;
4977   QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4978 
4979   void *InsertPos = 0;
4980   QualifiedTemplateName *QTN =
4981     QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4982   if (!QTN) {
4983     QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4984     QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4985   }
4986 
4987   return TemplateName(QTN);
4988 }
4989 
4990 /// \brief Retrieve the template name that represents a dependent
4991 /// template name such as \c MetaFun::template apply.
4992 TemplateName
4993 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4994                                      const IdentifierInfo *Name) const {
4995   assert((!NNS || NNS->isDependent()) &&
4996          "Nested name specifier must be dependent");
4997 
4998   llvm::FoldingSetNodeID ID;
4999   DependentTemplateName::Profile(ID, NNS, Name);
5000 
5001   void *InsertPos = 0;
5002   DependentTemplateName *QTN =
5003     DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5004 
5005   if (QTN)
5006     return TemplateName(QTN);
5007 
5008   NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5009   if (CanonNNS == NNS) {
5010     QTN = new (*this,4) DependentTemplateName(NNS, Name);
5011   } else {
5012     TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
5013     QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
5014     DependentTemplateName *CheckQTN =
5015       DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5016     assert(!CheckQTN && "Dependent type name canonicalization broken");
5017     (void)CheckQTN;
5018   }
5019 
5020   DependentTemplateNames.InsertNode(QTN, InsertPos);
5021   return TemplateName(QTN);
5022 }
5023 
5024 /// \brief Retrieve the template name that represents a dependent
5025 /// template name such as \c MetaFun::template operator+.
5026 TemplateName
5027 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
5028                                      OverloadedOperatorKind Operator) const {
5029   assert((!NNS || NNS->isDependent()) &&
5030          "Nested name specifier must be dependent");
5031 
5032   llvm::FoldingSetNodeID ID;
5033   DependentTemplateName::Profile(ID, NNS, Operator);
5034 
5035   void *InsertPos = 0;
5036   DependentTemplateName *QTN
5037     = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5038 
5039   if (QTN)
5040     return TemplateName(QTN);
5041 
5042   NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5043   if (CanonNNS == NNS) {
5044     QTN = new (*this,4) DependentTemplateName(NNS, Operator);
5045   } else {
5046     TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
5047     QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
5048 
5049     DependentTemplateName *CheckQTN
5050       = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5051     assert(!CheckQTN && "Dependent template name canonicalization broken");
5052     (void)CheckQTN;
5053   }
5054 
5055   DependentTemplateNames.InsertNode(QTN, InsertPos);
5056   return TemplateName(QTN);
5057 }
5058 
5059 TemplateName
5060 ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
5061                                          TemplateName replacement) const {
5062   llvm::FoldingSetNodeID ID;
5063   SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
5064 
5065   void *insertPos = 0;
5066   SubstTemplateTemplateParmStorage *subst
5067     = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
5068 
5069   if (!subst) {
5070     subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
5071     SubstTemplateTemplateParms.InsertNode(subst, insertPos);
5072   }
5073 
5074   return TemplateName(subst);
5075 }
5076 
5077 TemplateName
5078 ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
5079                                        const TemplateArgument &ArgPack) const {
5080   ASTContext &Self = const_cast<ASTContext &>(*this);
5081   llvm::FoldingSetNodeID ID;
5082   SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
5083 
5084   void *InsertPos = 0;
5085   SubstTemplateTemplateParmPackStorage *Subst
5086     = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
5087 
5088   if (!Subst) {
5089     Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
5090                                                            ArgPack.pack_size(),
5091                                                          ArgPack.pack_begin());
5092     SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
5093   }
5094 
5095   return TemplateName(Subst);
5096 }
5097 
5098 /// getFromTargetType - Given one of the integer types provided by
5099 /// TargetInfo, produce the corresponding type. The unsigned @p Type
5100 /// is actually a value of type @c TargetInfo::IntType.
5101 CanQualType ASTContext::getFromTargetType(unsigned Type) const {
5102   switch (Type) {
5103   case TargetInfo::NoInt: return CanQualType();
5104   case TargetInfo::SignedShort: return ShortTy;
5105   case TargetInfo::UnsignedShort: return UnsignedShortTy;
5106   case TargetInfo::SignedInt: return IntTy;
5107   case TargetInfo::UnsignedInt: return UnsignedIntTy;
5108   case TargetInfo::SignedLong: return LongTy;
5109   case TargetInfo::UnsignedLong: return UnsignedLongTy;
5110   case TargetInfo::SignedLongLong: return LongLongTy;
5111   case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
5112   }
5113 
5114   llvm_unreachable("Unhandled TargetInfo::IntType value");
5115 }
5116 
5117 //===----------------------------------------------------------------------===//
5118 //                        Type Predicates.
5119 //===----------------------------------------------------------------------===//
5120 
5121 /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
5122 /// garbage collection attribute.
5123 ///
5124 Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
5125   if (getLangOptions().getGC() == LangOptions::NonGC)
5126     return Qualifiers::GCNone;
5127 
5128   assert(getLangOptions().ObjC1);
5129   Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
5130 
5131   // Default behaviour under objective-C's gc is for ObjC pointers
5132   // (or pointers to them) be treated as though they were declared
5133   // as __strong.
5134   if (GCAttrs == Qualifiers::GCNone) {
5135     if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
5136       return Qualifiers::Strong;
5137     else if (Ty->isPointerType())
5138       return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
5139   } else {
5140     // It's not valid to set GC attributes on anything that isn't a
5141     // pointer.
5142 #ifndef NDEBUG
5143     QualType CT = Ty->getCanonicalTypeInternal();
5144     while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
5145       CT = AT->getElementType();
5146     assert(CT->isAnyPointerType() || CT->isBlockPointerType());
5147 #endif
5148   }
5149   return GCAttrs;
5150 }
5151 
5152 //===----------------------------------------------------------------------===//
5153 //                        Type Compatibility Testing
5154 //===----------------------------------------------------------------------===//
5155 
5156 /// areCompatVectorTypes - Return true if the two specified vector types are
5157 /// compatible.
5158 static bool areCompatVectorTypes(const VectorType *LHS,
5159                                  const VectorType *RHS) {
5160   assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
5161   return LHS->getElementType() == RHS->getElementType() &&
5162          LHS->getNumElements() == RHS->getNumElements();
5163 }
5164 
5165 bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
5166                                           QualType SecondVec) {
5167   assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
5168   assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
5169 
5170   if (hasSameUnqualifiedType(FirstVec, SecondVec))
5171     return true;
5172 
5173   // Treat Neon vector types and most AltiVec vector types as if they are the
5174   // equivalent GCC vector types.
5175   const VectorType *First = FirstVec->getAs<VectorType>();
5176   const VectorType *Second = SecondVec->getAs<VectorType>();
5177   if (First->getNumElements() == Second->getNumElements() &&
5178       hasSameType(First->getElementType(), Second->getElementType()) &&
5179       First->getVectorKind() != VectorType::AltiVecPixel &&
5180       First->getVectorKind() != VectorType::AltiVecBool &&
5181       Second->getVectorKind() != VectorType::AltiVecPixel &&
5182       Second->getVectorKind() != VectorType::AltiVecBool)
5183     return true;
5184 
5185   return false;
5186 }
5187 
5188 //===----------------------------------------------------------------------===//
5189 // ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
5190 //===----------------------------------------------------------------------===//
5191 
5192 /// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
5193 /// inheritance hierarchy of 'rProto'.
5194 bool
5195 ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
5196                                            ObjCProtocolDecl *rProto) const {
5197   if (declaresSameEntity(lProto, rProto))
5198     return true;
5199   for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
5200        E = rProto->protocol_end(); PI != E; ++PI)
5201     if (ProtocolCompatibleWithProtocol(lProto, *PI))
5202       return true;
5203   return false;
5204 }
5205 
5206 /// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
5207 /// return true if lhs's protocols conform to rhs's protocol; false
5208 /// otherwise.
5209 bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
5210   if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
5211     return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
5212   return false;
5213 }
5214 
5215 /// ObjCQualifiedClassTypesAreCompatible - compare  Class<p,...> and
5216 /// Class<p1, ...>.
5217 bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
5218                                                       QualType rhs) {
5219   const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
5220   const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
5221   assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
5222 
5223   for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5224        E = lhsQID->qual_end(); I != E; ++I) {
5225     bool match = false;
5226     ObjCProtocolDecl *lhsProto = *I;
5227     for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5228          E = rhsOPT->qual_end(); J != E; ++J) {
5229       ObjCProtocolDecl *rhsProto = *J;
5230       if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
5231         match = true;
5232         break;
5233       }
5234     }
5235     if (!match)
5236       return false;
5237   }
5238   return true;
5239 }
5240 
5241 /// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
5242 /// ObjCQualifiedIDType.
5243 bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
5244                                                    bool compare) {
5245   // Allow id<P..> and an 'id' or void* type in all cases.
5246   if (lhs->isVoidPointerType() ||
5247       lhs->isObjCIdType() || lhs->isObjCClassType())
5248     return true;
5249   else if (rhs->isVoidPointerType() ||
5250            rhs->isObjCIdType() || rhs->isObjCClassType())
5251     return true;
5252 
5253   if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
5254     const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
5255 
5256     if (!rhsOPT) return false;
5257 
5258     if (rhsOPT->qual_empty()) {
5259       // If the RHS is a unqualified interface pointer "NSString*",
5260       // make sure we check the class hierarchy.
5261       if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5262         for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5263              E = lhsQID->qual_end(); I != E; ++I) {
5264           // when comparing an id<P> on lhs with a static type on rhs,
5265           // see if static class implements all of id's protocols, directly or
5266           // through its super class and categories.
5267           if (!rhsID->ClassImplementsProtocol(*I, true))
5268             return false;
5269         }
5270       }
5271       // If there are no qualifiers and no interface, we have an 'id'.
5272       return true;
5273     }
5274     // Both the right and left sides have qualifiers.
5275     for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5276          E = lhsQID->qual_end(); I != E; ++I) {
5277       ObjCProtocolDecl *lhsProto = *I;
5278       bool match = false;
5279 
5280       // when comparing an id<P> on lhs with a static type on rhs,
5281       // see if static class implements all of id's protocols, directly or
5282       // through its super class and categories.
5283       for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5284            E = rhsOPT->qual_end(); J != E; ++J) {
5285         ObjCProtocolDecl *rhsProto = *J;
5286         if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5287             (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5288           match = true;
5289           break;
5290         }
5291       }
5292       // If the RHS is a qualified interface pointer "NSString<P>*",
5293       // make sure we check the class hierarchy.
5294       if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5295         for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5296              E = lhsQID->qual_end(); I != E; ++I) {
5297           // when comparing an id<P> on lhs with a static type on rhs,
5298           // see if static class implements all of id's protocols, directly or
5299           // through its super class and categories.
5300           if (rhsID->ClassImplementsProtocol(*I, true)) {
5301             match = true;
5302             break;
5303           }
5304         }
5305       }
5306       if (!match)
5307         return false;
5308     }
5309 
5310     return true;
5311   }
5312 
5313   const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
5314   assert(rhsQID && "One of the LHS/RHS should be id<x>");
5315 
5316   if (const ObjCObjectPointerType *lhsOPT =
5317         lhs->getAsObjCInterfacePointerType()) {
5318     // If both the right and left sides have qualifiers.
5319     for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
5320          E = lhsOPT->qual_end(); I != E; ++I) {
5321       ObjCProtocolDecl *lhsProto = *I;
5322       bool match = false;
5323 
5324       // when comparing an id<P> on rhs with a static type on lhs,
5325       // see if static class implements all of id's protocols, directly or
5326       // through its super class and categories.
5327       // First, lhs protocols in the qualifier list must be found, direct
5328       // or indirect in rhs's qualifier list or it is a mismatch.
5329       for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5330            E = rhsQID->qual_end(); J != E; ++J) {
5331         ObjCProtocolDecl *rhsProto = *J;
5332         if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5333             (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5334           match = true;
5335           break;
5336         }
5337       }
5338       if (!match)
5339         return false;
5340     }
5341 
5342     // Static class's protocols, or its super class or category protocols
5343     // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
5344     if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
5345       llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
5346       CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
5347       // This is rather dubious but matches gcc's behavior. If lhs has
5348       // no type qualifier and its class has no static protocol(s)
5349       // assume that it is mismatch.
5350       if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
5351         return false;
5352       for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5353            LHSInheritedProtocols.begin(),
5354            E = LHSInheritedProtocols.end(); I != E; ++I) {
5355         bool match = false;
5356         ObjCProtocolDecl *lhsProto = (*I);
5357         for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5358              E = rhsQID->qual_end(); J != E; ++J) {
5359           ObjCProtocolDecl *rhsProto = *J;
5360           if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5361               (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5362             match = true;
5363             break;
5364           }
5365         }
5366         if (!match)
5367           return false;
5368       }
5369     }
5370     return true;
5371   }
5372   return false;
5373 }
5374 
5375 /// canAssignObjCInterfaces - Return true if the two interface types are
5376 /// compatible for assignment from RHS to LHS.  This handles validation of any
5377 /// protocol qualifiers on the LHS or RHS.
5378 ///
5379 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
5380                                          const ObjCObjectPointerType *RHSOPT) {
5381   const ObjCObjectType* LHS = LHSOPT->getObjectType();
5382   const ObjCObjectType* RHS = RHSOPT->getObjectType();
5383 
5384   // If either type represents the built-in 'id' or 'Class' types, return true.
5385   if (LHS->isObjCUnqualifiedIdOrClass() ||
5386       RHS->isObjCUnqualifiedIdOrClass())
5387     return true;
5388 
5389   if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
5390     return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5391                                              QualType(RHSOPT,0),
5392                                              false);
5393 
5394   if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
5395     return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
5396                                                 QualType(RHSOPT,0));
5397 
5398   // If we have 2 user-defined types, fall into that path.
5399   if (LHS->getInterface() && RHS->getInterface())
5400     return canAssignObjCInterfaces(LHS, RHS);
5401 
5402   return false;
5403 }
5404 
5405 /// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
5406 /// for providing type-safety for objective-c pointers used to pass/return
5407 /// arguments in block literals. When passed as arguments, passing 'A*' where
5408 /// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
5409 /// not OK. For the return type, the opposite is not OK.
5410 bool ASTContext::canAssignObjCInterfacesInBlockPointer(
5411                                          const ObjCObjectPointerType *LHSOPT,
5412                                          const ObjCObjectPointerType *RHSOPT,
5413                                          bool BlockReturnType) {
5414   if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
5415     return true;
5416 
5417   if (LHSOPT->isObjCBuiltinType()) {
5418     return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
5419   }
5420 
5421   if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
5422     return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5423                                              QualType(RHSOPT,0),
5424                                              false);
5425 
5426   const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
5427   const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
5428   if (LHS && RHS)  { // We have 2 user-defined types.
5429     if (LHS != RHS) {
5430       if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
5431         return BlockReturnType;
5432       if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
5433         return !BlockReturnType;
5434     }
5435     else
5436       return true;
5437   }
5438   return false;
5439 }
5440 
5441 /// getIntersectionOfProtocols - This routine finds the intersection of set
5442 /// of protocols inherited from two distinct objective-c pointer objects.
5443 /// It is used to build composite qualifier list of the composite type of
5444 /// the conditional expression involving two objective-c pointer objects.
5445 static
5446 void getIntersectionOfProtocols(ASTContext &Context,
5447                                 const ObjCObjectPointerType *LHSOPT,
5448                                 const ObjCObjectPointerType *RHSOPT,
5449       SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
5450 
5451   const ObjCObjectType* LHS = LHSOPT->getObjectType();
5452   const ObjCObjectType* RHS = RHSOPT->getObjectType();
5453   assert(LHS->getInterface() && "LHS must have an interface base");
5454   assert(RHS->getInterface() && "RHS must have an interface base");
5455 
5456   llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
5457   unsigned LHSNumProtocols = LHS->getNumProtocols();
5458   if (LHSNumProtocols > 0)
5459     InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
5460   else {
5461     llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
5462     Context.CollectInheritedProtocols(LHS->getInterface(),
5463                                       LHSInheritedProtocols);
5464     InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
5465                                 LHSInheritedProtocols.end());
5466   }
5467 
5468   unsigned RHSNumProtocols = RHS->getNumProtocols();
5469   if (RHSNumProtocols > 0) {
5470     ObjCProtocolDecl **RHSProtocols =
5471       const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
5472     for (unsigned i = 0; i < RHSNumProtocols; ++i)
5473       if (InheritedProtocolSet.count(RHSProtocols[i]))
5474         IntersectionOfProtocols.push_back(RHSProtocols[i]);
5475   } else {
5476     llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
5477     Context.CollectInheritedProtocols(RHS->getInterface(),
5478                                       RHSInheritedProtocols);
5479     for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5480          RHSInheritedProtocols.begin(),
5481          E = RHSInheritedProtocols.end(); I != E; ++I)
5482       if (InheritedProtocolSet.count((*I)))
5483         IntersectionOfProtocols.push_back((*I));
5484   }
5485 }
5486 
5487 /// areCommonBaseCompatible - Returns common base class of the two classes if
5488 /// one found. Note that this is O'2 algorithm. But it will be called as the
5489 /// last type comparison in a ?-exp of ObjC pointer types before a
5490 /// warning is issued. So, its invokation is extremely rare.
5491 QualType ASTContext::areCommonBaseCompatible(
5492                                           const ObjCObjectPointerType *Lptr,
5493                                           const ObjCObjectPointerType *Rptr) {
5494   const ObjCObjectType *LHS = Lptr->getObjectType();
5495   const ObjCObjectType *RHS = Rptr->getObjectType();
5496   const ObjCInterfaceDecl* LDecl = LHS->getInterface();
5497   const ObjCInterfaceDecl* RDecl = RHS->getInterface();
5498   if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
5499     return QualType();
5500 
5501   do {
5502     LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
5503     if (canAssignObjCInterfaces(LHS, RHS)) {
5504       SmallVector<ObjCProtocolDecl *, 8> Protocols;
5505       getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
5506 
5507       QualType Result = QualType(LHS, 0);
5508       if (!Protocols.empty())
5509         Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
5510       Result = getObjCObjectPointerType(Result);
5511       return Result;
5512     }
5513   } while ((LDecl = LDecl->getSuperClass()));
5514 
5515   return QualType();
5516 }
5517 
5518 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
5519                                          const ObjCObjectType *RHS) {
5520   assert(LHS->getInterface() && "LHS is not an interface type");
5521   assert(RHS->getInterface() && "RHS is not an interface type");
5522 
5523   // Verify that the base decls are compatible: the RHS must be a subclass of
5524   // the LHS.
5525   if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
5526     return false;
5527 
5528   // RHS must have a superset of the protocols in the LHS.  If the LHS is not
5529   // protocol qualified at all, then we are good.
5530   if (LHS->getNumProtocols() == 0)
5531     return true;
5532 
5533   // Okay, we know the LHS has protocol qualifiers.  If the RHS doesn't,
5534   // more detailed analysis is required.
5535   if (RHS->getNumProtocols() == 0) {
5536     // OK, if LHS is a superclass of RHS *and*
5537     // this superclass is assignment compatible with LHS.
5538     // false otherwise.
5539     bool IsSuperClass =
5540       LHS->getInterface()->isSuperClassOf(RHS->getInterface());
5541     if (IsSuperClass) {
5542       // OK if conversion of LHS to SuperClass results in narrowing of types
5543       // ; i.e., SuperClass may implement at least one of the protocols
5544       // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
5545       // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
5546       llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
5547       CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
5548       // If super class has no protocols, it is not a match.
5549       if (SuperClassInheritedProtocols.empty())
5550         return false;
5551 
5552       for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5553            LHSPE = LHS->qual_end();
5554            LHSPI != LHSPE; LHSPI++) {
5555         bool SuperImplementsProtocol = false;
5556         ObjCProtocolDecl *LHSProto = (*LHSPI);
5557 
5558         for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5559              SuperClassInheritedProtocols.begin(),
5560              E = SuperClassInheritedProtocols.end(); I != E; ++I) {
5561           ObjCProtocolDecl *SuperClassProto = (*I);
5562           if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
5563             SuperImplementsProtocol = true;
5564             break;
5565           }
5566         }
5567         if (!SuperImplementsProtocol)
5568           return false;
5569       }
5570       return true;
5571     }
5572     return false;
5573   }
5574 
5575   for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5576                                      LHSPE = LHS->qual_end();
5577        LHSPI != LHSPE; LHSPI++) {
5578     bool RHSImplementsProtocol = false;
5579 
5580     // If the RHS doesn't implement the protocol on the left, the types
5581     // are incompatible.
5582     for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
5583                                        RHSPE = RHS->qual_end();
5584          RHSPI != RHSPE; RHSPI++) {
5585       if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
5586         RHSImplementsProtocol = true;
5587         break;
5588       }
5589     }
5590     // FIXME: For better diagnostics, consider passing back the protocol name.
5591     if (!RHSImplementsProtocol)
5592       return false;
5593   }
5594   // The RHS implements all protocols listed on the LHS.
5595   return true;
5596 }
5597 
5598 bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
5599   // get the "pointed to" types
5600   const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
5601   const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
5602 
5603   if (!LHSOPT || !RHSOPT)
5604     return false;
5605 
5606   return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
5607          canAssignObjCInterfaces(RHSOPT, LHSOPT);
5608 }
5609 
5610 bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
5611   return canAssignObjCInterfaces(
5612                 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
5613                 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
5614 }
5615 
5616 /// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
5617 /// both shall have the identically qualified version of a compatible type.
5618 /// C99 6.2.7p1: Two types have compatible types if their types are the
5619 /// same. See 6.7.[2,3,5] for additional rules.
5620 bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
5621                                     bool CompareUnqualified) {
5622   if (getLangOptions().CPlusPlus)
5623     return hasSameType(LHS, RHS);
5624 
5625   return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
5626 }
5627 
5628 bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
5629   return typesAreCompatible(LHS, RHS);
5630 }
5631 
5632 bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
5633   return !mergeTypes(LHS, RHS, true).isNull();
5634 }
5635 
5636 /// mergeTransparentUnionType - if T is a transparent union type and a member
5637 /// of T is compatible with SubType, return the merged type, else return
5638 /// QualType()
5639 QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
5640                                                bool OfBlockPointer,
5641                                                bool Unqualified) {
5642   if (const RecordType *UT = T->getAsUnionType()) {
5643     RecordDecl *UD = UT->getDecl();
5644     if (UD->hasAttr<TransparentUnionAttr>()) {
5645       for (RecordDecl::field_iterator it = UD->field_begin(),
5646            itend = UD->field_end(); it != itend; ++it) {
5647         QualType ET = it->getType().getUnqualifiedType();
5648         QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
5649         if (!MT.isNull())
5650           return MT;
5651       }
5652     }
5653   }
5654 
5655   return QualType();
5656 }
5657 
5658 /// mergeFunctionArgumentTypes - merge two types which appear as function
5659 /// argument types
5660 QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
5661                                                 bool OfBlockPointer,
5662                                                 bool Unqualified) {
5663   // GNU extension: two types are compatible if they appear as a function
5664   // argument, one of the types is a transparent union type and the other
5665   // type is compatible with a union member
5666   QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
5667                                               Unqualified);
5668   if (!lmerge.isNull())
5669     return lmerge;
5670 
5671   QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
5672                                               Unqualified);
5673   if (!rmerge.isNull())
5674     return rmerge;
5675 
5676   return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
5677 }
5678 
5679 QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
5680                                         bool OfBlockPointer,
5681                                         bool Unqualified) {
5682   const FunctionType *lbase = lhs->getAs<FunctionType>();
5683   const FunctionType *rbase = rhs->getAs<FunctionType>();
5684   const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
5685   const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
5686   bool allLTypes = true;
5687   bool allRTypes = true;
5688 
5689   // Check return type
5690   QualType retType;
5691   if (OfBlockPointer) {
5692     QualType RHS = rbase->getResultType();
5693     QualType LHS = lbase->getResultType();
5694     bool UnqualifiedResult = Unqualified;
5695     if (!UnqualifiedResult)
5696       UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
5697     retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
5698   }
5699   else
5700     retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
5701                          Unqualified);
5702   if (retType.isNull()) return QualType();
5703 
5704   if (Unqualified)
5705     retType = retType.getUnqualifiedType();
5706 
5707   CanQualType LRetType = getCanonicalType(lbase->getResultType());
5708   CanQualType RRetType = getCanonicalType(rbase->getResultType());
5709   if (Unqualified) {
5710     LRetType = LRetType.getUnqualifiedType();
5711     RRetType = RRetType.getUnqualifiedType();
5712   }
5713 
5714   if (getCanonicalType(retType) != LRetType)
5715     allLTypes = false;
5716   if (getCanonicalType(retType) != RRetType)
5717     allRTypes = false;
5718 
5719   // FIXME: double check this
5720   // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
5721   //                           rbase->getRegParmAttr() != 0 &&
5722   //                           lbase->getRegParmAttr() != rbase->getRegParmAttr()?
5723   FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
5724   FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
5725 
5726   // Compatible functions must have compatible calling conventions
5727   if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
5728     return QualType();
5729 
5730   // Regparm is part of the calling convention.
5731   if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
5732     return QualType();
5733   if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
5734     return QualType();
5735 
5736   if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
5737     return QualType();
5738 
5739   // functypes which return are preferred over those that do not.
5740   if (lbaseInfo.getNoReturn() && !rbaseInfo.getNoReturn())
5741     allLTypes = false;
5742   else if (!lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn())
5743     allRTypes = false;
5744   // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
5745   bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
5746 
5747   FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
5748 
5749   if (lproto && rproto) { // two C99 style function prototypes
5750     assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
5751            "C++ shouldn't be here");
5752     unsigned lproto_nargs = lproto->getNumArgs();
5753     unsigned rproto_nargs = rproto->getNumArgs();
5754 
5755     // Compatible functions must have the same number of arguments
5756     if (lproto_nargs != rproto_nargs)
5757       return QualType();
5758 
5759     // Variadic and non-variadic functions aren't compatible
5760     if (lproto->isVariadic() != rproto->isVariadic())
5761       return QualType();
5762 
5763     if (lproto->getTypeQuals() != rproto->getTypeQuals())
5764       return QualType();
5765 
5766     if (LangOpts.ObjCAutoRefCount &&
5767         !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
5768       return QualType();
5769 
5770     // Check argument compatibility
5771     SmallVector<QualType, 10> types;
5772     for (unsigned i = 0; i < lproto_nargs; i++) {
5773       QualType largtype = lproto->getArgType(i).getUnqualifiedType();
5774       QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
5775       QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
5776                                                     OfBlockPointer,
5777                                                     Unqualified);
5778       if (argtype.isNull()) return QualType();
5779 
5780       if (Unqualified)
5781         argtype = argtype.getUnqualifiedType();
5782 
5783       types.push_back(argtype);
5784       if (Unqualified) {
5785         largtype = largtype.getUnqualifiedType();
5786         rargtype = rargtype.getUnqualifiedType();
5787       }
5788 
5789       if (getCanonicalType(argtype) != getCanonicalType(largtype))
5790         allLTypes = false;
5791       if (getCanonicalType(argtype) != getCanonicalType(rargtype))
5792         allRTypes = false;
5793     }
5794 
5795     if (allLTypes) return lhs;
5796     if (allRTypes) return rhs;
5797 
5798     FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
5799     EPI.ExtInfo = einfo;
5800     return getFunctionType(retType, types.begin(), types.size(), EPI);
5801   }
5802 
5803   if (lproto) allRTypes = false;
5804   if (rproto) allLTypes = false;
5805 
5806   const FunctionProtoType *proto = lproto ? lproto : rproto;
5807   if (proto) {
5808     assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
5809     if (proto->isVariadic()) return QualType();
5810     // Check that the types are compatible with the types that
5811     // would result from default argument promotions (C99 6.7.5.3p15).
5812     // The only types actually affected are promotable integer
5813     // types and floats, which would be passed as a different
5814     // type depending on whether the prototype is visible.
5815     unsigned proto_nargs = proto->getNumArgs();
5816     for (unsigned i = 0; i < proto_nargs; ++i) {
5817       QualType argTy = proto->getArgType(i);
5818 
5819       // Look at the promotion type of enum types, since that is the type used
5820       // to pass enum values.
5821       if (const EnumType *Enum = argTy->getAs<EnumType>())
5822         argTy = Enum->getDecl()->getPromotionType();
5823 
5824       if (argTy->isPromotableIntegerType() ||
5825           getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
5826         return QualType();
5827     }
5828 
5829     if (allLTypes) return lhs;
5830     if (allRTypes) return rhs;
5831 
5832     FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
5833     EPI.ExtInfo = einfo;
5834     return getFunctionType(retType, proto->arg_type_begin(),
5835                            proto->getNumArgs(), EPI);
5836   }
5837 
5838   if (allLTypes) return lhs;
5839   if (allRTypes) return rhs;
5840   return getFunctionNoProtoType(retType, einfo);
5841 }
5842 
5843 QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
5844                                 bool OfBlockPointer,
5845                                 bool Unqualified, bool BlockReturnType) {
5846   // C++ [expr]: If an expression initially has the type "reference to T", the
5847   // type is adjusted to "T" prior to any further analysis, the expression
5848   // designates the object or function denoted by the reference, and the
5849   // expression is an lvalue unless the reference is an rvalue reference and
5850   // the expression is a function call (possibly inside parentheses).
5851   assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
5852   assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
5853 
5854   if (Unqualified) {
5855     LHS = LHS.getUnqualifiedType();
5856     RHS = RHS.getUnqualifiedType();
5857   }
5858 
5859   QualType LHSCan = getCanonicalType(LHS),
5860            RHSCan = getCanonicalType(RHS);
5861 
5862   // If two types are identical, they are compatible.
5863   if (LHSCan == RHSCan)
5864     return LHS;
5865 
5866   // If the qualifiers are different, the types aren't compatible... mostly.
5867   Qualifiers LQuals = LHSCan.getLocalQualifiers();
5868   Qualifiers RQuals = RHSCan.getLocalQualifiers();
5869   if (LQuals != RQuals) {
5870     // If any of these qualifiers are different, we have a type
5871     // mismatch.
5872     if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5873         LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
5874         LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
5875       return QualType();
5876 
5877     // Exactly one GC qualifier difference is allowed: __strong is
5878     // okay if the other type has no GC qualifier but is an Objective
5879     // C object pointer (i.e. implicitly strong by default).  We fix
5880     // this by pretending that the unqualified type was actually
5881     // qualified __strong.
5882     Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5883     Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5884     assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5885 
5886     if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5887       return QualType();
5888 
5889     if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
5890       return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
5891     }
5892     if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
5893       return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
5894     }
5895     return QualType();
5896   }
5897 
5898   // Okay, qualifiers are equal.
5899 
5900   Type::TypeClass LHSClass = LHSCan->getTypeClass();
5901   Type::TypeClass RHSClass = RHSCan->getTypeClass();
5902 
5903   // We want to consider the two function types to be the same for these
5904   // comparisons, just force one to the other.
5905   if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
5906   if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
5907 
5908   // Same as above for arrays
5909   if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
5910     LHSClass = Type::ConstantArray;
5911   if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
5912     RHSClass = Type::ConstantArray;
5913 
5914   // ObjCInterfaces are just specialized ObjCObjects.
5915   if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
5916   if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
5917 
5918   // Canonicalize ExtVector -> Vector.
5919   if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
5920   if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
5921 
5922   // If the canonical type classes don't match.
5923   if (LHSClass != RHSClass) {
5924     // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
5925     // a signed integer type, or an unsigned integer type.
5926     // Compatibility is based on the underlying type, not the promotion
5927     // type.
5928     if (const EnumType* ETy = LHS->getAs<EnumType>()) {
5929       if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
5930         return RHS;
5931     }
5932     if (const EnumType* ETy = RHS->getAs<EnumType>()) {
5933       if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
5934         return LHS;
5935     }
5936     // allow block pointer type to match an 'id' type.
5937     if (OfBlockPointer && !BlockReturnType) {
5938        if (LHS->isObjCIdType() && RHS->isBlockPointerType())
5939          return LHS;
5940       if (RHS->isObjCIdType() && LHS->isBlockPointerType())
5941         return RHS;
5942     }
5943 
5944     return QualType();
5945   }
5946 
5947   // The canonical type classes match.
5948   switch (LHSClass) {
5949 #define TYPE(Class, Base)
5950 #define ABSTRACT_TYPE(Class, Base)
5951 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
5952 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5953 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
5954 #include "clang/AST/TypeNodes.def"
5955     llvm_unreachable("Non-canonical and dependent types shouldn't get here");
5956 
5957   case Type::LValueReference:
5958   case Type::RValueReference:
5959   case Type::MemberPointer:
5960     llvm_unreachable("C++ should never be in mergeTypes");
5961 
5962   case Type::ObjCInterface:
5963   case Type::IncompleteArray:
5964   case Type::VariableArray:
5965   case Type::FunctionProto:
5966   case Type::ExtVector:
5967     llvm_unreachable("Types are eliminated above");
5968 
5969   case Type::Pointer:
5970   {
5971     // Merge two pointer types, while trying to preserve typedef info
5972     QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
5973     QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
5974     if (Unqualified) {
5975       LHSPointee = LHSPointee.getUnqualifiedType();
5976       RHSPointee = RHSPointee.getUnqualifiedType();
5977     }
5978     QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
5979                                      Unqualified);
5980     if (ResultType.isNull()) return QualType();
5981     if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
5982       return LHS;
5983     if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
5984       return RHS;
5985     return getPointerType(ResultType);
5986   }
5987   case Type::BlockPointer:
5988   {
5989     // Merge two block pointer types, while trying to preserve typedef info
5990     QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
5991     QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
5992     if (Unqualified) {
5993       LHSPointee = LHSPointee.getUnqualifiedType();
5994       RHSPointee = RHSPointee.getUnqualifiedType();
5995     }
5996     QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
5997                                      Unqualified);
5998     if (ResultType.isNull()) return QualType();
5999     if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
6000       return LHS;
6001     if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
6002       return RHS;
6003     return getBlockPointerType(ResultType);
6004   }
6005   case Type::Atomic:
6006   {
6007     // Merge two pointer types, while trying to preserve typedef info
6008     QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
6009     QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
6010     if (Unqualified) {
6011       LHSValue = LHSValue.getUnqualifiedType();
6012       RHSValue = RHSValue.getUnqualifiedType();
6013     }
6014     QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
6015                                      Unqualified);
6016     if (ResultType.isNull()) return QualType();
6017     if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
6018       return LHS;
6019     if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
6020       return RHS;
6021     return getAtomicType(ResultType);
6022   }
6023   case Type::ConstantArray:
6024   {
6025     const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
6026     const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
6027     if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
6028       return QualType();
6029 
6030     QualType LHSElem = getAsArrayType(LHS)->getElementType();
6031     QualType RHSElem = getAsArrayType(RHS)->getElementType();
6032     if (Unqualified) {
6033       LHSElem = LHSElem.getUnqualifiedType();
6034       RHSElem = RHSElem.getUnqualifiedType();
6035     }
6036 
6037     QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
6038     if (ResultType.isNull()) return QualType();
6039     if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6040       return LHS;
6041     if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6042       return RHS;
6043     if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
6044                                           ArrayType::ArraySizeModifier(), 0);
6045     if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
6046                                           ArrayType::ArraySizeModifier(), 0);
6047     const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
6048     const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
6049     if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6050       return LHS;
6051     if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6052       return RHS;
6053     if (LVAT) {
6054       // FIXME: This isn't correct! But tricky to implement because
6055       // the array's size has to be the size of LHS, but the type
6056       // has to be different.
6057       return LHS;
6058     }
6059     if (RVAT) {
6060       // FIXME: This isn't correct! But tricky to implement because
6061       // the array's size has to be the size of RHS, but the type
6062       // has to be different.
6063       return RHS;
6064     }
6065     if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
6066     if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
6067     return getIncompleteArrayType(ResultType,
6068                                   ArrayType::ArraySizeModifier(), 0);
6069   }
6070   case Type::FunctionNoProto:
6071     return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
6072   case Type::Record:
6073   case Type::Enum:
6074     return QualType();
6075   case Type::Builtin:
6076     // Only exactly equal builtin types are compatible, which is tested above.
6077     return QualType();
6078   case Type::Complex:
6079     // Distinct complex types are incompatible.
6080     return QualType();
6081   case Type::Vector:
6082     // FIXME: The merged type should be an ExtVector!
6083     if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
6084                              RHSCan->getAs<VectorType>()))
6085       return LHS;
6086     return QualType();
6087   case Type::ObjCObject: {
6088     // Check if the types are assignment compatible.
6089     // FIXME: This should be type compatibility, e.g. whether
6090     // "LHS x; RHS x;" at global scope is legal.
6091     const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
6092     const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
6093     if (canAssignObjCInterfaces(LHSIface, RHSIface))
6094       return LHS;
6095 
6096     return QualType();
6097   }
6098   case Type::ObjCObjectPointer: {
6099     if (OfBlockPointer) {
6100       if (canAssignObjCInterfacesInBlockPointer(
6101                                           LHS->getAs<ObjCObjectPointerType>(),
6102                                           RHS->getAs<ObjCObjectPointerType>(),
6103                                           BlockReturnType))
6104         return LHS;
6105       return QualType();
6106     }
6107     if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
6108                                 RHS->getAs<ObjCObjectPointerType>()))
6109       return LHS;
6110 
6111     return QualType();
6112   }
6113   }
6114 
6115   llvm_unreachable("Invalid Type::Class!");
6116 }
6117 
6118 bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
6119                    const FunctionProtoType *FromFunctionType,
6120                    const FunctionProtoType *ToFunctionType) {
6121   if (FromFunctionType->hasAnyConsumedArgs() !=
6122       ToFunctionType->hasAnyConsumedArgs())
6123     return false;
6124   FunctionProtoType::ExtProtoInfo FromEPI =
6125     FromFunctionType->getExtProtoInfo();
6126   FunctionProtoType::ExtProtoInfo ToEPI =
6127     ToFunctionType->getExtProtoInfo();
6128   if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
6129     for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
6130          ArgIdx != NumArgs; ++ArgIdx)  {
6131       if (FromEPI.ConsumedArguments[ArgIdx] !=
6132           ToEPI.ConsumedArguments[ArgIdx])
6133         return false;
6134     }
6135   return true;
6136 }
6137 
6138 /// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
6139 /// 'RHS' attributes and returns the merged version; including for function
6140 /// return types.
6141 QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
6142   QualType LHSCan = getCanonicalType(LHS),
6143   RHSCan = getCanonicalType(RHS);
6144   // If two types are identical, they are compatible.
6145   if (LHSCan == RHSCan)
6146     return LHS;
6147   if (RHSCan->isFunctionType()) {
6148     if (!LHSCan->isFunctionType())
6149       return QualType();
6150     QualType OldReturnType =
6151       cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
6152     QualType NewReturnType =
6153       cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
6154     QualType ResReturnType =
6155       mergeObjCGCQualifiers(NewReturnType, OldReturnType);
6156     if (ResReturnType.isNull())
6157       return QualType();
6158     if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
6159       // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
6160       // In either case, use OldReturnType to build the new function type.
6161       const FunctionType *F = LHS->getAs<FunctionType>();
6162       if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
6163         FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6164         EPI.ExtInfo = getFunctionExtInfo(LHS);
6165         QualType ResultType
6166           = getFunctionType(OldReturnType, FPT->arg_type_begin(),
6167                             FPT->getNumArgs(), EPI);
6168         return ResultType;
6169       }
6170     }
6171     return QualType();
6172   }
6173 
6174   // If the qualifiers are different, the types can still be merged.
6175   Qualifiers LQuals = LHSCan.getLocalQualifiers();
6176   Qualifiers RQuals = RHSCan.getLocalQualifiers();
6177   if (LQuals != RQuals) {
6178     // If any of these qualifiers are different, we have a type mismatch.
6179     if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
6180         LQuals.getAddressSpace() != RQuals.getAddressSpace())
6181       return QualType();
6182 
6183     // Exactly one GC qualifier difference is allowed: __strong is
6184     // okay if the other type has no GC qualifier but is an Objective
6185     // C object pointer (i.e. implicitly strong by default).  We fix
6186     // this by pretending that the unqualified type was actually
6187     // qualified __strong.
6188     Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6189     Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6190     assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6191 
6192     if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6193       return QualType();
6194 
6195     if (GC_L == Qualifiers::Strong)
6196       return LHS;
6197     if (GC_R == Qualifiers::Strong)
6198       return RHS;
6199     return QualType();
6200   }
6201 
6202   if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
6203     QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6204     QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6205     QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
6206     if (ResQT == LHSBaseQT)
6207       return LHS;
6208     if (ResQT == RHSBaseQT)
6209       return RHS;
6210   }
6211   return QualType();
6212 }
6213 
6214 //===----------------------------------------------------------------------===//
6215 //                         Integer Predicates
6216 //===----------------------------------------------------------------------===//
6217 
6218 unsigned ASTContext::getIntWidth(QualType T) const {
6219   if (const EnumType *ET = dyn_cast<EnumType>(T))
6220     T = ET->getDecl()->getIntegerType();
6221   if (T->isBooleanType())
6222     return 1;
6223   // For builtin types, just use the standard type sizing method
6224   return (unsigned)getTypeSize(T);
6225 }
6226 
6227 QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
6228   assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
6229 
6230   // Turn <4 x signed int> -> <4 x unsigned int>
6231   if (const VectorType *VTy = T->getAs<VectorType>())
6232     return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
6233                          VTy->getNumElements(), VTy->getVectorKind());
6234 
6235   // For enums, we return the unsigned version of the base type.
6236   if (const EnumType *ETy = T->getAs<EnumType>())
6237     T = ETy->getDecl()->getIntegerType();
6238 
6239   const BuiltinType *BTy = T->getAs<BuiltinType>();
6240   assert(BTy && "Unexpected signed integer type");
6241   switch (BTy->getKind()) {
6242   case BuiltinType::Char_S:
6243   case BuiltinType::SChar:
6244     return UnsignedCharTy;
6245   case BuiltinType::Short:
6246     return UnsignedShortTy;
6247   case BuiltinType::Int:
6248     return UnsignedIntTy;
6249   case BuiltinType::Long:
6250     return UnsignedLongTy;
6251   case BuiltinType::LongLong:
6252     return UnsignedLongLongTy;
6253   case BuiltinType::Int128:
6254     return UnsignedInt128Ty;
6255   default:
6256     llvm_unreachable("Unexpected signed integer type");
6257   }
6258 }
6259 
6260 ASTMutationListener::~ASTMutationListener() { }
6261 
6262 
6263 //===----------------------------------------------------------------------===//
6264 //                          Builtin Type Computation
6265 //===----------------------------------------------------------------------===//
6266 
6267 /// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
6268 /// pointer over the consumed characters.  This returns the resultant type.  If
6269 /// AllowTypeModifiers is false then modifier like * are not parsed, just basic
6270 /// types.  This allows "v2i*" to be parsed as a pointer to a v2i instead of
6271 /// a vector of "i*".
6272 ///
6273 /// RequiresICE is filled in on return to indicate whether the value is required
6274 /// to be an Integer Constant Expression.
6275 static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
6276                                   ASTContext::GetBuiltinTypeError &Error,
6277                                   bool &RequiresICE,
6278                                   bool AllowTypeModifiers) {
6279   // Modifiers.
6280   int HowLong = 0;
6281   bool Signed = false, Unsigned = false;
6282   RequiresICE = false;
6283 
6284   // Read the prefixed modifiers first.
6285   bool Done = false;
6286   while (!Done) {
6287     switch (*Str++) {
6288     default: Done = true; --Str; break;
6289     case 'I':
6290       RequiresICE = true;
6291       break;
6292     case 'S':
6293       assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
6294       assert(!Signed && "Can't use 'S' modifier multiple times!");
6295       Signed = true;
6296       break;
6297     case 'U':
6298       assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
6299       assert(!Unsigned && "Can't use 'S' modifier multiple times!");
6300       Unsigned = true;
6301       break;
6302     case 'L':
6303       assert(HowLong <= 2 && "Can't have LLLL modifier");
6304       ++HowLong;
6305       break;
6306     }
6307   }
6308 
6309   QualType Type;
6310 
6311   // Read the base type.
6312   switch (*Str++) {
6313   default: llvm_unreachable("Unknown builtin type letter!");
6314   case 'v':
6315     assert(HowLong == 0 && !Signed && !Unsigned &&
6316            "Bad modifiers used with 'v'!");
6317     Type = Context.VoidTy;
6318     break;
6319   case 'f':
6320     assert(HowLong == 0 && !Signed && !Unsigned &&
6321            "Bad modifiers used with 'f'!");
6322     Type = Context.FloatTy;
6323     break;
6324   case 'd':
6325     assert(HowLong < 2 && !Signed && !Unsigned &&
6326            "Bad modifiers used with 'd'!");
6327     if (HowLong)
6328       Type = Context.LongDoubleTy;
6329     else
6330       Type = Context.DoubleTy;
6331     break;
6332   case 's':
6333     assert(HowLong == 0 && "Bad modifiers used with 's'!");
6334     if (Unsigned)
6335       Type = Context.UnsignedShortTy;
6336     else
6337       Type = Context.ShortTy;
6338     break;
6339   case 'i':
6340     if (HowLong == 3)
6341       Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
6342     else if (HowLong == 2)
6343       Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
6344     else if (HowLong == 1)
6345       Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
6346     else
6347       Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
6348     break;
6349   case 'c':
6350     assert(HowLong == 0 && "Bad modifiers used with 'c'!");
6351     if (Signed)
6352       Type = Context.SignedCharTy;
6353     else if (Unsigned)
6354       Type = Context.UnsignedCharTy;
6355     else
6356       Type = Context.CharTy;
6357     break;
6358   case 'b': // boolean
6359     assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
6360     Type = Context.BoolTy;
6361     break;
6362   case 'z':  // size_t.
6363     assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
6364     Type = Context.getSizeType();
6365     break;
6366   case 'F':
6367     Type = Context.getCFConstantStringType();
6368     break;
6369   case 'G':
6370     Type = Context.getObjCIdType();
6371     break;
6372   case 'H':
6373     Type = Context.getObjCSelType();
6374     break;
6375   case 'a':
6376     Type = Context.getBuiltinVaListType();
6377     assert(!Type.isNull() && "builtin va list type not initialized!");
6378     break;
6379   case 'A':
6380     // This is a "reference" to a va_list; however, what exactly
6381     // this means depends on how va_list is defined. There are two
6382     // different kinds of va_list: ones passed by value, and ones
6383     // passed by reference.  An example of a by-value va_list is
6384     // x86, where va_list is a char*. An example of by-ref va_list
6385     // is x86-64, where va_list is a __va_list_tag[1]. For x86,
6386     // we want this argument to be a char*&; for x86-64, we want
6387     // it to be a __va_list_tag*.
6388     Type = Context.getBuiltinVaListType();
6389     assert(!Type.isNull() && "builtin va list type not initialized!");
6390     if (Type->isArrayType())
6391       Type = Context.getArrayDecayedType(Type);
6392     else
6393       Type = Context.getLValueReferenceType(Type);
6394     break;
6395   case 'V': {
6396     char *End;
6397     unsigned NumElements = strtoul(Str, &End, 10);
6398     assert(End != Str && "Missing vector size");
6399     Str = End;
6400 
6401     QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
6402                                              RequiresICE, false);
6403     assert(!RequiresICE && "Can't require vector ICE");
6404 
6405     // TODO: No way to make AltiVec vectors in builtins yet.
6406     Type = Context.getVectorType(ElementType, NumElements,
6407                                  VectorType::GenericVector);
6408     break;
6409   }
6410   case 'X': {
6411     QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6412                                              false);
6413     assert(!RequiresICE && "Can't require complex ICE");
6414     Type = Context.getComplexType(ElementType);
6415     break;
6416   }
6417   case 'Y' : {
6418     Type = Context.getPointerDiffType();
6419     break;
6420   }
6421   case 'P':
6422     Type = Context.getFILEType();
6423     if (Type.isNull()) {
6424       Error = ASTContext::GE_Missing_stdio;
6425       return QualType();
6426     }
6427     break;
6428   case 'J':
6429     if (Signed)
6430       Type = Context.getsigjmp_bufType();
6431     else
6432       Type = Context.getjmp_bufType();
6433 
6434     if (Type.isNull()) {
6435       Error = ASTContext::GE_Missing_setjmp;
6436       return QualType();
6437     }
6438     break;
6439   case 'K':
6440     assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
6441     Type = Context.getucontext_tType();
6442 
6443     if (Type.isNull()) {
6444       Error = ASTContext::GE_Missing_ucontext;
6445       return QualType();
6446     }
6447     break;
6448   }
6449 
6450   // If there are modifiers and if we're allowed to parse them, go for it.
6451   Done = !AllowTypeModifiers;
6452   while (!Done) {
6453     switch (char c = *Str++) {
6454     default: Done = true; --Str; break;
6455     case '*':
6456     case '&': {
6457       // Both pointers and references can have their pointee types
6458       // qualified with an address space.
6459       char *End;
6460       unsigned AddrSpace = strtoul(Str, &End, 10);
6461       if (End != Str && AddrSpace != 0) {
6462         Type = Context.getAddrSpaceQualType(Type, AddrSpace);
6463         Str = End;
6464       }
6465       if (c == '*')
6466         Type = Context.getPointerType(Type);
6467       else
6468         Type = Context.getLValueReferenceType(Type);
6469       break;
6470     }
6471     // FIXME: There's no way to have a built-in with an rvalue ref arg.
6472     case 'C':
6473       Type = Type.withConst();
6474       break;
6475     case 'D':
6476       Type = Context.getVolatileType(Type);
6477       break;
6478     case 'R':
6479       Type = Type.withRestrict();
6480       break;
6481     }
6482   }
6483 
6484   assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
6485          "Integer constant 'I' type must be an integer");
6486 
6487   return Type;
6488 }
6489 
6490 /// GetBuiltinType - Return the type for the specified builtin.
6491 QualType ASTContext::GetBuiltinType(unsigned Id,
6492                                     GetBuiltinTypeError &Error,
6493                                     unsigned *IntegerConstantArgs) const {
6494   const char *TypeStr = BuiltinInfo.GetTypeString(Id);
6495 
6496   SmallVector<QualType, 8> ArgTypes;
6497 
6498   bool RequiresICE = false;
6499   Error = GE_None;
6500   QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
6501                                        RequiresICE, true);
6502   if (Error != GE_None)
6503     return QualType();
6504 
6505   assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
6506 
6507   while (TypeStr[0] && TypeStr[0] != '.') {
6508     QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
6509     if (Error != GE_None)
6510       return QualType();
6511 
6512     // If this argument is required to be an IntegerConstantExpression and the
6513     // caller cares, fill in the bitmask we return.
6514     if (RequiresICE && IntegerConstantArgs)
6515       *IntegerConstantArgs |= 1 << ArgTypes.size();
6516 
6517     // Do array -> pointer decay.  The builtin should use the decayed type.
6518     if (Ty->isArrayType())
6519       Ty = getArrayDecayedType(Ty);
6520 
6521     ArgTypes.push_back(Ty);
6522   }
6523 
6524   assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
6525          "'.' should only occur at end of builtin type list!");
6526 
6527   FunctionType::ExtInfo EI;
6528   if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
6529 
6530   bool Variadic = (TypeStr[0] == '.');
6531 
6532   // We really shouldn't be making a no-proto type here, especially in C++.
6533   if (ArgTypes.empty() && Variadic)
6534     return getFunctionNoProtoType(ResType, EI);
6535 
6536   FunctionProtoType::ExtProtoInfo EPI;
6537   EPI.ExtInfo = EI;
6538   EPI.Variadic = Variadic;
6539 
6540   return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
6541 }
6542 
6543 GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
6544   GVALinkage External = GVA_StrongExternal;
6545 
6546   Linkage L = FD->getLinkage();
6547   switch (L) {
6548   case NoLinkage:
6549   case InternalLinkage:
6550   case UniqueExternalLinkage:
6551     return GVA_Internal;
6552 
6553   case ExternalLinkage:
6554     switch (FD->getTemplateSpecializationKind()) {
6555     case TSK_Undeclared:
6556     case TSK_ExplicitSpecialization:
6557       External = GVA_StrongExternal;
6558       break;
6559 
6560     case TSK_ExplicitInstantiationDefinition:
6561       return GVA_ExplicitTemplateInstantiation;
6562 
6563     case TSK_ExplicitInstantiationDeclaration:
6564     case TSK_ImplicitInstantiation:
6565       External = GVA_TemplateInstantiation;
6566       break;
6567     }
6568   }
6569 
6570   if (!FD->isInlined())
6571     return External;
6572 
6573   if (!getLangOptions().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
6574     // GNU or C99 inline semantics. Determine whether this symbol should be
6575     // externally visible.
6576     if (FD->isInlineDefinitionExternallyVisible())
6577       return External;
6578 
6579     // C99 inline semantics, where the symbol is not externally visible.
6580     return GVA_C99Inline;
6581   }
6582 
6583   // C++0x [temp.explicit]p9:
6584   //   [ Note: The intent is that an inline function that is the subject of
6585   //   an explicit instantiation declaration will still be implicitly
6586   //   instantiated when used so that the body can be considered for
6587   //   inlining, but that no out-of-line copy of the inline function would be
6588   //   generated in the translation unit. -- end note ]
6589   if (FD->getTemplateSpecializationKind()
6590                                        == TSK_ExplicitInstantiationDeclaration)
6591     return GVA_C99Inline;
6592 
6593   return GVA_CXXInline;
6594 }
6595 
6596 GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
6597   // If this is a static data member, compute the kind of template
6598   // specialization. Otherwise, this variable is not part of a
6599   // template.
6600   TemplateSpecializationKind TSK = TSK_Undeclared;
6601   if (VD->isStaticDataMember())
6602     TSK = VD->getTemplateSpecializationKind();
6603 
6604   Linkage L = VD->getLinkage();
6605   if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
6606       VD->getType()->getLinkage() == UniqueExternalLinkage)
6607     L = UniqueExternalLinkage;
6608 
6609   switch (L) {
6610   case NoLinkage:
6611   case InternalLinkage:
6612   case UniqueExternalLinkage:
6613     return GVA_Internal;
6614 
6615   case ExternalLinkage:
6616     switch (TSK) {
6617     case TSK_Undeclared:
6618     case TSK_ExplicitSpecialization:
6619       return GVA_StrongExternal;
6620 
6621     case TSK_ExplicitInstantiationDeclaration:
6622       llvm_unreachable("Variable should not be instantiated");
6623       // Fall through to treat this like any other instantiation.
6624 
6625     case TSK_ExplicitInstantiationDefinition:
6626       return GVA_ExplicitTemplateInstantiation;
6627 
6628     case TSK_ImplicitInstantiation:
6629       return GVA_TemplateInstantiation;
6630     }
6631   }
6632 
6633   llvm_unreachable("Invalid Linkage!");
6634 }
6635 
6636 bool ASTContext::DeclMustBeEmitted(const Decl *D) {
6637   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6638     if (!VD->isFileVarDecl())
6639       return false;
6640   } else if (!isa<FunctionDecl>(D))
6641     return false;
6642 
6643   // Weak references don't produce any output by themselves.
6644   if (D->hasAttr<WeakRefAttr>())
6645     return false;
6646 
6647   // Aliases and used decls are required.
6648   if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
6649     return true;
6650 
6651   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6652     // Forward declarations aren't required.
6653     if (!FD->doesThisDeclarationHaveABody())
6654       return FD->doesDeclarationForceExternallyVisibleDefinition();
6655 
6656     // Constructors and destructors are required.
6657     if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
6658       return true;
6659 
6660     // The key function for a class is required.
6661     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6662       const CXXRecordDecl *RD = MD->getParent();
6663       if (MD->isOutOfLine() && RD->isDynamicClass()) {
6664         const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
6665         if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
6666           return true;
6667       }
6668     }
6669 
6670     GVALinkage Linkage = GetGVALinkageForFunction(FD);
6671 
6672     // static, static inline, always_inline, and extern inline functions can
6673     // always be deferred.  Normal inline functions can be deferred in C99/C++.
6674     // Implicit template instantiations can also be deferred in C++.
6675     if (Linkage == GVA_Internal  || Linkage == GVA_C99Inline ||
6676         Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
6677       return false;
6678     return true;
6679   }
6680 
6681   const VarDecl *VD = cast<VarDecl>(D);
6682   assert(VD->isFileVarDecl() && "Expected file scoped var");
6683 
6684   if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
6685     return false;
6686 
6687   // Structs that have non-trivial constructors or destructors are required.
6688 
6689   // FIXME: Handle references.
6690   // FIXME: Be more selective about which constructors we care about.
6691   if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
6692     if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
6693       if (RD->hasDefinition() && !(RD->hasTrivialDefaultConstructor() &&
6694                                    RD->hasTrivialCopyConstructor() &&
6695                                    RD->hasTrivialMoveConstructor() &&
6696                                    RD->hasTrivialDestructor()))
6697         return true;
6698     }
6699   }
6700 
6701   GVALinkage L = GetGVALinkageForVariable(VD);
6702   if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
6703     if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
6704       return false;
6705   }
6706 
6707   return true;
6708 }
6709 
6710 CallingConv ASTContext::getDefaultMethodCallConv() {
6711   // Pass through to the C++ ABI object
6712   return ABI->getDefaultMethodCallConv();
6713 }
6714 
6715 bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
6716   // Pass through to the C++ ABI object
6717   return ABI->isNearlyEmpty(RD);
6718 }
6719 
6720 MangleContext *ASTContext::createMangleContext() {
6721   switch (Target->getCXXABI()) {
6722   case CXXABI_ARM:
6723   case CXXABI_Itanium:
6724     return createItaniumMangleContext(*this, getDiagnostics());
6725   case CXXABI_Microsoft:
6726     return createMicrosoftMangleContext(*this, getDiagnostics());
6727   }
6728   llvm_unreachable("Unsupported ABI");
6729 }
6730 
6731 CXXABI::~CXXABI() {}
6732 
6733 size_t ASTContext::getSideTableAllocatedMemory() const {
6734   return ASTRecordLayouts.getMemorySize()
6735     + llvm::capacity_in_bytes(ObjCLayouts)
6736     + llvm::capacity_in_bytes(KeyFunctions)
6737     + llvm::capacity_in_bytes(ObjCImpls)
6738     + llvm::capacity_in_bytes(BlockVarCopyInits)
6739     + llvm::capacity_in_bytes(DeclAttrs)
6740     + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
6741     + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
6742     + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
6743     + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
6744     + llvm::capacity_in_bytes(OverriddenMethods)
6745     + llvm::capacity_in_bytes(Types)
6746     + llvm::capacity_in_bytes(VariableArrayTypes)
6747     + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
6748 }
6749 
6750 void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
6751   ParamIndices[D] = index;
6752 }
6753 
6754 unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
6755   ParameterIndexTable::const_iterator I = ParamIndices.find(D);
6756   assert(I != ParamIndices.end() &&
6757          "ParmIndices lacks entry set by ParmVarDecl");
6758   return I->second;
6759 }
6760