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