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