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