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