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