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