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