ASTContext.cpp revision 193401
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/DeclCXX.h"
16#include "clang/AST/DeclObjC.h"
17#include "clang/AST/DeclTemplate.h"
18#include "clang/AST/Expr.h"
19#include "clang/AST/ExternalASTSource.h"
20#include "clang/AST/RecordLayout.h"
21#include "clang/Basic/SourceManager.h"
22#include "clang/Basic/TargetInfo.h"
23#include "llvm/ADT/StringExtras.h"
24#include "llvm/Support/MathExtras.h"
25#include "llvm/Support/MemoryBuffer.h"
26using namespace clang;
27
28enum FloatingRank {
29  FloatRank, DoubleRank, LongDoubleRank
30};
31
32ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
33                       TargetInfo &t,
34                       IdentifierTable &idents, SelectorTable &sels,
35                       bool FreeMem, unsigned size_reserve,
36                       bool InitializeBuiltins) :
37  GlobalNestedNameSpecifier(0), CFConstantStringTypeDecl(0),
38  ObjCFastEnumerationStateTypeDecl(0), SourceMgr(SM), LangOpts(LOpts),
39  FreeMemory(FreeMem), Target(t), Idents(idents), Selectors(sels),
40  ExternalSource(0) {
41  if (size_reserve > 0) Types.reserve(size_reserve);
42  InitBuiltinTypes();
43  TUDecl = TranslationUnitDecl::Create(*this);
44  BuiltinInfo.InitializeTargetBuiltins(Target);
45  if (InitializeBuiltins)
46    this->InitializeBuiltins(idents);
47  PrintingPolicy.CPlusPlus = LangOpts.CPlusPlus;
48}
49
50ASTContext::~ASTContext() {
51  // Deallocate all the types.
52  while (!Types.empty()) {
53    Types.back()->Destroy(*this);
54    Types.pop_back();
55  }
56
57  {
58    llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
59      I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end();
60    while (I != E) {
61      ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
62      delete R;
63    }
64  }
65
66  {
67    llvm::DenseMap<const ObjCContainerDecl*, const ASTRecordLayout*>::iterator
68      I = ObjCLayouts.begin(), E = ObjCLayouts.end();
69    while (I != E) {
70      ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
71      delete R;
72    }
73  }
74
75  // Destroy nested-name-specifiers.
76  for (llvm::FoldingSet<NestedNameSpecifier>::iterator
77         NNS = NestedNameSpecifiers.begin(),
78         NNSEnd = NestedNameSpecifiers.end();
79       NNS != NNSEnd;
80       /* Increment in loop */)
81    (*NNS++).Destroy(*this);
82
83  if (GlobalNestedNameSpecifier)
84    GlobalNestedNameSpecifier->Destroy(*this);
85
86  TUDecl->Destroy(*this);
87}
88
89void ASTContext::InitializeBuiltins(IdentifierTable &idents) {
90  BuiltinInfo.InitializeBuiltins(idents, LangOpts.NoBuiltin);
91}
92
93void
94ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
95  ExternalSource.reset(Source.take());
96}
97
98void ASTContext::PrintStats() const {
99  fprintf(stderr, "*** AST Context Stats:\n");
100  fprintf(stderr, "  %d types total.\n", (int)Types.size());
101
102  unsigned counts[] = {
103#define TYPE(Name, Parent) 0,
104#define ABSTRACT_TYPE(Name, Parent)
105#include "clang/AST/TypeNodes.def"
106    0 // Extra
107  };
108
109  for (unsigned i = 0, e = Types.size(); i != e; ++i) {
110    Type *T = Types[i];
111    counts[(unsigned)T->getTypeClass()]++;
112  }
113
114  unsigned Idx = 0;
115  unsigned TotalBytes = 0;
116#define TYPE(Name, Parent)                                              \
117  if (counts[Idx])                                                      \
118    fprintf(stderr, "    %d %s types\n", (int)counts[Idx], #Name);      \
119  TotalBytes += counts[Idx] * sizeof(Name##Type);                       \
120  ++Idx;
121#define ABSTRACT_TYPE(Name, Parent)
122#include "clang/AST/TypeNodes.def"
123
124  fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
125
126  if (ExternalSource.get()) {
127    fprintf(stderr, "\n");
128    ExternalSource->PrintStats();
129  }
130}
131
132
133void ASTContext::InitBuiltinType(QualType &R, BuiltinType::Kind K) {
134  Types.push_back((R = QualType(new (*this,8) BuiltinType(K),0)).getTypePtr());
135}
136
137void ASTContext::InitBuiltinTypes() {
138  assert(VoidTy.isNull() && "Context reinitialized?");
139
140  // C99 6.2.5p19.
141  InitBuiltinType(VoidTy,              BuiltinType::Void);
142
143  // C99 6.2.5p2.
144  InitBuiltinType(BoolTy,              BuiltinType::Bool);
145  // C99 6.2.5p3.
146  if (Target.isCharSigned())
147    InitBuiltinType(CharTy,            BuiltinType::Char_S);
148  else
149    InitBuiltinType(CharTy,            BuiltinType::Char_U);
150  // C99 6.2.5p4.
151  InitBuiltinType(SignedCharTy,        BuiltinType::SChar);
152  InitBuiltinType(ShortTy,             BuiltinType::Short);
153  InitBuiltinType(IntTy,               BuiltinType::Int);
154  InitBuiltinType(LongTy,              BuiltinType::Long);
155  InitBuiltinType(LongLongTy,          BuiltinType::LongLong);
156
157  // C99 6.2.5p6.
158  InitBuiltinType(UnsignedCharTy,      BuiltinType::UChar);
159  InitBuiltinType(UnsignedShortTy,     BuiltinType::UShort);
160  InitBuiltinType(UnsignedIntTy,       BuiltinType::UInt);
161  InitBuiltinType(UnsignedLongTy,      BuiltinType::ULong);
162  InitBuiltinType(UnsignedLongLongTy,  BuiltinType::ULongLong);
163
164  // C99 6.2.5p10.
165  InitBuiltinType(FloatTy,             BuiltinType::Float);
166  InitBuiltinType(DoubleTy,            BuiltinType::Double);
167  InitBuiltinType(LongDoubleTy,        BuiltinType::LongDouble);
168
169  // GNU extension, 128-bit integers.
170  InitBuiltinType(Int128Ty,            BuiltinType::Int128);
171  InitBuiltinType(UnsignedInt128Ty,    BuiltinType::UInt128);
172
173  if (LangOpts.CPlusPlus) // C++ 3.9.1p5
174    InitBuiltinType(WCharTy,           BuiltinType::WChar);
175  else // C99
176    WCharTy = getFromTargetType(Target.getWCharType());
177
178  // Placeholder type for functions.
179  InitBuiltinType(OverloadTy,          BuiltinType::Overload);
180
181  // Placeholder type for type-dependent expressions whose type is
182  // completely unknown. No code should ever check a type against
183  // DependentTy and users should never see it; however, it is here to
184  // help diagnose failures to properly check for type-dependent
185  // expressions.
186  InitBuiltinType(DependentTy,         BuiltinType::Dependent);
187
188  // C99 6.2.5p11.
189  FloatComplexTy      = getComplexType(FloatTy);
190  DoubleComplexTy     = getComplexType(DoubleTy);
191  LongDoubleComplexTy = getComplexType(LongDoubleTy);
192
193  BuiltinVaListType = QualType();
194  ObjCIdType = QualType();
195  IdStructType = 0;
196  ObjCClassType = QualType();
197  ClassStructType = 0;
198
199  ObjCConstantStringType = QualType();
200
201  // void * type
202  VoidPtrTy = getPointerType(VoidTy);
203
204  // nullptr type (C++0x 2.14.7)
205  InitBuiltinType(NullPtrTy,           BuiltinType::NullPtr);
206}
207
208//===----------------------------------------------------------------------===//
209//                         Type Sizing and Analysis
210//===----------------------------------------------------------------------===//
211
212/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
213/// scalar floating point type.
214const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
215  const BuiltinType *BT = T->getAsBuiltinType();
216  assert(BT && "Not a floating point type!");
217  switch (BT->getKind()) {
218  default: assert(0 && "Not a floating point type!");
219  case BuiltinType::Float:      return Target.getFloatFormat();
220  case BuiltinType::Double:     return Target.getDoubleFormat();
221  case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
222  }
223}
224
225/// getDeclAlign - Return a conservative estimate of the alignment of the
226/// specified decl.  Note that bitfields do not have a valid alignment, so
227/// this method will assert on them.
228unsigned ASTContext::getDeclAlignInBytes(const Decl *D) {
229  unsigned Align = Target.getCharWidth();
230
231  if (const AlignedAttr* AA = D->getAttr<AlignedAttr>())
232    Align = std::max(Align, AA->getAlignment());
233
234  if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
235    QualType T = VD->getType();
236    if (const ReferenceType* RT = T->getAsReferenceType()) {
237      unsigned AS = RT->getPointeeType().getAddressSpace();
238      Align = Target.getPointerAlign(AS);
239    } else if (!T->isIncompleteType() && !T->isFunctionType()) {
240      // Incomplete or function types default to 1.
241      while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
242        T = cast<ArrayType>(T)->getElementType();
243
244      Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
245    }
246  }
247
248  return Align / Target.getCharWidth();
249}
250
251/// getTypeSize - Return the size of the specified type, in bits.  This method
252/// does not work on incomplete types.
253std::pair<uint64_t, unsigned>
254ASTContext::getTypeInfo(const Type *T) {
255  uint64_t Width=0;
256  unsigned Align=8;
257  switch (T->getTypeClass()) {
258#define TYPE(Class, Base)
259#define ABSTRACT_TYPE(Class, Base)
260#define NON_CANONICAL_TYPE(Class, Base)
261#define DEPENDENT_TYPE(Class, Base) case Type::Class:
262#include "clang/AST/TypeNodes.def"
263    assert(false && "Should not see dependent types");
264    break;
265
266  case Type::FunctionNoProto:
267  case Type::FunctionProto:
268    // GCC extension: alignof(function) = 32 bits
269    Width = 0;
270    Align = 32;
271    break;
272
273  case Type::IncompleteArray:
274  case Type::VariableArray:
275    Width = 0;
276    Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
277    break;
278
279  case Type::ConstantArray: {
280    const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
281
282    std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
283    Width = EltInfo.first*CAT->getSize().getZExtValue();
284    Align = EltInfo.second;
285    break;
286  }
287  case Type::ExtVector:
288  case Type::Vector: {
289    std::pair<uint64_t, unsigned> EltInfo =
290      getTypeInfo(cast<VectorType>(T)->getElementType());
291    Width = EltInfo.first*cast<VectorType>(T)->getNumElements();
292    Align = Width;
293    // If the alignment is not a power of 2, round up to the next power of 2.
294    // This happens for non-power-of-2 length vectors.
295    // FIXME: this should probably be a target property.
296    Align = 1 << llvm::Log2_32_Ceil(Align);
297    break;
298  }
299
300  case Type::Builtin:
301    switch (cast<BuiltinType>(T)->getKind()) {
302    default: assert(0 && "Unknown builtin type!");
303    case BuiltinType::Void:
304      // GCC extension: alignof(void) = 8 bits.
305      Width = 0;
306      Align = 8;
307      break;
308
309    case BuiltinType::Bool:
310      Width = Target.getBoolWidth();
311      Align = Target.getBoolAlign();
312      break;
313    case BuiltinType::Char_S:
314    case BuiltinType::Char_U:
315    case BuiltinType::UChar:
316    case BuiltinType::SChar:
317      Width = Target.getCharWidth();
318      Align = Target.getCharAlign();
319      break;
320    case BuiltinType::WChar:
321      Width = Target.getWCharWidth();
322      Align = Target.getWCharAlign();
323      break;
324    case BuiltinType::UShort:
325    case BuiltinType::Short:
326      Width = Target.getShortWidth();
327      Align = Target.getShortAlign();
328      break;
329    case BuiltinType::UInt:
330    case BuiltinType::Int:
331      Width = Target.getIntWidth();
332      Align = Target.getIntAlign();
333      break;
334    case BuiltinType::ULong:
335    case BuiltinType::Long:
336      Width = Target.getLongWidth();
337      Align = Target.getLongAlign();
338      break;
339    case BuiltinType::ULongLong:
340    case BuiltinType::LongLong:
341      Width = Target.getLongLongWidth();
342      Align = Target.getLongLongAlign();
343      break;
344    case BuiltinType::Int128:
345    case BuiltinType::UInt128:
346      Width = 128;
347      Align = 128; // int128_t is 128-bit aligned on all targets.
348      break;
349    case BuiltinType::Float:
350      Width = Target.getFloatWidth();
351      Align = Target.getFloatAlign();
352      break;
353    case BuiltinType::Double:
354      Width = Target.getDoubleWidth();
355      Align = Target.getDoubleAlign();
356      break;
357    case BuiltinType::LongDouble:
358      Width = Target.getLongDoubleWidth();
359      Align = Target.getLongDoubleAlign();
360      break;
361    case BuiltinType::NullPtr:
362      Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
363      Align = Target.getPointerAlign(0); //   == sizeof(void*)
364      break;
365    }
366    break;
367  case Type::FixedWidthInt:
368    // FIXME: This isn't precisely correct; the width/alignment should depend
369    // on the available types for the target
370    Width = cast<FixedWidthIntType>(T)->getWidth();
371    Width = std::max(llvm::NextPowerOf2(Width - 1), (uint64_t)8);
372    Align = Width;
373    break;
374  case Type::ExtQual:
375    // FIXME: Pointers into different addr spaces could have different sizes and
376    // alignment requirements: getPointerInfo should take an AddrSpace.
377    return getTypeInfo(QualType(cast<ExtQualType>(T)->getBaseType(), 0));
378  case Type::ObjCQualifiedId:
379  case Type::ObjCQualifiedInterface:
380    Width = Target.getPointerWidth(0);
381    Align = Target.getPointerAlign(0);
382    break;
383  case Type::BlockPointer: {
384    unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
385    Width = Target.getPointerWidth(AS);
386    Align = Target.getPointerAlign(AS);
387    break;
388  }
389  case Type::Pointer: {
390    unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
391    Width = Target.getPointerWidth(AS);
392    Align = Target.getPointerAlign(AS);
393    break;
394  }
395  case Type::LValueReference:
396  case Type::RValueReference:
397    // "When applied to a reference or a reference type, the result is the size
398    // of the referenced type." C++98 5.3.3p2: expr.sizeof.
399    // FIXME: This is wrong for struct layout: a reference in a struct has
400    // pointer size.
401    return getTypeInfo(cast<ReferenceType>(T)->getPointeeType());
402  case Type::MemberPointer: {
403    // FIXME: This is ABI dependent. We use the Itanium C++ ABI.
404    // http://www.codesourcery.com/public/cxx-abi/abi.html#member-pointers
405    // If we ever want to support other ABIs this needs to be abstracted.
406
407    QualType Pointee = cast<MemberPointerType>(T)->getPointeeType();
408    std::pair<uint64_t, unsigned> PtrDiffInfo =
409      getTypeInfo(getPointerDiffType());
410    Width = PtrDiffInfo.first;
411    if (Pointee->isFunctionType())
412      Width *= 2;
413    Align = PtrDiffInfo.second;
414    break;
415  }
416  case Type::Complex: {
417    // Complex types have the same alignment as their elements, but twice the
418    // size.
419    std::pair<uint64_t, unsigned> EltInfo =
420      getTypeInfo(cast<ComplexType>(T)->getElementType());
421    Width = EltInfo.first*2;
422    Align = EltInfo.second;
423    break;
424  }
425  case Type::ObjCInterface: {
426    const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
427    const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
428    Width = Layout.getSize();
429    Align = Layout.getAlignment();
430    break;
431  }
432  case Type::Record:
433  case Type::Enum: {
434    const TagType *TT = cast<TagType>(T);
435
436    if (TT->getDecl()->isInvalidDecl()) {
437      Width = 1;
438      Align = 1;
439      break;
440    }
441
442    if (const EnumType *ET = dyn_cast<EnumType>(TT))
443      return getTypeInfo(ET->getDecl()->getIntegerType());
444
445    const RecordType *RT = cast<RecordType>(TT);
446    const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
447    Width = Layout.getSize();
448    Align = Layout.getAlignment();
449    break;
450  }
451
452  case Type::Typedef: {
453    const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
454    if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>()) {
455      Align = Aligned->getAlignment();
456      Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
457    } else
458      return getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
459    break;
460  }
461
462  case Type::TypeOfExpr:
463    return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
464                         .getTypePtr());
465
466  case Type::TypeOf:
467    return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
468
469  case Type::QualifiedName:
470    return getTypeInfo(cast<QualifiedNameType>(T)->getNamedType().getTypePtr());
471
472  case Type::TemplateSpecialization:
473    assert(getCanonicalType(T) != T &&
474           "Cannot request the size of a dependent type");
475    // FIXME: this is likely to be wrong once we support template
476    // aliases, since a template alias could refer to a typedef that
477    // has an __aligned__ attribute on it.
478    return getTypeInfo(getCanonicalType(T));
479  }
480
481  assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
482  return std::make_pair(Width, Align);
483}
484
485/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
486/// type for the current target in bits.  This can be different than the ABI
487/// alignment in cases where it is beneficial for performance to overalign
488/// a data type.
489unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
490  unsigned ABIAlign = getTypeAlign(T);
491
492  // Double and long long should be naturally aligned if possible.
493  if (const ComplexType* CT = T->getAsComplexType())
494    T = CT->getElementType().getTypePtr();
495  if (T->isSpecificBuiltinType(BuiltinType::Double) ||
496      T->isSpecificBuiltinType(BuiltinType::LongLong))
497    return std::max(ABIAlign, (unsigned)getTypeSize(T));
498
499  return ABIAlign;
500}
501
502
503/// LayoutField - Field layout.
504void ASTRecordLayout::LayoutField(const FieldDecl *FD, unsigned FieldNo,
505                                  bool IsUnion, unsigned StructPacking,
506                                  ASTContext &Context) {
507  unsigned FieldPacking = StructPacking;
508  uint64_t FieldOffset = IsUnion ? 0 : Size;
509  uint64_t FieldSize;
510  unsigned FieldAlign;
511
512  // FIXME: Should this override struct packing? Probably we want to
513  // take the minimum?
514  if (const PackedAttr *PA = FD->getAttr<PackedAttr>())
515    FieldPacking = PA->getAlignment();
516
517  if (const Expr *BitWidthExpr = FD->getBitWidth()) {
518    // TODO: Need to check this algorithm on other targets!
519    //       (tested on Linux-X86)
520    FieldSize = BitWidthExpr->EvaluateAsInt(Context).getZExtValue();
521
522    std::pair<uint64_t, unsigned> FieldInfo =
523      Context.getTypeInfo(FD->getType());
524    uint64_t TypeSize = FieldInfo.first;
525
526    // Determine the alignment of this bitfield. The packing
527    // attributes define a maximum and the alignment attribute defines
528    // a minimum.
529    // FIXME: What is the right behavior when the specified alignment
530    // is smaller than the specified packing?
531    FieldAlign = FieldInfo.second;
532    if (FieldPacking)
533      FieldAlign = std::min(FieldAlign, FieldPacking);
534    if (const AlignedAttr *AA = FD->getAttr<AlignedAttr>())
535      FieldAlign = std::max(FieldAlign, AA->getAlignment());
536
537    // Check if we need to add padding to give the field the correct
538    // alignment.
539    if (FieldSize == 0 || (FieldOffset & (FieldAlign-1)) + FieldSize > TypeSize)
540      FieldOffset = (FieldOffset + (FieldAlign-1)) & ~(FieldAlign-1);
541
542    // Padding members don't affect overall alignment
543    if (!FD->getIdentifier())
544      FieldAlign = 1;
545  } else {
546    if (FD->getType()->isIncompleteArrayType()) {
547      // This is a flexible array member; we can't directly
548      // query getTypeInfo about these, so we figure it out here.
549      // Flexible array members don't have any size, but they
550      // have to be aligned appropriately for their element type.
551      FieldSize = 0;
552      const ArrayType* ATy = Context.getAsArrayType(FD->getType());
553      FieldAlign = Context.getTypeAlign(ATy->getElementType());
554    } else if (const ReferenceType *RT = FD->getType()->getAsReferenceType()) {
555      unsigned AS = RT->getPointeeType().getAddressSpace();
556      FieldSize = Context.Target.getPointerWidth(AS);
557      FieldAlign = Context.Target.getPointerAlign(AS);
558    } else {
559      std::pair<uint64_t, unsigned> FieldInfo =
560        Context.getTypeInfo(FD->getType());
561      FieldSize = FieldInfo.first;
562      FieldAlign = FieldInfo.second;
563    }
564
565    // Determine the alignment of this bitfield. The packing
566    // attributes define a maximum and the alignment attribute defines
567    // a minimum. Additionally, the packing alignment must be at least
568    // a byte for non-bitfields.
569    //
570    // FIXME: What is the right behavior when the specified alignment
571    // is smaller than the specified packing?
572    if (FieldPacking)
573      FieldAlign = std::min(FieldAlign, std::max(8U, FieldPacking));
574    if (const AlignedAttr *AA = FD->getAttr<AlignedAttr>())
575      FieldAlign = std::max(FieldAlign, AA->getAlignment());
576
577    // Round up the current record size to the field's alignment boundary.
578    FieldOffset = (FieldOffset + (FieldAlign-1)) & ~(FieldAlign-1);
579  }
580
581  // Place this field at the current location.
582  FieldOffsets[FieldNo] = FieldOffset;
583
584  // Reserve space for this field.
585  if (IsUnion) {
586    Size = std::max(Size, FieldSize);
587  } else {
588    Size = FieldOffset + FieldSize;
589  }
590
591  // Remember the next available offset.
592  NextOffset = Size;
593
594  // Remember max struct/class alignment.
595  Alignment = std::max(Alignment, FieldAlign);
596}
597
598static void CollectLocalObjCIvars(ASTContext *Ctx,
599                                  const ObjCInterfaceDecl *OI,
600                                  llvm::SmallVectorImpl<FieldDecl*> &Fields) {
601  for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
602       E = OI->ivar_end(); I != E; ++I) {
603    ObjCIvarDecl *IVDecl = *I;
604    if (!IVDecl->isInvalidDecl())
605      Fields.push_back(cast<FieldDecl>(IVDecl));
606  }
607}
608
609void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
610                             llvm::SmallVectorImpl<FieldDecl*> &Fields) {
611  if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
612    CollectObjCIvars(SuperClass, Fields);
613  CollectLocalObjCIvars(this, OI, Fields);
614}
615
616void ASTContext::CollectProtocolSynthesizedIvars(const ObjCProtocolDecl *PD,
617                                llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
618  for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(*this),
619       E = PD->prop_end(*this); I != E; ++I)
620    if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
621      Ivars.push_back(Ivar);
622
623  // Also look into nested protocols.
624  for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
625       E = PD->protocol_end(); P != E; ++P)
626    CollectProtocolSynthesizedIvars(*P, Ivars);
627}
628
629/// CollectSynthesizedIvars -
630/// This routine collect synthesized ivars for the designated class.
631///
632void ASTContext::CollectSynthesizedIvars(const ObjCInterfaceDecl *OI,
633                                llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
634  for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(*this),
635       E = OI->prop_end(*this); I != E; ++I) {
636    if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
637      Ivars.push_back(Ivar);
638  }
639  // Also look into interface's protocol list for properties declared
640  // in the protocol and whose ivars are synthesized.
641  for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
642       PE = OI->protocol_end(); P != PE; ++P) {
643    ObjCProtocolDecl *PD = (*P);
644    CollectProtocolSynthesizedIvars(PD, Ivars);
645  }
646}
647
648/// getInterfaceLayoutImpl - Get or compute information about the
649/// layout of the given interface.
650///
651/// \param Impl - If given, also include the layout of the interface's
652/// implementation. This may differ by including synthesized ivars.
653const ASTRecordLayout &
654ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
655                          const ObjCImplementationDecl *Impl) {
656  assert(!D->isForwardDecl() && "Invalid interface decl!");
657
658  // Look up this layout, if already laid out, return what we have.
659  ObjCContainerDecl *Key =
660    Impl ? (ObjCContainerDecl*) Impl : (ObjCContainerDecl*) D;
661  if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
662    return *Entry;
663
664  unsigned FieldCount = D->ivar_size();
665  // Add in synthesized ivar count if laying out an implementation.
666  if (Impl) {
667    llvm::SmallVector<ObjCIvarDecl*, 16> Ivars;
668    CollectSynthesizedIvars(D, Ivars);
669    FieldCount += Ivars.size();
670    // If there aren't any sythesized ivars then reuse the interface
671    // entry. Note we can't cache this because we simply free all
672    // entries later; however we shouldn't look up implementations
673    // frequently.
674    if (FieldCount == D->ivar_size())
675      return getObjCLayout(D, 0);
676  }
677
678  ASTRecordLayout *NewEntry = NULL;
679  if (ObjCInterfaceDecl *SD = D->getSuperClass()) {
680    const ASTRecordLayout &SL = getASTObjCInterfaceLayout(SD);
681    unsigned Alignment = SL.getAlignment();
682
683    // We start laying out ivars not at the end of the superclass
684    // structure, but at the next byte following the last field.
685    uint64_t Size = llvm::RoundUpToAlignment(SL.NextOffset, 8);
686
687    ObjCLayouts[Key] = NewEntry = new ASTRecordLayout(Size, Alignment);
688    NewEntry->InitializeLayout(FieldCount);
689  } else {
690    ObjCLayouts[Key] = NewEntry = new ASTRecordLayout();
691    NewEntry->InitializeLayout(FieldCount);
692  }
693
694  unsigned StructPacking = 0;
695  if (const PackedAttr *PA = D->getAttr<PackedAttr>())
696    StructPacking = PA->getAlignment();
697
698  if (const AlignedAttr *AA = D->getAttr<AlignedAttr>())
699    NewEntry->SetAlignment(std::max(NewEntry->getAlignment(),
700                                    AA->getAlignment()));
701
702  // Layout each ivar sequentially.
703  unsigned i = 0;
704  for (ObjCInterfaceDecl::ivar_iterator IVI = D->ivar_begin(),
705       IVE = D->ivar_end(); IVI != IVE; ++IVI) {
706    const ObjCIvarDecl* Ivar = (*IVI);
707    NewEntry->LayoutField(Ivar, i++, false, StructPacking, *this);
708  }
709  // And synthesized ivars, if this is an implementation.
710  if (Impl) {
711    // FIXME. Do we need to colltect twice?
712    llvm::SmallVector<ObjCIvarDecl*, 16> Ivars;
713    CollectSynthesizedIvars(D, Ivars);
714    for (unsigned k = 0, e = Ivars.size(); k != e; ++k)
715      NewEntry->LayoutField(Ivars[k], i++, false, StructPacking, *this);
716  }
717
718  // Finally, round the size of the total struct up to the alignment of the
719  // struct itself.
720  NewEntry->FinalizeLayout();
721  return *NewEntry;
722}
723
724const ASTRecordLayout &
725ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
726  return getObjCLayout(D, 0);
727}
728
729const ASTRecordLayout &
730ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
731  return getObjCLayout(D->getClassInterface(), D);
732}
733
734/// getASTRecordLayout - Get or compute information about the layout of the
735/// specified record (struct/union/class), which indicates its size and field
736/// position information.
737const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D) {
738  D = D->getDefinition(*this);
739  assert(D && "Cannot get layout of forward declarations!");
740
741  // Look up this layout, if already laid out, return what we have.
742  const ASTRecordLayout *&Entry = ASTRecordLayouts[D];
743  if (Entry) return *Entry;
744
745  // Allocate and assign into ASTRecordLayouts here.  The "Entry" reference can
746  // be invalidated (dangle) if the ASTRecordLayouts hashtable is inserted into.
747  ASTRecordLayout *NewEntry = new ASTRecordLayout();
748  Entry = NewEntry;
749
750  // FIXME: Avoid linear walk through the fields, if possible.
751  NewEntry->InitializeLayout(std::distance(D->field_begin(*this),
752                                           D->field_end(*this)));
753  bool IsUnion = D->isUnion();
754
755  unsigned StructPacking = 0;
756  if (const PackedAttr *PA = D->getAttr<PackedAttr>())
757    StructPacking = PA->getAlignment();
758
759  if (const AlignedAttr *AA = D->getAttr<AlignedAttr>())
760    NewEntry->SetAlignment(std::max(NewEntry->getAlignment(),
761                                    AA->getAlignment()));
762
763  // Layout each field, for now, just sequentially, respecting alignment.  In
764  // the future, this will need to be tweakable by targets.
765  unsigned FieldIdx = 0;
766  for (RecordDecl::field_iterator Field = D->field_begin(*this),
767                               FieldEnd = D->field_end(*this);
768       Field != FieldEnd; (void)++Field, ++FieldIdx)
769    NewEntry->LayoutField(*Field, FieldIdx, IsUnion, StructPacking, *this);
770
771  // Finally, round the size of the total struct up to the alignment of the
772  // struct itself.
773  NewEntry->FinalizeLayout(getLangOptions().CPlusPlus);
774  return *NewEntry;
775}
776
777//===----------------------------------------------------------------------===//
778//                   Type creation/memoization methods
779//===----------------------------------------------------------------------===//
780
781QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
782  QualType CanT = getCanonicalType(T);
783  if (CanT.getAddressSpace() == AddressSpace)
784    return T;
785
786  // If we are composing extended qualifiers together, merge together into one
787  // ExtQualType node.
788  unsigned CVRQuals = T.getCVRQualifiers();
789  QualType::GCAttrTypes GCAttr = QualType::GCNone;
790  Type *TypeNode = T.getTypePtr();
791
792  if (ExtQualType *EQT = dyn_cast<ExtQualType>(TypeNode)) {
793    // If this type already has an address space specified, it cannot get
794    // another one.
795    assert(EQT->getAddressSpace() == 0 &&
796           "Type cannot be in multiple addr spaces!");
797    GCAttr = EQT->getObjCGCAttr();
798    TypeNode = EQT->getBaseType();
799  }
800
801  // Check if we've already instantiated this type.
802  llvm::FoldingSetNodeID ID;
803  ExtQualType::Profile(ID, TypeNode, AddressSpace, GCAttr);
804  void *InsertPos = 0;
805  if (ExtQualType *EXTQy = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos))
806    return QualType(EXTQy, CVRQuals);
807
808  // If the base type isn't canonical, this won't be a canonical type either,
809  // so fill in the canonical type field.
810  QualType Canonical;
811  if (!TypeNode->isCanonical()) {
812    Canonical = getAddrSpaceQualType(CanT, AddressSpace);
813
814    // Update InsertPos, the previous call could have invalidated it.
815    ExtQualType *NewIP = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos);
816    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
817  }
818  ExtQualType *New =
819    new (*this, 8) ExtQualType(TypeNode, Canonical, AddressSpace, GCAttr);
820  ExtQualTypes.InsertNode(New, InsertPos);
821  Types.push_back(New);
822  return QualType(New, CVRQuals);
823}
824
825QualType ASTContext::getObjCGCQualType(QualType T,
826                                       QualType::GCAttrTypes GCAttr) {
827  QualType CanT = getCanonicalType(T);
828  if (CanT.getObjCGCAttr() == GCAttr)
829    return T;
830
831  if (T->isPointerType()) {
832    QualType Pointee = T->getAsPointerType()->getPointeeType();
833    if (Pointee->isPointerType()) {
834      QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
835      return getPointerType(ResultType);
836    }
837  }
838  // If we are composing extended qualifiers together, merge together into one
839  // ExtQualType node.
840  unsigned CVRQuals = T.getCVRQualifiers();
841  Type *TypeNode = T.getTypePtr();
842  unsigned AddressSpace = 0;
843
844  if (ExtQualType *EQT = dyn_cast<ExtQualType>(TypeNode)) {
845    // If this type already has an address space specified, it cannot get
846    // another one.
847    assert(EQT->getObjCGCAttr() == QualType::GCNone &&
848           "Type cannot be in multiple addr spaces!");
849    AddressSpace = EQT->getAddressSpace();
850    TypeNode = EQT->getBaseType();
851  }
852
853  // Check if we've already instantiated an gc qual'd type of this type.
854  llvm::FoldingSetNodeID ID;
855  ExtQualType::Profile(ID, TypeNode, AddressSpace, GCAttr);
856  void *InsertPos = 0;
857  if (ExtQualType *EXTQy = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos))
858    return QualType(EXTQy, CVRQuals);
859
860  // If the base type isn't canonical, this won't be a canonical type either,
861  // so fill in the canonical type field.
862  // FIXME: Isn't this also not canonical if the base type is a array
863  // or pointer type?  I can't find any documentation for objc_gc, though...
864  QualType Canonical;
865  if (!T->isCanonical()) {
866    Canonical = getObjCGCQualType(CanT, GCAttr);
867
868    // Update InsertPos, the previous call could have invalidated it.
869    ExtQualType *NewIP = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos);
870    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
871  }
872  ExtQualType *New =
873    new (*this, 8) ExtQualType(TypeNode, Canonical, AddressSpace, GCAttr);
874  ExtQualTypes.InsertNode(New, InsertPos);
875  Types.push_back(New);
876  return QualType(New, CVRQuals);
877}
878
879/// getComplexType - Return the uniqued reference to the type for a complex
880/// number with the specified element type.
881QualType ASTContext::getComplexType(QualType T) {
882  // Unique pointers, to guarantee there is only one pointer of a particular
883  // structure.
884  llvm::FoldingSetNodeID ID;
885  ComplexType::Profile(ID, T);
886
887  void *InsertPos = 0;
888  if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
889    return QualType(CT, 0);
890
891  // If the pointee type isn't canonical, this won't be a canonical type either,
892  // so fill in the canonical type field.
893  QualType Canonical;
894  if (!T->isCanonical()) {
895    Canonical = getComplexType(getCanonicalType(T));
896
897    // Get the new insert position for the node we care about.
898    ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
899    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
900  }
901  ComplexType *New = new (*this,8) ComplexType(T, Canonical);
902  Types.push_back(New);
903  ComplexTypes.InsertNode(New, InsertPos);
904  return QualType(New, 0);
905}
906
907QualType ASTContext::getFixedWidthIntType(unsigned Width, bool Signed) {
908  llvm::DenseMap<unsigned, FixedWidthIntType*> &Map = Signed ?
909     SignedFixedWidthIntTypes : UnsignedFixedWidthIntTypes;
910  FixedWidthIntType *&Entry = Map[Width];
911  if (!Entry)
912    Entry = new FixedWidthIntType(Width, Signed);
913  return QualType(Entry, 0);
914}
915
916/// getPointerType - Return the uniqued reference to the type for a pointer to
917/// the specified type.
918QualType ASTContext::getPointerType(QualType T) {
919  // Unique pointers, to guarantee there is only one pointer of a particular
920  // structure.
921  llvm::FoldingSetNodeID ID;
922  PointerType::Profile(ID, T);
923
924  void *InsertPos = 0;
925  if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
926    return QualType(PT, 0);
927
928  // If the pointee type isn't canonical, this won't be a canonical type either,
929  // so fill in the canonical type field.
930  QualType Canonical;
931  if (!T->isCanonical()) {
932    Canonical = getPointerType(getCanonicalType(T));
933
934    // Get the new insert position for the node we care about.
935    PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
936    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
937  }
938  PointerType *New = new (*this,8) PointerType(T, Canonical);
939  Types.push_back(New);
940  PointerTypes.InsertNode(New, InsertPos);
941  return QualType(New, 0);
942}
943
944/// getBlockPointerType - Return the uniqued reference to the type for
945/// a pointer to the specified block.
946QualType ASTContext::getBlockPointerType(QualType T) {
947  assert(T->isFunctionType() && "block of function types only");
948  // Unique pointers, to guarantee there is only one block of a particular
949  // structure.
950  llvm::FoldingSetNodeID ID;
951  BlockPointerType::Profile(ID, T);
952
953  void *InsertPos = 0;
954  if (BlockPointerType *PT =
955        BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
956    return QualType(PT, 0);
957
958  // If the block pointee type isn't canonical, this won't be a canonical
959  // type either so fill in the canonical type field.
960  QualType Canonical;
961  if (!T->isCanonical()) {
962    Canonical = getBlockPointerType(getCanonicalType(T));
963
964    // Get the new insert position for the node we care about.
965    BlockPointerType *NewIP =
966      BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
967    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
968  }
969  BlockPointerType *New = new (*this,8) BlockPointerType(T, Canonical);
970  Types.push_back(New);
971  BlockPointerTypes.InsertNode(New, InsertPos);
972  return QualType(New, 0);
973}
974
975/// getLValueReferenceType - Return the uniqued reference to the type for an
976/// lvalue reference to the specified type.
977QualType ASTContext::getLValueReferenceType(QualType T) {
978  // Unique pointers, to guarantee there is only one pointer of a particular
979  // structure.
980  llvm::FoldingSetNodeID ID;
981  ReferenceType::Profile(ID, T);
982
983  void *InsertPos = 0;
984  if (LValueReferenceType *RT =
985        LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
986    return QualType(RT, 0);
987
988  // If the referencee type isn't canonical, this won't be a canonical type
989  // either, so fill in the canonical type field.
990  QualType Canonical;
991  if (!T->isCanonical()) {
992    Canonical = getLValueReferenceType(getCanonicalType(T));
993
994    // Get the new insert position for the node we care about.
995    LValueReferenceType *NewIP =
996      LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
997    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
998  }
999
1000  LValueReferenceType *New = new (*this,8) LValueReferenceType(T, Canonical);
1001  Types.push_back(New);
1002  LValueReferenceTypes.InsertNode(New, InsertPos);
1003  return QualType(New, 0);
1004}
1005
1006/// getRValueReferenceType - Return the uniqued reference to the type for an
1007/// rvalue reference to the specified type.
1008QualType ASTContext::getRValueReferenceType(QualType T) {
1009  // Unique pointers, to guarantee there is only one pointer of a particular
1010  // structure.
1011  llvm::FoldingSetNodeID ID;
1012  ReferenceType::Profile(ID, T);
1013
1014  void *InsertPos = 0;
1015  if (RValueReferenceType *RT =
1016        RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1017    return QualType(RT, 0);
1018
1019  // If the referencee type isn't canonical, this won't be a canonical type
1020  // either, so fill in the canonical type field.
1021  QualType Canonical;
1022  if (!T->isCanonical()) {
1023    Canonical = getRValueReferenceType(getCanonicalType(T));
1024
1025    // Get the new insert position for the node we care about.
1026    RValueReferenceType *NewIP =
1027      RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1028    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1029  }
1030
1031  RValueReferenceType *New = new (*this,8) RValueReferenceType(T, Canonical);
1032  Types.push_back(New);
1033  RValueReferenceTypes.InsertNode(New, InsertPos);
1034  return QualType(New, 0);
1035}
1036
1037/// getMemberPointerType - Return the uniqued reference to the type for a
1038/// member pointer to the specified type, in the specified class.
1039QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls)
1040{
1041  // Unique pointers, to guarantee there is only one pointer of a particular
1042  // structure.
1043  llvm::FoldingSetNodeID ID;
1044  MemberPointerType::Profile(ID, T, Cls);
1045
1046  void *InsertPos = 0;
1047  if (MemberPointerType *PT =
1048      MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1049    return QualType(PT, 0);
1050
1051  // If the pointee or class type isn't canonical, this won't be a canonical
1052  // type either, so fill in the canonical type field.
1053  QualType Canonical;
1054  if (!T->isCanonical()) {
1055    Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1056
1057    // Get the new insert position for the node we care about.
1058    MemberPointerType *NewIP =
1059      MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1060    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1061  }
1062  MemberPointerType *New = new (*this,8) MemberPointerType(T, Cls, Canonical);
1063  Types.push_back(New);
1064  MemberPointerTypes.InsertNode(New, InsertPos);
1065  return QualType(New, 0);
1066}
1067
1068/// getConstantArrayType - Return the unique reference to the type for an
1069/// array of the specified element type.
1070QualType ASTContext::getConstantArrayType(QualType EltTy,
1071                                          const llvm::APInt &ArySizeIn,
1072                                          ArrayType::ArraySizeModifier ASM,
1073                                          unsigned EltTypeQuals) {
1074  assert((EltTy->isDependentType() || EltTy->isConstantSizeType()) &&
1075         "Constant array of VLAs is illegal!");
1076
1077  // Convert the array size into a canonical width matching the pointer size for
1078  // the target.
1079  llvm::APInt ArySize(ArySizeIn);
1080  ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
1081
1082  llvm::FoldingSetNodeID ID;
1083  ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
1084
1085  void *InsertPos = 0;
1086  if (ConstantArrayType *ATP =
1087      ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1088    return QualType(ATP, 0);
1089
1090  // If the element type isn't canonical, this won't be a canonical type either,
1091  // so fill in the canonical type field.
1092  QualType Canonical;
1093  if (!EltTy->isCanonical()) {
1094    Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
1095                                     ASM, EltTypeQuals);
1096    // Get the new insert position for the node we care about.
1097    ConstantArrayType *NewIP =
1098      ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1099    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1100  }
1101
1102  ConstantArrayType *New =
1103    new(*this,8)ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
1104  ConstantArrayTypes.InsertNode(New, InsertPos);
1105  Types.push_back(New);
1106  return QualType(New, 0);
1107}
1108
1109/// getVariableArrayType - Returns a non-unique reference to the type for a
1110/// variable array of the specified element type.
1111QualType ASTContext::getVariableArrayType(QualType EltTy, Expr *NumElts,
1112                                          ArrayType::ArraySizeModifier ASM,
1113                                          unsigned EltTypeQuals) {
1114  // Since we don't unique expressions, it isn't possible to unique VLA's
1115  // that have an expression provided for their size.
1116
1117  VariableArrayType *New =
1118    new(*this,8)VariableArrayType(EltTy,QualType(), NumElts, ASM, EltTypeQuals);
1119
1120  VariableArrayTypes.push_back(New);
1121  Types.push_back(New);
1122  return QualType(New, 0);
1123}
1124
1125/// getDependentSizedArrayType - Returns a non-unique reference to
1126/// the type for a dependently-sized array of the specified element
1127/// type. FIXME: We will need these to be uniqued, or at least
1128/// comparable, at some point.
1129QualType ASTContext::getDependentSizedArrayType(QualType EltTy, Expr *NumElts,
1130                                                ArrayType::ArraySizeModifier ASM,
1131                                                unsigned EltTypeQuals) {
1132  assert((NumElts->isTypeDependent() || NumElts->isValueDependent()) &&
1133         "Size must be type- or value-dependent!");
1134
1135  // Since we don't unique expressions, it isn't possible to unique
1136  // dependently-sized array types.
1137
1138  DependentSizedArrayType *New =
1139      new (*this,8) DependentSizedArrayType(EltTy, QualType(), NumElts,
1140                                            ASM, EltTypeQuals);
1141
1142  DependentSizedArrayTypes.push_back(New);
1143  Types.push_back(New);
1144  return QualType(New, 0);
1145}
1146
1147QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1148                                            ArrayType::ArraySizeModifier ASM,
1149                                            unsigned EltTypeQuals) {
1150  llvm::FoldingSetNodeID ID;
1151  IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
1152
1153  void *InsertPos = 0;
1154  if (IncompleteArrayType *ATP =
1155       IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1156    return QualType(ATP, 0);
1157
1158  // If the element type isn't canonical, this won't be a canonical type
1159  // either, so fill in the canonical type field.
1160  QualType Canonical;
1161
1162  if (!EltTy->isCanonical()) {
1163    Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
1164                                       ASM, EltTypeQuals);
1165
1166    // Get the new insert position for the node we care about.
1167    IncompleteArrayType *NewIP =
1168      IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1169    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1170  }
1171
1172  IncompleteArrayType *New = new (*this,8) IncompleteArrayType(EltTy, Canonical,
1173                                                           ASM, EltTypeQuals);
1174
1175  IncompleteArrayTypes.InsertNode(New, InsertPos);
1176  Types.push_back(New);
1177  return QualType(New, 0);
1178}
1179
1180/// getVectorType - Return the unique reference to a vector type of
1181/// the specified element type and size. VectorType must be a built-in type.
1182QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts) {
1183  BuiltinType *baseType;
1184
1185  baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
1186  assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
1187
1188  // Check if we've already instantiated a vector of this type.
1189  llvm::FoldingSetNodeID ID;
1190  VectorType::Profile(ID, vecType, NumElts, Type::Vector);
1191  void *InsertPos = 0;
1192  if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1193    return QualType(VTP, 0);
1194
1195  // If the element type isn't canonical, this won't be a canonical type either,
1196  // so fill in the canonical type field.
1197  QualType Canonical;
1198  if (!vecType->isCanonical()) {
1199    Canonical = getVectorType(getCanonicalType(vecType), NumElts);
1200
1201    // Get the new insert position for the node we care about.
1202    VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1203    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1204  }
1205  VectorType *New = new (*this,8) VectorType(vecType, NumElts, Canonical);
1206  VectorTypes.InsertNode(New, InsertPos);
1207  Types.push_back(New);
1208  return QualType(New, 0);
1209}
1210
1211/// getExtVectorType - Return the unique reference to an extended vector type of
1212/// the specified element type and size. VectorType must be a built-in type.
1213QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
1214  BuiltinType *baseType;
1215
1216  baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
1217  assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
1218
1219  // Check if we've already instantiated a vector of this type.
1220  llvm::FoldingSetNodeID ID;
1221  VectorType::Profile(ID, vecType, NumElts, Type::ExtVector);
1222  void *InsertPos = 0;
1223  if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1224    return QualType(VTP, 0);
1225
1226  // If the element type isn't canonical, this won't be a canonical type either,
1227  // so fill in the canonical type field.
1228  QualType Canonical;
1229  if (!vecType->isCanonical()) {
1230    Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
1231
1232    // Get the new insert position for the node we care about.
1233    VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1234    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1235  }
1236  ExtVectorType *New = new (*this,8) ExtVectorType(vecType, NumElts, Canonical);
1237  VectorTypes.InsertNode(New, InsertPos);
1238  Types.push_back(New);
1239  return QualType(New, 0);
1240}
1241
1242/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
1243///
1244QualType ASTContext::getFunctionNoProtoType(QualType ResultTy) {
1245  // Unique functions, to guarantee there is only one function of a particular
1246  // structure.
1247  llvm::FoldingSetNodeID ID;
1248  FunctionNoProtoType::Profile(ID, ResultTy);
1249
1250  void *InsertPos = 0;
1251  if (FunctionNoProtoType *FT =
1252        FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
1253    return QualType(FT, 0);
1254
1255  QualType Canonical;
1256  if (!ResultTy->isCanonical()) {
1257    Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy));
1258
1259    // Get the new insert position for the node we care about.
1260    FunctionNoProtoType *NewIP =
1261      FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
1262    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1263  }
1264
1265  FunctionNoProtoType *New =new(*this,8)FunctionNoProtoType(ResultTy,Canonical);
1266  Types.push_back(New);
1267  FunctionNoProtoTypes.InsertNode(New, InsertPos);
1268  return QualType(New, 0);
1269}
1270
1271/// getFunctionType - Return a normal function type with a typed argument
1272/// list.  isVariadic indicates whether the argument list includes '...'.
1273QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
1274                                     unsigned NumArgs, bool isVariadic,
1275                                     unsigned TypeQuals, bool hasExceptionSpec,
1276                                     bool hasAnyExceptionSpec, unsigned NumExs,
1277                                     const QualType *ExArray) {
1278  // Unique functions, to guarantee there is only one function of a particular
1279  // structure.
1280  llvm::FoldingSetNodeID ID;
1281  FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
1282                             TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
1283                             NumExs, ExArray);
1284
1285  void *InsertPos = 0;
1286  if (FunctionProtoType *FTP =
1287        FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
1288    return QualType(FTP, 0);
1289
1290  // Determine whether the type being created is already canonical or not.
1291  bool isCanonical = ResultTy->isCanonical();
1292  if (hasExceptionSpec)
1293    isCanonical = false;
1294  for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
1295    if (!ArgArray[i]->isCanonical())
1296      isCanonical = false;
1297
1298  // If this type isn't canonical, get the canonical version of it.
1299  // The exception spec is not part of the canonical type.
1300  QualType Canonical;
1301  if (!isCanonical) {
1302    llvm::SmallVector<QualType, 16> CanonicalArgs;
1303    CanonicalArgs.reserve(NumArgs);
1304    for (unsigned i = 0; i != NumArgs; ++i)
1305      CanonicalArgs.push_back(getCanonicalType(ArgArray[i]));
1306
1307    Canonical = getFunctionType(getCanonicalType(ResultTy),
1308                                CanonicalArgs.data(), NumArgs,
1309                                isVariadic, TypeQuals);
1310
1311    // Get the new insert position for the node we care about.
1312    FunctionProtoType *NewIP =
1313      FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
1314    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1315  }
1316
1317  // FunctionProtoType objects are allocated with extra bytes after them
1318  // for two variable size arrays (for parameter and exception types) at the
1319  // end of them.
1320  FunctionProtoType *FTP =
1321    (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1322                                 NumArgs*sizeof(QualType) +
1323                                 NumExs*sizeof(QualType), 8);
1324  new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
1325                              TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
1326                              ExArray, NumExs, Canonical);
1327  Types.push_back(FTP);
1328  FunctionProtoTypes.InsertNode(FTP, InsertPos);
1329  return QualType(FTP, 0);
1330}
1331
1332/// getTypeDeclType - Return the unique reference to the type for the
1333/// specified type declaration.
1334QualType ASTContext::getTypeDeclType(TypeDecl *Decl, TypeDecl* PrevDecl) {
1335  assert(Decl && "Passed null for Decl param");
1336  if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1337
1338  if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
1339    return getTypedefType(Typedef);
1340  else if (isa<TemplateTypeParmDecl>(Decl)) {
1341    assert(false && "Template type parameter types are always available.");
1342  } else if (ObjCInterfaceDecl *ObjCInterface = dyn_cast<ObjCInterfaceDecl>(Decl))
1343    return getObjCInterfaceType(ObjCInterface);
1344
1345  if (RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
1346    if (PrevDecl)
1347      Decl->TypeForDecl = PrevDecl->TypeForDecl;
1348    else
1349      Decl->TypeForDecl = new (*this,8) RecordType(Record);
1350  }
1351  else if (EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
1352    if (PrevDecl)
1353      Decl->TypeForDecl = PrevDecl->TypeForDecl;
1354    else
1355      Decl->TypeForDecl = new (*this,8) EnumType(Enum);
1356  }
1357  else
1358    assert(false && "TypeDecl without a type?");
1359
1360  if (!PrevDecl) Types.push_back(Decl->TypeForDecl);
1361  return QualType(Decl->TypeForDecl, 0);
1362}
1363
1364/// getTypedefType - Return the unique reference to the type for the
1365/// specified typename decl.
1366QualType ASTContext::getTypedefType(TypedefDecl *Decl) {
1367  if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1368
1369  QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
1370  Decl->TypeForDecl = new(*this,8) TypedefType(Type::Typedef, Decl, Canonical);
1371  Types.push_back(Decl->TypeForDecl);
1372  return QualType(Decl->TypeForDecl, 0);
1373}
1374
1375/// getObjCInterfaceType - Return the unique reference to the type for the
1376/// specified ObjC interface decl.
1377QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) {
1378  if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1379
1380  ObjCInterfaceDecl *OID = const_cast<ObjCInterfaceDecl*>(Decl);
1381  Decl->TypeForDecl = new(*this,8) ObjCInterfaceType(Type::ObjCInterface, OID);
1382  Types.push_back(Decl->TypeForDecl);
1383  return QualType(Decl->TypeForDecl, 0);
1384}
1385
1386/// \brief Retrieve the template type parameter type for a template
1387/// parameter with the given depth, index, and (optionally) name.
1388QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
1389                                             IdentifierInfo *Name) {
1390  llvm::FoldingSetNodeID ID;
1391  TemplateTypeParmType::Profile(ID, Depth, Index, Name);
1392  void *InsertPos = 0;
1393  TemplateTypeParmType *TypeParm
1394    = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1395
1396  if (TypeParm)
1397    return QualType(TypeParm, 0);
1398
1399  if (Name)
1400    TypeParm = new (*this, 8) TemplateTypeParmType(Depth, Index, Name,
1401                                         getTemplateTypeParmType(Depth, Index));
1402  else
1403    TypeParm = new (*this, 8) TemplateTypeParmType(Depth, Index);
1404
1405  Types.push_back(TypeParm);
1406  TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1407
1408  return QualType(TypeParm, 0);
1409}
1410
1411QualType
1412ASTContext::getTemplateSpecializationType(TemplateName Template,
1413                                          const TemplateArgument *Args,
1414                                          unsigned NumArgs,
1415                                          QualType Canon) {
1416  if (!Canon.isNull())
1417    Canon = getCanonicalType(Canon);
1418
1419  llvm::FoldingSetNodeID ID;
1420  TemplateSpecializationType::Profile(ID, Template, Args, NumArgs);
1421
1422  void *InsertPos = 0;
1423  TemplateSpecializationType *Spec
1424    = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
1425
1426  if (Spec)
1427    return QualType(Spec, 0);
1428
1429  void *Mem = Allocate((sizeof(TemplateSpecializationType) +
1430                        sizeof(TemplateArgument) * NumArgs),
1431                       8);
1432  Spec = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, Canon);
1433  Types.push_back(Spec);
1434  TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
1435
1436  return QualType(Spec, 0);
1437}
1438
1439QualType
1440ASTContext::getQualifiedNameType(NestedNameSpecifier *NNS,
1441                                 QualType NamedType) {
1442  llvm::FoldingSetNodeID ID;
1443  QualifiedNameType::Profile(ID, NNS, NamedType);
1444
1445  void *InsertPos = 0;
1446  QualifiedNameType *T
1447    = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
1448  if (T)
1449    return QualType(T, 0);
1450
1451  T = new (*this) QualifiedNameType(NNS, NamedType,
1452                                    getCanonicalType(NamedType));
1453  Types.push_back(T);
1454  QualifiedNameTypes.InsertNode(T, InsertPos);
1455  return QualType(T, 0);
1456}
1457
1458QualType ASTContext::getTypenameType(NestedNameSpecifier *NNS,
1459                                     const IdentifierInfo *Name,
1460                                     QualType Canon) {
1461  assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1462
1463  if (Canon.isNull()) {
1464    NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1465    if (CanonNNS != NNS)
1466      Canon = getTypenameType(CanonNNS, Name);
1467  }
1468
1469  llvm::FoldingSetNodeID ID;
1470  TypenameType::Profile(ID, NNS, Name);
1471
1472  void *InsertPos = 0;
1473  TypenameType *T
1474    = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1475  if (T)
1476    return QualType(T, 0);
1477
1478  T = new (*this) TypenameType(NNS, Name, Canon);
1479  Types.push_back(T);
1480  TypenameTypes.InsertNode(T, InsertPos);
1481  return QualType(T, 0);
1482}
1483
1484QualType
1485ASTContext::getTypenameType(NestedNameSpecifier *NNS,
1486                            const TemplateSpecializationType *TemplateId,
1487                            QualType Canon) {
1488  assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1489
1490  if (Canon.isNull()) {
1491    NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1492    QualType CanonType = getCanonicalType(QualType(TemplateId, 0));
1493    if (CanonNNS != NNS || CanonType != QualType(TemplateId, 0)) {
1494      const TemplateSpecializationType *CanonTemplateId
1495        = CanonType->getAsTemplateSpecializationType();
1496      assert(CanonTemplateId &&
1497             "Canonical type must also be a template specialization type");
1498      Canon = getTypenameType(CanonNNS, CanonTemplateId);
1499    }
1500  }
1501
1502  llvm::FoldingSetNodeID ID;
1503  TypenameType::Profile(ID, NNS, TemplateId);
1504
1505  void *InsertPos = 0;
1506  TypenameType *T
1507    = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1508  if (T)
1509    return QualType(T, 0);
1510
1511  T = new (*this) TypenameType(NNS, TemplateId, Canon);
1512  Types.push_back(T);
1513  TypenameTypes.InsertNode(T, InsertPos);
1514  return QualType(T, 0);
1515}
1516
1517/// CmpProtocolNames - Comparison predicate for sorting protocols
1518/// alphabetically.
1519static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
1520                            const ObjCProtocolDecl *RHS) {
1521  return LHS->getDeclName() < RHS->getDeclName();
1522}
1523
1524static void SortAndUniqueProtocols(ObjCProtocolDecl **&Protocols,
1525                                   unsigned &NumProtocols) {
1526  ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
1527
1528  // Sort protocols, keyed by name.
1529  std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
1530
1531  // Remove duplicates.
1532  ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
1533  NumProtocols = ProtocolsEnd-Protocols;
1534}
1535
1536
1537/// getObjCQualifiedInterfaceType - Return a ObjCQualifiedInterfaceType type for
1538/// the given interface decl and the conforming protocol list.
1539QualType ASTContext::getObjCQualifiedInterfaceType(ObjCInterfaceDecl *Decl,
1540                       ObjCProtocolDecl **Protocols, unsigned NumProtocols) {
1541  // Sort the protocol list alphabetically to canonicalize it.
1542  SortAndUniqueProtocols(Protocols, NumProtocols);
1543
1544  llvm::FoldingSetNodeID ID;
1545  ObjCQualifiedInterfaceType::Profile(ID, Decl, Protocols, NumProtocols);
1546
1547  void *InsertPos = 0;
1548  if (ObjCQualifiedInterfaceType *QT =
1549      ObjCQualifiedInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos))
1550    return QualType(QT, 0);
1551
1552  // No Match;
1553  ObjCQualifiedInterfaceType *QType =
1554    new (*this,8) ObjCQualifiedInterfaceType(Decl, Protocols, NumProtocols);
1555
1556  Types.push_back(QType);
1557  ObjCQualifiedInterfaceTypes.InsertNode(QType, InsertPos);
1558  return QualType(QType, 0);
1559}
1560
1561/// getObjCQualifiedIdType - Return an ObjCQualifiedIdType for the 'id' decl
1562/// and the conforming protocol list.
1563QualType ASTContext::getObjCQualifiedIdType(ObjCProtocolDecl **Protocols,
1564                                            unsigned NumProtocols) {
1565  // Sort the protocol list alphabetically to canonicalize it.
1566  SortAndUniqueProtocols(Protocols, NumProtocols);
1567
1568  llvm::FoldingSetNodeID ID;
1569  ObjCQualifiedIdType::Profile(ID, Protocols, NumProtocols);
1570
1571  void *InsertPos = 0;
1572  if (ObjCQualifiedIdType *QT =
1573        ObjCQualifiedIdTypes.FindNodeOrInsertPos(ID, InsertPos))
1574    return QualType(QT, 0);
1575
1576  // No Match;
1577  ObjCQualifiedIdType *QType =
1578    new (*this,8) ObjCQualifiedIdType(Protocols, NumProtocols);
1579  Types.push_back(QType);
1580  ObjCQualifiedIdTypes.InsertNode(QType, InsertPos);
1581  return QualType(QType, 0);
1582}
1583
1584/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
1585/// TypeOfExprType AST's (since expression's are never shared). For example,
1586/// multiple declarations that refer to "typeof(x)" all contain different
1587/// DeclRefExpr's. This doesn't effect the type checker, since it operates
1588/// on canonical type's (which are always unique).
1589QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
1590  QualType Canonical = getCanonicalType(tofExpr->getType());
1591  TypeOfExprType *toe = new (*this,8) TypeOfExprType(tofExpr, Canonical);
1592  Types.push_back(toe);
1593  return QualType(toe, 0);
1594}
1595
1596/// getTypeOfType -  Unlike many "get<Type>" functions, we don't unique
1597/// TypeOfType AST's. The only motivation to unique these nodes would be
1598/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
1599/// an issue. This doesn't effect the type checker, since it operates
1600/// on canonical type's (which are always unique).
1601QualType ASTContext::getTypeOfType(QualType tofType) {
1602  QualType Canonical = getCanonicalType(tofType);
1603  TypeOfType *tot = new (*this,8) TypeOfType(tofType, Canonical);
1604  Types.push_back(tot);
1605  return QualType(tot, 0);
1606}
1607
1608/// getTagDeclType - Return the unique reference to the type for the
1609/// specified TagDecl (struct/union/class/enum) decl.
1610QualType ASTContext::getTagDeclType(TagDecl *Decl) {
1611  assert (Decl);
1612  return getTypeDeclType(Decl);
1613}
1614
1615/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
1616/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
1617/// needs to agree with the definition in <stddef.h>.
1618QualType ASTContext::getSizeType() const {
1619  return getFromTargetType(Target.getSizeType());
1620}
1621
1622/// getSignedWCharType - Return the type of "signed wchar_t".
1623/// Used when in C++, as a GCC extension.
1624QualType ASTContext::getSignedWCharType() const {
1625  // FIXME: derive from "Target" ?
1626  return WCharTy;
1627}
1628
1629/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
1630/// Used when in C++, as a GCC extension.
1631QualType ASTContext::getUnsignedWCharType() const {
1632  // FIXME: derive from "Target" ?
1633  return UnsignedIntTy;
1634}
1635
1636/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
1637/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
1638QualType ASTContext::getPointerDiffType() const {
1639  return getFromTargetType(Target.getPtrDiffType(0));
1640}
1641
1642//===----------------------------------------------------------------------===//
1643//                              Type Operators
1644//===----------------------------------------------------------------------===//
1645
1646/// getCanonicalType - Return the canonical (structural) type corresponding to
1647/// the specified potentially non-canonical type.  The non-canonical version
1648/// of a type may have many "decorated" versions of types.  Decorators can
1649/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
1650/// to be free of any of these, allowing two canonical types to be compared
1651/// for exact equality with a simple pointer comparison.
1652QualType ASTContext::getCanonicalType(QualType T) {
1653  QualType CanType = T.getTypePtr()->getCanonicalTypeInternal();
1654
1655  // If the result has type qualifiers, make sure to canonicalize them as well.
1656  unsigned TypeQuals = T.getCVRQualifiers() | CanType.getCVRQualifiers();
1657  if (TypeQuals == 0) return CanType;
1658
1659  // If the type qualifiers are on an array type, get the canonical type of the
1660  // array with the qualifiers applied to the element type.
1661  ArrayType *AT = dyn_cast<ArrayType>(CanType);
1662  if (!AT)
1663    return CanType.getQualifiedType(TypeQuals);
1664
1665  // Get the canonical version of the element with the extra qualifiers on it.
1666  // This can recursively sink qualifiers through multiple levels of arrays.
1667  QualType NewEltTy=AT->getElementType().getWithAdditionalQualifiers(TypeQuals);
1668  NewEltTy = getCanonicalType(NewEltTy);
1669
1670  if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
1671    return getConstantArrayType(NewEltTy, CAT->getSize(),CAT->getSizeModifier(),
1672                                CAT->getIndexTypeQualifier());
1673  if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
1674    return getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
1675                                  IAT->getIndexTypeQualifier());
1676
1677  if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
1678    return getDependentSizedArrayType(NewEltTy, DSAT->getSizeExpr(),
1679                                      DSAT->getSizeModifier(),
1680                                      DSAT->getIndexTypeQualifier());
1681
1682  VariableArrayType *VAT = cast<VariableArrayType>(AT);
1683  return getVariableArrayType(NewEltTy, VAT->getSizeExpr(),
1684                              VAT->getSizeModifier(),
1685                              VAT->getIndexTypeQualifier());
1686}
1687
1688Decl *ASTContext::getCanonicalDecl(Decl *D) {
1689  if (!D)
1690    return 0;
1691
1692  if (TagDecl *Tag = dyn_cast<TagDecl>(D)) {
1693    QualType T = getTagDeclType(Tag);
1694    return cast<TagDecl>(cast<TagType>(T.getTypePtr()->CanonicalType)
1695                         ->getDecl());
1696  }
1697
1698  if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(D)) {
1699    while (Template->getPreviousDeclaration())
1700      Template = Template->getPreviousDeclaration();
1701    return Template;
1702  }
1703
1704  if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
1705    while (Function->getPreviousDeclaration())
1706      Function = Function->getPreviousDeclaration();
1707    return const_cast<FunctionDecl *>(Function);
1708  }
1709
1710  if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
1711    while (Var->getPreviousDeclaration())
1712      Var = Var->getPreviousDeclaration();
1713    return const_cast<VarDecl *>(Var);
1714  }
1715
1716  return D;
1717}
1718
1719TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
1720  // If this template name refers to a template, the canonical
1721  // template name merely stores the template itself.
1722  if (TemplateDecl *Template = Name.getAsTemplateDecl())
1723    return TemplateName(cast<TemplateDecl>(getCanonicalDecl(Template)));
1724
1725  DependentTemplateName *DTN = Name.getAsDependentTemplateName();
1726  assert(DTN && "Non-dependent template names must refer to template decls.");
1727  return DTN->CanonicalTemplateName;
1728}
1729
1730NestedNameSpecifier *
1731ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
1732  if (!NNS)
1733    return 0;
1734
1735  switch (NNS->getKind()) {
1736  case NestedNameSpecifier::Identifier:
1737    // Canonicalize the prefix but keep the identifier the same.
1738    return NestedNameSpecifier::Create(*this,
1739                         getCanonicalNestedNameSpecifier(NNS->getPrefix()),
1740                                       NNS->getAsIdentifier());
1741
1742  case NestedNameSpecifier::Namespace:
1743    // A namespace is canonical; build a nested-name-specifier with
1744    // this namespace and no prefix.
1745    return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
1746
1747  case NestedNameSpecifier::TypeSpec:
1748  case NestedNameSpecifier::TypeSpecWithTemplate: {
1749    QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
1750    NestedNameSpecifier *Prefix = 0;
1751
1752    // FIXME: This isn't the right check!
1753    if (T->isDependentType())
1754      Prefix = getCanonicalNestedNameSpecifier(NNS->getPrefix());
1755
1756    return NestedNameSpecifier::Create(*this, Prefix,
1757                 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
1758                                       T.getTypePtr());
1759  }
1760
1761  case NestedNameSpecifier::Global:
1762    // The global specifier is canonical and unique.
1763    return NNS;
1764  }
1765
1766  // Required to silence a GCC warning
1767  return 0;
1768}
1769
1770
1771const ArrayType *ASTContext::getAsArrayType(QualType T) {
1772  // Handle the non-qualified case efficiently.
1773  if (T.getCVRQualifiers() == 0) {
1774    // Handle the common positive case fast.
1775    if (const ArrayType *AT = dyn_cast<ArrayType>(T))
1776      return AT;
1777  }
1778
1779  // Handle the common negative case fast, ignoring CVR qualifiers.
1780  QualType CType = T->getCanonicalTypeInternal();
1781
1782  // Make sure to look through type qualifiers (like ExtQuals) for the negative
1783  // test.
1784  if (!isa<ArrayType>(CType) &&
1785      !isa<ArrayType>(CType.getUnqualifiedType()))
1786    return 0;
1787
1788  // Apply any CVR qualifiers from the array type to the element type.  This
1789  // implements C99 6.7.3p8: "If the specification of an array type includes
1790  // any type qualifiers, the element type is so qualified, not the array type."
1791
1792  // If we get here, we either have type qualifiers on the type, or we have
1793  // sugar such as a typedef in the way.  If we have type qualifiers on the type
1794  // we must propagate them down into the elemeng type.
1795  unsigned CVRQuals = T.getCVRQualifiers();
1796  unsigned AddrSpace = 0;
1797  Type *Ty = T.getTypePtr();
1798
1799  // Rip through ExtQualType's and typedefs to get to a concrete type.
1800  while (1) {
1801    if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(Ty)) {
1802      AddrSpace = EXTQT->getAddressSpace();
1803      Ty = EXTQT->getBaseType();
1804    } else {
1805      T = Ty->getDesugaredType();
1806      if (T.getTypePtr() == Ty && T.getCVRQualifiers() == 0)
1807        break;
1808      CVRQuals |= T.getCVRQualifiers();
1809      Ty = T.getTypePtr();
1810    }
1811  }
1812
1813  // If we have a simple case, just return now.
1814  const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
1815  if (ATy == 0 || (AddrSpace == 0 && CVRQuals == 0))
1816    return ATy;
1817
1818  // Otherwise, we have an array and we have qualifiers on it.  Push the
1819  // qualifiers into the array element type and return a new array type.
1820  // Get the canonical version of the element with the extra qualifiers on it.
1821  // This can recursively sink qualifiers through multiple levels of arrays.
1822  QualType NewEltTy = ATy->getElementType();
1823  if (AddrSpace)
1824    NewEltTy = getAddrSpaceQualType(NewEltTy, AddrSpace);
1825  NewEltTy = NewEltTy.getWithAdditionalQualifiers(CVRQuals);
1826
1827  if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
1828    return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
1829                                                CAT->getSizeModifier(),
1830                                                CAT->getIndexTypeQualifier()));
1831  if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
1832    return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
1833                                                  IAT->getSizeModifier(),
1834                                                 IAT->getIndexTypeQualifier()));
1835
1836  if (const DependentSizedArrayType *DSAT
1837        = dyn_cast<DependentSizedArrayType>(ATy))
1838    return cast<ArrayType>(
1839                     getDependentSizedArrayType(NewEltTy,
1840                                                DSAT->getSizeExpr(),
1841                                                DSAT->getSizeModifier(),
1842                                                DSAT->getIndexTypeQualifier()));
1843
1844  const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
1845  return cast<ArrayType>(getVariableArrayType(NewEltTy, VAT->getSizeExpr(),
1846                                              VAT->getSizeModifier(),
1847                                              VAT->getIndexTypeQualifier()));
1848}
1849
1850
1851/// getArrayDecayedType - Return the properly qualified result of decaying the
1852/// specified array type to a pointer.  This operation is non-trivial when
1853/// handling typedefs etc.  The canonical type of "T" must be an array type,
1854/// this returns a pointer to a properly qualified element of the array.
1855///
1856/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
1857QualType ASTContext::getArrayDecayedType(QualType Ty) {
1858  // Get the element type with 'getAsArrayType' so that we don't lose any
1859  // typedefs in the element type of the array.  This also handles propagation
1860  // of type qualifiers from the array type into the element type if present
1861  // (C99 6.7.3p8).
1862  const ArrayType *PrettyArrayType = getAsArrayType(Ty);
1863  assert(PrettyArrayType && "Not an array type!");
1864
1865  QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
1866
1867  // int x[restrict 4] ->  int *restrict
1868  return PtrTy.getQualifiedType(PrettyArrayType->getIndexTypeQualifier());
1869}
1870
1871QualType ASTContext::getBaseElementType(const VariableArrayType *VAT) {
1872  QualType ElemTy = VAT->getElementType();
1873
1874  if (const VariableArrayType *VAT = getAsVariableArrayType(ElemTy))
1875    return getBaseElementType(VAT);
1876
1877  return ElemTy;
1878}
1879
1880/// getFloatingRank - Return a relative rank for floating point types.
1881/// This routine will assert if passed a built-in type that isn't a float.
1882static FloatingRank getFloatingRank(QualType T) {
1883  if (const ComplexType *CT = T->getAsComplexType())
1884    return getFloatingRank(CT->getElementType());
1885
1886  assert(T->getAsBuiltinType() && "getFloatingRank(): not a floating type");
1887  switch (T->getAsBuiltinType()->getKind()) {
1888  default: assert(0 && "getFloatingRank(): not a floating type");
1889  case BuiltinType::Float:      return FloatRank;
1890  case BuiltinType::Double:     return DoubleRank;
1891  case BuiltinType::LongDouble: return LongDoubleRank;
1892  }
1893}
1894
1895/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
1896/// point or a complex type (based on typeDomain/typeSize).
1897/// 'typeDomain' is a real floating point or complex type.
1898/// 'typeSize' is a real floating point or complex type.
1899QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
1900                                                       QualType Domain) const {
1901  FloatingRank EltRank = getFloatingRank(Size);
1902  if (Domain->isComplexType()) {
1903    switch (EltRank) {
1904    default: assert(0 && "getFloatingRank(): illegal value for rank");
1905    case FloatRank:      return FloatComplexTy;
1906    case DoubleRank:     return DoubleComplexTy;
1907    case LongDoubleRank: return LongDoubleComplexTy;
1908    }
1909  }
1910
1911  assert(Domain->isRealFloatingType() && "Unknown domain!");
1912  switch (EltRank) {
1913  default: assert(0 && "getFloatingRank(): illegal value for rank");
1914  case FloatRank:      return FloatTy;
1915  case DoubleRank:     return DoubleTy;
1916  case LongDoubleRank: return LongDoubleTy;
1917  }
1918}
1919
1920/// getFloatingTypeOrder - Compare the rank of the two specified floating
1921/// point types, ignoring the domain of the type (i.e. 'double' ==
1922/// '_Complex double').  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
1923/// LHS < RHS, return -1.
1924int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
1925  FloatingRank LHSR = getFloatingRank(LHS);
1926  FloatingRank RHSR = getFloatingRank(RHS);
1927
1928  if (LHSR == RHSR)
1929    return 0;
1930  if (LHSR > RHSR)
1931    return 1;
1932  return -1;
1933}
1934
1935/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
1936/// routine will assert if passed a built-in type that isn't an integer or enum,
1937/// or if it is not canonicalized.
1938unsigned ASTContext::getIntegerRank(Type *T) {
1939  assert(T->isCanonical() && "T should be canonicalized");
1940  if (EnumType* ET = dyn_cast<EnumType>(T))
1941    T = ET->getDecl()->getIntegerType().getTypePtr();
1942
1943  // There are two things which impact the integer rank: the width, and
1944  // the ordering of builtins.  The builtin ordering is encoded in the
1945  // bottom three bits; the width is encoded in the bits above that.
1946  if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T)) {
1947    return FWIT->getWidth() << 3;
1948  }
1949
1950  switch (cast<BuiltinType>(T)->getKind()) {
1951  default: assert(0 && "getIntegerRank(): not a built-in integer");
1952  case BuiltinType::Bool:
1953    return 1 + (getIntWidth(BoolTy) << 3);
1954  case BuiltinType::Char_S:
1955  case BuiltinType::Char_U:
1956  case BuiltinType::SChar:
1957  case BuiltinType::UChar:
1958    return 2 + (getIntWidth(CharTy) << 3);
1959  case BuiltinType::Short:
1960  case BuiltinType::UShort:
1961    return 3 + (getIntWidth(ShortTy) << 3);
1962  case BuiltinType::Int:
1963  case BuiltinType::UInt:
1964    return 4 + (getIntWidth(IntTy) << 3);
1965  case BuiltinType::Long:
1966  case BuiltinType::ULong:
1967    return 5 + (getIntWidth(LongTy) << 3);
1968  case BuiltinType::LongLong:
1969  case BuiltinType::ULongLong:
1970    return 6 + (getIntWidth(LongLongTy) << 3);
1971  case BuiltinType::Int128:
1972  case BuiltinType::UInt128:
1973    return 7 + (getIntWidth(Int128Ty) << 3);
1974  }
1975}
1976
1977/// getIntegerTypeOrder - Returns the highest ranked integer type:
1978/// C99 6.3.1.8p1.  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
1979/// LHS < RHS, return -1.
1980int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
1981  Type *LHSC = getCanonicalType(LHS).getTypePtr();
1982  Type *RHSC = getCanonicalType(RHS).getTypePtr();
1983  if (LHSC == RHSC) return 0;
1984
1985  bool LHSUnsigned = LHSC->isUnsignedIntegerType();
1986  bool RHSUnsigned = RHSC->isUnsignedIntegerType();
1987
1988  unsigned LHSRank = getIntegerRank(LHSC);
1989  unsigned RHSRank = getIntegerRank(RHSC);
1990
1991  if (LHSUnsigned == RHSUnsigned) {  // Both signed or both unsigned.
1992    if (LHSRank == RHSRank) return 0;
1993    return LHSRank > RHSRank ? 1 : -1;
1994  }
1995
1996  // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
1997  if (LHSUnsigned) {
1998    // If the unsigned [LHS] type is larger, return it.
1999    if (LHSRank >= RHSRank)
2000      return 1;
2001
2002    // If the signed type can represent all values of the unsigned type, it
2003    // wins.  Because we are dealing with 2's complement and types that are
2004    // powers of two larger than each other, this is always safe.
2005    return -1;
2006  }
2007
2008  // If the unsigned [RHS] type is larger, return it.
2009  if (RHSRank >= LHSRank)
2010    return -1;
2011
2012  // If the signed type can represent all values of the unsigned type, it
2013  // wins.  Because we are dealing with 2's complement and types that are
2014  // powers of two larger than each other, this is always safe.
2015  return 1;
2016}
2017
2018// getCFConstantStringType - Return the type used for constant CFStrings.
2019QualType ASTContext::getCFConstantStringType() {
2020  if (!CFConstantStringTypeDecl) {
2021    CFConstantStringTypeDecl =
2022      RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2023                         &Idents.get("NSConstantString"));
2024    QualType FieldTypes[4];
2025
2026    // const int *isa;
2027    FieldTypes[0] = getPointerType(IntTy.getQualifiedType(QualType::Const));
2028    // int flags;
2029    FieldTypes[1] = IntTy;
2030    // const char *str;
2031    FieldTypes[2] = getPointerType(CharTy.getQualifiedType(QualType::Const));
2032    // long length;
2033    FieldTypes[3] = LongTy;
2034
2035    // Create fields
2036    for (unsigned i = 0; i < 4; ++i) {
2037      FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
2038                                           SourceLocation(), 0,
2039                                           FieldTypes[i], /*BitWidth=*/0,
2040                                           /*Mutable=*/false);
2041      CFConstantStringTypeDecl->addDecl(*this, Field);
2042    }
2043
2044    CFConstantStringTypeDecl->completeDefinition(*this);
2045  }
2046
2047  return getTagDeclType(CFConstantStringTypeDecl);
2048}
2049
2050void ASTContext::setCFConstantStringType(QualType T) {
2051  const RecordType *Rec = T->getAsRecordType();
2052  assert(Rec && "Invalid CFConstantStringType");
2053  CFConstantStringTypeDecl = Rec->getDecl();
2054}
2055
2056QualType ASTContext::getObjCFastEnumerationStateType()
2057{
2058  if (!ObjCFastEnumerationStateTypeDecl) {
2059    ObjCFastEnumerationStateTypeDecl =
2060      RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2061                         &Idents.get("__objcFastEnumerationState"));
2062
2063    QualType FieldTypes[] = {
2064      UnsignedLongTy,
2065      getPointerType(ObjCIdType),
2066      getPointerType(UnsignedLongTy),
2067      getConstantArrayType(UnsignedLongTy,
2068                           llvm::APInt(32, 5), ArrayType::Normal, 0)
2069    };
2070
2071    for (size_t i = 0; i < 4; ++i) {
2072      FieldDecl *Field = FieldDecl::Create(*this,
2073                                           ObjCFastEnumerationStateTypeDecl,
2074                                           SourceLocation(), 0,
2075                                           FieldTypes[i], /*BitWidth=*/0,
2076                                           /*Mutable=*/false);
2077      ObjCFastEnumerationStateTypeDecl->addDecl(*this, Field);
2078    }
2079
2080    ObjCFastEnumerationStateTypeDecl->completeDefinition(*this);
2081  }
2082
2083  return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
2084}
2085
2086void ASTContext::setObjCFastEnumerationStateType(QualType T) {
2087  const RecordType *Rec = T->getAsRecordType();
2088  assert(Rec && "Invalid ObjCFAstEnumerationStateType");
2089  ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
2090}
2091
2092// This returns true if a type has been typedefed to BOOL:
2093// typedef <type> BOOL;
2094static bool isTypeTypedefedAsBOOL(QualType T) {
2095  if (const TypedefType *TT = dyn_cast<TypedefType>(T))
2096    if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
2097      return II->isStr("BOOL");
2098
2099  return false;
2100}
2101
2102/// getObjCEncodingTypeSize returns size of type for objective-c encoding
2103/// purpose.
2104int ASTContext::getObjCEncodingTypeSize(QualType type) {
2105  uint64_t sz = getTypeSize(type);
2106
2107  // Make all integer and enum types at least as large as an int
2108  if (sz > 0 && type->isIntegralType())
2109    sz = std::max(sz, getTypeSize(IntTy));
2110  // Treat arrays as pointers, since that's how they're passed in.
2111  else if (type->isArrayType())
2112    sz = getTypeSize(VoidPtrTy);
2113  return sz / getTypeSize(CharTy);
2114}
2115
2116/// getObjCEncodingForMethodDecl - Return the encoded type for this method
2117/// declaration.
2118void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
2119                                              std::string& S) {
2120  // FIXME: This is not very efficient.
2121  // Encode type qualifer, 'in', 'inout', etc. for the return type.
2122  getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
2123  // Encode result type.
2124  getObjCEncodingForType(Decl->getResultType(), S);
2125  // Compute size of all parameters.
2126  // Start with computing size of a pointer in number of bytes.
2127  // FIXME: There might(should) be a better way of doing this computation!
2128  SourceLocation Loc;
2129  int PtrSize = getTypeSize(VoidPtrTy) / getTypeSize(CharTy);
2130  // The first two arguments (self and _cmd) are pointers; account for
2131  // their size.
2132  int ParmOffset = 2 * PtrSize;
2133  for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
2134       E = Decl->param_end(); PI != E; ++PI) {
2135    QualType PType = (*PI)->getType();
2136    int sz = getObjCEncodingTypeSize(PType);
2137    assert (sz > 0 && "getObjCEncodingForMethodDecl - Incomplete param type");
2138    ParmOffset += sz;
2139  }
2140  S += llvm::utostr(ParmOffset);
2141  S += "@0:";
2142  S += llvm::utostr(PtrSize);
2143
2144  // Argument types.
2145  ParmOffset = 2 * PtrSize;
2146  for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
2147       E = Decl->param_end(); PI != E; ++PI) {
2148    ParmVarDecl *PVDecl = *PI;
2149    QualType PType = PVDecl->getOriginalType();
2150    if (const ArrayType *AT =
2151          dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
2152      // Use array's original type only if it has known number of
2153      // elements.
2154      if (!isa<ConstantArrayType>(AT))
2155        PType = PVDecl->getType();
2156    } else if (PType->isFunctionType())
2157      PType = PVDecl->getType();
2158    // Process argument qualifiers for user supplied arguments; such as,
2159    // 'in', 'inout', etc.
2160    getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
2161    getObjCEncodingForType(PType, S);
2162    S += llvm::utostr(ParmOffset);
2163    ParmOffset += getObjCEncodingTypeSize(PType);
2164  }
2165}
2166
2167/// getObjCEncodingForPropertyDecl - Return the encoded type for this
2168/// property declaration. If non-NULL, Container must be either an
2169/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
2170/// NULL when getting encodings for protocol properties.
2171/// Property attributes are stored as a comma-delimited C string. The simple
2172/// attributes readonly and bycopy are encoded as single characters. The
2173/// parametrized attributes, getter=name, setter=name, and ivar=name, are
2174/// encoded as single characters, followed by an identifier. Property types
2175/// are also encoded as a parametrized attribute. The characters used to encode
2176/// these attributes are defined by the following enumeration:
2177/// @code
2178/// enum PropertyAttributes {
2179/// kPropertyReadOnly = 'R',   // property is read-only.
2180/// kPropertyBycopy = 'C',     // property is a copy of the value last assigned
2181/// kPropertyByref = '&',  // property is a reference to the value last assigned
2182/// kPropertyDynamic = 'D',    // property is dynamic
2183/// kPropertyGetter = 'G',     // followed by getter selector name
2184/// kPropertySetter = 'S',     // followed by setter selector name
2185/// kPropertyInstanceVariable = 'V'  // followed by instance variable  name
2186/// kPropertyType = 't'              // followed by old-style type encoding.
2187/// kPropertyWeak = 'W'              // 'weak' property
2188/// kPropertyStrong = 'P'            // property GC'able
2189/// kPropertyNonAtomic = 'N'         // property non-atomic
2190/// };
2191/// @endcode
2192void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
2193                                                const Decl *Container,
2194                                                std::string& S) {
2195  // Collect information from the property implementation decl(s).
2196  bool Dynamic = false;
2197  ObjCPropertyImplDecl *SynthesizePID = 0;
2198
2199  // FIXME: Duplicated code due to poor abstraction.
2200  if (Container) {
2201    if (const ObjCCategoryImplDecl *CID =
2202        dyn_cast<ObjCCategoryImplDecl>(Container)) {
2203      for (ObjCCategoryImplDecl::propimpl_iterator
2204             i = CID->propimpl_begin(*this), e = CID->propimpl_end(*this);
2205           i != e; ++i) {
2206        ObjCPropertyImplDecl *PID = *i;
2207        if (PID->getPropertyDecl() == PD) {
2208          if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
2209            Dynamic = true;
2210          } else {
2211            SynthesizePID = PID;
2212          }
2213        }
2214      }
2215    } else {
2216      const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
2217      for (ObjCCategoryImplDecl::propimpl_iterator
2218             i = OID->propimpl_begin(*this), e = OID->propimpl_end(*this);
2219           i != e; ++i) {
2220        ObjCPropertyImplDecl *PID = *i;
2221        if (PID->getPropertyDecl() == PD) {
2222          if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
2223            Dynamic = true;
2224          } else {
2225            SynthesizePID = PID;
2226          }
2227        }
2228      }
2229    }
2230  }
2231
2232  // FIXME: This is not very efficient.
2233  S = "T";
2234
2235  // Encode result type.
2236  // GCC has some special rules regarding encoding of properties which
2237  // closely resembles encoding of ivars.
2238  getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
2239                             true /* outermost type */,
2240                             true /* encoding for property */);
2241
2242  if (PD->isReadOnly()) {
2243    S += ",R";
2244  } else {
2245    switch (PD->getSetterKind()) {
2246    case ObjCPropertyDecl::Assign: break;
2247    case ObjCPropertyDecl::Copy:   S += ",C"; break;
2248    case ObjCPropertyDecl::Retain: S += ",&"; break;
2249    }
2250  }
2251
2252  // It really isn't clear at all what this means, since properties
2253  // are "dynamic by default".
2254  if (Dynamic)
2255    S += ",D";
2256
2257  if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
2258    S += ",N";
2259
2260  if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
2261    S += ",G";
2262    S += PD->getGetterName().getAsString();
2263  }
2264
2265  if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
2266    S += ",S";
2267    S += PD->getSetterName().getAsString();
2268  }
2269
2270  if (SynthesizePID) {
2271    const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
2272    S += ",V";
2273    S += OID->getNameAsString();
2274  }
2275
2276  // FIXME: OBJCGC: weak & strong
2277}
2278
2279/// getLegacyIntegralTypeEncoding -
2280/// Another legacy compatibility encoding: 32-bit longs are encoded as
2281/// 'l' or 'L' , but not always.  For typedefs, we need to use
2282/// 'i' or 'I' instead if encoding a struct field, or a pointer!
2283///
2284void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
2285  if (dyn_cast<TypedefType>(PointeeTy.getTypePtr())) {
2286    if (const BuiltinType *BT = PointeeTy->getAsBuiltinType()) {
2287      if (BT->getKind() == BuiltinType::ULong &&
2288          ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
2289        PointeeTy = UnsignedIntTy;
2290      else
2291        if (BT->getKind() == BuiltinType::Long &&
2292            ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
2293          PointeeTy = IntTy;
2294    }
2295  }
2296}
2297
2298void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
2299                                        const FieldDecl *Field) {
2300  // We follow the behavior of gcc, expanding structures which are
2301  // directly pointed to, and expanding embedded structures. Note that
2302  // these rules are sufficient to prevent recursive encoding of the
2303  // same type.
2304  getObjCEncodingForTypeImpl(T, S, true, true, Field,
2305                             true /* outermost type */);
2306}
2307
2308static void EncodeBitField(const ASTContext *Context, std::string& S,
2309                           const FieldDecl *FD) {
2310  const Expr *E = FD->getBitWidth();
2311  assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
2312  ASTContext *Ctx = const_cast<ASTContext*>(Context);
2313  unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
2314  S += 'b';
2315  S += llvm::utostr(N);
2316}
2317
2318void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
2319                                            bool ExpandPointedToStructures,
2320                                            bool ExpandStructures,
2321                                            const FieldDecl *FD,
2322                                            bool OutermostType,
2323                                            bool EncodingProperty) {
2324  if (const BuiltinType *BT = T->getAsBuiltinType()) {
2325    if (FD && FD->isBitField()) {
2326      EncodeBitField(this, S, FD);
2327    }
2328    else {
2329      char encoding;
2330      switch (BT->getKind()) {
2331      default: assert(0 && "Unhandled builtin type kind");
2332      case BuiltinType::Void:       encoding = 'v'; break;
2333      case BuiltinType::Bool:       encoding = 'B'; break;
2334      case BuiltinType::Char_U:
2335      case BuiltinType::UChar:      encoding = 'C'; break;
2336      case BuiltinType::UShort:     encoding = 'S'; break;
2337      case BuiltinType::UInt:       encoding = 'I'; break;
2338      case BuiltinType::ULong:
2339          encoding =
2340            (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q';
2341          break;
2342      case BuiltinType::UInt128:    encoding = 'T'; break;
2343      case BuiltinType::ULongLong:  encoding = 'Q'; break;
2344      case BuiltinType::Char_S:
2345      case BuiltinType::SChar:      encoding = 'c'; break;
2346      case BuiltinType::Short:      encoding = 's'; break;
2347      case BuiltinType::Int:        encoding = 'i'; break;
2348      case BuiltinType::Long:
2349        encoding =
2350          (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q';
2351        break;
2352      case BuiltinType::LongLong:   encoding = 'q'; break;
2353      case BuiltinType::Int128:     encoding = 't'; break;
2354      case BuiltinType::Float:      encoding = 'f'; break;
2355      case BuiltinType::Double:     encoding = 'd'; break;
2356      case BuiltinType::LongDouble: encoding = 'd'; break;
2357      }
2358
2359      S += encoding;
2360    }
2361  } else if (const ComplexType *CT = T->getAsComplexType()) {
2362    S += 'j';
2363    getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
2364                               false);
2365  } else if (T->isObjCQualifiedIdType()) {
2366    getObjCEncodingForTypeImpl(getObjCIdType(), S,
2367                               ExpandPointedToStructures,
2368                               ExpandStructures, FD);
2369    if (FD || EncodingProperty) {
2370      // Note that we do extended encoding of protocol qualifer list
2371      // Only when doing ivar or property encoding.
2372      const ObjCQualifiedIdType *QIDT = T->getAsObjCQualifiedIdType();
2373      S += '"';
2374      for (ObjCQualifiedIdType::qual_iterator I = QIDT->qual_begin(),
2375           E = QIDT->qual_end(); I != E; ++I) {
2376        S += '<';
2377        S += (*I)->getNameAsString();
2378        S += '>';
2379      }
2380      S += '"';
2381    }
2382    return;
2383  }
2384  else if (const PointerType *PT = T->getAsPointerType()) {
2385    QualType PointeeTy = PT->getPointeeType();
2386    bool isReadOnly = false;
2387    // For historical/compatibility reasons, the read-only qualifier of the
2388    // pointee gets emitted _before_ the '^'.  The read-only qualifier of
2389    // the pointer itself gets ignored, _unless_ we are looking at a typedef!
2390    // Also, do not emit the 'r' for anything but the outermost type!
2391    if (dyn_cast<TypedefType>(T.getTypePtr())) {
2392      if (OutermostType && T.isConstQualified()) {
2393        isReadOnly = true;
2394        S += 'r';
2395      }
2396    }
2397    else if (OutermostType) {
2398      QualType P = PointeeTy;
2399      while (P->getAsPointerType())
2400        P = P->getAsPointerType()->getPointeeType();
2401      if (P.isConstQualified()) {
2402        isReadOnly = true;
2403        S += 'r';
2404      }
2405    }
2406    if (isReadOnly) {
2407      // Another legacy compatibility encoding. Some ObjC qualifier and type
2408      // combinations need to be rearranged.
2409      // Rewrite "in const" from "nr" to "rn"
2410      const char * s = S.c_str();
2411      int len = S.length();
2412      if (len >= 2 && s[len-2] == 'n' && s[len-1] == 'r') {
2413        std::string replace = "rn";
2414        S.replace(S.end()-2, S.end(), replace);
2415      }
2416    }
2417    if (isObjCIdStructType(PointeeTy)) {
2418      S += '@';
2419      return;
2420    }
2421    else if (PointeeTy->isObjCInterfaceType()) {
2422      if (!EncodingProperty &&
2423          isa<TypedefType>(PointeeTy.getTypePtr())) {
2424        // Another historical/compatibility reason.
2425        // We encode the underlying type which comes out as
2426        // {...};
2427        S += '^';
2428        getObjCEncodingForTypeImpl(PointeeTy, S,
2429                                   false, ExpandPointedToStructures,
2430                                   NULL);
2431        return;
2432      }
2433      S += '@';
2434      if (FD || EncodingProperty) {
2435        const ObjCInterfaceType *OIT =
2436                PointeeTy.getUnqualifiedType()->getAsObjCInterfaceType();
2437        ObjCInterfaceDecl *OI = OIT->getDecl();
2438        S += '"';
2439        S += OI->getNameAsCString();
2440        for (ObjCInterfaceType::qual_iterator I = OIT->qual_begin(),
2441             E = OIT->qual_end(); I != E; ++I) {
2442          S += '<';
2443          S += (*I)->getNameAsString();
2444          S += '>';
2445        }
2446        S += '"';
2447      }
2448      return;
2449    } else if (isObjCClassStructType(PointeeTy)) {
2450      S += '#';
2451      return;
2452    } else if (isObjCSelType(PointeeTy)) {
2453      S += ':';
2454      return;
2455    }
2456
2457    if (PointeeTy->isCharType()) {
2458      // char pointer types should be encoded as '*' unless it is a
2459      // type that has been typedef'd to 'BOOL'.
2460      if (!isTypeTypedefedAsBOOL(PointeeTy)) {
2461        S += '*';
2462        return;
2463      }
2464    }
2465
2466    S += '^';
2467    getLegacyIntegralTypeEncoding(PointeeTy);
2468
2469    getObjCEncodingForTypeImpl(PointeeTy, S,
2470                               false, ExpandPointedToStructures,
2471                               NULL);
2472  } else if (const ArrayType *AT =
2473               // Ignore type qualifiers etc.
2474               dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
2475    if (isa<IncompleteArrayType>(AT)) {
2476      // Incomplete arrays are encoded as a pointer to the array element.
2477      S += '^';
2478
2479      getObjCEncodingForTypeImpl(AT->getElementType(), S,
2480                                 false, ExpandStructures, FD);
2481    } else {
2482      S += '[';
2483
2484      if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
2485        S += llvm::utostr(CAT->getSize().getZExtValue());
2486      else {
2487        //Variable length arrays are encoded as a regular array with 0 elements.
2488        assert(isa<VariableArrayType>(AT) && "Unknown array type!");
2489        S += '0';
2490      }
2491
2492      getObjCEncodingForTypeImpl(AT->getElementType(), S,
2493                                 false, ExpandStructures, FD);
2494      S += ']';
2495    }
2496  } else if (T->getAsFunctionType()) {
2497    S += '?';
2498  } else if (const RecordType *RTy = T->getAsRecordType()) {
2499    RecordDecl *RDecl = RTy->getDecl();
2500    S += RDecl->isUnion() ? '(' : '{';
2501    // Anonymous structures print as '?'
2502    if (const IdentifierInfo *II = RDecl->getIdentifier()) {
2503      S += II->getName();
2504    } else {
2505      S += '?';
2506    }
2507    if (ExpandStructures) {
2508      S += '=';
2509      for (RecordDecl::field_iterator Field = RDecl->field_begin(*this),
2510                                   FieldEnd = RDecl->field_end(*this);
2511           Field != FieldEnd; ++Field) {
2512        if (FD) {
2513          S += '"';
2514          S += Field->getNameAsString();
2515          S += '"';
2516        }
2517
2518        // Special case bit-fields.
2519        if (Field->isBitField()) {
2520          getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
2521                                     (*Field));
2522        } else {
2523          QualType qt = Field->getType();
2524          getLegacyIntegralTypeEncoding(qt);
2525          getObjCEncodingForTypeImpl(qt, S, false, true,
2526                                     FD);
2527        }
2528      }
2529    }
2530    S += RDecl->isUnion() ? ')' : '}';
2531  } else if (T->isEnumeralType()) {
2532    if (FD && FD->isBitField())
2533      EncodeBitField(this, S, FD);
2534    else
2535      S += 'i';
2536  } else if (T->isBlockPointerType()) {
2537    S += "@?"; // Unlike a pointer-to-function, which is "^?".
2538  } else if (T->isObjCInterfaceType()) {
2539    // @encode(class_name)
2540    ObjCInterfaceDecl *OI = T->getAsObjCInterfaceType()->getDecl();
2541    S += '{';
2542    const IdentifierInfo *II = OI->getIdentifier();
2543    S += II->getName();
2544    S += '=';
2545    llvm::SmallVector<FieldDecl*, 32> RecFields;
2546    CollectObjCIvars(OI, RecFields);
2547    for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
2548      if (RecFields[i]->isBitField())
2549        getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
2550                                   RecFields[i]);
2551      else
2552        getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
2553                                   FD);
2554    }
2555    S += '}';
2556  }
2557  else
2558    assert(0 && "@encode for type not implemented!");
2559}
2560
2561void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
2562                                                 std::string& S) const {
2563  if (QT & Decl::OBJC_TQ_In)
2564    S += 'n';
2565  if (QT & Decl::OBJC_TQ_Inout)
2566    S += 'N';
2567  if (QT & Decl::OBJC_TQ_Out)
2568    S += 'o';
2569  if (QT & Decl::OBJC_TQ_Bycopy)
2570    S += 'O';
2571  if (QT & Decl::OBJC_TQ_Byref)
2572    S += 'R';
2573  if (QT & Decl::OBJC_TQ_Oneway)
2574    S += 'V';
2575}
2576
2577void ASTContext::setBuiltinVaListType(QualType T)
2578{
2579  assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
2580
2581  BuiltinVaListType = T;
2582}
2583
2584void ASTContext::setObjCIdType(QualType T)
2585{
2586  ObjCIdType = T;
2587
2588  const TypedefType *TT = T->getAsTypedefType();
2589  if (!TT)
2590    return;
2591
2592  TypedefDecl *TD = TT->getDecl();
2593
2594  // typedef struct objc_object *id;
2595  const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
2596  // User error - caller will issue diagnostics.
2597  if (!ptr)
2598    return;
2599  const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
2600  // User error - caller will issue diagnostics.
2601  if (!rec)
2602    return;
2603  IdStructType = rec;
2604}
2605
2606void ASTContext::setObjCSelType(QualType T)
2607{
2608  ObjCSelType = T;
2609
2610  const TypedefType *TT = T->getAsTypedefType();
2611  if (!TT)
2612    return;
2613  TypedefDecl *TD = TT->getDecl();
2614
2615  // typedef struct objc_selector *SEL;
2616  const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
2617  if (!ptr)
2618    return;
2619  const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
2620  if (!rec)
2621    return;
2622  SelStructType = rec;
2623}
2624
2625void ASTContext::setObjCProtoType(QualType QT)
2626{
2627  ObjCProtoType = QT;
2628}
2629
2630void ASTContext::setObjCClassType(QualType T)
2631{
2632  ObjCClassType = T;
2633
2634  const TypedefType *TT = T->getAsTypedefType();
2635  if (!TT)
2636    return;
2637  TypedefDecl *TD = TT->getDecl();
2638
2639  // typedef struct objc_class *Class;
2640  const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
2641  assert(ptr && "'Class' incorrectly typed");
2642  const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
2643  assert(rec && "'Class' incorrectly typed");
2644  ClassStructType = rec;
2645}
2646
2647void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
2648  assert(ObjCConstantStringType.isNull() &&
2649         "'NSConstantString' type already set!");
2650
2651  ObjCConstantStringType = getObjCInterfaceType(Decl);
2652}
2653
2654/// \brief Retrieve the template name that represents a qualified
2655/// template name such as \c std::vector.
2656TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
2657                                                  bool TemplateKeyword,
2658                                                  TemplateDecl *Template) {
2659  llvm::FoldingSetNodeID ID;
2660  QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
2661
2662  void *InsertPos = 0;
2663  QualifiedTemplateName *QTN =
2664    QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
2665  if (!QTN) {
2666    QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
2667    QualifiedTemplateNames.InsertNode(QTN, InsertPos);
2668  }
2669
2670  return TemplateName(QTN);
2671}
2672
2673/// \brief Retrieve the template name that represents a dependent
2674/// template name such as \c MetaFun::template apply.
2675TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
2676                                                  const IdentifierInfo *Name) {
2677  assert(NNS->isDependent() && "Nested name specifier must be dependent");
2678
2679  llvm::FoldingSetNodeID ID;
2680  DependentTemplateName::Profile(ID, NNS, Name);
2681
2682  void *InsertPos = 0;
2683  DependentTemplateName *QTN =
2684    DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
2685
2686  if (QTN)
2687    return TemplateName(QTN);
2688
2689  NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
2690  if (CanonNNS == NNS) {
2691    QTN = new (*this,4) DependentTemplateName(NNS, Name);
2692  } else {
2693    TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
2694    QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
2695  }
2696
2697  DependentTemplateNames.InsertNode(QTN, InsertPos);
2698  return TemplateName(QTN);
2699}
2700
2701/// getFromTargetType - Given one of the integer types provided by
2702/// TargetInfo, produce the corresponding type. The unsigned @p Type
2703/// is actually a value of type @c TargetInfo::IntType.
2704QualType ASTContext::getFromTargetType(unsigned Type) const {
2705  switch (Type) {
2706  case TargetInfo::NoInt: return QualType();
2707  case TargetInfo::SignedShort: return ShortTy;
2708  case TargetInfo::UnsignedShort: return UnsignedShortTy;
2709  case TargetInfo::SignedInt: return IntTy;
2710  case TargetInfo::UnsignedInt: return UnsignedIntTy;
2711  case TargetInfo::SignedLong: return LongTy;
2712  case TargetInfo::UnsignedLong: return UnsignedLongTy;
2713  case TargetInfo::SignedLongLong: return LongLongTy;
2714  case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
2715  }
2716
2717  assert(false && "Unhandled TargetInfo::IntType value");
2718  return QualType();
2719}
2720
2721//===----------------------------------------------------------------------===//
2722//                        Type Predicates.
2723//===----------------------------------------------------------------------===//
2724
2725/// isObjCNSObjectType - Return true if this is an NSObject object using
2726/// NSObject attribute on a c-style pointer type.
2727/// FIXME - Make it work directly on types.
2728///
2729bool ASTContext::isObjCNSObjectType(QualType Ty) const {
2730  if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
2731    if (TypedefDecl *TD = TDT->getDecl())
2732      if (TD->getAttr<ObjCNSObjectAttr>())
2733        return true;
2734  }
2735  return false;
2736}
2737
2738/// isObjCObjectPointerType - Returns true if type is an Objective-C pointer
2739/// to an object type.  This includes "id" and "Class" (two 'special' pointers
2740/// to struct), Interface* (pointer to ObjCInterfaceType) and id<P> (qualified
2741/// ID type).
2742bool ASTContext::isObjCObjectPointerType(QualType Ty) const {
2743  if (Ty->isObjCQualifiedIdType())
2744    return true;
2745
2746  // Blocks are objects.
2747  if (Ty->isBlockPointerType())
2748    return true;
2749
2750  // All other object types are pointers.
2751  const PointerType *PT = Ty->getAsPointerType();
2752  if (PT == 0)
2753    return false;
2754
2755  // If this a pointer to an interface (e.g. NSString*), it is ok.
2756  if (PT->getPointeeType()->isObjCInterfaceType() ||
2757      // If is has NSObject attribute, OK as well.
2758      isObjCNSObjectType(Ty))
2759    return true;
2760
2761  // Check to see if this is 'id' or 'Class', both of which are typedefs for
2762  // pointer types.  This looks for the typedef specifically, not for the
2763  // underlying type.  Iteratively strip off typedefs so that we can handle
2764  // typedefs of typedefs.
2765  while (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
2766    if (Ty.getUnqualifiedType() == getObjCIdType() ||
2767        Ty.getUnqualifiedType() == getObjCClassType())
2768      return true;
2769
2770    Ty = TDT->getDecl()->getUnderlyingType();
2771  }
2772
2773  return false;
2774}
2775
2776/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
2777/// garbage collection attribute.
2778///
2779QualType::GCAttrTypes ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
2780  QualType::GCAttrTypes GCAttrs = QualType::GCNone;
2781  if (getLangOptions().ObjC1 &&
2782      getLangOptions().getGCMode() != LangOptions::NonGC) {
2783    GCAttrs = Ty.getObjCGCAttr();
2784    // Default behavious under objective-c's gc is for objective-c pointers
2785    // (or pointers to them) be treated as though they were declared
2786    // as __strong.
2787    if (GCAttrs == QualType::GCNone) {
2788      if (isObjCObjectPointerType(Ty))
2789        GCAttrs = QualType::Strong;
2790      else if (Ty->isPointerType())
2791        return getObjCGCAttrKind(Ty->getAsPointerType()->getPointeeType());
2792    }
2793    // Non-pointers have none gc'able attribute regardless of the attribute
2794    // set on them.
2795    else if (!Ty->isPointerType() && !isObjCObjectPointerType(Ty))
2796      return QualType::GCNone;
2797  }
2798  return GCAttrs;
2799}
2800
2801//===----------------------------------------------------------------------===//
2802//                        Type Compatibility Testing
2803//===----------------------------------------------------------------------===//
2804
2805/// typesAreBlockCompatible - This routine is called when comparing two
2806/// block types. Types must be strictly compatible here. For example,
2807/// C unfortunately doesn't produce an error for the following:
2808///
2809///   int (*emptyArgFunc)();
2810///   int (*intArgList)(int) = emptyArgFunc;
2811///
2812/// For blocks, we will produce an error for the following (similar to C++):
2813///
2814///   int (^emptyArgBlock)();
2815///   int (^intArgBlock)(int) = emptyArgBlock;
2816///
2817/// FIXME: When the dust settles on this integration, fold this into mergeTypes.
2818///
2819bool ASTContext::typesAreBlockCompatible(QualType lhs, QualType rhs) {
2820  const FunctionType *lbase = lhs->getAsFunctionType();
2821  const FunctionType *rbase = rhs->getAsFunctionType();
2822  const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
2823  const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
2824  if (lproto && rproto == 0)
2825    return false;
2826  return !mergeTypes(lhs, rhs).isNull();
2827}
2828
2829/// areCompatVectorTypes - Return true if the two specified vector types are
2830/// compatible.
2831static bool areCompatVectorTypes(const VectorType *LHS,
2832                                 const VectorType *RHS) {
2833  assert(LHS->isCanonical() && RHS->isCanonical());
2834  return LHS->getElementType() == RHS->getElementType() &&
2835         LHS->getNumElements() == RHS->getNumElements();
2836}
2837
2838/// canAssignObjCInterfaces - Return true if the two interface types are
2839/// compatible for assignment from RHS to LHS.  This handles validation of any
2840/// protocol qualifiers on the LHS or RHS.
2841///
2842bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
2843                                         const ObjCInterfaceType *RHS) {
2844  // Verify that the base decls are compatible: the RHS must be a subclass of
2845  // the LHS.
2846  if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
2847    return false;
2848
2849  // RHS must have a superset of the protocols in the LHS.  If the LHS is not
2850  // protocol qualified at all, then we are good.
2851  if (!isa<ObjCQualifiedInterfaceType>(LHS))
2852    return true;
2853
2854  // Okay, we know the LHS has protocol qualifiers.  If the RHS doesn't, then it
2855  // isn't a superset.
2856  if (!isa<ObjCQualifiedInterfaceType>(RHS))
2857    return true;  // FIXME: should return false!
2858
2859  // Finally, we must have two protocol-qualified interfaces.
2860  const ObjCQualifiedInterfaceType *LHSP =cast<ObjCQualifiedInterfaceType>(LHS);
2861  const ObjCQualifiedInterfaceType *RHSP =cast<ObjCQualifiedInterfaceType>(RHS);
2862
2863  // All LHS protocols must have a presence on the RHS.
2864  assert(LHSP->qual_begin() != LHSP->qual_end() && "Empty LHS protocol list?");
2865
2866  for (ObjCQualifiedInterfaceType::qual_iterator LHSPI = LHSP->qual_begin(),
2867                                                 LHSPE = LHSP->qual_end();
2868       LHSPI != LHSPE; LHSPI++) {
2869    bool RHSImplementsProtocol = false;
2870
2871    // If the RHS doesn't implement the protocol on the left, the types
2872    // are incompatible.
2873    for (ObjCQualifiedInterfaceType::qual_iterator RHSPI = RHSP->qual_begin(),
2874                                                   RHSPE = RHSP->qual_end();
2875         !RHSImplementsProtocol && (RHSPI != RHSPE); RHSPI++) {
2876      if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier()))
2877        RHSImplementsProtocol = true;
2878    }
2879    // FIXME: For better diagnostics, consider passing back the protocol name.
2880    if (!RHSImplementsProtocol)
2881      return false;
2882  }
2883  // The RHS implements all protocols listed on the LHS.
2884  return true;
2885}
2886
2887bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
2888  // get the "pointed to" types
2889  const PointerType *LHSPT = LHS->getAsPointerType();
2890  const PointerType *RHSPT = RHS->getAsPointerType();
2891
2892  if (!LHSPT || !RHSPT)
2893    return false;
2894
2895  QualType lhptee = LHSPT->getPointeeType();
2896  QualType rhptee = RHSPT->getPointeeType();
2897  const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2898  const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2899  // ID acts sort of like void* for ObjC interfaces
2900  if (LHSIface && isObjCIdStructType(rhptee))
2901    return true;
2902  if (RHSIface && isObjCIdStructType(lhptee))
2903    return true;
2904  if (!LHSIface || !RHSIface)
2905    return false;
2906  return canAssignObjCInterfaces(LHSIface, RHSIface) ||
2907         canAssignObjCInterfaces(RHSIface, LHSIface);
2908}
2909
2910/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
2911/// both shall have the identically qualified version of a compatible type.
2912/// C99 6.2.7p1: Two types have compatible types if their types are the
2913/// same. See 6.7.[2,3,5] for additional rules.
2914bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
2915  return !mergeTypes(LHS, RHS).isNull();
2916}
2917
2918QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) {
2919  const FunctionType *lbase = lhs->getAsFunctionType();
2920  const FunctionType *rbase = rhs->getAsFunctionType();
2921  const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
2922  const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
2923  bool allLTypes = true;
2924  bool allRTypes = true;
2925
2926  // Check return type
2927  QualType retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
2928  if (retType.isNull()) return QualType();
2929  if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
2930    allLTypes = false;
2931  if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
2932    allRTypes = false;
2933
2934  if (lproto && rproto) { // two C99 style function prototypes
2935    assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
2936           "C++ shouldn't be here");
2937    unsigned lproto_nargs = lproto->getNumArgs();
2938    unsigned rproto_nargs = rproto->getNumArgs();
2939
2940    // Compatible functions must have the same number of arguments
2941    if (lproto_nargs != rproto_nargs)
2942      return QualType();
2943
2944    // Variadic and non-variadic functions aren't compatible
2945    if (lproto->isVariadic() != rproto->isVariadic())
2946      return QualType();
2947
2948    if (lproto->getTypeQuals() != rproto->getTypeQuals())
2949      return QualType();
2950
2951    // Check argument compatibility
2952    llvm::SmallVector<QualType, 10> types;
2953    for (unsigned i = 0; i < lproto_nargs; i++) {
2954      QualType largtype = lproto->getArgType(i).getUnqualifiedType();
2955      QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
2956      QualType argtype = mergeTypes(largtype, rargtype);
2957      if (argtype.isNull()) return QualType();
2958      types.push_back(argtype);
2959      if (getCanonicalType(argtype) != getCanonicalType(largtype))
2960        allLTypes = false;
2961      if (getCanonicalType(argtype) != getCanonicalType(rargtype))
2962        allRTypes = false;
2963    }
2964    if (allLTypes) return lhs;
2965    if (allRTypes) return rhs;
2966    return getFunctionType(retType, types.begin(), types.size(),
2967                           lproto->isVariadic(), lproto->getTypeQuals());
2968  }
2969
2970  if (lproto) allRTypes = false;
2971  if (rproto) allLTypes = false;
2972
2973  const FunctionProtoType *proto = lproto ? lproto : rproto;
2974  if (proto) {
2975    assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
2976    if (proto->isVariadic()) return QualType();
2977    // Check that the types are compatible with the types that
2978    // would result from default argument promotions (C99 6.7.5.3p15).
2979    // The only types actually affected are promotable integer
2980    // types and floats, which would be passed as a different
2981    // type depending on whether the prototype is visible.
2982    unsigned proto_nargs = proto->getNumArgs();
2983    for (unsigned i = 0; i < proto_nargs; ++i) {
2984      QualType argTy = proto->getArgType(i);
2985      if (argTy->isPromotableIntegerType() ||
2986          getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
2987        return QualType();
2988    }
2989
2990    if (allLTypes) return lhs;
2991    if (allRTypes) return rhs;
2992    return getFunctionType(retType, proto->arg_type_begin(),
2993                           proto->getNumArgs(), lproto->isVariadic(),
2994                           lproto->getTypeQuals());
2995  }
2996
2997  if (allLTypes) return lhs;
2998  if (allRTypes) return rhs;
2999  return getFunctionNoProtoType(retType);
3000}
3001
3002QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) {
3003  // C++ [expr]: If an expression initially has the type "reference to T", the
3004  // type is adjusted to "T" prior to any further analysis, the expression
3005  // designates the object or function denoted by the reference, and the
3006  // expression is an lvalue unless the reference is an rvalue reference and
3007  // the expression is a function call (possibly inside parentheses).
3008  // FIXME: C++ shouldn't be going through here!  The rules are different
3009  // enough that they should be handled separately.
3010  // FIXME: Merging of lvalue and rvalue references is incorrect. C++ *really*
3011  // shouldn't be going through here!
3012  if (const ReferenceType *RT = LHS->getAsReferenceType())
3013    LHS = RT->getPointeeType();
3014  if (const ReferenceType *RT = RHS->getAsReferenceType())
3015    RHS = RT->getPointeeType();
3016
3017  QualType LHSCan = getCanonicalType(LHS),
3018           RHSCan = getCanonicalType(RHS);
3019
3020  // If two types are identical, they are compatible.
3021  if (LHSCan == RHSCan)
3022    return LHS;
3023
3024  // If the qualifiers are different, the types aren't compatible
3025  // Note that we handle extended qualifiers later, in the
3026  // case for ExtQualType.
3027  if (LHSCan.getCVRQualifiers() != RHSCan.getCVRQualifiers())
3028    return QualType();
3029
3030  Type::TypeClass LHSClass = LHSCan->getTypeClass();
3031  Type::TypeClass RHSClass = RHSCan->getTypeClass();
3032
3033  // We want to consider the two function types to be the same for these
3034  // comparisons, just force one to the other.
3035  if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
3036  if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
3037
3038  // Strip off objc_gc attributes off the top level so they can be merged.
3039  // This is a complete mess, but the attribute itself doesn't make much sense.
3040  if (RHSClass == Type::ExtQual) {
3041    QualType::GCAttrTypes GCAttr = RHSCan.getObjCGCAttr();
3042    if (GCAttr != QualType::GCNone) {
3043      QualType::GCAttrTypes GCLHSAttr = LHSCan.getObjCGCAttr();
3044      // __weak attribute must appear on both declarations.
3045      // __strong attribue is redundant if other decl is an objective-c
3046      // object pointer (or decorated with __strong attribute); otherwise
3047      // issue error.
3048      if ((GCAttr == QualType::Weak && GCLHSAttr != GCAttr) ||
3049          (GCAttr == QualType::Strong && GCLHSAttr != GCAttr &&
3050           LHSCan->isPointerType() && !isObjCObjectPointerType(LHSCan) &&
3051           !isObjCIdStructType(LHSCan->getAsPointerType()->getPointeeType())))
3052        return QualType();
3053
3054      RHS = QualType(cast<ExtQualType>(RHS.getDesugaredType())->getBaseType(),
3055                     RHS.getCVRQualifiers());
3056      QualType Result = mergeTypes(LHS, RHS);
3057      if (!Result.isNull()) {
3058        if (Result.getObjCGCAttr() == QualType::GCNone)
3059          Result = getObjCGCQualType(Result, GCAttr);
3060        else if (Result.getObjCGCAttr() != GCAttr)
3061          Result = QualType();
3062      }
3063      return Result;
3064    }
3065  }
3066  if (LHSClass == Type::ExtQual) {
3067    QualType::GCAttrTypes GCAttr = LHSCan.getObjCGCAttr();
3068    if (GCAttr != QualType::GCNone) {
3069      QualType::GCAttrTypes GCRHSAttr = RHSCan.getObjCGCAttr();
3070      // __weak attribute must appear on both declarations. __strong
3071      // __strong attribue is redundant if other decl is an objective-c
3072      // object pointer (or decorated with __strong attribute); otherwise
3073      // issue error.
3074      if ((GCAttr == QualType::Weak && GCRHSAttr != GCAttr) ||
3075          (GCAttr == QualType::Strong && GCRHSAttr != GCAttr &&
3076           RHSCan->isPointerType() && !isObjCObjectPointerType(RHSCan) &&
3077           !isObjCIdStructType(RHSCan->getAsPointerType()->getPointeeType())))
3078        return QualType();
3079
3080      LHS = QualType(cast<ExtQualType>(LHS.getDesugaredType())->getBaseType(),
3081                     LHS.getCVRQualifiers());
3082      QualType Result = mergeTypes(LHS, RHS);
3083      if (!Result.isNull()) {
3084        if (Result.getObjCGCAttr() == QualType::GCNone)
3085          Result = getObjCGCQualType(Result, GCAttr);
3086        else if (Result.getObjCGCAttr() != GCAttr)
3087          Result = QualType();
3088      }
3089      return Result;
3090    }
3091  }
3092
3093  // Same as above for arrays
3094  if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
3095    LHSClass = Type::ConstantArray;
3096  if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
3097    RHSClass = Type::ConstantArray;
3098
3099  // Canonicalize ExtVector -> Vector.
3100  if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
3101  if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
3102
3103  // Consider qualified interfaces and interfaces the same.
3104  if (LHSClass == Type::ObjCQualifiedInterface) LHSClass = Type::ObjCInterface;
3105  if (RHSClass == Type::ObjCQualifiedInterface) RHSClass = Type::ObjCInterface;
3106
3107  // If the canonical type classes don't match.
3108  if (LHSClass != RHSClass) {
3109    const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
3110    const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
3111
3112    // 'id' and 'Class' act sort of like void* for ObjC interfaces
3113    if (LHSIface && (isObjCIdStructType(RHS) || isObjCClassStructType(RHS)))
3114      return LHS;
3115    if (RHSIface && (isObjCIdStructType(LHS) || isObjCClassStructType(LHS)))
3116      return RHS;
3117
3118    // ID is compatible with all qualified id types.
3119    if (LHS->isObjCQualifiedIdType()) {
3120      if (const PointerType *PT = RHS->getAsPointerType()) {
3121        QualType pType = PT->getPointeeType();
3122        if (isObjCIdStructType(pType) || isObjCClassStructType(pType))
3123          return LHS;
3124        // FIXME: need to use ObjCQualifiedIdTypesAreCompatible(LHS, RHS, true).
3125        // Unfortunately, this API is part of Sema (which we don't have access
3126        // to. Need to refactor. The following check is insufficient, since we
3127        // need to make sure the class implements the protocol.
3128        if (pType->isObjCInterfaceType())
3129          return LHS;
3130      }
3131    }
3132    if (RHS->isObjCQualifiedIdType()) {
3133      if (const PointerType *PT = LHS->getAsPointerType()) {
3134        QualType pType = PT->getPointeeType();
3135        if (isObjCIdStructType(pType) || isObjCClassStructType(pType))
3136          return RHS;
3137        // FIXME: need to use ObjCQualifiedIdTypesAreCompatible(LHS, RHS, true).
3138        // Unfortunately, this API is part of Sema (which we don't have access
3139        // to. Need to refactor. The following check is insufficient, since we
3140        // need to make sure the class implements the protocol.
3141        if (pType->isObjCInterfaceType())
3142          return RHS;
3143      }
3144    }
3145    // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
3146    // a signed integer type, or an unsigned integer type.
3147    if (const EnumType* ETy = LHS->getAsEnumType()) {
3148      if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
3149        return RHS;
3150    }
3151    if (const EnumType* ETy = RHS->getAsEnumType()) {
3152      if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
3153        return LHS;
3154    }
3155
3156    return QualType();
3157  }
3158
3159  // The canonical type classes match.
3160  switch (LHSClass) {
3161#define TYPE(Class, Base)
3162#define ABSTRACT_TYPE(Class, Base)
3163#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3164#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3165#include "clang/AST/TypeNodes.def"
3166    assert(false && "Non-canonical and dependent types shouldn't get here");
3167    return QualType();
3168
3169  case Type::LValueReference:
3170  case Type::RValueReference:
3171  case Type::MemberPointer:
3172    assert(false && "C++ should never be in mergeTypes");
3173    return QualType();
3174
3175  case Type::IncompleteArray:
3176  case Type::VariableArray:
3177  case Type::FunctionProto:
3178  case Type::ExtVector:
3179  case Type::ObjCQualifiedInterface:
3180    assert(false && "Types are eliminated above");
3181    return QualType();
3182
3183  case Type::Pointer:
3184  {
3185    // Merge two pointer types, while trying to preserve typedef info
3186    QualType LHSPointee = LHS->getAsPointerType()->getPointeeType();
3187    QualType RHSPointee = RHS->getAsPointerType()->getPointeeType();
3188    QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
3189    if (ResultType.isNull()) return QualType();
3190    if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
3191      return LHS;
3192    if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
3193      return RHS;
3194    return getPointerType(ResultType);
3195  }
3196  case Type::BlockPointer:
3197  {
3198    // Merge two block pointer types, while trying to preserve typedef info
3199    QualType LHSPointee = LHS->getAsBlockPointerType()->getPointeeType();
3200    QualType RHSPointee = RHS->getAsBlockPointerType()->getPointeeType();
3201    QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
3202    if (ResultType.isNull()) return QualType();
3203    if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
3204      return LHS;
3205    if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
3206      return RHS;
3207    return getBlockPointerType(ResultType);
3208  }
3209  case Type::ConstantArray:
3210  {
3211    const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
3212    const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
3213    if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
3214      return QualType();
3215
3216    QualType LHSElem = getAsArrayType(LHS)->getElementType();
3217    QualType RHSElem = getAsArrayType(RHS)->getElementType();
3218    QualType ResultType = mergeTypes(LHSElem, RHSElem);
3219    if (ResultType.isNull()) return QualType();
3220    if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
3221      return LHS;
3222    if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
3223      return RHS;
3224    if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
3225                                          ArrayType::ArraySizeModifier(), 0);
3226    if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
3227                                          ArrayType::ArraySizeModifier(), 0);
3228    const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
3229    const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
3230    if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
3231      return LHS;
3232    if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
3233      return RHS;
3234    if (LVAT) {
3235      // FIXME: This isn't correct! But tricky to implement because
3236      // the array's size has to be the size of LHS, but the type
3237      // has to be different.
3238      return LHS;
3239    }
3240    if (RVAT) {
3241      // FIXME: This isn't correct! But tricky to implement because
3242      // the array's size has to be the size of RHS, but the type
3243      // has to be different.
3244      return RHS;
3245    }
3246    if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
3247    if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
3248    return getIncompleteArrayType(ResultType, ArrayType::ArraySizeModifier(),0);
3249  }
3250  case Type::FunctionNoProto:
3251    return mergeFunctionTypes(LHS, RHS);
3252  case Type::Record:
3253  case Type::Enum:
3254    // FIXME: Why are these compatible?
3255    if (isObjCIdStructType(LHS) && isObjCClassStructType(RHS)) return LHS;
3256    if (isObjCClassStructType(LHS) && isObjCIdStructType(RHS)) return LHS;
3257    return QualType();
3258  case Type::Builtin:
3259    // Only exactly equal builtin types are compatible, which is tested above.
3260    return QualType();
3261  case Type::Complex:
3262    // Distinct complex types are incompatible.
3263    return QualType();
3264  case Type::Vector:
3265    // FIXME: The merged type should be an ExtVector!
3266    if (areCompatVectorTypes(LHS->getAsVectorType(), RHS->getAsVectorType()))
3267      return LHS;
3268    return QualType();
3269  case Type::ObjCInterface: {
3270    // Check if the interfaces are assignment compatible.
3271    // FIXME: This should be type compatibility, e.g. whether
3272    // "LHS x; RHS x;" at global scope is legal.
3273    const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
3274    const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
3275    if (LHSIface && RHSIface &&
3276        canAssignObjCInterfaces(LHSIface, RHSIface))
3277      return LHS;
3278
3279    return QualType();
3280  }
3281  case Type::ObjCQualifiedId:
3282    // Distinct qualified id's are not compatible.
3283    return QualType();
3284  case Type::FixedWidthInt:
3285    // Distinct fixed-width integers are not compatible.
3286    return QualType();
3287  case Type::ExtQual:
3288    // FIXME: ExtQual types can be compatible even if they're not
3289    // identical!
3290    return QualType();
3291    // First attempt at an implementation, but I'm not really sure it's
3292    // right...
3293#if 0
3294    ExtQualType* LQual = cast<ExtQualType>(LHSCan);
3295    ExtQualType* RQual = cast<ExtQualType>(RHSCan);
3296    if (LQual->getAddressSpace() != RQual->getAddressSpace() ||
3297        LQual->getObjCGCAttr() != RQual->getObjCGCAttr())
3298      return QualType();
3299    QualType LHSBase, RHSBase, ResultType, ResCanUnqual;
3300    LHSBase = QualType(LQual->getBaseType(), 0);
3301    RHSBase = QualType(RQual->getBaseType(), 0);
3302    ResultType = mergeTypes(LHSBase, RHSBase);
3303    if (ResultType.isNull()) return QualType();
3304    ResCanUnqual = getCanonicalType(ResultType).getUnqualifiedType();
3305    if (LHSCan.getUnqualifiedType() == ResCanUnqual)
3306      return LHS;
3307    if (RHSCan.getUnqualifiedType() == ResCanUnqual)
3308      return RHS;
3309    ResultType = getAddrSpaceQualType(ResultType, LQual->getAddressSpace());
3310    ResultType = getObjCGCQualType(ResultType, LQual->getObjCGCAttr());
3311    ResultType.setCVRQualifiers(LHSCan.getCVRQualifiers());
3312    return ResultType;
3313#endif
3314
3315  case Type::TemplateSpecialization:
3316    assert(false && "Dependent types have no size");
3317    break;
3318  }
3319
3320  return QualType();
3321}
3322
3323//===----------------------------------------------------------------------===//
3324//                         Integer Predicates
3325//===----------------------------------------------------------------------===//
3326
3327unsigned ASTContext::getIntWidth(QualType T) {
3328  if (T == BoolTy)
3329    return 1;
3330  if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T)) {
3331    return FWIT->getWidth();
3332  }
3333  // For builtin types, just use the standard type sizing method
3334  return (unsigned)getTypeSize(T);
3335}
3336
3337QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
3338  assert(T->isSignedIntegerType() && "Unexpected type");
3339  if (const EnumType* ETy = T->getAsEnumType())
3340    T = ETy->getDecl()->getIntegerType();
3341  const BuiltinType* BTy = T->getAsBuiltinType();
3342  assert (BTy && "Unexpected signed integer type");
3343  switch (BTy->getKind()) {
3344  case BuiltinType::Char_S:
3345  case BuiltinType::SChar:
3346    return UnsignedCharTy;
3347  case BuiltinType::Short:
3348    return UnsignedShortTy;
3349  case BuiltinType::Int:
3350    return UnsignedIntTy;
3351  case BuiltinType::Long:
3352    return UnsignedLongTy;
3353  case BuiltinType::LongLong:
3354    return UnsignedLongLongTy;
3355  case BuiltinType::Int128:
3356    return UnsignedInt128Ty;
3357  default:
3358    assert(0 && "Unexpected signed integer type");
3359    return QualType();
3360  }
3361}
3362
3363ExternalASTSource::~ExternalASTSource() { }
3364
3365void ExternalASTSource::PrintStats() { }
3366