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