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