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