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