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