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