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