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