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