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