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