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