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