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