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