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