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