ASTContext.cpp revision 4afa39deaa245592977136d367251ee2c173dd8d
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/Expr.h"
18#include "clang/AST/RecordLayout.h"
19#include "clang/Basic/TargetInfo.h"
20#include "llvm/ADT/StringExtras.h"
21#include "llvm/Bitcode/Serialize.h"
22#include "llvm/Bitcode/Deserialize.h"
23#include "llvm/Support/MathExtras.h"
24
25using namespace clang;
26
27enum FloatingRank {
28  FloatRank, DoubleRank, LongDoubleRank
29};
30
31ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
32                       TargetInfo &t,
33                       IdentifierTable &idents, SelectorTable &sels,
34                       unsigned size_reserve) :
35  CFConstantStringTypeDecl(0), ObjCFastEnumerationStateTypeDecl(0),
36  SourceMgr(SM), LangOpts(LOpts), Target(t),
37  Idents(idents), Selectors(sels)
38{
39  if (size_reserve > 0) Types.reserve(size_reserve);
40  InitBuiltinTypes();
41  BuiltinInfo.InitializeBuiltins(idents, Target);
42  TUDecl = TranslationUnitDecl::Create(*this);
43}
44
45ASTContext::~ASTContext() {
46  // Deallocate all the types.
47  while (!Types.empty()) {
48    Types.back()->Destroy(*this);
49    Types.pop_back();
50  }
51
52  {
53    llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
54      I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end();
55    while (I != E) {
56      ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
57      delete R;
58    }
59  }
60
61  {
62    llvm::DenseMap<const ObjCInterfaceDecl*, const ASTRecordLayout*>::iterator
63      I = ASTObjCInterfaces.begin(), E = ASTObjCInterfaces.end();
64    while (I != E) {
65      ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
66      delete R;
67    }
68  }
69
70  {
71    llvm::DenseMap<const ObjCInterfaceDecl*, const RecordDecl*>::iterator
72      I = ASTRecordForInterface.begin(), E = ASTRecordForInterface.end();
73    while (I != E) {
74      RecordDecl *R = const_cast<RecordDecl*>((I++)->second);
75      R->Destroy(*this);
76    }
77  }
78
79  TUDecl->Destroy(*this);
80}
81
82void ASTContext::PrintStats() const {
83  fprintf(stderr, "*** AST Context Stats:\n");
84  fprintf(stderr, "  %d types total.\n", (int)Types.size());
85  unsigned NumBuiltin = 0, NumPointer = 0, NumArray = 0, NumFunctionP = 0;
86  unsigned NumVector = 0, NumComplex = 0, NumBlockPointer = 0;
87  unsigned NumFunctionNP = 0, NumTypeName = 0, NumTagged = 0, NumReference = 0;
88
89  unsigned NumTagStruct = 0, NumTagUnion = 0, NumTagEnum = 0, NumTagClass = 0;
90  unsigned NumObjCInterfaces = 0, NumObjCQualifiedInterfaces = 0;
91  unsigned NumObjCQualifiedIds = 0;
92  unsigned NumTypeOfTypes = 0, NumTypeOfExprs = 0;
93
94  for (unsigned i = 0, e = Types.size(); i != e; ++i) {
95    Type *T = Types[i];
96    if (isa<BuiltinType>(T))
97      ++NumBuiltin;
98    else if (isa<PointerType>(T))
99      ++NumPointer;
100    else if (isa<BlockPointerType>(T))
101      ++NumBlockPointer;
102    else if (isa<ReferenceType>(T))
103      ++NumReference;
104    else if (isa<ComplexType>(T))
105      ++NumComplex;
106    else if (isa<ArrayType>(T))
107      ++NumArray;
108    else if (isa<VectorType>(T))
109      ++NumVector;
110    else if (isa<FunctionTypeNoProto>(T))
111      ++NumFunctionNP;
112    else if (isa<FunctionTypeProto>(T))
113      ++NumFunctionP;
114    else if (isa<TypedefType>(T))
115      ++NumTypeName;
116    else if (TagType *TT = dyn_cast<TagType>(T)) {
117      ++NumTagged;
118      switch (TT->getDecl()->getTagKind()) {
119      default: assert(0 && "Unknown tagged type!");
120      case TagDecl::TK_struct: ++NumTagStruct; break;
121      case TagDecl::TK_union:  ++NumTagUnion; break;
122      case TagDecl::TK_class:  ++NumTagClass; break;
123      case TagDecl::TK_enum:   ++NumTagEnum; break;
124      }
125    } else if (isa<ObjCInterfaceType>(T))
126      ++NumObjCInterfaces;
127    else if (isa<ObjCQualifiedInterfaceType>(T))
128      ++NumObjCQualifiedInterfaces;
129    else if (isa<ObjCQualifiedIdType>(T))
130      ++NumObjCQualifiedIds;
131    else if (isa<TypeOfType>(T))
132      ++NumTypeOfTypes;
133    else if (isa<TypeOfExpr>(T))
134      ++NumTypeOfExprs;
135    else {
136      QualType(T, 0).dump();
137      assert(0 && "Unknown type!");
138    }
139  }
140
141  fprintf(stderr, "    %d builtin types\n", NumBuiltin);
142  fprintf(stderr, "    %d pointer types\n", NumPointer);
143  fprintf(stderr, "    %d block pointer types\n", NumBlockPointer);
144  fprintf(stderr, "    %d reference types\n", NumReference);
145  fprintf(stderr, "    %d complex types\n", NumComplex);
146  fprintf(stderr, "    %d array types\n", NumArray);
147  fprintf(stderr, "    %d vector types\n", NumVector);
148  fprintf(stderr, "    %d function types with proto\n", NumFunctionP);
149  fprintf(stderr, "    %d function types with no proto\n", NumFunctionNP);
150  fprintf(stderr, "    %d typename (typedef) types\n", NumTypeName);
151  fprintf(stderr, "    %d tagged types\n", NumTagged);
152  fprintf(stderr, "      %d struct types\n", NumTagStruct);
153  fprintf(stderr, "      %d union types\n", NumTagUnion);
154  fprintf(stderr, "      %d class types\n", NumTagClass);
155  fprintf(stderr, "      %d enum types\n", NumTagEnum);
156  fprintf(stderr, "    %d interface types\n", NumObjCInterfaces);
157  fprintf(stderr, "    %d protocol qualified interface types\n",
158          NumObjCQualifiedInterfaces);
159  fprintf(stderr, "    %d protocol qualified id types\n",
160          NumObjCQualifiedIds);
161  fprintf(stderr, "    %d typeof types\n", NumTypeOfTypes);
162  fprintf(stderr, "    %d typeof exprs\n", NumTypeOfExprs);
163
164  fprintf(stderr, "Total bytes = %d\n", int(NumBuiltin*sizeof(BuiltinType)+
165    NumPointer*sizeof(PointerType)+NumArray*sizeof(ArrayType)+
166    NumComplex*sizeof(ComplexType)+NumVector*sizeof(VectorType)+
167    NumFunctionP*sizeof(FunctionTypeProto)+
168    NumFunctionNP*sizeof(FunctionTypeNoProto)+
169    NumTypeName*sizeof(TypedefType)+NumTagged*sizeof(TagType)+
170    NumTypeOfTypes*sizeof(TypeOfType)+NumTypeOfExprs*sizeof(TypeOfExpr)));
171}
172
173
174void ASTContext::InitBuiltinType(QualType &R, BuiltinType::Kind K) {
175  void *Mem = Allocator.Allocate(sizeof(BuiltinType), 8);
176  Types.push_back((R = QualType(new (Mem) BuiltinType(K),0)).getTypePtr());
177}
178
179void ASTContext::InitBuiltinTypes() {
180  assert(VoidTy.isNull() && "Context reinitialized?");
181
182  // C99 6.2.5p19.
183  InitBuiltinType(VoidTy,              BuiltinType::Void);
184
185  // C99 6.2.5p2.
186  InitBuiltinType(BoolTy,              BuiltinType::Bool);
187  // C99 6.2.5p3.
188  if (Target.isCharSigned())
189    InitBuiltinType(CharTy,            BuiltinType::Char_S);
190  else
191    InitBuiltinType(CharTy,            BuiltinType::Char_U);
192  // C99 6.2.5p4.
193  InitBuiltinType(SignedCharTy,        BuiltinType::SChar);
194  InitBuiltinType(ShortTy,             BuiltinType::Short);
195  InitBuiltinType(IntTy,               BuiltinType::Int);
196  InitBuiltinType(LongTy,              BuiltinType::Long);
197  InitBuiltinType(LongLongTy,          BuiltinType::LongLong);
198
199  // C99 6.2.5p6.
200  InitBuiltinType(UnsignedCharTy,      BuiltinType::UChar);
201  InitBuiltinType(UnsignedShortTy,     BuiltinType::UShort);
202  InitBuiltinType(UnsignedIntTy,       BuiltinType::UInt);
203  InitBuiltinType(UnsignedLongTy,      BuiltinType::ULong);
204  InitBuiltinType(UnsignedLongLongTy,  BuiltinType::ULongLong);
205
206  // C99 6.2.5p10.
207  InitBuiltinType(FloatTy,             BuiltinType::Float);
208  InitBuiltinType(DoubleTy,            BuiltinType::Double);
209  InitBuiltinType(LongDoubleTy,        BuiltinType::LongDouble);
210
211  // C++ 3.9.1p5
212  InitBuiltinType(WCharTy,             BuiltinType::WChar);
213
214  // Placeholder type for functions.
215  InitBuiltinType(OverloadTy,          BuiltinType::Overload);
216
217  // Placeholder type for type-dependent expressions whose type is
218  // completely unknown. No code should ever check a type against
219  // DependentTy and users should never see it; however, it is here to
220  // help diagnose failures to properly check for type-dependent
221  // expressions.
222  InitBuiltinType(DependentTy,         BuiltinType::Dependent);
223
224  // C99 6.2.5p11.
225  FloatComplexTy      = getComplexType(FloatTy);
226  DoubleComplexTy     = getComplexType(DoubleTy);
227  LongDoubleComplexTy = getComplexType(LongDoubleTy);
228
229  BuiltinVaListType = QualType();
230  ObjCIdType = QualType();
231  IdStructType = 0;
232  ObjCClassType = QualType();
233  ClassStructType = 0;
234
235  ObjCConstantStringType = QualType();
236
237  // void * type
238  VoidPtrTy = getPointerType(VoidTy);
239}
240
241//===----------------------------------------------------------------------===//
242//                         Type Sizing and Analysis
243//===----------------------------------------------------------------------===//
244
245/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
246/// scalar floating point type.
247const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
248  const BuiltinType *BT = T->getAsBuiltinType();
249  assert(BT && "Not a floating point type!");
250  switch (BT->getKind()) {
251  default: assert(0 && "Not a floating point type!");
252  case BuiltinType::Float:      return Target.getFloatFormat();
253  case BuiltinType::Double:     return Target.getDoubleFormat();
254  case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
255  }
256}
257
258
259/// getTypeSize - Return the size of the specified type, in bits.  This method
260/// does not work on incomplete types.
261std::pair<uint64_t, unsigned>
262ASTContext::getTypeInfo(const Type *T) {
263  T = getCanonicalType(T);
264  uint64_t Width;
265  unsigned Align;
266  switch (T->getTypeClass()) {
267  case Type::TypeName: assert(0 && "Not a canonical type!");
268  case Type::FunctionNoProto:
269  case Type::FunctionProto:
270  default:
271    assert(0 && "Incomplete types have no size!");
272  case Type::VariableArray:
273    assert(0 && "VLAs not implemented yet!");
274  case Type::DependentSizedArray:
275    assert(0 && "Dependently-sized arrays don't have a known size");
276  case Type::ConstantArray: {
277    const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
278
279    std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
280    Width = EltInfo.first*CAT->getSize().getZExtValue();
281    Align = EltInfo.second;
282    break;
283  }
284  case Type::ExtVector:
285  case Type::Vector: {
286    std::pair<uint64_t, unsigned> EltInfo =
287      getTypeInfo(cast<VectorType>(T)->getElementType());
288    Width = EltInfo.first*cast<VectorType>(T)->getNumElements();
289    Align = Width;
290    // If the alignment is not a power of 2, round up to the next power of 2.
291    // This happens for non-power-of-2 length vectors.
292    // FIXME: this should probably be a target property.
293    Align = 1 << llvm::Log2_32_Ceil(Align);
294    break;
295  }
296
297  case Type::Builtin:
298    switch (cast<BuiltinType>(T)->getKind()) {
299    default: assert(0 && "Unknown builtin type!");
300    case BuiltinType::Void:
301      assert(0 && "Incomplete types have no size!");
302    case BuiltinType::Bool:
303      Width = Target.getBoolWidth();
304      Align = Target.getBoolAlign();
305      break;
306    case BuiltinType::Char_S:
307    case BuiltinType::Char_U:
308    case BuiltinType::UChar:
309    case BuiltinType::SChar:
310      Width = Target.getCharWidth();
311      Align = Target.getCharAlign();
312      break;
313    case BuiltinType::WChar:
314      Width = Target.getWCharWidth();
315      Align = Target.getWCharAlign();
316      break;
317    case BuiltinType::UShort:
318    case BuiltinType::Short:
319      Width = Target.getShortWidth();
320      Align = Target.getShortAlign();
321      break;
322    case BuiltinType::UInt:
323    case BuiltinType::Int:
324      Width = Target.getIntWidth();
325      Align = Target.getIntAlign();
326      break;
327    case BuiltinType::ULong:
328    case BuiltinType::Long:
329      Width = Target.getLongWidth();
330      Align = Target.getLongAlign();
331      break;
332    case BuiltinType::ULongLong:
333    case BuiltinType::LongLong:
334      Width = Target.getLongLongWidth();
335      Align = Target.getLongLongAlign();
336      break;
337    case BuiltinType::Float:
338      Width = Target.getFloatWidth();
339      Align = Target.getFloatAlign();
340      break;
341    case BuiltinType::Double:
342      Width = Target.getDoubleWidth();
343      Align = Target.getDoubleAlign();
344      break;
345    case BuiltinType::LongDouble:
346      Width = Target.getLongDoubleWidth();
347      Align = Target.getLongDoubleAlign();
348      break;
349    }
350    break;
351  case Type::ASQual:
352    // FIXME: Pointers into different addr spaces could have different sizes and
353    // alignment requirements: getPointerInfo should take an AddrSpace.
354    return getTypeInfo(QualType(cast<ASQualType>(T)->getBaseType(), 0));
355  case Type::ObjCQualifiedId:
356    Width = Target.getPointerWidth(0);
357    Align = Target.getPointerAlign(0);
358    break;
359  case Type::BlockPointer: {
360    unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
361    Width = Target.getPointerWidth(AS);
362    Align = Target.getPointerAlign(AS);
363    break;
364  }
365  case Type::Pointer: {
366    unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
367    Width = Target.getPointerWidth(AS);
368    Align = Target.getPointerAlign(AS);
369    break;
370  }
371  case Type::Reference:
372    // "When applied to a reference or a reference type, the result is the size
373    // of the referenced type." C++98 5.3.3p2: expr.sizeof.
374    // FIXME: This is wrong for struct layout: a reference in a struct has
375    // pointer size.
376    return getTypeInfo(cast<ReferenceType>(T)->getPointeeType());
377
378  case Type::Complex: {
379    // Complex types have the same alignment as their elements, but twice the
380    // size.
381    std::pair<uint64_t, unsigned> EltInfo =
382      getTypeInfo(cast<ComplexType>(T)->getElementType());
383    Width = EltInfo.first*2;
384    Align = EltInfo.second;
385    break;
386  }
387  case Type::ObjCInterface: {
388    const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
389    const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
390    Width = Layout.getSize();
391    Align = Layout.getAlignment();
392    break;
393  }
394  case Type::Tagged: {
395    const TagType *TT = cast<TagType>(T);
396
397    if (TT->getDecl()->isInvalidDecl()) {
398      Width = 1;
399      Align = 1;
400      break;
401    }
402
403    if (const EnumType *ET = dyn_cast<EnumType>(TT))
404      return getTypeInfo(ET->getDecl()->getIntegerType());
405
406    const RecordType *RT = cast<RecordType>(TT);
407    const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
408    Width = Layout.getSize();
409    Align = Layout.getAlignment();
410    break;
411  }
412  }
413
414  assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
415  return std::make_pair(Width, Align);
416}
417
418/// LayoutField - Field layout.
419void ASTRecordLayout::LayoutField(const FieldDecl *FD, unsigned FieldNo,
420                                  bool IsUnion, unsigned StructPacking,
421                                  ASTContext &Context) {
422  unsigned FieldPacking = StructPacking;
423  uint64_t FieldOffset = IsUnion ? 0 : Size;
424  uint64_t FieldSize;
425  unsigned FieldAlign;
426
427  // FIXME: Should this override struct packing? Probably we want to
428  // take the minimum?
429  if (const PackedAttr *PA = FD->getAttr<PackedAttr>())
430    FieldPacking = PA->getAlignment();
431
432  if (const Expr *BitWidthExpr = FD->getBitWidth()) {
433    // TODO: Need to check this algorithm on other targets!
434    //       (tested on Linux-X86)
435    FieldSize =
436      BitWidthExpr->getIntegerConstantExprValue(Context).getZExtValue();
437
438    std::pair<uint64_t, unsigned> FieldInfo =
439      Context.getTypeInfo(FD->getType());
440    uint64_t TypeSize = FieldInfo.first;
441
442    // Determine the alignment of this bitfield. The packing
443    // attributes define a maximum and the alignment attribute defines
444    // a minimum.
445    // FIXME: What is the right behavior when the specified alignment
446    // is smaller than the specified packing?
447    FieldAlign = FieldInfo.second;
448    if (FieldPacking)
449      FieldAlign = std::min(FieldAlign, FieldPacking);
450    if (const AlignedAttr *AA = FD->getAttr<AlignedAttr>())
451      FieldAlign = std::max(FieldAlign, AA->getAlignment());
452
453    // Check if we need to add padding to give the field the correct
454    // alignment.
455    if (FieldSize == 0 || (FieldOffset & (FieldAlign-1)) + FieldSize > TypeSize)
456      FieldOffset = (FieldOffset + (FieldAlign-1)) & ~(FieldAlign-1);
457
458    // Padding members don't affect overall alignment
459    if (!FD->getIdentifier())
460      FieldAlign = 1;
461  } else {
462    if (FD->getType()->isIncompleteArrayType()) {
463      // This is a flexible array member; we can't directly
464      // query getTypeInfo about these, so we figure it out here.
465      // Flexible array members don't have any size, but they
466      // have to be aligned appropriately for their element type.
467      FieldSize = 0;
468      const ArrayType* ATy = Context.getAsArrayType(FD->getType());
469      FieldAlign = Context.getTypeAlign(ATy->getElementType());
470    } else {
471      std::pair<uint64_t, unsigned> FieldInfo =
472        Context.getTypeInfo(FD->getType());
473      FieldSize = FieldInfo.first;
474      FieldAlign = FieldInfo.second;
475    }
476
477    // Determine the alignment of this bitfield. The packing
478    // attributes define a maximum and the alignment attribute defines
479    // a minimum. Additionally, the packing alignment must be at least
480    // a byte for non-bitfields.
481    //
482    // FIXME: What is the right behavior when the specified alignment
483    // is smaller than the specified packing?
484    if (FieldPacking)
485      FieldAlign = std::min(FieldAlign, std::max(8U, FieldPacking));
486    if (const AlignedAttr *AA = FD->getAttr<AlignedAttr>())
487      FieldAlign = std::max(FieldAlign, AA->getAlignment());
488
489    // Round up the current record size to the field's alignment boundary.
490    FieldOffset = (FieldOffset + (FieldAlign-1)) & ~(FieldAlign-1);
491  }
492
493  // Place this field at the current location.
494  FieldOffsets[FieldNo] = FieldOffset;
495
496  // Reserve space for this field.
497  if (IsUnion) {
498    Size = std::max(Size, FieldSize);
499  } else {
500    Size = FieldOffset + FieldSize;
501  }
502
503  // Remember max struct/class alignment.
504  Alignment = std::max(Alignment, FieldAlign);
505}
506
507static void CollectObjCIvars(const ObjCInterfaceDecl *OI,
508                             std::vector<FieldDecl*> &Fields) {
509  const ObjCInterfaceDecl *SuperClass = OI->getSuperClass();
510  if (SuperClass)
511    CollectObjCIvars(SuperClass, Fields);
512  for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
513       E = OI->ivar_end(); I != E; ++I) {
514    ObjCIvarDecl *IVDecl = (*I);
515    if (!IVDecl->isInvalidDecl())
516      Fields.push_back(cast<FieldDecl>(IVDecl));
517  }
518}
519
520/// addRecordToClass - produces record info. for the class for its
521/// ivars and all those inherited.
522///
523const RecordDecl *ASTContext::addRecordToClass(const ObjCInterfaceDecl *D)
524{
525  const RecordDecl *&RD = ASTRecordForInterface[D];
526  if (RD)
527    return RD;
528  std::vector<FieldDecl*> RecFields;
529  CollectObjCIvars(D, RecFields);
530  RecordDecl *NewRD = RecordDecl::Create(*this, TagDecl::TK_struct, 0,
531                                         D->getLocation(),
532                                         D->getIdentifier());
533  /// FIXME! Can do collection of ivars and adding to the record while
534  /// doing it.
535  for (unsigned int i = 0; i != RecFields.size(); i++) {
536    FieldDecl *Field =  FieldDecl::Create(*this, NewRD,
537                                          RecFields[i]->getLocation(),
538                                          RecFields[i]->getIdentifier(),
539                                          RecFields[i]->getType(),
540                                          RecFields[i]->getBitWidth(), false);
541    NewRD->addDecl(Field);
542  }
543  NewRD->completeDefinition(*this);
544  RD = NewRD;
545  return RD;
546}
547
548/// setFieldDecl - maps a field for the given Ivar reference node.
549//
550void ASTContext::setFieldDecl(const ObjCInterfaceDecl *OI,
551                              const ObjCIvarDecl *Ivar,
552                              const ObjCIvarRefExpr *MRef) {
553  FieldDecl *FD = (const_cast<ObjCInterfaceDecl *>(OI))->
554                    lookupFieldDeclForIvar(*this, Ivar);
555  ASTFieldForIvarRef[MRef] = FD;
556}
557
558/// getASTObjcInterfaceLayout - Get or compute information about the layout of
559/// the specified Objective C, which indicates its size and ivar
560/// position information.
561const ASTRecordLayout &
562ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
563  // Look up this layout, if already laid out, return what we have.
564  const ASTRecordLayout *&Entry = ASTObjCInterfaces[D];
565  if (Entry) return *Entry;
566
567  // Allocate and assign into ASTRecordLayouts here.  The "Entry" reference can
568  // be invalidated (dangle) if the ASTRecordLayouts hashtable is inserted into.
569  ASTRecordLayout *NewEntry = NULL;
570  unsigned FieldCount = D->ivar_size();
571  if (ObjCInterfaceDecl *SD = D->getSuperClass()) {
572    FieldCount++;
573    const ASTRecordLayout &SL = getASTObjCInterfaceLayout(SD);
574    unsigned Alignment = SL.getAlignment();
575    uint64_t Size = SL.getSize();
576    NewEntry = new ASTRecordLayout(Size, Alignment);
577    NewEntry->InitializeLayout(FieldCount);
578    // Super class is at the beginning of the layout.
579    NewEntry->SetFieldOffset(0, 0);
580  } else {
581    NewEntry = new ASTRecordLayout();
582    NewEntry->InitializeLayout(FieldCount);
583  }
584  Entry = NewEntry;
585
586  unsigned StructPacking = 0;
587  if (const PackedAttr *PA = D->getAttr<PackedAttr>())
588    StructPacking = PA->getAlignment();
589
590  if (const AlignedAttr *AA = D->getAttr<AlignedAttr>())
591    NewEntry->SetAlignment(std::max(NewEntry->getAlignment(),
592                                    AA->getAlignment()));
593
594  // Layout each ivar sequentially.
595  unsigned i = 0;
596  for (ObjCInterfaceDecl::ivar_iterator IVI = D->ivar_begin(),
597       IVE = D->ivar_end(); IVI != IVE; ++IVI) {
598    const ObjCIvarDecl* Ivar = (*IVI);
599    NewEntry->LayoutField(Ivar, i++, false, StructPacking, *this);
600  }
601
602  // Finally, round the size of the total struct up to the alignment of the
603  // struct itself.
604  NewEntry->FinalizeLayout();
605  return *NewEntry;
606}
607
608/// getASTRecordLayout - Get or compute information about the layout of the
609/// specified record (struct/union/class), which indicates its size and field
610/// position information.
611const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D) {
612  D = D->getDefinition(*this);
613  assert(D && "Cannot get layout of forward declarations!");
614
615  // Look up this layout, if already laid out, return what we have.
616  const ASTRecordLayout *&Entry = ASTRecordLayouts[D];
617  if (Entry) return *Entry;
618
619  // Allocate and assign into ASTRecordLayouts here.  The "Entry" reference can
620  // be invalidated (dangle) if the ASTRecordLayouts hashtable is inserted into.
621  ASTRecordLayout *NewEntry = new ASTRecordLayout();
622  Entry = NewEntry;
623
624  // FIXME: Avoid linear walk through the fields, if possible.
625  NewEntry->InitializeLayout(std::distance(D->field_begin(), D->field_end()));
626  bool IsUnion = D->isUnion();
627
628  unsigned StructPacking = 0;
629  if (const PackedAttr *PA = D->getAttr<PackedAttr>())
630    StructPacking = PA->getAlignment();
631
632  if (const AlignedAttr *AA = D->getAttr<AlignedAttr>())
633    NewEntry->SetAlignment(std::max(NewEntry->getAlignment(),
634                                    AA->getAlignment()));
635
636  // Layout each field, for now, just sequentially, respecting alignment.  In
637  // the future, this will need to be tweakable by targets.
638  unsigned FieldIdx = 0;
639  for (RecordDecl::field_iterator Field = D->field_begin(),
640                               FieldEnd = D->field_end();
641       Field != FieldEnd; (void)++Field, ++FieldIdx)
642    NewEntry->LayoutField(*Field, FieldIdx, IsUnion, StructPacking, *this);
643
644  // Finally, round the size of the total struct up to the alignment of the
645  // struct itself.
646  NewEntry->FinalizeLayout();
647  return *NewEntry;
648}
649
650//===----------------------------------------------------------------------===//
651//                   Type creation/memoization methods
652//===----------------------------------------------------------------------===//
653
654QualType ASTContext::getASQualType(QualType T, unsigned AddressSpace) {
655  QualType CanT = getCanonicalType(T);
656  if (CanT.getAddressSpace() == AddressSpace)
657    return T;
658
659  // Type's cannot have multiple ASQuals, therefore we know we only have to deal
660  // with CVR qualifiers from here on out.
661  assert(CanT.getAddressSpace() == 0 &&
662         "Type is already address space qualified");
663
664  // Check if we've already instantiated an address space qual'd type of this
665  // type.
666  llvm::FoldingSetNodeID ID;
667  ASQualType::Profile(ID, T.getTypePtr(), AddressSpace);
668  void *InsertPos = 0;
669  if (ASQualType *ASQy = ASQualTypes.FindNodeOrInsertPos(ID, InsertPos))
670    return QualType(ASQy, 0);
671
672  // If the base type isn't canonical, this won't be a canonical type either,
673  // so fill in the canonical type field.
674  QualType Canonical;
675  if (!T->isCanonical()) {
676    Canonical = getASQualType(CanT, AddressSpace);
677
678    // Get the new insert position for the node we care about.
679    ASQualType *NewIP = ASQualTypes.FindNodeOrInsertPos(ID, InsertPos);
680    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
681  }
682  void *Mem = Allocator.Allocate(sizeof(ASQualType), 8);
683  ASQualType *New = new (Mem) ASQualType(T.getTypePtr(), Canonical, AddressSpace);
684  ASQualTypes.InsertNode(New, InsertPos);
685  Types.push_back(New);
686  return QualType(New, T.getCVRQualifiers());
687}
688
689
690/// getComplexType - Return the uniqued reference to the type for a complex
691/// number with the specified element type.
692QualType ASTContext::getComplexType(QualType T) {
693  // Unique pointers, to guarantee there is only one pointer of a particular
694  // structure.
695  llvm::FoldingSetNodeID ID;
696  ComplexType::Profile(ID, T);
697
698  void *InsertPos = 0;
699  if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
700    return QualType(CT, 0);
701
702  // If the pointee type isn't canonical, this won't be a canonical type either,
703  // so fill in the canonical type field.
704  QualType Canonical;
705  if (!T->isCanonical()) {
706    Canonical = getComplexType(getCanonicalType(T));
707
708    // Get the new insert position for the node we care about.
709    ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
710    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
711  }
712  void *Mem = Allocator.Allocate(sizeof(ComplexType), 8);
713  ComplexType *New = new (Mem) ComplexType(T, Canonical);
714  Types.push_back(New);
715  ComplexTypes.InsertNode(New, InsertPos);
716  return QualType(New, 0);
717}
718
719
720/// getPointerType - Return the uniqued reference to the type for a pointer to
721/// the specified type.
722QualType ASTContext::getPointerType(QualType T) {
723  // Unique pointers, to guarantee there is only one pointer of a particular
724  // structure.
725  llvm::FoldingSetNodeID ID;
726  PointerType::Profile(ID, T);
727
728  void *InsertPos = 0;
729  if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
730    return QualType(PT, 0);
731
732  // If the pointee type isn't canonical, this won't be a canonical type either,
733  // so fill in the canonical type field.
734  QualType Canonical;
735  if (!T->isCanonical()) {
736    Canonical = getPointerType(getCanonicalType(T));
737
738    // Get the new insert position for the node we care about.
739    PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
740    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
741  }
742  void *Mem = Allocator.Allocate(sizeof(PointerType), 8);
743  PointerType *New = new (Mem) PointerType(T, Canonical);
744  Types.push_back(New);
745  PointerTypes.InsertNode(New, InsertPos);
746  return QualType(New, 0);
747}
748
749/// getBlockPointerType - Return the uniqued reference to the type for
750/// a pointer to the specified block.
751QualType ASTContext::getBlockPointerType(QualType T) {
752  assert(T->isFunctionType() && "block of function types only");
753  // Unique pointers, to guarantee there is only one block of a particular
754  // structure.
755  llvm::FoldingSetNodeID ID;
756  BlockPointerType::Profile(ID, T);
757
758  void *InsertPos = 0;
759  if (BlockPointerType *PT =
760        BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
761    return QualType(PT, 0);
762
763  // If the block pointee type isn't canonical, this won't be a canonical
764  // type either so fill in the canonical type field.
765  QualType Canonical;
766  if (!T->isCanonical()) {
767    Canonical = getBlockPointerType(getCanonicalType(T));
768
769    // Get the new insert position for the node we care about.
770    BlockPointerType *NewIP =
771      BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
772    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
773  }
774  void *Mem = Allocator.Allocate(sizeof(BlockPointerType), 8);
775  BlockPointerType *New = new (Mem) BlockPointerType(T, Canonical);
776  Types.push_back(New);
777  BlockPointerTypes.InsertNode(New, InsertPos);
778  return QualType(New, 0);
779}
780
781/// getReferenceType - Return the uniqued reference to the type for a reference
782/// to the specified type.
783QualType ASTContext::getReferenceType(QualType T) {
784  // Unique pointers, to guarantee there is only one pointer of a particular
785  // structure.
786  llvm::FoldingSetNodeID ID;
787  ReferenceType::Profile(ID, T);
788
789  void *InsertPos = 0;
790  if (ReferenceType *RT = ReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
791    return QualType(RT, 0);
792
793  // If the referencee type isn't canonical, this won't be a canonical type
794  // either, so fill in the canonical type field.
795  QualType Canonical;
796  if (!T->isCanonical()) {
797    Canonical = getReferenceType(getCanonicalType(T));
798
799    // Get the new insert position for the node we care about.
800    ReferenceType *NewIP = ReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
801    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
802  }
803
804  void *Mem = Allocator.Allocate(sizeof(ReferenceType), 8);
805  ReferenceType *New = new (Mem) ReferenceType(T, Canonical);
806  Types.push_back(New);
807  ReferenceTypes.InsertNode(New, InsertPos);
808  return QualType(New, 0);
809}
810
811/// getConstantArrayType - Return the unique reference to the type for an
812/// array of the specified element type.
813QualType ASTContext::getConstantArrayType(QualType EltTy,
814                                          const llvm::APInt &ArySize,
815                                          ArrayType::ArraySizeModifier ASM,
816                                          unsigned EltTypeQuals) {
817  llvm::FoldingSetNodeID ID;
818  ConstantArrayType::Profile(ID, EltTy, ArySize);
819
820  void *InsertPos = 0;
821  if (ConstantArrayType *ATP =
822      ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
823    return QualType(ATP, 0);
824
825  // If the element type isn't canonical, this won't be a canonical type either,
826  // so fill in the canonical type field.
827  QualType Canonical;
828  if (!EltTy->isCanonical()) {
829    Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
830                                     ASM, EltTypeQuals);
831    // Get the new insert position for the node we care about.
832    ConstantArrayType *NewIP =
833      ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
834    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
835  }
836
837  void *Mem = Allocator.Allocate(sizeof(ConstantArrayType), 8);
838  ConstantArrayType *New =
839    new (Mem) ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
840  ConstantArrayTypes.InsertNode(New, InsertPos);
841  Types.push_back(New);
842  return QualType(New, 0);
843}
844
845/// getVariableArrayType - Returns a non-unique reference to the type for a
846/// variable array of the specified element type.
847QualType ASTContext::getVariableArrayType(QualType EltTy, Expr *NumElts,
848                                          ArrayType::ArraySizeModifier ASM,
849                                          unsigned EltTypeQuals) {
850  // Since we don't unique expressions, it isn't possible to unique VLA's
851  // that have an expression provided for their size.
852
853  void *Mem = Allocator.Allocate(sizeof(VariableArrayType), 8);
854  VariableArrayType *New =
855    new (Mem) VariableArrayType(EltTy, QualType(), NumElts, ASM, EltTypeQuals);
856
857  VariableArrayTypes.push_back(New);
858  Types.push_back(New);
859  return QualType(New, 0);
860}
861
862/// getDependentSizedArrayType - Returns a non-unique reference to
863/// the type for a dependently-sized array of the specified element
864/// type. FIXME: We will need these to be uniqued, or at least
865/// comparable, at some point.
866QualType ASTContext::getDependentSizedArrayType(QualType EltTy, Expr *NumElts,
867                                                ArrayType::ArraySizeModifier ASM,
868                                                unsigned EltTypeQuals) {
869  assert((NumElts->isTypeDependent() || NumElts->isValueDependent()) &&
870         "Size must be type- or value-dependent!");
871
872  // Since we don't unique expressions, it isn't possible to unique
873  // dependently-sized array types.
874
875  void *Mem = Allocator.Allocate(sizeof(DependentSizedArrayType), 8);
876  DependentSizedArrayType *New =
877      new (Mem) DependentSizedArrayType(EltTy, QualType(), NumElts,
878                                        ASM, EltTypeQuals);
879
880  DependentSizedArrayTypes.push_back(New);
881  Types.push_back(New);
882  return QualType(New, 0);
883}
884
885QualType ASTContext::getIncompleteArrayType(QualType EltTy,
886                                            ArrayType::ArraySizeModifier ASM,
887                                            unsigned EltTypeQuals) {
888  llvm::FoldingSetNodeID ID;
889  IncompleteArrayType::Profile(ID, EltTy);
890
891  void *InsertPos = 0;
892  if (IncompleteArrayType *ATP =
893       IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
894    return QualType(ATP, 0);
895
896  // If the element type isn't canonical, this won't be a canonical type
897  // either, so fill in the canonical type field.
898  QualType Canonical;
899
900  if (!EltTy->isCanonical()) {
901    Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
902                                       ASM, EltTypeQuals);
903
904    // Get the new insert position for the node we care about.
905    IncompleteArrayType *NewIP =
906      IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
907    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
908  }
909
910  void *Mem = Allocator.Allocate(sizeof(IncompleteArrayType), 8);
911  IncompleteArrayType *New = new (Mem) IncompleteArrayType(EltTy, Canonical,
912                                                           ASM, EltTypeQuals);
913
914  IncompleteArrayTypes.InsertNode(New, InsertPos);
915  Types.push_back(New);
916  return QualType(New, 0);
917}
918
919/// getVectorType - Return the unique reference to a vector type of
920/// the specified element type and size. VectorType must be a built-in type.
921QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts) {
922  BuiltinType *baseType;
923
924  baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
925  assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
926
927  // Check if we've already instantiated a vector of this type.
928  llvm::FoldingSetNodeID ID;
929  VectorType::Profile(ID, vecType, NumElts, Type::Vector);
930  void *InsertPos = 0;
931  if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
932    return QualType(VTP, 0);
933
934  // If the element type isn't canonical, this won't be a canonical type either,
935  // so fill in the canonical type field.
936  QualType Canonical;
937  if (!vecType->isCanonical()) {
938    Canonical = getVectorType(getCanonicalType(vecType), NumElts);
939
940    // Get the new insert position for the node we care about.
941    VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
942    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
943  }
944  void *Mem = Allocator.Allocate(sizeof(VectorType), 8);
945  VectorType *New = new (Mem) VectorType(vecType, NumElts, Canonical);
946  VectorTypes.InsertNode(New, InsertPos);
947  Types.push_back(New);
948  return QualType(New, 0);
949}
950
951/// getExtVectorType - Return the unique reference to an extended vector type of
952/// the specified element type and size. VectorType must be a built-in type.
953QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
954  BuiltinType *baseType;
955
956  baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
957  assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
958
959  // Check if we've already instantiated a vector of this type.
960  llvm::FoldingSetNodeID ID;
961  VectorType::Profile(ID, vecType, NumElts, Type::ExtVector);
962  void *InsertPos = 0;
963  if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
964    return QualType(VTP, 0);
965
966  // If the element type isn't canonical, this won't be a canonical type either,
967  // so fill in the canonical type field.
968  QualType Canonical;
969  if (!vecType->isCanonical()) {
970    Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
971
972    // Get the new insert position for the node we care about.
973    VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
974    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
975  }
976  void *Mem = Allocator.Allocate(sizeof(ExtVectorType), 8);
977  ExtVectorType *New = new (Mem) ExtVectorType(vecType, NumElts, Canonical);
978  VectorTypes.InsertNode(New, InsertPos);
979  Types.push_back(New);
980  return QualType(New, 0);
981}
982
983/// getFunctionTypeNoProto - Return a K&R style C function type like 'int()'.
984///
985QualType ASTContext::getFunctionTypeNoProto(QualType ResultTy) {
986  // Unique functions, to guarantee there is only one function of a particular
987  // structure.
988  llvm::FoldingSetNodeID ID;
989  FunctionTypeNoProto::Profile(ID, ResultTy);
990
991  void *InsertPos = 0;
992  if (FunctionTypeNoProto *FT =
993        FunctionTypeNoProtos.FindNodeOrInsertPos(ID, InsertPos))
994    return QualType(FT, 0);
995
996  QualType Canonical;
997  if (!ResultTy->isCanonical()) {
998    Canonical = getFunctionTypeNoProto(getCanonicalType(ResultTy));
999
1000    // Get the new insert position for the node we care about.
1001    FunctionTypeNoProto *NewIP =
1002      FunctionTypeNoProtos.FindNodeOrInsertPos(ID, InsertPos);
1003    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1004  }
1005
1006  FunctionTypeNoProto *New = new FunctionTypeNoProto(ResultTy, Canonical);
1007  Types.push_back(New);
1008  FunctionTypeNoProtos.InsertNode(New, InsertPos);
1009  return QualType(New, 0);
1010}
1011
1012/// getFunctionType - Return a normal function type with a typed argument
1013/// list.  isVariadic indicates whether the argument list includes '...'.
1014QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
1015                                     unsigned NumArgs, bool isVariadic,
1016                                     unsigned TypeQuals) {
1017  // Unique functions, to guarantee there is only one function of a particular
1018  // structure.
1019  llvm::FoldingSetNodeID ID;
1020  FunctionTypeProto::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
1021                             TypeQuals);
1022
1023  void *InsertPos = 0;
1024  if (FunctionTypeProto *FTP =
1025        FunctionTypeProtos.FindNodeOrInsertPos(ID, InsertPos))
1026    return QualType(FTP, 0);
1027
1028  // Determine whether the type being created is already canonical or not.
1029  bool isCanonical = ResultTy->isCanonical();
1030  for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
1031    if (!ArgArray[i]->isCanonical())
1032      isCanonical = false;
1033
1034  // If this type isn't canonical, get the canonical version of it.
1035  QualType Canonical;
1036  if (!isCanonical) {
1037    llvm::SmallVector<QualType, 16> CanonicalArgs;
1038    CanonicalArgs.reserve(NumArgs);
1039    for (unsigned i = 0; i != NumArgs; ++i)
1040      CanonicalArgs.push_back(getCanonicalType(ArgArray[i]));
1041
1042    Canonical = getFunctionType(getCanonicalType(ResultTy),
1043                                &CanonicalArgs[0], NumArgs,
1044                                isVariadic, TypeQuals);
1045
1046    // Get the new insert position for the node we care about.
1047    FunctionTypeProto *NewIP =
1048      FunctionTypeProtos.FindNodeOrInsertPos(ID, InsertPos);
1049    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1050  }
1051
1052  // FunctionTypeProto objects are allocated with extra bytes after them
1053  // for a variable size array (for parameter types) at the end of them.
1054  // FIXME: Can we do better than forcing a 16-byte alignment?
1055  FunctionTypeProto *FTP =
1056    (FunctionTypeProto*)Allocator.Allocate(sizeof(FunctionTypeProto) +
1057                                           NumArgs*sizeof(QualType), 16);
1058  new (FTP) FunctionTypeProto(ResultTy, ArgArray, NumArgs, isVariadic,
1059                              TypeQuals, Canonical);
1060  Types.push_back(FTP);
1061  FunctionTypeProtos.InsertNode(FTP, InsertPos);
1062  return QualType(FTP, 0);
1063}
1064
1065/// getTypeDeclType - Return the unique reference to the type for the
1066/// specified type declaration.
1067QualType ASTContext::getTypeDeclType(TypeDecl *Decl, TypeDecl* PrevDecl) {
1068  assert(Decl && "Passed null for Decl param");
1069  if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1070
1071  if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
1072    return getTypedefType(Typedef);
1073  else if (TemplateTypeParmDecl *TP = dyn_cast<TemplateTypeParmDecl>(Decl))
1074    return getTemplateTypeParmType(TP);
1075  else if (ObjCInterfaceDecl *ObjCInterface = dyn_cast<ObjCInterfaceDecl>(Decl))
1076    return getObjCInterfaceType(ObjCInterface);
1077
1078  if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Decl)) {
1079    if (PrevDecl)
1080      Decl->TypeForDecl = PrevDecl->TypeForDecl;
1081    else {
1082      void *Mem = Allocator.Allocate(sizeof(CXXRecordType), 8);
1083      Decl->TypeForDecl = new (Mem) CXXRecordType(CXXRecord);
1084    }
1085  }
1086  else if (RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
1087    if (PrevDecl)
1088      Decl->TypeForDecl = PrevDecl->TypeForDecl;
1089    else {
1090      void *Mem = Allocator.Allocate(sizeof(RecordType), 8);
1091      Decl->TypeForDecl = new (Mem) RecordType(Record);
1092    }
1093  }
1094  else if (EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
1095    if (PrevDecl)
1096      Decl->TypeForDecl = PrevDecl->TypeForDecl;
1097    else {
1098      void *Mem = Allocator.Allocate(sizeof(EnumType), 8);
1099      Decl->TypeForDecl = new (Mem) EnumType(Enum);
1100    }
1101  }
1102  else
1103    assert(false && "TypeDecl without a type?");
1104
1105  if (!PrevDecl) Types.push_back(Decl->TypeForDecl);
1106  return QualType(Decl->TypeForDecl, 0);
1107}
1108
1109/// getTypedefType - Return the unique reference to the type for the
1110/// specified typename decl.
1111QualType ASTContext::getTypedefType(TypedefDecl *Decl) {
1112  if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1113
1114  QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
1115  void *Mem = Allocator.Allocate(sizeof(TypedefType), 8);
1116  Decl->TypeForDecl = new (Mem) TypedefType(Type::TypeName, Decl, Canonical);
1117  Types.push_back(Decl->TypeForDecl);
1118  return QualType(Decl->TypeForDecl, 0);
1119}
1120
1121/// getTemplateTypeParmType - Return the unique reference to the type
1122/// for the specified template type parameter declaration.
1123QualType ASTContext::getTemplateTypeParmType(TemplateTypeParmDecl *Decl) {
1124  if (!Decl->TypeForDecl) {
1125    void *Mem = Allocator.Allocate(sizeof(TemplateTypeParmType), 8);
1126    Decl->TypeForDecl = new (Mem) TemplateTypeParmType(Decl);
1127    Types.push_back(Decl->TypeForDecl);
1128  }
1129  return QualType(Decl->TypeForDecl, 0);
1130}
1131
1132/// getObjCInterfaceType - Return the unique reference to the type for the
1133/// specified ObjC interface decl.
1134QualType ASTContext::getObjCInterfaceType(ObjCInterfaceDecl *Decl) {
1135  if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1136
1137  void *Mem = Allocator.Allocate(sizeof(ObjCInterfaceType), 8);
1138  Decl->TypeForDecl = new (Mem) ObjCInterfaceType(Type::ObjCInterface, Decl);
1139  Types.push_back(Decl->TypeForDecl);
1140  return QualType(Decl->TypeForDecl, 0);
1141}
1142
1143/// CmpProtocolNames - Comparison predicate for sorting protocols
1144/// alphabetically.
1145static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
1146                            const ObjCProtocolDecl *RHS) {
1147  return LHS->getDeclName() < RHS->getDeclName();
1148}
1149
1150static void SortAndUniqueProtocols(ObjCProtocolDecl **&Protocols,
1151                                   unsigned &NumProtocols) {
1152  ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
1153
1154  // Sort protocols, keyed by name.
1155  std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
1156
1157  // Remove duplicates.
1158  ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
1159  NumProtocols = ProtocolsEnd-Protocols;
1160}
1161
1162
1163/// getObjCQualifiedInterfaceType - Return a ObjCQualifiedInterfaceType type for
1164/// the given interface decl and the conforming protocol list.
1165QualType ASTContext::getObjCQualifiedInterfaceType(ObjCInterfaceDecl *Decl,
1166                       ObjCProtocolDecl **Protocols, unsigned NumProtocols) {
1167  // Sort the protocol list alphabetically to canonicalize it.
1168  SortAndUniqueProtocols(Protocols, NumProtocols);
1169
1170  llvm::FoldingSetNodeID ID;
1171  ObjCQualifiedInterfaceType::Profile(ID, Decl, Protocols, NumProtocols);
1172
1173  void *InsertPos = 0;
1174  if (ObjCQualifiedInterfaceType *QT =
1175      ObjCQualifiedInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos))
1176    return QualType(QT, 0);
1177
1178  // No Match;
1179  void *Mem = Allocator.Allocate(sizeof(ObjCQualifiedInterfaceType), 8);
1180  ObjCQualifiedInterfaceType *QType =
1181    new (Mem) ObjCQualifiedInterfaceType(Decl, Protocols, NumProtocols);
1182
1183  Types.push_back(QType);
1184  ObjCQualifiedInterfaceTypes.InsertNode(QType, InsertPos);
1185  return QualType(QType, 0);
1186}
1187
1188/// getObjCQualifiedIdType - Return an ObjCQualifiedIdType for the 'id' decl
1189/// and the conforming protocol list.
1190QualType ASTContext::getObjCQualifiedIdType(ObjCProtocolDecl **Protocols,
1191                                            unsigned NumProtocols) {
1192  // Sort the protocol list alphabetically to canonicalize it.
1193  SortAndUniqueProtocols(Protocols, NumProtocols);
1194
1195  llvm::FoldingSetNodeID ID;
1196  ObjCQualifiedIdType::Profile(ID, Protocols, NumProtocols);
1197
1198  void *InsertPos = 0;
1199  if (ObjCQualifiedIdType *QT =
1200        ObjCQualifiedIdTypes.FindNodeOrInsertPos(ID, InsertPos))
1201    return QualType(QT, 0);
1202
1203  // No Match;
1204  void *Mem = Allocator.Allocate(sizeof(ObjCQualifiedIdType), 8);
1205  ObjCQualifiedIdType *QType =
1206    new (Mem) ObjCQualifiedIdType(Protocols, NumProtocols);
1207  Types.push_back(QType);
1208  ObjCQualifiedIdTypes.InsertNode(QType, InsertPos);
1209  return QualType(QType, 0);
1210}
1211
1212/// getTypeOfExpr - Unlike many "get<Type>" functions, we can't unique
1213/// TypeOfExpr AST's (since expression's are never shared). For example,
1214/// multiple declarations that refer to "typeof(x)" all contain different
1215/// DeclRefExpr's. This doesn't effect the type checker, since it operates
1216/// on canonical type's (which are always unique).
1217QualType ASTContext::getTypeOfExpr(Expr *tofExpr) {
1218  QualType Canonical = getCanonicalType(tofExpr->getType());
1219  TypeOfExpr *toe = new TypeOfExpr(tofExpr, Canonical);
1220  Types.push_back(toe);
1221  return QualType(toe, 0);
1222}
1223
1224/// getTypeOfType -  Unlike many "get<Type>" functions, we don't unique
1225/// TypeOfType AST's. The only motivation to unique these nodes would be
1226/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
1227/// an issue. This doesn't effect the type checker, since it operates
1228/// on canonical type's (which are always unique).
1229QualType ASTContext::getTypeOfType(QualType tofType) {
1230  QualType Canonical = getCanonicalType(tofType);
1231  void *Mem = Allocator.Allocate(sizeof(TypeOfType), 8);
1232  TypeOfType *tot = new (Mem) TypeOfType(tofType, Canonical);
1233  Types.push_back(tot);
1234  return QualType(tot, 0);
1235}
1236
1237/// getTagDeclType - Return the unique reference to the type for the
1238/// specified TagDecl (struct/union/class/enum) decl.
1239QualType ASTContext::getTagDeclType(TagDecl *Decl) {
1240  assert (Decl);
1241  return getTypeDeclType(Decl);
1242}
1243
1244/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
1245/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
1246/// needs to agree with the definition in <stddef.h>.
1247QualType ASTContext::getSizeType() const {
1248  return getFromTargetType(Target.getSizeType());
1249}
1250
1251/// getWCharType - Return the unique type for "wchar_t" (C99 7.17), the
1252/// width of characters in wide strings, The value is target dependent and
1253/// needs to agree with the definition in <stddef.h>.
1254QualType ASTContext::getWCharType() const {
1255  if (LangOpts.CPlusPlus)
1256    return WCharTy;
1257
1258  // FIXME: In C, shouldn't WCharTy just be a typedef of the target's
1259  // wide-character type?
1260  return getFromTargetType(Target.getWCharType());
1261}
1262
1263/// getSignedWCharType - Return the type of "signed wchar_t".
1264/// Used when in C++, as a GCC extension.
1265QualType ASTContext::getSignedWCharType() const {
1266  // FIXME: derive from "Target" ?
1267  return WCharTy;
1268}
1269
1270/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
1271/// Used when in C++, as a GCC extension.
1272QualType ASTContext::getUnsignedWCharType() const {
1273  // FIXME: derive from "Target" ?
1274  return UnsignedIntTy;
1275}
1276
1277/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
1278/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
1279QualType ASTContext::getPointerDiffType() const {
1280  return getFromTargetType(Target.getPtrDiffType(0));
1281}
1282
1283//===----------------------------------------------------------------------===//
1284//                              Type Operators
1285//===----------------------------------------------------------------------===//
1286
1287/// getCanonicalType - Return the canonical (structural) type corresponding to
1288/// the specified potentially non-canonical type.  The non-canonical version
1289/// of a type may have many "decorated" versions of types.  Decorators can
1290/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
1291/// to be free of any of these, allowing two canonical types to be compared
1292/// for exact equality with a simple pointer comparison.
1293QualType ASTContext::getCanonicalType(QualType T) {
1294  QualType CanType = T.getTypePtr()->getCanonicalTypeInternal();
1295
1296  // If the result has type qualifiers, make sure to canonicalize them as well.
1297  unsigned TypeQuals = T.getCVRQualifiers() | CanType.getCVRQualifiers();
1298  if (TypeQuals == 0) return CanType;
1299
1300  // If the type qualifiers are on an array type, get the canonical type of the
1301  // array with the qualifiers applied to the element type.
1302  ArrayType *AT = dyn_cast<ArrayType>(CanType);
1303  if (!AT)
1304    return CanType.getQualifiedType(TypeQuals);
1305
1306  // Get the canonical version of the element with the extra qualifiers on it.
1307  // This can recursively sink qualifiers through multiple levels of arrays.
1308  QualType NewEltTy=AT->getElementType().getWithAdditionalQualifiers(TypeQuals);
1309  NewEltTy = getCanonicalType(NewEltTy);
1310
1311  if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
1312    return getConstantArrayType(NewEltTy, CAT->getSize(),CAT->getSizeModifier(),
1313                                CAT->getIndexTypeQualifier());
1314  if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
1315    return getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
1316                                  IAT->getIndexTypeQualifier());
1317
1318  if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
1319    return getDependentSizedArrayType(NewEltTy, DSAT->getSizeExpr(),
1320                                      DSAT->getSizeModifier(),
1321                                      DSAT->getIndexTypeQualifier());
1322
1323  VariableArrayType *VAT = cast<VariableArrayType>(AT);
1324  return getVariableArrayType(NewEltTy, VAT->getSizeExpr(),
1325                              VAT->getSizeModifier(),
1326                              VAT->getIndexTypeQualifier());
1327}
1328
1329
1330const ArrayType *ASTContext::getAsArrayType(QualType T) {
1331  // Handle the non-qualified case efficiently.
1332  if (T.getCVRQualifiers() == 0) {
1333    // Handle the common positive case fast.
1334    if (const ArrayType *AT = dyn_cast<ArrayType>(T))
1335      return AT;
1336  }
1337
1338  // Handle the common negative case fast, ignoring CVR qualifiers.
1339  QualType CType = T->getCanonicalTypeInternal();
1340
1341  // Make sure to look through type qualifiers (like ASQuals) for the negative
1342  // test.
1343  if (!isa<ArrayType>(CType) &&
1344      !isa<ArrayType>(CType.getUnqualifiedType()))
1345    return 0;
1346
1347  // Apply any CVR qualifiers from the array type to the element type.  This
1348  // implements C99 6.7.3p8: "If the specification of an array type includes
1349  // any type qualifiers, the element type is so qualified, not the array type."
1350
1351  // If we get here, we either have type qualifiers on the type, or we have
1352  // sugar such as a typedef in the way.  If we have type qualifiers on the type
1353  // we must propagate them down into the elemeng type.
1354  unsigned CVRQuals = T.getCVRQualifiers();
1355  unsigned AddrSpace = 0;
1356  Type *Ty = T.getTypePtr();
1357
1358  // Rip through ASQualType's and typedefs to get to a concrete type.
1359  while (1) {
1360    if (const ASQualType *ASQT = dyn_cast<ASQualType>(Ty)) {
1361      AddrSpace = ASQT->getAddressSpace();
1362      Ty = ASQT->getBaseType();
1363    } else {
1364      T = Ty->getDesugaredType();
1365      if (T.getTypePtr() == Ty && T.getCVRQualifiers() == 0)
1366        break;
1367      CVRQuals |= T.getCVRQualifiers();
1368      Ty = T.getTypePtr();
1369    }
1370  }
1371
1372  // If we have a simple case, just return now.
1373  const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
1374  if (ATy == 0 || (AddrSpace == 0 && CVRQuals == 0))
1375    return ATy;
1376
1377  // Otherwise, we have an array and we have qualifiers on it.  Push the
1378  // qualifiers into the array element type and return a new array type.
1379  // Get the canonical version of the element with the extra qualifiers on it.
1380  // This can recursively sink qualifiers through multiple levels of arrays.
1381  QualType NewEltTy = ATy->getElementType();
1382  if (AddrSpace)
1383    NewEltTy = getASQualType(NewEltTy, AddrSpace);
1384  NewEltTy = NewEltTy.getWithAdditionalQualifiers(CVRQuals);
1385
1386  if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
1387    return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
1388                                                CAT->getSizeModifier(),
1389                                                CAT->getIndexTypeQualifier()));
1390  if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
1391    return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
1392                                                  IAT->getSizeModifier(),
1393                                                 IAT->getIndexTypeQualifier()));
1394
1395  if (const DependentSizedArrayType *DSAT
1396        = dyn_cast<DependentSizedArrayType>(ATy))
1397    return cast<ArrayType>(
1398                     getDependentSizedArrayType(NewEltTy,
1399                                                DSAT->getSizeExpr(),
1400                                                DSAT->getSizeModifier(),
1401                                                DSAT->getIndexTypeQualifier()));
1402
1403  const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
1404  return cast<ArrayType>(getVariableArrayType(NewEltTy, VAT->getSizeExpr(),
1405                                              VAT->getSizeModifier(),
1406                                              VAT->getIndexTypeQualifier()));
1407}
1408
1409
1410/// getArrayDecayedType - Return the properly qualified result of decaying the
1411/// specified array type to a pointer.  This operation is non-trivial when
1412/// handling typedefs etc.  The canonical type of "T" must be an array type,
1413/// this returns a pointer to a properly qualified element of the array.
1414///
1415/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
1416QualType ASTContext::getArrayDecayedType(QualType Ty) {
1417  // Get the element type with 'getAsArrayType' so that we don't lose any
1418  // typedefs in the element type of the array.  This also handles propagation
1419  // of type qualifiers from the array type into the element type if present
1420  // (C99 6.7.3p8).
1421  const ArrayType *PrettyArrayType = getAsArrayType(Ty);
1422  assert(PrettyArrayType && "Not an array type!");
1423
1424  QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
1425
1426  // int x[restrict 4] ->  int *restrict
1427  return PtrTy.getQualifiedType(PrettyArrayType->getIndexTypeQualifier());
1428}
1429
1430QualType ASTContext::getBaseElementType(const VariableArrayType *VAT) {
1431  QualType ElemTy = VAT->getElementType();
1432
1433  if (const VariableArrayType *VAT = getAsVariableArrayType(ElemTy))
1434    return getBaseElementType(VAT);
1435
1436  return ElemTy;
1437}
1438
1439/// getFloatingRank - Return a relative rank for floating point types.
1440/// This routine will assert if passed a built-in type that isn't a float.
1441static FloatingRank getFloatingRank(QualType T) {
1442  if (const ComplexType *CT = T->getAsComplexType())
1443    return getFloatingRank(CT->getElementType());
1444
1445  assert(T->getAsBuiltinType() && "getFloatingRank(): not a floating type");
1446  switch (T->getAsBuiltinType()->getKind()) {
1447  default: assert(0 && "getFloatingRank(): not a floating type");
1448  case BuiltinType::Float:      return FloatRank;
1449  case BuiltinType::Double:     return DoubleRank;
1450  case BuiltinType::LongDouble: return LongDoubleRank;
1451  }
1452}
1453
1454/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
1455/// point or a complex type (based on typeDomain/typeSize).
1456/// 'typeDomain' is a real floating point or complex type.
1457/// 'typeSize' is a real floating point or complex type.
1458QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
1459                                                       QualType Domain) const {
1460  FloatingRank EltRank = getFloatingRank(Size);
1461  if (Domain->isComplexType()) {
1462    switch (EltRank) {
1463    default: assert(0 && "getFloatingRank(): illegal value for rank");
1464    case FloatRank:      return FloatComplexTy;
1465    case DoubleRank:     return DoubleComplexTy;
1466    case LongDoubleRank: return LongDoubleComplexTy;
1467    }
1468  }
1469
1470  assert(Domain->isRealFloatingType() && "Unknown domain!");
1471  switch (EltRank) {
1472  default: assert(0 && "getFloatingRank(): illegal value for rank");
1473  case FloatRank:      return FloatTy;
1474  case DoubleRank:     return DoubleTy;
1475  case LongDoubleRank: return LongDoubleTy;
1476  }
1477}
1478
1479/// getFloatingTypeOrder - Compare the rank of the two specified floating
1480/// point types, ignoring the domain of the type (i.e. 'double' ==
1481/// '_Complex double').  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
1482/// LHS < RHS, return -1.
1483int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
1484  FloatingRank LHSR = getFloatingRank(LHS);
1485  FloatingRank RHSR = getFloatingRank(RHS);
1486
1487  if (LHSR == RHSR)
1488    return 0;
1489  if (LHSR > RHSR)
1490    return 1;
1491  return -1;
1492}
1493
1494/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
1495/// routine will assert if passed a built-in type that isn't an integer or enum,
1496/// or if it is not canonicalized.
1497static unsigned getIntegerRank(Type *T) {
1498  assert(T->isCanonical() && "T should be canonicalized");
1499  if (isa<EnumType>(T))
1500    return 4;
1501
1502  switch (cast<BuiltinType>(T)->getKind()) {
1503  default: assert(0 && "getIntegerRank(): not a built-in integer");
1504  case BuiltinType::Bool:
1505    return 1;
1506  case BuiltinType::Char_S:
1507  case BuiltinType::Char_U:
1508  case BuiltinType::SChar:
1509  case BuiltinType::UChar:
1510    return 2;
1511  case BuiltinType::Short:
1512  case BuiltinType::UShort:
1513    return 3;
1514  case BuiltinType::Int:
1515  case BuiltinType::UInt:
1516    return 4;
1517  case BuiltinType::Long:
1518  case BuiltinType::ULong:
1519    return 5;
1520  case BuiltinType::LongLong:
1521  case BuiltinType::ULongLong:
1522    return 6;
1523  }
1524}
1525
1526/// getIntegerTypeOrder - Returns the highest ranked integer type:
1527/// C99 6.3.1.8p1.  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
1528/// LHS < RHS, return -1.
1529int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
1530  Type *LHSC = getCanonicalType(LHS).getTypePtr();
1531  Type *RHSC = getCanonicalType(RHS).getTypePtr();
1532  if (LHSC == RHSC) return 0;
1533
1534  bool LHSUnsigned = LHSC->isUnsignedIntegerType();
1535  bool RHSUnsigned = RHSC->isUnsignedIntegerType();
1536
1537  unsigned LHSRank = getIntegerRank(LHSC);
1538  unsigned RHSRank = getIntegerRank(RHSC);
1539
1540  if (LHSUnsigned == RHSUnsigned) {  // Both signed or both unsigned.
1541    if (LHSRank == RHSRank) return 0;
1542    return LHSRank > RHSRank ? 1 : -1;
1543  }
1544
1545  // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
1546  if (LHSUnsigned) {
1547    // If the unsigned [LHS] type is larger, return it.
1548    if (LHSRank >= RHSRank)
1549      return 1;
1550
1551    // If the signed type can represent all values of the unsigned type, it
1552    // wins.  Because we are dealing with 2's complement and types that are
1553    // powers of two larger than each other, this is always safe.
1554    return -1;
1555  }
1556
1557  // If the unsigned [RHS] type is larger, return it.
1558  if (RHSRank >= LHSRank)
1559    return -1;
1560
1561  // If the signed type can represent all values of the unsigned type, it
1562  // wins.  Because we are dealing with 2's complement and types that are
1563  // powers of two larger than each other, this is always safe.
1564  return 1;
1565}
1566
1567// getCFConstantStringType - Return the type used for constant CFStrings.
1568QualType ASTContext::getCFConstantStringType() {
1569  if (!CFConstantStringTypeDecl) {
1570    CFConstantStringTypeDecl =
1571      RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
1572                         &Idents.get("NSConstantString"));
1573    QualType FieldTypes[4];
1574
1575    // const int *isa;
1576    FieldTypes[0] = getPointerType(IntTy.getQualifiedType(QualType::Const));
1577    // int flags;
1578    FieldTypes[1] = IntTy;
1579    // const char *str;
1580    FieldTypes[2] = getPointerType(CharTy.getQualifiedType(QualType::Const));
1581    // long length;
1582    FieldTypes[3] = LongTy;
1583
1584    // Create fields
1585    for (unsigned i = 0; i < 4; ++i) {
1586      FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
1587                                           SourceLocation(), 0,
1588                                           FieldTypes[i], /*BitWidth=*/0,
1589                                           /*Mutable=*/false);
1590      CFConstantStringTypeDecl->addDecl(Field);
1591    }
1592
1593    CFConstantStringTypeDecl->completeDefinition(*this);
1594  }
1595
1596  return getTagDeclType(CFConstantStringTypeDecl);
1597}
1598
1599QualType ASTContext::getObjCFastEnumerationStateType()
1600{
1601  if (!ObjCFastEnumerationStateTypeDecl) {
1602    ObjCFastEnumerationStateTypeDecl =
1603      RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
1604                         &Idents.get("__objcFastEnumerationState"));
1605
1606    QualType FieldTypes[] = {
1607      UnsignedLongTy,
1608      getPointerType(ObjCIdType),
1609      getPointerType(UnsignedLongTy),
1610      getConstantArrayType(UnsignedLongTy,
1611                           llvm::APInt(32, 5), ArrayType::Normal, 0)
1612    };
1613
1614    for (size_t i = 0; i < 4; ++i) {
1615      FieldDecl *Field = FieldDecl::Create(*this,
1616                                           ObjCFastEnumerationStateTypeDecl,
1617                                           SourceLocation(), 0,
1618                                           FieldTypes[i], /*BitWidth=*/0,
1619                                           /*Mutable=*/false);
1620      ObjCFastEnumerationStateTypeDecl->addDecl(Field);
1621    }
1622
1623    ObjCFastEnumerationStateTypeDecl->completeDefinition(*this);
1624  }
1625
1626  return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
1627}
1628
1629// This returns true if a type has been typedefed to BOOL:
1630// typedef <type> BOOL;
1631static bool isTypeTypedefedAsBOOL(QualType T) {
1632  if (const TypedefType *TT = dyn_cast<TypedefType>(T))
1633    if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
1634      return II->isStr("BOOL");
1635
1636  return false;
1637}
1638
1639/// getObjCEncodingTypeSize returns size of type for objective-c encoding
1640/// purpose.
1641int ASTContext::getObjCEncodingTypeSize(QualType type) {
1642  uint64_t sz = getTypeSize(type);
1643
1644  // Make all integer and enum types at least as large as an int
1645  if (sz > 0 && type->isIntegralType())
1646    sz = std::max(sz, getTypeSize(IntTy));
1647  // Treat arrays as pointers, since that's how they're passed in.
1648  else if (type->isArrayType())
1649    sz = getTypeSize(VoidPtrTy);
1650  return sz / getTypeSize(CharTy);
1651}
1652
1653/// getObjCEncodingForMethodDecl - Return the encoded type for this method
1654/// declaration.
1655void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
1656                                              std::string& S) {
1657  // FIXME: This is not very efficient.
1658  // Encode type qualifer, 'in', 'inout', etc. for the return type.
1659  getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
1660  // Encode result type.
1661  getObjCEncodingForType(Decl->getResultType(), S);
1662  // Compute size of all parameters.
1663  // Start with computing size of a pointer in number of bytes.
1664  // FIXME: There might(should) be a better way of doing this computation!
1665  SourceLocation Loc;
1666  int PtrSize = getTypeSize(VoidPtrTy) / getTypeSize(CharTy);
1667  // The first two arguments (self and _cmd) are pointers; account for
1668  // their size.
1669  int ParmOffset = 2 * PtrSize;
1670  int NumOfParams = Decl->getNumParams();
1671  for (int i = 0; i < NumOfParams; i++) {
1672    QualType PType = Decl->getParamDecl(i)->getType();
1673    int sz = getObjCEncodingTypeSize (PType);
1674    assert (sz > 0 && "getObjCEncodingForMethodDecl - Incomplete param type");
1675    ParmOffset += sz;
1676  }
1677  S += llvm::utostr(ParmOffset);
1678  S += "@0:";
1679  S += llvm::utostr(PtrSize);
1680
1681  // Argument types.
1682  ParmOffset = 2 * PtrSize;
1683  for (int i = 0; i < NumOfParams; i++) {
1684    ParmVarDecl *PVDecl = Decl->getParamDecl(i);
1685    QualType PType = PVDecl->getOriginalType();
1686    if (const ArrayType *AT =
1687          dyn_cast<ArrayType>(PType->getCanonicalTypeInternal()))
1688        // Use array's original type only if it has known number of
1689        // elements.
1690        if (!dyn_cast<ConstantArrayType>(AT))
1691          PType = PVDecl->getType();
1692    // Process argument qualifiers for user supplied arguments; such as,
1693    // 'in', 'inout', etc.
1694    getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
1695    getObjCEncodingForType(PType, S);
1696    S += llvm::utostr(ParmOffset);
1697    ParmOffset += getObjCEncodingTypeSize(PType);
1698  }
1699}
1700
1701/// getObjCEncodingForPropertyDecl - Return the encoded type for this
1702/// method declaration. If non-NULL, Container must be either an
1703/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
1704/// NULL when getting encodings for protocol properties.
1705void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
1706                                                const Decl *Container,
1707                                                std::string& S) {
1708  // Collect information from the property implementation decl(s).
1709  bool Dynamic = false;
1710  ObjCPropertyImplDecl *SynthesizePID = 0;
1711
1712  // FIXME: Duplicated code due to poor abstraction.
1713  if (Container) {
1714    if (const ObjCCategoryImplDecl *CID =
1715        dyn_cast<ObjCCategoryImplDecl>(Container)) {
1716      for (ObjCCategoryImplDecl::propimpl_iterator
1717             i = CID->propimpl_begin(), e = CID->propimpl_end(); i != e; ++i) {
1718        ObjCPropertyImplDecl *PID = *i;
1719        if (PID->getPropertyDecl() == PD) {
1720          if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
1721            Dynamic = true;
1722          } else {
1723            SynthesizePID = PID;
1724          }
1725        }
1726      }
1727    } else {
1728      const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
1729      for (ObjCCategoryImplDecl::propimpl_iterator
1730             i = OID->propimpl_begin(), e = OID->propimpl_end(); i != e; ++i) {
1731        ObjCPropertyImplDecl *PID = *i;
1732        if (PID->getPropertyDecl() == PD) {
1733          if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
1734            Dynamic = true;
1735          } else {
1736            SynthesizePID = PID;
1737          }
1738        }
1739      }
1740    }
1741  }
1742
1743  // FIXME: This is not very efficient.
1744  S = "T";
1745
1746  // Encode result type.
1747  // FIXME: GCC uses a generating_property_type_encoding mode during
1748  // this part. Investigate.
1749  getObjCEncodingForType(PD->getType(), S);
1750
1751  if (PD->isReadOnly()) {
1752    S += ",R";
1753  } else {
1754    switch (PD->getSetterKind()) {
1755    case ObjCPropertyDecl::Assign: break;
1756    case ObjCPropertyDecl::Copy:   S += ",C"; break;
1757    case ObjCPropertyDecl::Retain: S += ",&"; break;
1758    }
1759  }
1760
1761  // It really isn't clear at all what this means, since properties
1762  // are "dynamic by default".
1763  if (Dynamic)
1764    S += ",D";
1765
1766  if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
1767    S += ",G";
1768    S += PD->getGetterName().getAsString();
1769  }
1770
1771  if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
1772    S += ",S";
1773    S += PD->getSetterName().getAsString();
1774  }
1775
1776  if (SynthesizePID) {
1777    const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
1778    S += ",V";
1779    S += OID->getNameAsString();
1780  }
1781
1782  // FIXME: OBJCGC: weak & strong
1783}
1784
1785/// getLegacyIntegralTypeEncoding -
1786/// Another legacy compatibility encoding: 32-bit longs are encoded as
1787/// 'l' or 'L', but not always.  For typedefs, we need to use
1788/// 'i' or 'I' instead if encoding a struct field, or a pointer!
1789///
1790void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
1791  if (dyn_cast<TypedefType>(PointeeTy.getTypePtr())) {
1792    if (const BuiltinType *BT = PointeeTy->getAsBuiltinType()) {
1793      if (BT->getKind() == BuiltinType::ULong)
1794        PointeeTy = UnsignedIntTy;
1795        else if (BT->getKind() == BuiltinType::Long)
1796          PointeeTy = IntTy;
1797    }
1798  }
1799}
1800
1801void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
1802                                        FieldDecl *Field) const {
1803  // We follow the behavior of gcc, expanding structures which are
1804  // directly pointed to, and expanding embedded structures. Note that
1805  // these rules are sufficient to prevent recursive encoding of the
1806  // same type.
1807  getObjCEncodingForTypeImpl(T, S, true, true, Field,
1808                             true /* outermost type */);
1809}
1810
1811static void EncodeBitField(const ASTContext *Context, std::string& S,
1812                           FieldDecl *FD) {
1813  const Expr *E = FD->getBitWidth();
1814  assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
1815  ASTContext *Ctx = const_cast<ASTContext*>(Context);
1816  unsigned N = E->getIntegerConstantExprValue(*Ctx).getZExtValue();
1817  S += 'b';
1818  S += llvm::utostr(N);
1819}
1820
1821void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
1822                                            bool ExpandPointedToStructures,
1823                                            bool ExpandStructures,
1824                                            FieldDecl *FD,
1825                                            bool OutermostType) const {
1826  if (const BuiltinType *BT = T->getAsBuiltinType()) {
1827    if (FD && FD->isBitField()) {
1828      EncodeBitField(this, S, FD);
1829    }
1830    else {
1831      char encoding;
1832      switch (BT->getKind()) {
1833      default: assert(0 && "Unhandled builtin type kind");
1834      case BuiltinType::Void:       encoding = 'v'; break;
1835      case BuiltinType::Bool:       encoding = 'B'; break;
1836      case BuiltinType::Char_U:
1837      case BuiltinType::UChar:      encoding = 'C'; break;
1838      case BuiltinType::UShort:     encoding = 'S'; break;
1839      case BuiltinType::UInt:       encoding = 'I'; break;
1840      case BuiltinType::ULong:      encoding = 'L'; break;
1841      case BuiltinType::ULongLong:  encoding = 'Q'; break;
1842      case BuiltinType::Char_S:
1843      case BuiltinType::SChar:      encoding = 'c'; break;
1844      case BuiltinType::Short:      encoding = 's'; break;
1845      case BuiltinType::Int:        encoding = 'i'; break;
1846      case BuiltinType::Long:       encoding = 'l'; break;
1847      case BuiltinType::LongLong:   encoding = 'q'; break;
1848      case BuiltinType::Float:      encoding = 'f'; break;
1849      case BuiltinType::Double:     encoding = 'd'; break;
1850      case BuiltinType::LongDouble: encoding = 'd'; break;
1851      }
1852
1853      S += encoding;
1854    }
1855  }
1856  else if (T->isObjCQualifiedIdType()) {
1857    // Treat id<P...> same as 'id' for encoding purposes.
1858    return getObjCEncodingForTypeImpl(getObjCIdType(), S,
1859                                      ExpandPointedToStructures,
1860                                      ExpandStructures, FD);
1861  }
1862  else if (const PointerType *PT = T->getAsPointerType()) {
1863    QualType PointeeTy = PT->getPointeeType();
1864    bool isReadOnly = false;
1865    // For historical/compatibility reasons, the read-only qualifier of the
1866    // pointee gets emitted _before_ the '^'.  The read-only qualifier of
1867    // the pointer itself gets ignored, _unless_ we are looking at a typedef!
1868    // Also, do not emit the 'r' for anything but the outermost type!
1869    if (dyn_cast<TypedefType>(T.getTypePtr())) {
1870      if (OutermostType && T.isConstQualified()) {
1871        isReadOnly = true;
1872        S += 'r';
1873      }
1874    }
1875    else if (OutermostType) {
1876      QualType P = PointeeTy;
1877      while (P->getAsPointerType())
1878        P = P->getAsPointerType()->getPointeeType();
1879      if (P.isConstQualified()) {
1880        isReadOnly = true;
1881        S += 'r';
1882      }
1883    }
1884    if (isReadOnly) {
1885      // Another legacy compatibility encoding. Some ObjC qualifier and type
1886      // combinations need to be rearranged.
1887      // Rewrite "in const" from "nr" to "rn"
1888      const char * s = S.c_str();
1889      int len = S.length();
1890      if (len >= 2 && s[len-2] == 'n' && s[len-1] == 'r') {
1891        std::string replace = "rn";
1892        S.replace(S.end()-2, S.end(), replace);
1893      }
1894    }
1895    if (isObjCIdType(PointeeTy)) {
1896      S += '@';
1897      return;
1898    }
1899    else if (PointeeTy->isObjCInterfaceType()) {
1900      if (dyn_cast<TypedefType>(PointeeTy.getTypePtr())) {
1901        // Another historical/compatibility reason.
1902        // We encode the underlying type which comes out as
1903        // {...};
1904        S += '^';
1905        getObjCEncodingForTypeImpl(PointeeTy, S,
1906                                   false, ExpandPointedToStructures,
1907                                   NULL);
1908        return;
1909      }
1910      S += '@';
1911      if (FD) {
1912        ObjCInterfaceDecl *OI = PointeeTy->getAsObjCInterfaceType()->getDecl();
1913        S += '"';
1914        S += OI->getNameAsCString();
1915        S += '"';
1916      }
1917      return;
1918    } else if (isObjCClassType(PointeeTy)) {
1919      S += '#';
1920      return;
1921    } else if (isObjCSelType(PointeeTy)) {
1922      S += ':';
1923      return;
1924    }
1925
1926    if (PointeeTy->isCharType()) {
1927      // char pointer types should be encoded as '*' unless it is a
1928      // type that has been typedef'd to 'BOOL'.
1929      if (!isTypeTypedefedAsBOOL(PointeeTy)) {
1930        S += '*';
1931        return;
1932      }
1933    }
1934
1935    S += '^';
1936    getLegacyIntegralTypeEncoding(PointeeTy);
1937
1938    getObjCEncodingForTypeImpl(PointeeTy, S,
1939                               false, ExpandPointedToStructures,
1940                               NULL);
1941  } else if (const ArrayType *AT =
1942               // Ignore type qualifiers etc.
1943               dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
1944    S += '[';
1945
1946    if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
1947      S += llvm::utostr(CAT->getSize().getZExtValue());
1948    else
1949      assert(0 && "Unhandled array type!");
1950
1951    getObjCEncodingForTypeImpl(AT->getElementType(), S,
1952                               false, ExpandStructures, FD);
1953    S += ']';
1954  } else if (T->getAsFunctionType()) {
1955    S += '?';
1956  } else if (const RecordType *RTy = T->getAsRecordType()) {
1957    RecordDecl *RDecl = RTy->getDecl();
1958    S += RDecl->isUnion() ? '(' : '{';
1959    // Anonymous structures print as '?'
1960    if (const IdentifierInfo *II = RDecl->getIdentifier()) {
1961      S += II->getName();
1962    } else {
1963      S += '?';
1964    }
1965    if (ExpandStructures) {
1966      S += '=';
1967      for (RecordDecl::field_iterator Field = RDecl->field_begin(),
1968                                   FieldEnd = RDecl->field_end();
1969           Field != FieldEnd; ++Field) {
1970        if (FD) {
1971          S += '"';
1972          S += Field->getNameAsString();
1973          S += '"';
1974        }
1975
1976        // Special case bit-fields.
1977        if (Field->isBitField()) {
1978          getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
1979                                     (*Field));
1980        } else {
1981          QualType qt = Field->getType();
1982          getLegacyIntegralTypeEncoding(qt);
1983          getObjCEncodingForTypeImpl(qt, S, false, true,
1984                                     FD);
1985        }
1986      }
1987    }
1988    S += RDecl->isUnion() ? ')' : '}';
1989  } else if (T->isEnumeralType()) {
1990    if (FD && FD->isBitField())
1991      EncodeBitField(this, S, FD);
1992    else
1993      S += 'i';
1994  } else if (T->isBlockPointerType()) {
1995    S += '^'; // This type string is the same as general pointers.
1996  } else if (T->isObjCInterfaceType()) {
1997    // @encode(class_name)
1998    ObjCInterfaceDecl *OI = T->getAsObjCInterfaceType()->getDecl();
1999    S += '{';
2000    const IdentifierInfo *II = OI->getIdentifier();
2001    S += II->getName();
2002    S += '=';
2003    std::vector<FieldDecl*> RecFields;
2004    CollectObjCIvars(OI, RecFields);
2005    for (unsigned int i = 0; i != RecFields.size(); i++) {
2006      if (RecFields[i]->isBitField())
2007        getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
2008                                   RecFields[i]);
2009      else
2010        getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
2011                                   FD);
2012    }
2013    S += '}';
2014  }
2015  else
2016    assert(0 && "@encode for type not implemented!");
2017}
2018
2019void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
2020                                                 std::string& S) const {
2021  if (QT & Decl::OBJC_TQ_In)
2022    S += 'n';
2023  if (QT & Decl::OBJC_TQ_Inout)
2024    S += 'N';
2025  if (QT & Decl::OBJC_TQ_Out)
2026    S += 'o';
2027  if (QT & Decl::OBJC_TQ_Bycopy)
2028    S += 'O';
2029  if (QT & Decl::OBJC_TQ_Byref)
2030    S += 'R';
2031  if (QT & Decl::OBJC_TQ_Oneway)
2032    S += 'V';
2033}
2034
2035void ASTContext::setBuiltinVaListType(QualType T)
2036{
2037  assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
2038
2039  BuiltinVaListType = T;
2040}
2041
2042void ASTContext::setObjCIdType(TypedefDecl *TD)
2043{
2044  ObjCIdType = getTypedefType(TD);
2045
2046  // typedef struct objc_object *id;
2047  const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
2048  // User error - caller will issue diagnostics.
2049  if (!ptr)
2050    return;
2051  const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
2052  // User error - caller will issue diagnostics.
2053  if (!rec)
2054    return;
2055  IdStructType = rec;
2056}
2057
2058void ASTContext::setObjCSelType(TypedefDecl *TD)
2059{
2060  ObjCSelType = getTypedefType(TD);
2061
2062  // typedef struct objc_selector *SEL;
2063  const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
2064  if (!ptr)
2065    return;
2066  const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
2067  if (!rec)
2068    return;
2069  SelStructType = rec;
2070}
2071
2072void ASTContext::setObjCProtoType(QualType QT)
2073{
2074  ObjCProtoType = QT;
2075}
2076
2077void ASTContext::setObjCClassType(TypedefDecl *TD)
2078{
2079  ObjCClassType = getTypedefType(TD);
2080
2081  // typedef struct objc_class *Class;
2082  const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
2083  assert(ptr && "'Class' incorrectly typed");
2084  const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
2085  assert(rec && "'Class' incorrectly typed");
2086  ClassStructType = rec;
2087}
2088
2089void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
2090  assert(ObjCConstantStringType.isNull() &&
2091         "'NSConstantString' type already set!");
2092
2093  ObjCConstantStringType = getObjCInterfaceType(Decl);
2094}
2095
2096/// getFromTargetType - Given one of the integer types provided by
2097/// TargetInfo, produce the corresponding type. The unsigned @p Type
2098/// is actually a value of type @c TargetInfo::IntType.
2099QualType ASTContext::getFromTargetType(unsigned Type) const {
2100  switch (Type) {
2101  case TargetInfo::NoInt: return QualType();
2102  case TargetInfo::SignedShort: return ShortTy;
2103  case TargetInfo::UnsignedShort: return UnsignedShortTy;
2104  case TargetInfo::SignedInt: return IntTy;
2105  case TargetInfo::UnsignedInt: return UnsignedIntTy;
2106  case TargetInfo::SignedLong: return LongTy;
2107  case TargetInfo::UnsignedLong: return UnsignedLongTy;
2108  case TargetInfo::SignedLongLong: return LongLongTy;
2109  case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
2110  }
2111
2112  assert(false && "Unhandled TargetInfo::IntType value");
2113  return QualType();
2114}
2115
2116//===----------------------------------------------------------------------===//
2117//                        Type Predicates.
2118//===----------------------------------------------------------------------===//
2119
2120/// isObjCNSObjectType - Return true if this is an NSObject object using
2121/// NSObject attribute on a c-style pointer type.
2122/// FIXME - Make it work directly on types.
2123///
2124bool ASTContext::isObjCNSObjectType(QualType Ty) const {
2125  if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
2126    if (TypedefDecl *TD = TDT->getDecl())
2127      if (TD->getAttr<ObjCNSObjectAttr>())
2128        return true;
2129  }
2130  return false;
2131}
2132
2133/// isObjCObjectPointerType - Returns true if type is an Objective-C pointer
2134/// to an object type.  This includes "id" and "Class" (two 'special' pointers
2135/// to struct), Interface* (pointer to ObjCInterfaceType) and id<P> (qualified
2136/// ID type).
2137bool ASTContext::isObjCObjectPointerType(QualType Ty) const {
2138  if (Ty->isObjCQualifiedIdType())
2139    return true;
2140
2141  // Blocks are objects.
2142  if (Ty->isBlockPointerType())
2143    return true;
2144
2145  // All other object types are pointers.
2146  if (!Ty->isPointerType())
2147    return false;
2148
2149  // Check to see if this is 'id' or 'Class', both of which are typedefs for
2150  // pointer types.  This looks for the typedef specifically, not for the
2151  // underlying type.
2152  if (Ty == getObjCIdType() || Ty == getObjCClassType())
2153    return true;
2154
2155  // If this a pointer to an interface (e.g. NSString*), it is ok.
2156  if (Ty->getAsPointerType()->getPointeeType()->isObjCInterfaceType())
2157    return true;
2158
2159  // If is has NSObject attribute, OK as well.
2160  return isObjCNSObjectType(Ty);
2161}
2162
2163//===----------------------------------------------------------------------===//
2164//                        Type Compatibility Testing
2165//===----------------------------------------------------------------------===//
2166
2167/// typesAreBlockCompatible - This routine is called when comparing two
2168/// block types. Types must be strictly compatible here. For example,
2169/// C unfortunately doesn't produce an error for the following:
2170///
2171///   int (*emptyArgFunc)();
2172///   int (*intArgList)(int) = emptyArgFunc;
2173///
2174/// For blocks, we will produce an error for the following (similar to C++):
2175///
2176///   int (^emptyArgBlock)();
2177///   int (^intArgBlock)(int) = emptyArgBlock;
2178///
2179/// FIXME: When the dust settles on this integration, fold this into mergeTypes.
2180///
2181bool ASTContext::typesAreBlockCompatible(QualType lhs, QualType rhs) {
2182  const FunctionType *lbase = lhs->getAsFunctionType();
2183  const FunctionType *rbase = rhs->getAsFunctionType();
2184  const FunctionTypeProto *lproto = dyn_cast<FunctionTypeProto>(lbase);
2185  const FunctionTypeProto *rproto = dyn_cast<FunctionTypeProto>(rbase);
2186  if (lproto && rproto)
2187    return !mergeTypes(lhs, rhs).isNull();
2188  return false;
2189}
2190
2191/// areCompatVectorTypes - Return true if the two specified vector types are
2192/// compatible.
2193static bool areCompatVectorTypes(const VectorType *LHS,
2194                                 const VectorType *RHS) {
2195  assert(LHS->isCanonical() && RHS->isCanonical());
2196  return LHS->getElementType() == RHS->getElementType() &&
2197         LHS->getNumElements() == RHS->getNumElements();
2198}
2199
2200/// canAssignObjCInterfaces - Return true if the two interface types are
2201/// compatible for assignment from RHS to LHS.  This handles validation of any
2202/// protocol qualifiers on the LHS or RHS.
2203///
2204bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
2205                                         const ObjCInterfaceType *RHS) {
2206  // Verify that the base decls are compatible: the RHS must be a subclass of
2207  // the LHS.
2208  if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
2209    return false;
2210
2211  // RHS must have a superset of the protocols in the LHS.  If the LHS is not
2212  // protocol qualified at all, then we are good.
2213  if (!isa<ObjCQualifiedInterfaceType>(LHS))
2214    return true;
2215
2216  // Okay, we know the LHS has protocol qualifiers.  If the RHS doesn't, then it
2217  // isn't a superset.
2218  if (!isa<ObjCQualifiedInterfaceType>(RHS))
2219    return true;  // FIXME: should return false!
2220
2221  // Finally, we must have two protocol-qualified interfaces.
2222  const ObjCQualifiedInterfaceType *LHSP =cast<ObjCQualifiedInterfaceType>(LHS);
2223  const ObjCQualifiedInterfaceType *RHSP =cast<ObjCQualifiedInterfaceType>(RHS);
2224  ObjCQualifiedInterfaceType::qual_iterator LHSPI = LHSP->qual_begin();
2225  ObjCQualifiedInterfaceType::qual_iterator LHSPE = LHSP->qual_end();
2226  ObjCQualifiedInterfaceType::qual_iterator RHSPI = RHSP->qual_begin();
2227  ObjCQualifiedInterfaceType::qual_iterator RHSPE = RHSP->qual_end();
2228
2229  // All protocols in LHS must have a presence in RHS.  Since the protocol lists
2230  // are both sorted alphabetically and have no duplicates, we can scan RHS and
2231  // LHS in a single parallel scan until we run out of elements in LHS.
2232  assert(LHSPI != LHSPE && "Empty LHS protocol list?");
2233  ObjCProtocolDecl *LHSProto = *LHSPI;
2234
2235  while (RHSPI != RHSPE) {
2236    ObjCProtocolDecl *RHSProto = *RHSPI++;
2237    // If the RHS has a protocol that the LHS doesn't, ignore it.
2238    if (RHSProto != LHSProto)
2239      continue;
2240
2241    // Otherwise, the RHS does have this element.
2242    ++LHSPI;
2243    if (LHSPI == LHSPE)
2244      return true;  // All protocols in LHS exist in RHS.
2245
2246    LHSProto = *LHSPI;
2247  }
2248
2249  // If we got here, we didn't find one of the LHS's protocols in the RHS list.
2250  return false;
2251}
2252
2253/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
2254/// both shall have the identically qualified version of a compatible type.
2255/// C99 6.2.7p1: Two types have compatible types if their types are the
2256/// same. See 6.7.[2,3,5] for additional rules.
2257bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
2258  return !mergeTypes(LHS, RHS).isNull();
2259}
2260
2261QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) {
2262  const FunctionType *lbase = lhs->getAsFunctionType();
2263  const FunctionType *rbase = rhs->getAsFunctionType();
2264  const FunctionTypeProto *lproto = dyn_cast<FunctionTypeProto>(lbase);
2265  const FunctionTypeProto *rproto = dyn_cast<FunctionTypeProto>(rbase);
2266  bool allLTypes = true;
2267  bool allRTypes = true;
2268
2269  // Check return type
2270  QualType retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
2271  if (retType.isNull()) return QualType();
2272  if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
2273    allLTypes = false;
2274  if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
2275    allRTypes = false;
2276
2277  if (lproto && rproto) { // two C99 style function prototypes
2278    unsigned lproto_nargs = lproto->getNumArgs();
2279    unsigned rproto_nargs = rproto->getNumArgs();
2280
2281    // Compatible functions must have the same number of arguments
2282    if (lproto_nargs != rproto_nargs)
2283      return QualType();
2284
2285    // Variadic and non-variadic functions aren't compatible
2286    if (lproto->isVariadic() != rproto->isVariadic())
2287      return QualType();
2288
2289    if (lproto->getTypeQuals() != rproto->getTypeQuals())
2290      return QualType();
2291
2292    // Check argument compatibility
2293    llvm::SmallVector<QualType, 10> types;
2294    for (unsigned i = 0; i < lproto_nargs; i++) {
2295      QualType largtype = lproto->getArgType(i).getUnqualifiedType();
2296      QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
2297      QualType argtype = mergeTypes(largtype, rargtype);
2298      if (argtype.isNull()) return QualType();
2299      types.push_back(argtype);
2300      if (getCanonicalType(argtype) != getCanonicalType(largtype))
2301        allLTypes = false;
2302      if (getCanonicalType(argtype) != getCanonicalType(rargtype))
2303        allRTypes = false;
2304    }
2305    if (allLTypes) return lhs;
2306    if (allRTypes) return rhs;
2307    return getFunctionType(retType, types.begin(), types.size(),
2308                           lproto->isVariadic(), lproto->getTypeQuals());
2309  }
2310
2311  if (lproto) allRTypes = false;
2312  if (rproto) allLTypes = false;
2313
2314  const FunctionTypeProto *proto = lproto ? lproto : rproto;
2315  if (proto) {
2316    if (proto->isVariadic()) return QualType();
2317    // Check that the types are compatible with the types that
2318    // would result from default argument promotions (C99 6.7.5.3p15).
2319    // The only types actually affected are promotable integer
2320    // types and floats, which would be passed as a different
2321    // type depending on whether the prototype is visible.
2322    unsigned proto_nargs = proto->getNumArgs();
2323    for (unsigned i = 0; i < proto_nargs; ++i) {
2324      QualType argTy = proto->getArgType(i);
2325      if (argTy->isPromotableIntegerType() ||
2326          getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
2327        return QualType();
2328    }
2329
2330    if (allLTypes) return lhs;
2331    if (allRTypes) return rhs;
2332    return getFunctionType(retType, proto->arg_type_begin(),
2333                           proto->getNumArgs(), lproto->isVariadic(),
2334                           lproto->getTypeQuals());
2335  }
2336
2337  if (allLTypes) return lhs;
2338  if (allRTypes) return rhs;
2339  return getFunctionTypeNoProto(retType);
2340}
2341
2342QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) {
2343  // C++ [expr]: If an expression initially has the type "reference to T", the
2344  // type is adjusted to "T" prior to any further analysis, the expression
2345  // designates the object or function denoted by the reference, and the
2346  // expression is an lvalue.
2347  // FIXME: C++ shouldn't be going through here!  The rules are different
2348  // enough that they should be handled separately.
2349  if (const ReferenceType *RT = LHS->getAsReferenceType())
2350    LHS = RT->getPointeeType();
2351  if (const ReferenceType *RT = RHS->getAsReferenceType())
2352    RHS = RT->getPointeeType();
2353
2354  QualType LHSCan = getCanonicalType(LHS),
2355           RHSCan = getCanonicalType(RHS);
2356
2357  // If two types are identical, they are compatible.
2358  if (LHSCan == RHSCan)
2359    return LHS;
2360
2361  // If the qualifiers are different, the types aren't compatible
2362  if (LHSCan.getCVRQualifiers() != RHSCan.getCVRQualifiers() ||
2363      LHSCan.getAddressSpace() != RHSCan.getAddressSpace())
2364    return QualType();
2365
2366  Type::TypeClass LHSClass = LHSCan->getTypeClass();
2367  Type::TypeClass RHSClass = RHSCan->getTypeClass();
2368
2369  // We want to consider the two function types to be the same for these
2370  // comparisons, just force one to the other.
2371  if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
2372  if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
2373
2374  // Same as above for arrays
2375  if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
2376    LHSClass = Type::ConstantArray;
2377  if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
2378    RHSClass = Type::ConstantArray;
2379
2380  // Canonicalize ExtVector -> Vector.
2381  if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
2382  if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
2383
2384  // Consider qualified interfaces and interfaces the same.
2385  if (LHSClass == Type::ObjCQualifiedInterface) LHSClass = Type::ObjCInterface;
2386  if (RHSClass == Type::ObjCQualifiedInterface) RHSClass = Type::ObjCInterface;
2387
2388  // If the canonical type classes don't match.
2389  if (LHSClass != RHSClass) {
2390    // ID is compatible with all qualified id types.
2391    if (LHS->isObjCQualifiedIdType()) {
2392      if (const PointerType *PT = RHS->getAsPointerType()) {
2393        QualType pType = PT->getPointeeType();
2394        if (isObjCIdType(pType))
2395          return LHS;
2396        // FIXME: need to use ObjCQualifiedIdTypesAreCompatible(LHS, RHS, true).
2397        // Unfortunately, this API is part of Sema (which we don't have access
2398        // to. Need to refactor. The following check is insufficient, since we
2399        // need to make sure the class implements the protocol.
2400        if (pType->isObjCInterfaceType())
2401          return LHS;
2402      }
2403    }
2404    if (RHS->isObjCQualifiedIdType()) {
2405      if (const PointerType *PT = LHS->getAsPointerType()) {
2406        QualType pType = PT->getPointeeType();
2407        if (isObjCIdType(pType))
2408          return RHS;
2409        // FIXME: need to use ObjCQualifiedIdTypesAreCompatible(LHS, RHS, true).
2410        // Unfortunately, this API is part of Sema (which we don't have access
2411        // to. Need to refactor. The following check is insufficient, since we
2412        // need to make sure the class implements the protocol.
2413        if (pType->isObjCInterfaceType())
2414          return RHS;
2415      }
2416    }
2417    // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
2418    // a signed integer type, or an unsigned integer type.
2419    if (const EnumType* ETy = LHS->getAsEnumType()) {
2420      if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
2421        return RHS;
2422    }
2423    if (const EnumType* ETy = RHS->getAsEnumType()) {
2424      if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
2425        return LHS;
2426    }
2427
2428    return QualType();
2429  }
2430
2431  // The canonical type classes match.
2432  switch (LHSClass) {
2433  case Type::Pointer:
2434  {
2435    // Merge two pointer types, while trying to preserve typedef info
2436    QualType LHSPointee = LHS->getAsPointerType()->getPointeeType();
2437    QualType RHSPointee = RHS->getAsPointerType()->getPointeeType();
2438    QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
2439    if (ResultType.isNull()) return QualType();
2440    if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
2441      return LHS;
2442    if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
2443      return RHS;
2444    return getPointerType(ResultType);
2445  }
2446  case Type::BlockPointer:
2447  {
2448    // Merge two block pointer types, while trying to preserve typedef info
2449    QualType LHSPointee = LHS->getAsBlockPointerType()->getPointeeType();
2450    QualType RHSPointee = RHS->getAsBlockPointerType()->getPointeeType();
2451    QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
2452    if (ResultType.isNull()) return QualType();
2453    if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
2454      return LHS;
2455    if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
2456      return RHS;
2457    return getBlockPointerType(ResultType);
2458  }
2459  case Type::ConstantArray:
2460  {
2461    const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
2462    const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
2463    if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
2464      return QualType();
2465
2466    QualType LHSElem = getAsArrayType(LHS)->getElementType();
2467    QualType RHSElem = getAsArrayType(RHS)->getElementType();
2468    QualType ResultType = mergeTypes(LHSElem, RHSElem);
2469    if (ResultType.isNull()) return QualType();
2470    if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
2471      return LHS;
2472    if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
2473      return RHS;
2474    if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
2475                                          ArrayType::ArraySizeModifier(), 0);
2476    if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
2477                                          ArrayType::ArraySizeModifier(), 0);
2478    const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
2479    const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
2480    if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
2481      return LHS;
2482    if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
2483      return RHS;
2484    if (LVAT) {
2485      // FIXME: This isn't correct! But tricky to implement because
2486      // the array's size has to be the size of LHS, but the type
2487      // has to be different.
2488      return LHS;
2489    }
2490    if (RVAT) {
2491      // FIXME: This isn't correct! But tricky to implement because
2492      // the array's size has to be the size of RHS, but the type
2493      // has to be different.
2494      return RHS;
2495    }
2496    if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
2497    if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
2498    return getIncompleteArrayType(ResultType, ArrayType::ArraySizeModifier(),0);
2499  }
2500  case Type::FunctionNoProto:
2501    return mergeFunctionTypes(LHS, RHS);
2502  case Type::Tagged:
2503    // FIXME: Why are these compatible?
2504    if (isObjCIdType(LHS) && isObjCClassType(RHS)) return LHS;
2505    if (isObjCClassType(LHS) && isObjCIdType(RHS)) return LHS;
2506    return QualType();
2507  case Type::Builtin:
2508    // Only exactly equal builtin types are compatible, which is tested above.
2509    return QualType();
2510  case Type::Vector:
2511    if (areCompatVectorTypes(LHS->getAsVectorType(), RHS->getAsVectorType()))
2512      return LHS;
2513    return QualType();
2514  case Type::ObjCInterface:
2515    // Distinct ObjC interfaces are not compatible; see canAssignObjCInterfaces
2516    // for checking assignment/comparison safety
2517    return QualType();
2518  case Type::ObjCQualifiedId:
2519    // Distinct qualified id's are not compatible.
2520    return QualType();
2521  default:
2522    assert(0 && "unexpected type");
2523    return QualType();
2524  }
2525}
2526
2527//===----------------------------------------------------------------------===//
2528//                         Integer Predicates
2529//===----------------------------------------------------------------------===//
2530
2531unsigned ASTContext::getIntWidth(QualType T) {
2532  if (T == BoolTy)
2533    return 1;
2534  // At the moment, only bool has padding bits
2535  return (unsigned)getTypeSize(T);
2536}
2537
2538QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
2539  assert(T->isSignedIntegerType() && "Unexpected type");
2540  if (const EnumType* ETy = T->getAsEnumType())
2541    T = ETy->getDecl()->getIntegerType();
2542  const BuiltinType* BTy = T->getAsBuiltinType();
2543  assert (BTy && "Unexpected signed integer type");
2544  switch (BTy->getKind()) {
2545  case BuiltinType::Char_S:
2546  case BuiltinType::SChar:
2547    return UnsignedCharTy;
2548  case BuiltinType::Short:
2549    return UnsignedShortTy;
2550  case BuiltinType::Int:
2551    return UnsignedIntTy;
2552  case BuiltinType::Long:
2553    return UnsignedLongTy;
2554  case BuiltinType::LongLong:
2555    return UnsignedLongLongTy;
2556  default:
2557    assert(0 && "Unexpected signed integer type");
2558    return QualType();
2559  }
2560}
2561
2562
2563//===----------------------------------------------------------------------===//
2564//                         Serialization Support
2565//===----------------------------------------------------------------------===//
2566
2567/// Emit - Serialize an ASTContext object to Bitcode.
2568void ASTContext::Emit(llvm::Serializer& S) const {
2569  S.Emit(LangOpts);
2570  S.EmitRef(SourceMgr);
2571  S.EmitRef(Target);
2572  S.EmitRef(Idents);
2573  S.EmitRef(Selectors);
2574
2575  // Emit the size of the type vector so that we can reserve that size
2576  // when we reconstitute the ASTContext object.
2577  S.EmitInt(Types.size());
2578
2579  for (std::vector<Type*>::const_iterator I=Types.begin(), E=Types.end();
2580                                          I!=E;++I)
2581    (*I)->Emit(S);
2582
2583  S.EmitOwnedPtr(TUDecl);
2584
2585  // FIXME: S.EmitOwnedPtr(CFConstantStringTypeDecl);
2586}
2587
2588ASTContext* ASTContext::Create(llvm::Deserializer& D) {
2589
2590  // Read the language options.
2591  LangOptions LOpts;
2592  LOpts.Read(D);
2593
2594  SourceManager &SM = D.ReadRef<SourceManager>();
2595  TargetInfo &t = D.ReadRef<TargetInfo>();
2596  IdentifierTable &idents = D.ReadRef<IdentifierTable>();
2597  SelectorTable &sels = D.ReadRef<SelectorTable>();
2598
2599  unsigned size_reserve = D.ReadInt();
2600
2601  ASTContext* A = new ASTContext(LOpts, SM, t, idents, sels,
2602                                 size_reserve);
2603
2604  for (unsigned i = 0; i < size_reserve; ++i)
2605    Type::Create(*A,i,D);
2606
2607  A->TUDecl = cast<TranslationUnitDecl>(D.ReadOwnedPtr<Decl>(*A));
2608
2609  // FIXME: A->CFConstantStringTypeDecl = D.ReadOwnedPtr<RecordDecl>();
2610
2611  return A;
2612}
2613