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