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