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