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