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