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