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