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