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