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