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 "CXXABI.h"
16 #include "clang/AST/ASTMutationListener.h"
17 #include "clang/AST/Attr.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/Comment.h"
20 #include "clang/AST/CommentCommandTraits.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclTemplate.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/ExternalASTSource.h"
27 #include "clang/AST/Mangle.h"
28 #include "clang/AST/MangleNumberingContext.h"
29 #include "clang/AST/RecordLayout.h"
30 #include "clang/AST/RecursiveASTVisitor.h"
31 #include "clang/AST/TypeLoc.h"
32 #include "clang/Basic/Builtins.h"
33 #include "clang/Basic/SourceManager.h"
34 #include "clang/Basic/TargetInfo.h"
35 #include "llvm/ADT/SmallString.h"
36 #include "llvm/ADT/StringExtras.h"
37 #include "llvm/ADT/Triple.h"
38 #include "llvm/Support/Capacity.h"
39 #include "llvm/Support/MathExtras.h"
40 #include "llvm/Support/raw_ostream.h"
41 #include <map>
42 
43 using namespace clang;
44 
45 unsigned ASTContext::NumImplicitDefaultConstructors;
46 unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
47 unsigned ASTContext::NumImplicitCopyConstructors;
48 unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
49 unsigned ASTContext::NumImplicitMoveConstructors;
50 unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
51 unsigned ASTContext::NumImplicitCopyAssignmentOperators;
52 unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
53 unsigned ASTContext::NumImplicitMoveAssignmentOperators;
54 unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
55 unsigned ASTContext::NumImplicitDestructors;
56 unsigned ASTContext::NumImplicitDestructorsDeclared;
57 
58 enum FloatingRank {
59   HalfRank, FloatRank, DoubleRank, LongDoubleRank
60 };
61 
62 RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
63   if (!CommentsLoaded && ExternalSource) {
64     ExternalSource->ReadComments();
65     CommentsLoaded = true;
66   }
67 
68   assert(D);
69 
70   // User can not attach documentation to implicit declarations.
71   if (D->isImplicit())
72     return NULL;
73 
74   // User can not attach documentation to implicit instantiations.
75   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
76     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
77       return NULL;
78   }
79 
80   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
81     if (VD->isStaticDataMember() &&
82         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
83       return NULL;
84   }
85 
86   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
87     if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
88       return NULL;
89   }
90 
91   if (const ClassTemplateSpecializationDecl *CTSD =
92           dyn_cast<ClassTemplateSpecializationDecl>(D)) {
93     TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
94     if (TSK == TSK_ImplicitInstantiation ||
95         TSK == TSK_Undeclared)
96       return NULL;
97   }
98 
99   if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
100     if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
101       return NULL;
102   }
103   if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
104     // When tag declaration (but not definition!) is part of the
105     // decl-specifier-seq of some other declaration, it doesn't get comment
106     if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
107       return NULL;
108   }
109   // TODO: handle comments for function parameters properly.
110   if (isa<ParmVarDecl>(D))
111     return NULL;
112 
113   // TODO: we could look up template parameter documentation in the template
114   // documentation.
115   if (isa<TemplateTypeParmDecl>(D) ||
116       isa<NonTypeTemplateParmDecl>(D) ||
117       isa<TemplateTemplateParmDecl>(D))
118     return NULL;
119 
120   ArrayRef<RawComment *> RawComments = Comments.getComments();
121 
122   // If there are no comments anywhere, we won't find anything.
123   if (RawComments.empty())
124     return NULL;
125 
126   // Find declaration location.
127   // For Objective-C declarations we generally don't expect to have multiple
128   // declarators, thus use declaration starting location as the "declaration
129   // location".
130   // For all other declarations multiple declarators are used quite frequently,
131   // so we use the location of the identifier as the "declaration location".
132   SourceLocation DeclLoc;
133   if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
134       isa<ObjCPropertyDecl>(D) ||
135       isa<RedeclarableTemplateDecl>(D) ||
136       isa<ClassTemplateSpecializationDecl>(D))
137     DeclLoc = D->getLocStart();
138   else {
139     DeclLoc = D->getLocation();
140     // If location of the typedef name is in a macro, it is because being
141     // declared via a macro. Try using declaration's starting location
142     // as the "declaration location".
143     if (DeclLoc.isMacroID() && isa<TypedefDecl>(D))
144       DeclLoc = D->getLocStart();
145   }
146 
147   // If the declaration doesn't map directly to a location in a file, we
148   // can't find the comment.
149   if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
150     return NULL;
151 
152   // Find the comment that occurs just after this declaration.
153   ArrayRef<RawComment *>::iterator Comment;
154   {
155     // When searching for comments during parsing, the comment we are looking
156     // for is usually among the last two comments we parsed -- check them
157     // first.
158     RawComment CommentAtDeclLoc(
159         SourceMgr, SourceRange(DeclLoc), false,
160         LangOpts.CommentOpts.ParseAllComments);
161     BeforeThanCompare<RawComment> Compare(SourceMgr);
162     ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
163     bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
164     if (!Found && RawComments.size() >= 2) {
165       MaybeBeforeDecl--;
166       Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
167     }
168 
169     if (Found) {
170       Comment = MaybeBeforeDecl + 1;
171       assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
172                                          &CommentAtDeclLoc, Compare));
173     } else {
174       // Slow path.
175       Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
176                                  &CommentAtDeclLoc, Compare);
177     }
178   }
179 
180   // Decompose the location for the declaration and find the beginning of the
181   // file buffer.
182   std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
183 
184   // First check whether we have a trailing comment.
185   if (Comment != RawComments.end() &&
186       (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
187       (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
188        isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
189     std::pair<FileID, unsigned> CommentBeginDecomp
190       = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
191     // Check that Doxygen trailing comment comes after the declaration, starts
192     // on the same line and in the same file as the declaration.
193     if (DeclLocDecomp.first == CommentBeginDecomp.first &&
194         SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
195           == SourceMgr.getLineNumber(CommentBeginDecomp.first,
196                                      CommentBeginDecomp.second)) {
197       return *Comment;
198     }
199   }
200 
201   // The comment just after the declaration was not a trailing comment.
202   // Let's look at the previous comment.
203   if (Comment == RawComments.begin())
204     return NULL;
205   --Comment;
206 
207   // Check that we actually have a non-member Doxygen comment.
208   if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
209     return NULL;
210 
211   // Decompose the end of the comment.
212   std::pair<FileID, unsigned> CommentEndDecomp
213     = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
214 
215   // If the comment and the declaration aren't in the same file, then they
216   // aren't related.
217   if (DeclLocDecomp.first != CommentEndDecomp.first)
218     return NULL;
219 
220   // Get the corresponding buffer.
221   bool Invalid = false;
222   const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
223                                                &Invalid).data();
224   if (Invalid)
225     return NULL;
226 
227   // Extract text between the comment and declaration.
228   StringRef Text(Buffer + CommentEndDecomp.second,
229                  DeclLocDecomp.second - CommentEndDecomp.second);
230 
231   // There should be no other declarations or preprocessor directives between
232   // comment and declaration.
233   if (Text.find_first_of(";{}#@") != StringRef::npos)
234     return NULL;
235 
236   return *Comment;
237 }
238 
239 namespace {
240 /// If we have a 'templated' declaration for a template, adjust 'D' to
241 /// refer to the actual template.
242 /// If we have an implicit instantiation, adjust 'D' to refer to template.
243 const Decl *adjustDeclToTemplate(const Decl *D) {
244   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
245     // Is this function declaration part of a function template?
246     if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
247       return FTD;
248 
249     // Nothing to do if function is not an implicit instantiation.
250     if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
251       return D;
252 
253     // Function is an implicit instantiation of a function template?
254     if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
255       return FTD;
256 
257     // Function is instantiated from a member definition of a class template?
258     if (const FunctionDecl *MemberDecl =
259             FD->getInstantiatedFromMemberFunction())
260       return MemberDecl;
261 
262     return D;
263   }
264   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
265     // Static data member is instantiated from a member definition of a class
266     // template?
267     if (VD->isStaticDataMember())
268       if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
269         return MemberDecl;
270 
271     return D;
272   }
273   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
274     // Is this class declaration part of a class template?
275     if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
276       return CTD;
277 
278     // Class is an implicit instantiation of a class template or partial
279     // specialization?
280     if (const ClassTemplateSpecializationDecl *CTSD =
281             dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
282       if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
283         return D;
284       llvm::PointerUnion<ClassTemplateDecl *,
285                          ClassTemplatePartialSpecializationDecl *>
286           PU = CTSD->getSpecializedTemplateOrPartial();
287       return PU.is<ClassTemplateDecl*>() ?
288           static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
289           static_cast<const Decl*>(
290               PU.get<ClassTemplatePartialSpecializationDecl *>());
291     }
292 
293     // Class is instantiated from a member definition of a class template?
294     if (const MemberSpecializationInfo *Info =
295                    CRD->getMemberSpecializationInfo())
296       return Info->getInstantiatedFrom();
297 
298     return D;
299   }
300   if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
301     // Enum is instantiated from a member definition of a class template?
302     if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
303       return MemberDecl;
304 
305     return D;
306   }
307   // FIXME: Adjust alias templates?
308   return D;
309 }
310 } // unnamed namespace
311 
312 const RawComment *ASTContext::getRawCommentForAnyRedecl(
313                                                 const Decl *D,
314                                                 const Decl **OriginalDecl) const {
315   D = adjustDeclToTemplate(D);
316 
317   // Check whether we have cached a comment for this declaration already.
318   {
319     llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
320         RedeclComments.find(D);
321     if (Pos != RedeclComments.end()) {
322       const RawCommentAndCacheFlags &Raw = Pos->second;
323       if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
324         if (OriginalDecl)
325           *OriginalDecl = Raw.getOriginalDecl();
326         return Raw.getRaw();
327       }
328     }
329   }
330 
331   // Search for comments attached to declarations in the redeclaration chain.
332   const RawComment *RC = NULL;
333   const Decl *OriginalDeclForRC = NULL;
334   for (Decl::redecl_iterator I = D->redecls_begin(),
335                              E = D->redecls_end();
336        I != E; ++I) {
337     llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
338         RedeclComments.find(*I);
339     if (Pos != RedeclComments.end()) {
340       const RawCommentAndCacheFlags &Raw = Pos->second;
341       if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
342         RC = Raw.getRaw();
343         OriginalDeclForRC = Raw.getOriginalDecl();
344         break;
345       }
346     } else {
347       RC = getRawCommentForDeclNoCache(*I);
348       OriginalDeclForRC = *I;
349       RawCommentAndCacheFlags Raw;
350       if (RC) {
351         Raw.setRaw(RC);
352         Raw.setKind(RawCommentAndCacheFlags::FromDecl);
353       } else
354         Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
355       Raw.setOriginalDecl(*I);
356       RedeclComments[*I] = Raw;
357       if (RC)
358         break;
359     }
360   }
361 
362   // If we found a comment, it should be a documentation comment.
363   assert(!RC || RC->isDocumentation());
364 
365   if (OriginalDecl)
366     *OriginalDecl = OriginalDeclForRC;
367 
368   // Update cache for every declaration in the redeclaration chain.
369   RawCommentAndCacheFlags Raw;
370   Raw.setRaw(RC);
371   Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
372   Raw.setOriginalDecl(OriginalDeclForRC);
373 
374   for (Decl::redecl_iterator I = D->redecls_begin(),
375                              E = D->redecls_end();
376        I != E; ++I) {
377     RawCommentAndCacheFlags &R = RedeclComments[*I];
378     if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
379       R = Raw;
380   }
381 
382   return RC;
383 }
384 
385 static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
386                    SmallVectorImpl<const NamedDecl *> &Redeclared) {
387   const DeclContext *DC = ObjCMethod->getDeclContext();
388   if (const ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(DC)) {
389     const ObjCInterfaceDecl *ID = IMD->getClassInterface();
390     if (!ID)
391       return;
392     // Add redeclared method here.
393     for (ObjCInterfaceDecl::known_extensions_iterator
394            Ext = ID->known_extensions_begin(),
395            ExtEnd = ID->known_extensions_end();
396          Ext != ExtEnd; ++Ext) {
397       if (ObjCMethodDecl *RedeclaredMethod =
398             Ext->getMethod(ObjCMethod->getSelector(),
399                                   ObjCMethod->isInstanceMethod()))
400         Redeclared.push_back(RedeclaredMethod);
401     }
402   }
403 }
404 
405 comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
406                                                     const Decl *D) const {
407   comments::DeclInfo *ThisDeclInfo = new (*this) comments::DeclInfo;
408   ThisDeclInfo->CommentDecl = D;
409   ThisDeclInfo->IsFilled = false;
410   ThisDeclInfo->fill();
411   ThisDeclInfo->CommentDecl = FC->getDecl();
412   comments::FullComment *CFC =
413     new (*this) comments::FullComment(FC->getBlocks(),
414                                       ThisDeclInfo);
415   return CFC;
416 
417 }
418 
419 comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
420   const RawComment *RC = getRawCommentForDeclNoCache(D);
421   return RC ? RC->parse(*this, 0, D) : 0;
422 }
423 
424 comments::FullComment *ASTContext::getCommentForDecl(
425                                               const Decl *D,
426                                               const Preprocessor *PP) const {
427   if (D->isInvalidDecl())
428     return NULL;
429   D = adjustDeclToTemplate(D);
430 
431   const Decl *Canonical = D->getCanonicalDecl();
432   llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
433       ParsedComments.find(Canonical);
434 
435   if (Pos != ParsedComments.end()) {
436     if (Canonical != D) {
437       comments::FullComment *FC = Pos->second;
438       comments::FullComment *CFC = cloneFullComment(FC, D);
439       return CFC;
440     }
441     return Pos->second;
442   }
443 
444   const Decl *OriginalDecl;
445 
446   const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
447   if (!RC) {
448     if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
449       SmallVector<const NamedDecl*, 8> Overridden;
450       const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D);
451       if (OMD && OMD->isPropertyAccessor())
452         if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
453           if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
454             return cloneFullComment(FC, D);
455       if (OMD)
456         addRedeclaredMethods(OMD, Overridden);
457       getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
458       for (unsigned i = 0, e = Overridden.size(); i < e; i++)
459         if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
460           return cloneFullComment(FC, D);
461     }
462     else if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
463       // Attach any tag type's documentation to its typedef if latter
464       // does not have one of its own.
465       QualType QT = TD->getUnderlyingType();
466       if (const TagType *TT = QT->getAs<TagType>())
467         if (const Decl *TD = TT->getDecl())
468           if (comments::FullComment *FC = getCommentForDecl(TD, PP))
469             return cloneFullComment(FC, D);
470     }
471     else if (const ObjCInterfaceDecl *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
472       while (IC->getSuperClass()) {
473         IC = IC->getSuperClass();
474         if (comments::FullComment *FC = getCommentForDecl(IC, PP))
475           return cloneFullComment(FC, D);
476       }
477     }
478     else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
479       if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
480         if (comments::FullComment *FC = getCommentForDecl(IC, PP))
481           return cloneFullComment(FC, D);
482     }
483     else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
484       if (!(RD = RD->getDefinition()))
485         return NULL;
486       // Check non-virtual bases.
487       for (CXXRecordDecl::base_class_const_iterator I =
488            RD->bases_begin(), E = RD->bases_end(); I != E; ++I) {
489         if (I->isVirtual() || (I->getAccessSpecifier() != AS_public))
490           continue;
491         QualType Ty = I->getType();
492         if (Ty.isNull())
493           continue;
494         if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
495           if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
496             continue;
497 
498           if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
499             return cloneFullComment(FC, D);
500         }
501       }
502       // Check virtual bases.
503       for (CXXRecordDecl::base_class_const_iterator I =
504            RD->vbases_begin(), E = RD->vbases_end(); I != E; ++I) {
505         if (I->getAccessSpecifier() != AS_public)
506           continue;
507         QualType Ty = I->getType();
508         if (Ty.isNull())
509           continue;
510         if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
511           if (!(VirtualBase= VirtualBase->getDefinition()))
512             continue;
513           if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
514             return cloneFullComment(FC, D);
515         }
516       }
517     }
518     return NULL;
519   }
520 
521   // If the RawComment was attached to other redeclaration of this Decl, we
522   // should parse the comment in context of that other Decl.  This is important
523   // because comments can contain references to parameter names which can be
524   // different across redeclarations.
525   if (D != OriginalDecl)
526     return getCommentForDecl(OriginalDecl, PP);
527 
528   comments::FullComment *FC = RC->parse(*this, PP, D);
529   ParsedComments[Canonical] = FC;
530   return FC;
531 }
532 
533 void
534 ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
535                                                TemplateTemplateParmDecl *Parm) {
536   ID.AddInteger(Parm->getDepth());
537   ID.AddInteger(Parm->getPosition());
538   ID.AddBoolean(Parm->isParameterPack());
539 
540   TemplateParameterList *Params = Parm->getTemplateParameters();
541   ID.AddInteger(Params->size());
542   for (TemplateParameterList::const_iterator P = Params->begin(),
543                                           PEnd = Params->end();
544        P != PEnd; ++P) {
545     if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
546       ID.AddInteger(0);
547       ID.AddBoolean(TTP->isParameterPack());
548       continue;
549     }
550 
551     if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
552       ID.AddInteger(1);
553       ID.AddBoolean(NTTP->isParameterPack());
554       ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
555       if (NTTP->isExpandedParameterPack()) {
556         ID.AddBoolean(true);
557         ID.AddInteger(NTTP->getNumExpansionTypes());
558         for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
559           QualType T = NTTP->getExpansionType(I);
560           ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
561         }
562       } else
563         ID.AddBoolean(false);
564       continue;
565     }
566 
567     TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
568     ID.AddInteger(2);
569     Profile(ID, TTP);
570   }
571 }
572 
573 TemplateTemplateParmDecl *
574 ASTContext::getCanonicalTemplateTemplateParmDecl(
575                                           TemplateTemplateParmDecl *TTP) const {
576   // Check if we already have a canonical template template parameter.
577   llvm::FoldingSetNodeID ID;
578   CanonicalTemplateTemplateParm::Profile(ID, TTP);
579   void *InsertPos = 0;
580   CanonicalTemplateTemplateParm *Canonical
581     = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
582   if (Canonical)
583     return Canonical->getParam();
584 
585   // Build a canonical template parameter list.
586   TemplateParameterList *Params = TTP->getTemplateParameters();
587   SmallVector<NamedDecl *, 4> CanonParams;
588   CanonParams.reserve(Params->size());
589   for (TemplateParameterList::const_iterator P = Params->begin(),
590                                           PEnd = Params->end();
591        P != PEnd; ++P) {
592     if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
593       CanonParams.push_back(
594                   TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
595                                                SourceLocation(),
596                                                SourceLocation(),
597                                                TTP->getDepth(),
598                                                TTP->getIndex(), 0, false,
599                                                TTP->isParameterPack()));
600     else if (NonTypeTemplateParmDecl *NTTP
601              = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
602       QualType T = getCanonicalType(NTTP->getType());
603       TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
604       NonTypeTemplateParmDecl *Param;
605       if (NTTP->isExpandedParameterPack()) {
606         SmallVector<QualType, 2> ExpandedTypes;
607         SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
608         for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
609           ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
610           ExpandedTInfos.push_back(
611                                 getTrivialTypeSourceInfo(ExpandedTypes.back()));
612         }
613 
614         Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
615                                                 SourceLocation(),
616                                                 SourceLocation(),
617                                                 NTTP->getDepth(),
618                                                 NTTP->getPosition(), 0,
619                                                 T,
620                                                 TInfo,
621                                                 ExpandedTypes.data(),
622                                                 ExpandedTypes.size(),
623                                                 ExpandedTInfos.data());
624       } else {
625         Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
626                                                 SourceLocation(),
627                                                 SourceLocation(),
628                                                 NTTP->getDepth(),
629                                                 NTTP->getPosition(), 0,
630                                                 T,
631                                                 NTTP->isParameterPack(),
632                                                 TInfo);
633       }
634       CanonParams.push_back(Param);
635 
636     } else
637       CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
638                                            cast<TemplateTemplateParmDecl>(*P)));
639   }
640 
641   TemplateTemplateParmDecl *CanonTTP
642     = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
643                                        SourceLocation(), TTP->getDepth(),
644                                        TTP->getPosition(),
645                                        TTP->isParameterPack(),
646                                        0,
647                          TemplateParameterList::Create(*this, SourceLocation(),
648                                                        SourceLocation(),
649                                                        CanonParams.data(),
650                                                        CanonParams.size(),
651                                                        SourceLocation()));
652 
653   // Get the new insert position for the node we care about.
654   Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
655   assert(Canonical == 0 && "Shouldn't be in the map!");
656   (void)Canonical;
657 
658   // Create the canonical template template parameter entry.
659   Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
660   CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
661   return CanonTTP;
662 }
663 
664 CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
665   if (!LangOpts.CPlusPlus) return 0;
666 
667   switch (T.getCXXABI().getKind()) {
668   case TargetCXXABI::GenericARM:
669   case TargetCXXABI::iOS:
670     return CreateARMCXXABI(*this);
671   case TargetCXXABI::GenericAArch64: // Same as Itanium at this level
672   case TargetCXXABI::GenericItanium:
673     return CreateItaniumCXXABI(*this);
674   case TargetCXXABI::Microsoft:
675     return CreateMicrosoftCXXABI(*this);
676   }
677   llvm_unreachable("Invalid CXXABI type!");
678 }
679 
680 static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
681                                              const LangOptions &LOpts) {
682   if (LOpts.FakeAddressSpaceMap) {
683     // The fake address space map must have a distinct entry for each
684     // language-specific address space.
685     static const unsigned FakeAddrSpaceMap[] = {
686       1, // opencl_global
687       2, // opencl_local
688       3, // opencl_constant
689       4, // cuda_device
690       5, // cuda_constant
691       6  // cuda_shared
692     };
693     return &FakeAddrSpaceMap;
694   } else {
695     return &T.getAddressSpaceMap();
696   }
697 }
698 
699 static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
700                                           const LangOptions &LangOpts) {
701   switch (LangOpts.getAddressSpaceMapMangling()) {
702   case LangOptions::ASMM_Target:
703     return TI.useAddressSpaceMapMangling();
704   case LangOptions::ASMM_On:
705     return true;
706   case LangOptions::ASMM_Off:
707     return false;
708   }
709   llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
710 }
711 
712 ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
713                        const TargetInfo *t,
714                        IdentifierTable &idents, SelectorTable &sels,
715                        Builtin::Context &builtins,
716                        unsigned size_reserve,
717                        bool DelayInitialization)
718   : FunctionProtoTypes(this_()),
719     TemplateSpecializationTypes(this_()),
720     DependentTemplateSpecializationTypes(this_()),
721     SubstTemplateTemplateParmPacks(this_()),
722     GlobalNestedNameSpecifier(0),
723     Int128Decl(0), UInt128Decl(0), Float128StubDecl(0),
724     BuiltinVaListDecl(0),
725     ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
726     BOOLDecl(0),
727     CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
728     FILEDecl(0),
729     jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
730     BlockDescriptorType(0), BlockDescriptorExtendedType(0),
731     cudaConfigureCallDecl(0),
732     NullTypeSourceInfo(QualType()),
733     FirstLocalImport(), LastLocalImport(),
734     SourceMgr(SM), LangOpts(LOpts),
735     AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
736     Idents(idents), Selectors(sels),
737     BuiltinInfo(builtins),
738     DeclarationNames(*this),
739     ExternalSource(0), Listener(0),
740     Comments(SM), CommentsLoaded(false),
741     CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
742     LastSDM(0, 0)
743 {
744   if (size_reserve > 0) Types.reserve(size_reserve);
745   TUDecl = TranslationUnitDecl::Create(*this);
746 
747   if (!DelayInitialization) {
748     assert(t && "No target supplied for ASTContext initialization");
749     InitBuiltinTypes(*t);
750   }
751 }
752 
753 ASTContext::~ASTContext() {
754   // Release the DenseMaps associated with DeclContext objects.
755   // FIXME: Is this the ideal solution?
756   ReleaseDeclContextMaps();
757 
758   // Call all of the deallocation functions on all of their targets.
759   for (DeallocationMap::const_iterator I = Deallocations.begin(),
760            E = Deallocations.end(); I != E; ++I)
761     for (unsigned J = 0, N = I->second.size(); J != N; ++J)
762       (I->first)((I->second)[J]);
763 
764   // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
765   // because they can contain DenseMaps.
766   for (llvm::DenseMap<const ObjCContainerDecl*,
767        const ASTRecordLayout*>::iterator
768        I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
769     // Increment in loop to prevent using deallocated memory.
770     if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
771       R->Destroy(*this);
772 
773   for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
774        I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
775     // Increment in loop to prevent using deallocated memory.
776     if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
777       R->Destroy(*this);
778   }
779 
780   for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
781                                                     AEnd = DeclAttrs.end();
782        A != AEnd; ++A)
783     A->second->~AttrVec();
784 
785   for (llvm::DenseMap<const DeclContext *, MangleNumberingContext *>::iterator
786            I = MangleNumberingContexts.begin(),
787            E = MangleNumberingContexts.end();
788        I != E; ++I)
789     delete I->second;
790 }
791 
792 void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
793   Deallocations[Callback].push_back(Data);
794 }
795 
796 void
797 ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
798   ExternalSource.reset(Source.take());
799 }
800 
801 void ASTContext::PrintStats() const {
802   llvm::errs() << "\n*** AST Context Stats:\n";
803   llvm::errs() << "  " << Types.size() << " types total.\n";
804 
805   unsigned counts[] = {
806 #define TYPE(Name, Parent) 0,
807 #define ABSTRACT_TYPE(Name, Parent)
808 #include "clang/AST/TypeNodes.def"
809     0 // Extra
810   };
811 
812   for (unsigned i = 0, e = Types.size(); i != e; ++i) {
813     Type *T = Types[i];
814     counts[(unsigned)T->getTypeClass()]++;
815   }
816 
817   unsigned Idx = 0;
818   unsigned TotalBytes = 0;
819 #define TYPE(Name, Parent)                                              \
820   if (counts[Idx])                                                      \
821     llvm::errs() << "    " << counts[Idx] << " " << #Name               \
822                  << " types\n";                                         \
823   TotalBytes += counts[Idx] * sizeof(Name##Type);                       \
824   ++Idx;
825 #define ABSTRACT_TYPE(Name, Parent)
826 #include "clang/AST/TypeNodes.def"
827 
828   llvm::errs() << "Total bytes = " << TotalBytes << "\n";
829 
830   // Implicit special member functions.
831   llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
832                << NumImplicitDefaultConstructors
833                << " implicit default constructors created\n";
834   llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
835                << NumImplicitCopyConstructors
836                << " implicit copy constructors created\n";
837   if (getLangOpts().CPlusPlus)
838     llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
839                  << NumImplicitMoveConstructors
840                  << " implicit move constructors created\n";
841   llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
842                << NumImplicitCopyAssignmentOperators
843                << " implicit copy assignment operators created\n";
844   if (getLangOpts().CPlusPlus)
845     llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
846                  << NumImplicitMoveAssignmentOperators
847                  << " implicit move assignment operators created\n";
848   llvm::errs() << NumImplicitDestructorsDeclared << "/"
849                << NumImplicitDestructors
850                << " implicit destructors created\n";
851 
852   if (ExternalSource.get()) {
853     llvm::errs() << "\n";
854     ExternalSource->PrintStats();
855   }
856 
857   BumpAlloc.PrintStats();
858 }
859 
860 RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
861                                             RecordDecl::TagKind TK) const {
862   SourceLocation Loc;
863   RecordDecl *NewDecl;
864   if (getLangOpts().CPlusPlus)
865     NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
866                                     Loc, &Idents.get(Name));
867   else
868     NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
869                                  &Idents.get(Name));
870   NewDecl->setImplicit();
871   return NewDecl;
872 }
873 
874 TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
875                                               StringRef Name) const {
876   TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
877   TypedefDecl *NewDecl = TypedefDecl::Create(
878       const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
879       SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
880   NewDecl->setImplicit();
881   return NewDecl;
882 }
883 
884 TypedefDecl *ASTContext::getInt128Decl() const {
885   if (!Int128Decl)
886     Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
887   return Int128Decl;
888 }
889 
890 TypedefDecl *ASTContext::getUInt128Decl() const {
891   if (!UInt128Decl)
892     UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
893   return UInt128Decl;
894 }
895 
896 TypeDecl *ASTContext::getFloat128StubType() const {
897   assert(LangOpts.CPlusPlus && "should only be called for c++");
898   if (!Float128StubDecl)
899     Float128StubDecl = buildImplicitRecord("__float128");
900 
901   return Float128StubDecl;
902 }
903 
904 void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
905   BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
906   R = CanQualType::CreateUnsafe(QualType(Ty, 0));
907   Types.push_back(Ty);
908 }
909 
910 void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
911   assert((!this->Target || this->Target == &Target) &&
912          "Incorrect target reinitialization");
913   assert(VoidTy.isNull() && "Context reinitialized?");
914 
915   this->Target = &Target;
916 
917   ABI.reset(createCXXABI(Target));
918   AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
919   AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
920 
921   // C99 6.2.5p19.
922   InitBuiltinType(VoidTy,              BuiltinType::Void);
923 
924   // C99 6.2.5p2.
925   InitBuiltinType(BoolTy,              BuiltinType::Bool);
926   // C99 6.2.5p3.
927   if (LangOpts.CharIsSigned)
928     InitBuiltinType(CharTy,            BuiltinType::Char_S);
929   else
930     InitBuiltinType(CharTy,            BuiltinType::Char_U);
931   // C99 6.2.5p4.
932   InitBuiltinType(SignedCharTy,        BuiltinType::SChar);
933   InitBuiltinType(ShortTy,             BuiltinType::Short);
934   InitBuiltinType(IntTy,               BuiltinType::Int);
935   InitBuiltinType(LongTy,              BuiltinType::Long);
936   InitBuiltinType(LongLongTy,          BuiltinType::LongLong);
937 
938   // C99 6.2.5p6.
939   InitBuiltinType(UnsignedCharTy,      BuiltinType::UChar);
940   InitBuiltinType(UnsignedShortTy,     BuiltinType::UShort);
941   InitBuiltinType(UnsignedIntTy,       BuiltinType::UInt);
942   InitBuiltinType(UnsignedLongTy,      BuiltinType::ULong);
943   InitBuiltinType(UnsignedLongLongTy,  BuiltinType::ULongLong);
944 
945   // C99 6.2.5p10.
946   InitBuiltinType(FloatTy,             BuiltinType::Float);
947   InitBuiltinType(DoubleTy,            BuiltinType::Double);
948   InitBuiltinType(LongDoubleTy,        BuiltinType::LongDouble);
949 
950   // GNU extension, 128-bit integers.
951   InitBuiltinType(Int128Ty,            BuiltinType::Int128);
952   InitBuiltinType(UnsignedInt128Ty,    BuiltinType::UInt128);
953 
954   // C++ 3.9.1p5
955   if (TargetInfo::isTypeSigned(Target.getWCharType()))
956     InitBuiltinType(WCharTy,           BuiltinType::WChar_S);
957   else  // -fshort-wchar makes wchar_t be unsigned.
958     InitBuiltinType(WCharTy,           BuiltinType::WChar_U);
959   if (LangOpts.CPlusPlus && LangOpts.WChar)
960     WideCharTy = WCharTy;
961   else {
962     // C99 (or C++ using -fno-wchar).
963     WideCharTy = getFromTargetType(Target.getWCharType());
964   }
965 
966   WIntTy = getFromTargetType(Target.getWIntType());
967 
968   if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
969     InitBuiltinType(Char16Ty,           BuiltinType::Char16);
970   else // C99
971     Char16Ty = getFromTargetType(Target.getChar16Type());
972 
973   if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
974     InitBuiltinType(Char32Ty,           BuiltinType::Char32);
975   else // C99
976     Char32Ty = getFromTargetType(Target.getChar32Type());
977 
978   // Placeholder type for type-dependent expressions whose type is
979   // completely unknown. No code should ever check a type against
980   // DependentTy and users should never see it; however, it is here to
981   // help diagnose failures to properly check for type-dependent
982   // expressions.
983   InitBuiltinType(DependentTy,         BuiltinType::Dependent);
984 
985   // Placeholder type for functions.
986   InitBuiltinType(OverloadTy,          BuiltinType::Overload);
987 
988   // Placeholder type for bound members.
989   InitBuiltinType(BoundMemberTy,       BuiltinType::BoundMember);
990 
991   // Placeholder type for pseudo-objects.
992   InitBuiltinType(PseudoObjectTy,      BuiltinType::PseudoObject);
993 
994   // "any" type; useful for debugger-like clients.
995   InitBuiltinType(UnknownAnyTy,        BuiltinType::UnknownAny);
996 
997   // Placeholder type for unbridged ARC casts.
998   InitBuiltinType(ARCUnbridgedCastTy,  BuiltinType::ARCUnbridgedCast);
999 
1000   // Placeholder type for builtin functions.
1001   InitBuiltinType(BuiltinFnTy,  BuiltinType::BuiltinFn);
1002 
1003   // C99 6.2.5p11.
1004   FloatComplexTy      = getComplexType(FloatTy);
1005   DoubleComplexTy     = getComplexType(DoubleTy);
1006   LongDoubleComplexTy = getComplexType(LongDoubleTy);
1007 
1008   // Builtin types for 'id', 'Class', and 'SEL'.
1009   InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1010   InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
1011   InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
1012 
1013   if (LangOpts.OpenCL) {
1014     InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
1015     InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
1016     InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
1017     InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
1018     InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
1019     InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
1020 
1021     InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
1022     InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
1023   }
1024 
1025   // Builtin type for __objc_yes and __objc_no
1026   ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1027                        SignedCharTy : BoolTy);
1028 
1029   ObjCConstantStringType = QualType();
1030 
1031   ObjCSuperType = QualType();
1032 
1033   // void * type
1034   VoidPtrTy = getPointerType(VoidTy);
1035 
1036   // nullptr type (C++0x 2.14.7)
1037   InitBuiltinType(NullPtrTy,           BuiltinType::NullPtr);
1038 
1039   // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1040   InitBuiltinType(HalfTy, BuiltinType::Half);
1041 
1042   // Builtin type used to help define __builtin_va_list.
1043   VaListTagTy = QualType();
1044 }
1045 
1046 DiagnosticsEngine &ASTContext::getDiagnostics() const {
1047   return SourceMgr.getDiagnostics();
1048 }
1049 
1050 AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1051   AttrVec *&Result = DeclAttrs[D];
1052   if (!Result) {
1053     void *Mem = Allocate(sizeof(AttrVec));
1054     Result = new (Mem) AttrVec;
1055   }
1056 
1057   return *Result;
1058 }
1059 
1060 /// \brief Erase the attributes corresponding to the given declaration.
1061 void ASTContext::eraseDeclAttrs(const Decl *D) {
1062   llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1063   if (Pos != DeclAttrs.end()) {
1064     Pos->second->~AttrVec();
1065     DeclAttrs.erase(Pos);
1066   }
1067 }
1068 
1069 // FIXME: Remove ?
1070 MemberSpecializationInfo *
1071 ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
1072   assert(Var->isStaticDataMember() && "Not a static data member");
1073   return getTemplateOrSpecializationInfo(Var)
1074       .dyn_cast<MemberSpecializationInfo *>();
1075 }
1076 
1077 ASTContext::TemplateOrSpecializationInfo
1078 ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1079   llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1080       TemplateOrInstantiation.find(Var);
1081   if (Pos == TemplateOrInstantiation.end())
1082     return TemplateOrSpecializationInfo();
1083 
1084   return Pos->second;
1085 }
1086 
1087 void
1088 ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
1089                                                 TemplateSpecializationKind TSK,
1090                                           SourceLocation PointOfInstantiation) {
1091   assert(Inst->isStaticDataMember() && "Not a static data member");
1092   assert(Tmpl->isStaticDataMember() && "Not a static data member");
1093   setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1094                                             Tmpl, TSK, PointOfInstantiation));
1095 }
1096 
1097 void
1098 ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1099                                             TemplateOrSpecializationInfo TSI) {
1100   assert(!TemplateOrInstantiation[Inst] &&
1101          "Already noted what the variable was instantiated from");
1102   TemplateOrInstantiation[Inst] = TSI;
1103 }
1104 
1105 FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1106                                                      const FunctionDecl *FD){
1107   assert(FD && "Specialization is 0");
1108   llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
1109     = ClassScopeSpecializationPattern.find(FD);
1110   if (Pos == ClassScopeSpecializationPattern.end())
1111     return 0;
1112 
1113   return Pos->second;
1114 }
1115 
1116 void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1117                                         FunctionDecl *Pattern) {
1118   assert(FD && "Specialization is 0");
1119   assert(Pattern && "Class scope specialization pattern is 0");
1120   ClassScopeSpecializationPattern[FD] = Pattern;
1121 }
1122 
1123 NamedDecl *
1124 ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
1125   llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
1126     = InstantiatedFromUsingDecl.find(UUD);
1127   if (Pos == InstantiatedFromUsingDecl.end())
1128     return 0;
1129 
1130   return Pos->second;
1131 }
1132 
1133 void
1134 ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1135   assert((isa<UsingDecl>(Pattern) ||
1136           isa<UnresolvedUsingValueDecl>(Pattern) ||
1137           isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1138          "pattern decl is not a using decl");
1139   assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1140   InstantiatedFromUsingDecl[Inst] = Pattern;
1141 }
1142 
1143 UsingShadowDecl *
1144 ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1145   llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1146     = InstantiatedFromUsingShadowDecl.find(Inst);
1147   if (Pos == InstantiatedFromUsingShadowDecl.end())
1148     return 0;
1149 
1150   return Pos->second;
1151 }
1152 
1153 void
1154 ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1155                                                UsingShadowDecl *Pattern) {
1156   assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1157   InstantiatedFromUsingShadowDecl[Inst] = Pattern;
1158 }
1159 
1160 FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1161   llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1162     = InstantiatedFromUnnamedFieldDecl.find(Field);
1163   if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1164     return 0;
1165 
1166   return Pos->second;
1167 }
1168 
1169 void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1170                                                      FieldDecl *Tmpl) {
1171   assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1172   assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1173   assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1174          "Already noted what unnamed field was instantiated from");
1175 
1176   InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1177 }
1178 
1179 ASTContext::overridden_cxx_method_iterator
1180 ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1181   llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
1182     = OverriddenMethods.find(Method->getCanonicalDecl());
1183   if (Pos == OverriddenMethods.end())
1184     return 0;
1185 
1186   return Pos->second.begin();
1187 }
1188 
1189 ASTContext::overridden_cxx_method_iterator
1190 ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1191   llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
1192     = OverriddenMethods.find(Method->getCanonicalDecl());
1193   if (Pos == OverriddenMethods.end())
1194     return 0;
1195 
1196   return Pos->second.end();
1197 }
1198 
1199 unsigned
1200 ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1201   llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
1202     = OverriddenMethods.find(Method->getCanonicalDecl());
1203   if (Pos == OverriddenMethods.end())
1204     return 0;
1205 
1206   return Pos->second.size();
1207 }
1208 
1209 void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1210                                      const CXXMethodDecl *Overridden) {
1211   assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
1212   OverriddenMethods[Method].push_back(Overridden);
1213 }
1214 
1215 void ASTContext::getOverriddenMethods(
1216                       const NamedDecl *D,
1217                       SmallVectorImpl<const NamedDecl *> &Overridden) const {
1218   assert(D);
1219 
1220   if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
1221     Overridden.append(overridden_methods_begin(CXXMethod),
1222                       overridden_methods_end(CXXMethod));
1223     return;
1224   }
1225 
1226   const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1227   if (!Method)
1228     return;
1229 
1230   SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1231   Method->getOverriddenMethods(OverDecls);
1232   Overridden.append(OverDecls.begin(), OverDecls.end());
1233 }
1234 
1235 void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1236   assert(!Import->NextLocalImport && "Import declaration already in the chain");
1237   assert(!Import->isFromASTFile() && "Non-local import declaration");
1238   if (!FirstLocalImport) {
1239     FirstLocalImport = Import;
1240     LastLocalImport = Import;
1241     return;
1242   }
1243 
1244   LastLocalImport->NextLocalImport = Import;
1245   LastLocalImport = Import;
1246 }
1247 
1248 //===----------------------------------------------------------------------===//
1249 //                         Type Sizing and Analysis
1250 //===----------------------------------------------------------------------===//
1251 
1252 /// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1253 /// scalar floating point type.
1254 const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
1255   const BuiltinType *BT = T->getAs<BuiltinType>();
1256   assert(BT && "Not a floating point type!");
1257   switch (BT->getKind()) {
1258   default: llvm_unreachable("Not a floating point type!");
1259   case BuiltinType::Half:       return Target->getHalfFormat();
1260   case BuiltinType::Float:      return Target->getFloatFormat();
1261   case BuiltinType::Double:     return Target->getDoubleFormat();
1262   case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
1263   }
1264 }
1265 
1266 CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
1267   unsigned Align = Target->getCharWidth();
1268 
1269   bool UseAlignAttrOnly = false;
1270   if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1271     Align = AlignFromAttr;
1272 
1273     // __attribute__((aligned)) can increase or decrease alignment
1274     // *except* on a struct or struct member, where it only increases
1275     // alignment unless 'packed' is also specified.
1276     //
1277     // It is an error for alignas to decrease alignment, so we can
1278     // ignore that possibility;  Sema should diagnose it.
1279     if (isa<FieldDecl>(D)) {
1280       UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1281         cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1282     } else {
1283       UseAlignAttrOnly = true;
1284     }
1285   }
1286   else if (isa<FieldDecl>(D))
1287       UseAlignAttrOnly =
1288         D->hasAttr<PackedAttr>() ||
1289         cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1290 
1291   // If we're using the align attribute only, just ignore everything
1292   // else about the declaration and its type.
1293   if (UseAlignAttrOnly) {
1294     // do nothing
1295 
1296   } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
1297     QualType T = VD->getType();
1298     if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
1299       if (ForAlignof)
1300         T = RT->getPointeeType();
1301       else
1302         T = getPointerType(RT->getPointeeType());
1303     }
1304     if (!T->isIncompleteType() && !T->isFunctionType()) {
1305       // Adjust alignments of declarations with array type by the
1306       // large-array alignment on the target.
1307       if (const ArrayType *arrayType = getAsArrayType(T)) {
1308         unsigned MinWidth = Target->getLargeArrayMinWidth();
1309         if (!ForAlignof && MinWidth) {
1310           if (isa<VariableArrayType>(arrayType))
1311             Align = std::max(Align, Target->getLargeArrayAlign());
1312           else if (isa<ConstantArrayType>(arrayType) &&
1313                    MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1314             Align = std::max(Align, Target->getLargeArrayAlign());
1315         }
1316 
1317         // Walk through any array types while we're at it.
1318         T = getBaseElementType(arrayType);
1319       }
1320       Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
1321       if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1322         if (VD->hasGlobalStorage())
1323           Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1324       }
1325     }
1326 
1327     // Fields can be subject to extra alignment constraints, like if
1328     // the field is packed, the struct is packed, or the struct has a
1329     // a max-field-alignment constraint (#pragma pack).  So calculate
1330     // the actual alignment of the field within the struct, and then
1331     // (as we're expected to) constrain that by the alignment of the type.
1332     if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
1333       const RecordDecl *Parent = Field->getParent();
1334       // We can only produce a sensible answer if the record is valid.
1335       if (!Parent->isInvalidDecl()) {
1336         const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
1337 
1338         // Start with the record's overall alignment.
1339         unsigned FieldAlign = toBits(Layout.getAlignment());
1340 
1341         // Use the GCD of that and the offset within the record.
1342         uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1343         if (Offset > 0) {
1344           // Alignment is always a power of 2, so the GCD will be a power of 2,
1345           // which means we get to do this crazy thing instead of Euclid's.
1346           uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1347           if (LowBitOfOffset < FieldAlign)
1348             FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1349         }
1350 
1351         Align = std::min(Align, FieldAlign);
1352       }
1353     }
1354   }
1355 
1356   return toCharUnitsFromBits(Align);
1357 }
1358 
1359 // getTypeInfoDataSizeInChars - Return the size of a type, in
1360 // chars. If the type is a record, its data size is returned.  This is
1361 // the size of the memcpy that's performed when assigning this type
1362 // using a trivial copy/move assignment operator.
1363 std::pair<CharUnits, CharUnits>
1364 ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1365   std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1366 
1367   // In C++, objects can sometimes be allocated into the tail padding
1368   // of a base-class subobject.  We decide whether that's possible
1369   // during class layout, so here we can just trust the layout results.
1370   if (getLangOpts().CPlusPlus) {
1371     if (const RecordType *RT = T->getAs<RecordType>()) {
1372       const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1373       sizeAndAlign.first = layout.getDataSize();
1374     }
1375   }
1376 
1377   return sizeAndAlign;
1378 }
1379 
1380 /// getConstantArrayInfoInChars - Performing the computation in CharUnits
1381 /// instead of in bits prevents overflowing the uint64_t for some large arrays.
1382 std::pair<CharUnits, CharUnits>
1383 static getConstantArrayInfoInChars(const ASTContext &Context,
1384                                    const ConstantArrayType *CAT) {
1385   std::pair<CharUnits, CharUnits> EltInfo =
1386       Context.getTypeInfoInChars(CAT->getElementType());
1387   uint64_t Size = CAT->getSize().getZExtValue();
1388   assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1389               (uint64_t)(-1)/Size) &&
1390          "Overflow in array type char size evaluation");
1391   uint64_t Width = EltInfo.first.getQuantity() * Size;
1392   unsigned Align = EltInfo.second.getQuantity();
1393   if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1394       Context.getTargetInfo().getPointerWidth(0) == 64)
1395     Width = llvm::RoundUpToAlignment(Width, Align);
1396   return std::make_pair(CharUnits::fromQuantity(Width),
1397                         CharUnits::fromQuantity(Align));
1398 }
1399 
1400 std::pair<CharUnits, CharUnits>
1401 ASTContext::getTypeInfoInChars(const Type *T) const {
1402   if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1403     return getConstantArrayInfoInChars(*this, CAT);
1404   std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
1405   return std::make_pair(toCharUnitsFromBits(Info.first),
1406                         toCharUnitsFromBits(Info.second));
1407 }
1408 
1409 std::pair<CharUnits, CharUnits>
1410 ASTContext::getTypeInfoInChars(QualType T) const {
1411   return getTypeInfoInChars(T.getTypePtr());
1412 }
1413 
1414 std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
1415   TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
1416   if (it != MemoizedTypeInfo.end())
1417     return it->second;
1418 
1419   std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
1420   MemoizedTypeInfo.insert(std::make_pair(T, Info));
1421   return Info;
1422 }
1423 
1424 /// getTypeInfoImpl - Return the size of the specified type, in bits.  This
1425 /// method does not work on incomplete types.
1426 ///
1427 /// FIXME: Pointers into different addr spaces could have different sizes and
1428 /// alignment requirements: getPointerInfo should take an AddrSpace, this
1429 /// should take a QualType, &c.
1430 std::pair<uint64_t, unsigned>
1431 ASTContext::getTypeInfoImpl(const Type *T) const {
1432   uint64_t Width=0;
1433   unsigned Align=8;
1434   switch (T->getTypeClass()) {
1435 #define TYPE(Class, Base)
1436 #define ABSTRACT_TYPE(Class, Base)
1437 #define NON_CANONICAL_TYPE(Class, Base)
1438 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1439 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)                       \
1440   case Type::Class:                                                            \
1441   assert(!T->isDependentType() && "should not see dependent types here");      \
1442   return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
1443 #include "clang/AST/TypeNodes.def"
1444     llvm_unreachable("Should not see dependent types");
1445 
1446   case Type::FunctionNoProto:
1447   case Type::FunctionProto:
1448     // GCC extension: alignof(function) = 32 bits
1449     Width = 0;
1450     Align = 32;
1451     break;
1452 
1453   case Type::IncompleteArray:
1454   case Type::VariableArray:
1455     Width = 0;
1456     Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1457     break;
1458 
1459   case Type::ConstantArray: {
1460     const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
1461 
1462     std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
1463     uint64_t Size = CAT->getSize().getZExtValue();
1464     assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
1465            "Overflow in array type bit size evaluation");
1466     Width = EltInfo.first*Size;
1467     Align = EltInfo.second;
1468     if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1469         getTargetInfo().getPointerWidth(0) == 64)
1470       Width = llvm::RoundUpToAlignment(Width, Align);
1471     break;
1472   }
1473   case Type::ExtVector:
1474   case Type::Vector: {
1475     const VectorType *VT = cast<VectorType>(T);
1476     std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
1477     Width = EltInfo.first*VT->getNumElements();
1478     Align = Width;
1479     // If the alignment is not a power of 2, round up to the next power of 2.
1480     // This happens for non-power-of-2 length vectors.
1481     if (Align & (Align-1)) {
1482       Align = llvm::NextPowerOf2(Align);
1483       Width = llvm::RoundUpToAlignment(Width, Align);
1484     }
1485     // Adjust the alignment based on the target max.
1486     uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1487     if (TargetVectorAlign && TargetVectorAlign < Align)
1488       Align = TargetVectorAlign;
1489     break;
1490   }
1491 
1492   case Type::Builtin:
1493     switch (cast<BuiltinType>(T)->getKind()) {
1494     default: llvm_unreachable("Unknown builtin type!");
1495     case BuiltinType::Void:
1496       // GCC extension: alignof(void) = 8 bits.
1497       Width = 0;
1498       Align = 8;
1499       break;
1500 
1501     case BuiltinType::Bool:
1502       Width = Target->getBoolWidth();
1503       Align = Target->getBoolAlign();
1504       break;
1505     case BuiltinType::Char_S:
1506     case BuiltinType::Char_U:
1507     case BuiltinType::UChar:
1508     case BuiltinType::SChar:
1509       Width = Target->getCharWidth();
1510       Align = Target->getCharAlign();
1511       break;
1512     case BuiltinType::WChar_S:
1513     case BuiltinType::WChar_U:
1514       Width = Target->getWCharWidth();
1515       Align = Target->getWCharAlign();
1516       break;
1517     case BuiltinType::Char16:
1518       Width = Target->getChar16Width();
1519       Align = Target->getChar16Align();
1520       break;
1521     case BuiltinType::Char32:
1522       Width = Target->getChar32Width();
1523       Align = Target->getChar32Align();
1524       break;
1525     case BuiltinType::UShort:
1526     case BuiltinType::Short:
1527       Width = Target->getShortWidth();
1528       Align = Target->getShortAlign();
1529       break;
1530     case BuiltinType::UInt:
1531     case BuiltinType::Int:
1532       Width = Target->getIntWidth();
1533       Align = Target->getIntAlign();
1534       break;
1535     case BuiltinType::ULong:
1536     case BuiltinType::Long:
1537       Width = Target->getLongWidth();
1538       Align = Target->getLongAlign();
1539       break;
1540     case BuiltinType::ULongLong:
1541     case BuiltinType::LongLong:
1542       Width = Target->getLongLongWidth();
1543       Align = Target->getLongLongAlign();
1544       break;
1545     case BuiltinType::Int128:
1546     case BuiltinType::UInt128:
1547       Width = 128;
1548       Align = 128; // int128_t is 128-bit aligned on all targets.
1549       break;
1550     case BuiltinType::Half:
1551       Width = Target->getHalfWidth();
1552       Align = Target->getHalfAlign();
1553       break;
1554     case BuiltinType::Float:
1555       Width = Target->getFloatWidth();
1556       Align = Target->getFloatAlign();
1557       break;
1558     case BuiltinType::Double:
1559       Width = Target->getDoubleWidth();
1560       Align = Target->getDoubleAlign();
1561       break;
1562     case BuiltinType::LongDouble:
1563       Width = Target->getLongDoubleWidth();
1564       Align = Target->getLongDoubleAlign();
1565       break;
1566     case BuiltinType::NullPtr:
1567       Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1568       Align = Target->getPointerAlign(0); //   == sizeof(void*)
1569       break;
1570     case BuiltinType::ObjCId:
1571     case BuiltinType::ObjCClass:
1572     case BuiltinType::ObjCSel:
1573       Width = Target->getPointerWidth(0);
1574       Align = Target->getPointerAlign(0);
1575       break;
1576     case BuiltinType::OCLSampler:
1577       // Samplers are modeled as integers.
1578       Width = Target->getIntWidth();
1579       Align = Target->getIntAlign();
1580       break;
1581     case BuiltinType::OCLEvent:
1582     case BuiltinType::OCLImage1d:
1583     case BuiltinType::OCLImage1dArray:
1584     case BuiltinType::OCLImage1dBuffer:
1585     case BuiltinType::OCLImage2d:
1586     case BuiltinType::OCLImage2dArray:
1587     case BuiltinType::OCLImage3d:
1588       // Currently these types are pointers to opaque types.
1589       Width = Target->getPointerWidth(0);
1590       Align = Target->getPointerAlign(0);
1591       break;
1592     }
1593     break;
1594   case Type::ObjCObjectPointer:
1595     Width = Target->getPointerWidth(0);
1596     Align = Target->getPointerAlign(0);
1597     break;
1598   case Type::BlockPointer: {
1599     unsigned AS = getTargetAddressSpace(
1600         cast<BlockPointerType>(T)->getPointeeType());
1601     Width = Target->getPointerWidth(AS);
1602     Align = Target->getPointerAlign(AS);
1603     break;
1604   }
1605   case Type::LValueReference:
1606   case Type::RValueReference: {
1607     // alignof and sizeof should never enter this code path here, so we go
1608     // the pointer route.
1609     unsigned AS = getTargetAddressSpace(
1610         cast<ReferenceType>(T)->getPointeeType());
1611     Width = Target->getPointerWidth(AS);
1612     Align = Target->getPointerAlign(AS);
1613     break;
1614   }
1615   case Type::Pointer: {
1616     unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
1617     Width = Target->getPointerWidth(AS);
1618     Align = Target->getPointerAlign(AS);
1619     break;
1620   }
1621   case Type::MemberPointer: {
1622     const MemberPointerType *MPT = cast<MemberPointerType>(T);
1623     llvm::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
1624     break;
1625   }
1626   case Type::Complex: {
1627     // Complex types have the same alignment as their elements, but twice the
1628     // size.
1629     std::pair<uint64_t, unsigned> EltInfo =
1630       getTypeInfo(cast<ComplexType>(T)->getElementType());
1631     Width = EltInfo.first*2;
1632     Align = EltInfo.second;
1633     break;
1634   }
1635   case Type::ObjCObject:
1636     return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
1637   case Type::Adjusted:
1638   case Type::Decayed:
1639     return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
1640   case Type::ObjCInterface: {
1641     const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
1642     const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
1643     Width = toBits(Layout.getSize());
1644     Align = toBits(Layout.getAlignment());
1645     break;
1646   }
1647   case Type::Record:
1648   case Type::Enum: {
1649     const TagType *TT = cast<TagType>(T);
1650 
1651     if (TT->getDecl()->isInvalidDecl()) {
1652       Width = 8;
1653       Align = 8;
1654       break;
1655     }
1656 
1657     if (const EnumType *ET = dyn_cast<EnumType>(TT))
1658       return getTypeInfo(ET->getDecl()->getIntegerType());
1659 
1660     const RecordType *RT = cast<RecordType>(TT);
1661     const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
1662     Width = toBits(Layout.getSize());
1663     Align = toBits(Layout.getAlignment());
1664     break;
1665   }
1666 
1667   case Type::SubstTemplateTypeParm:
1668     return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1669                        getReplacementType().getTypePtr());
1670 
1671   case Type::Auto: {
1672     const AutoType *A = cast<AutoType>(T);
1673     assert(!A->getDeducedType().isNull() &&
1674            "cannot request the size of an undeduced or dependent auto type");
1675     return getTypeInfo(A->getDeducedType().getTypePtr());
1676   }
1677 
1678   case Type::Paren:
1679     return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1680 
1681   case Type::Typedef: {
1682     const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
1683     std::pair<uint64_t, unsigned> Info
1684       = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
1685     // If the typedef has an aligned attribute on it, it overrides any computed
1686     // alignment we have.  This violates the GCC documentation (which says that
1687     // attribute(aligned) can only round up) but matches its implementation.
1688     if (unsigned AttrAlign = Typedef->getMaxAlignment())
1689       Align = AttrAlign;
1690     else
1691       Align = Info.second;
1692     Width = Info.first;
1693     break;
1694   }
1695 
1696   case Type::Elaborated:
1697     return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
1698 
1699   case Type::Attributed:
1700     return getTypeInfo(
1701                   cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1702 
1703   case Type::Atomic: {
1704     // Start with the base type information.
1705     std::pair<uint64_t, unsigned> Info
1706       = getTypeInfo(cast<AtomicType>(T)->getValueType());
1707     Width = Info.first;
1708     Align = Info.second;
1709 
1710     // If the size of the type doesn't exceed the platform's max
1711     // atomic promotion width, make the size and alignment more
1712     // favorable to atomic operations:
1713     if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1714       // Round the size up to a power of 2.
1715       if (!llvm::isPowerOf2_64(Width))
1716         Width = llvm::NextPowerOf2(Width);
1717 
1718       // Set the alignment equal to the size.
1719       Align = static_cast<unsigned>(Width);
1720     }
1721   }
1722 
1723   }
1724 
1725   assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
1726   return std::make_pair(Width, Align);
1727 }
1728 
1729 /// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1730 CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1731   return CharUnits::fromQuantity(BitSize / getCharWidth());
1732 }
1733 
1734 /// toBits - Convert a size in characters to a size in characters.
1735 int64_t ASTContext::toBits(CharUnits CharSize) const {
1736   return CharSize.getQuantity() * getCharWidth();
1737 }
1738 
1739 /// getTypeSizeInChars - Return the size of the specified type, in characters.
1740 /// This method does not work on incomplete types.
1741 CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
1742   return getTypeInfoInChars(T).first;
1743 }
1744 CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
1745   return getTypeInfoInChars(T).first;
1746 }
1747 
1748 /// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
1749 /// characters. This method does not work on incomplete types.
1750 CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
1751   return toCharUnitsFromBits(getTypeAlign(T));
1752 }
1753 CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
1754   return toCharUnitsFromBits(getTypeAlign(T));
1755 }
1756 
1757 /// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1758 /// type for the current target in bits.  This can be different than the ABI
1759 /// alignment in cases where it is beneficial for performance to overalign
1760 /// a data type.
1761 unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
1762   unsigned ABIAlign = getTypeAlign(T);
1763 
1764   if (Target->getTriple().getArch() == llvm::Triple::xcore)
1765     return ABIAlign;  // Never overalign on XCore.
1766 
1767   // Double and long long should be naturally aligned if possible.
1768   if (const ComplexType* CT = T->getAs<ComplexType>())
1769     T = CT->getElementType().getTypePtr();
1770   if (T->isSpecificBuiltinType(BuiltinType::Double) ||
1771       T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1772       T->isSpecificBuiltinType(BuiltinType::ULongLong))
1773     return std::max(ABIAlign, (unsigned)getTypeSize(T));
1774 
1775   return ABIAlign;
1776 }
1777 
1778 /// getAlignOfGlobalVar - Return the alignment in bits that should be given
1779 /// to a global variable of the specified type.
1780 unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
1781   return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
1782 }
1783 
1784 /// getAlignOfGlobalVarInChars - Return the alignment in characters that
1785 /// should be given to a global variable of the specified type.
1786 CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
1787   return toCharUnitsFromBits(getAlignOfGlobalVar(T));
1788 }
1789 
1790 /// DeepCollectObjCIvars -
1791 /// This routine first collects all declared, but not synthesized, ivars in
1792 /// super class and then collects all ivars, including those synthesized for
1793 /// current class. This routine is used for implementation of current class
1794 /// when all ivars, declared and synthesized are known.
1795 ///
1796 void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1797                                       bool leafClass,
1798                             SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
1799   if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1800     DeepCollectObjCIvars(SuperClass, false, Ivars);
1801   if (!leafClass) {
1802     for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1803          E = OI->ivar_end(); I != E; ++I)
1804       Ivars.push_back(*I);
1805   } else {
1806     ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
1807     for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
1808          Iv= Iv->getNextIvar())
1809       Ivars.push_back(Iv);
1810   }
1811 }
1812 
1813 /// CollectInheritedProtocols - Collect all protocols in current class and
1814 /// those inherited by it.
1815 void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
1816                           llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
1817   if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
1818     // We can use protocol_iterator here instead of
1819     // all_referenced_protocol_iterator since we are walking all categories.
1820     for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1821          PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
1822       ObjCProtocolDecl *Proto = (*P);
1823       Protocols.insert(Proto->getCanonicalDecl());
1824       for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1825            PE = Proto->protocol_end(); P != PE; ++P) {
1826         Protocols.insert((*P)->getCanonicalDecl());
1827         CollectInheritedProtocols(*P, Protocols);
1828       }
1829     }
1830 
1831     // Categories of this Interface.
1832     for (ObjCInterfaceDecl::visible_categories_iterator
1833            Cat = OI->visible_categories_begin(),
1834            CatEnd = OI->visible_categories_end();
1835          Cat != CatEnd; ++Cat) {
1836       CollectInheritedProtocols(*Cat, Protocols);
1837     }
1838 
1839     if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1840       while (SD) {
1841         CollectInheritedProtocols(SD, Protocols);
1842         SD = SD->getSuperClass();
1843       }
1844   } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
1845     for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
1846          PE = OC->protocol_end(); P != PE; ++P) {
1847       ObjCProtocolDecl *Proto = (*P);
1848       Protocols.insert(Proto->getCanonicalDecl());
1849       for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1850            PE = Proto->protocol_end(); P != PE; ++P)
1851         CollectInheritedProtocols(*P, Protocols);
1852     }
1853   } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
1854     for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1855          PE = OP->protocol_end(); P != PE; ++P) {
1856       ObjCProtocolDecl *Proto = (*P);
1857       Protocols.insert(Proto->getCanonicalDecl());
1858       for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1859            PE = Proto->protocol_end(); P != PE; ++P)
1860         CollectInheritedProtocols(*P, Protocols);
1861     }
1862   }
1863 }
1864 
1865 unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
1866   unsigned count = 0;
1867   // Count ivars declared in class extension.
1868   for (ObjCInterfaceDecl::known_extensions_iterator
1869          Ext = OI->known_extensions_begin(),
1870          ExtEnd = OI->known_extensions_end();
1871        Ext != ExtEnd; ++Ext) {
1872     count += Ext->ivar_size();
1873   }
1874 
1875   // Count ivar defined in this class's implementation.  This
1876   // includes synthesized ivars.
1877   if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
1878     count += ImplDecl->ivar_size();
1879 
1880   return count;
1881 }
1882 
1883 bool ASTContext::isSentinelNullExpr(const Expr *E) {
1884   if (!E)
1885     return false;
1886 
1887   // nullptr_t is always treated as null.
1888   if (E->getType()->isNullPtrType()) return true;
1889 
1890   if (E->getType()->isAnyPointerType() &&
1891       E->IgnoreParenCasts()->isNullPointerConstant(*this,
1892                                                 Expr::NPC_ValueDependentIsNull))
1893     return true;
1894 
1895   // Unfortunately, __null has type 'int'.
1896   if (isa<GNUNullExpr>(E)) return true;
1897 
1898   return false;
1899 }
1900 
1901 /// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1902 ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1903   llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1904     I = ObjCImpls.find(D);
1905   if (I != ObjCImpls.end())
1906     return cast<ObjCImplementationDecl>(I->second);
1907   return 0;
1908 }
1909 /// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1910 ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1911   llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1912     I = ObjCImpls.find(D);
1913   if (I != ObjCImpls.end())
1914     return cast<ObjCCategoryImplDecl>(I->second);
1915   return 0;
1916 }
1917 
1918 /// \brief Set the implementation of ObjCInterfaceDecl.
1919 void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1920                            ObjCImplementationDecl *ImplD) {
1921   assert(IFaceD && ImplD && "Passed null params");
1922   ObjCImpls[IFaceD] = ImplD;
1923 }
1924 /// \brief Set the implementation of ObjCCategoryDecl.
1925 void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1926                            ObjCCategoryImplDecl *ImplD) {
1927   assert(CatD && ImplD && "Passed null params");
1928   ObjCImpls[CatD] = ImplD;
1929 }
1930 
1931 const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
1932                                               const NamedDecl *ND) const {
1933   if (const ObjCInterfaceDecl *ID =
1934           dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
1935     return ID;
1936   if (const ObjCCategoryDecl *CD =
1937           dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
1938     return CD->getClassInterface();
1939   if (const ObjCImplDecl *IMD =
1940           dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
1941     return IMD->getClassInterface();
1942 
1943   return 0;
1944 }
1945 
1946 /// \brief Get the copy initialization expression of VarDecl,or NULL if
1947 /// none exists.
1948 Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
1949   assert(VD && "Passed null params");
1950   assert(VD->hasAttr<BlocksAttr>() &&
1951          "getBlockVarCopyInits - not __block var");
1952   llvm::DenseMap<const VarDecl*, Expr*>::iterator
1953     I = BlockVarCopyInits.find(VD);
1954   return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1955 }
1956 
1957 /// \brief Set the copy inialization expression of a block var decl.
1958 void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1959   assert(VD && Init && "Passed null params");
1960   assert(VD->hasAttr<BlocksAttr>() &&
1961          "setBlockVarCopyInits - not __block var");
1962   BlockVarCopyInits[VD] = Init;
1963 }
1964 
1965 TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
1966                                                  unsigned DataSize) const {
1967   if (!DataSize)
1968     DataSize = TypeLoc::getFullDataSizeForType(T);
1969   else
1970     assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
1971            "incorrect data size provided to CreateTypeSourceInfo!");
1972 
1973   TypeSourceInfo *TInfo =
1974     (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1975   new (TInfo) TypeSourceInfo(T);
1976   return TInfo;
1977 }
1978 
1979 TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
1980                                                      SourceLocation L) const {
1981   TypeSourceInfo *DI = CreateTypeSourceInfo(T);
1982   DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
1983   return DI;
1984 }
1985 
1986 const ASTRecordLayout &
1987 ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
1988   return getObjCLayout(D, 0);
1989 }
1990 
1991 const ASTRecordLayout &
1992 ASTContext::getASTObjCImplementationLayout(
1993                                         const ObjCImplementationDecl *D) const {
1994   return getObjCLayout(D->getClassInterface(), D);
1995 }
1996 
1997 //===----------------------------------------------------------------------===//
1998 //                   Type creation/memoization methods
1999 //===----------------------------------------------------------------------===//
2000 
2001 QualType
2002 ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2003   unsigned fastQuals = quals.getFastQualifiers();
2004   quals.removeFastQualifiers();
2005 
2006   // Check if we've already instantiated this type.
2007   llvm::FoldingSetNodeID ID;
2008   ExtQuals::Profile(ID, baseType, quals);
2009   void *insertPos = 0;
2010   if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2011     assert(eq->getQualifiers() == quals);
2012     return QualType(eq, fastQuals);
2013   }
2014 
2015   // If the base type is not canonical, make the appropriate canonical type.
2016   QualType canon;
2017   if (!baseType->isCanonicalUnqualified()) {
2018     SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
2019     canonSplit.Quals.addConsistentQualifiers(quals);
2020     canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
2021 
2022     // Re-find the insert position.
2023     (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2024   }
2025 
2026   ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2027   ExtQualNodes.InsertNode(eq, insertPos);
2028   return QualType(eq, fastQuals);
2029 }
2030 
2031 QualType
2032 ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
2033   QualType CanT = getCanonicalType(T);
2034   if (CanT.getAddressSpace() == AddressSpace)
2035     return T;
2036 
2037   // If we are composing extended qualifiers together, merge together
2038   // into one ExtQuals node.
2039   QualifierCollector Quals;
2040   const Type *TypeNode = Quals.strip(T);
2041 
2042   // If this type already has an address space specified, it cannot get
2043   // another one.
2044   assert(!Quals.hasAddressSpace() &&
2045          "Type cannot be in multiple addr spaces!");
2046   Quals.addAddressSpace(AddressSpace);
2047 
2048   return getExtQualType(TypeNode, Quals);
2049 }
2050 
2051 QualType ASTContext::getObjCGCQualType(QualType T,
2052                                        Qualifiers::GC GCAttr) const {
2053   QualType CanT = getCanonicalType(T);
2054   if (CanT.getObjCGCAttr() == GCAttr)
2055     return T;
2056 
2057   if (const PointerType *ptr = T->getAs<PointerType>()) {
2058     QualType Pointee = ptr->getPointeeType();
2059     if (Pointee->isAnyPointerType()) {
2060       QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2061       return getPointerType(ResultType);
2062     }
2063   }
2064 
2065   // If we are composing extended qualifiers together, merge together
2066   // into one ExtQuals node.
2067   QualifierCollector Quals;
2068   const Type *TypeNode = Quals.strip(T);
2069 
2070   // If this type already has an ObjCGC specified, it cannot get
2071   // another one.
2072   assert(!Quals.hasObjCGCAttr() &&
2073          "Type cannot have multiple ObjCGCs!");
2074   Quals.addObjCGCAttr(GCAttr);
2075 
2076   return getExtQualType(TypeNode, Quals);
2077 }
2078 
2079 const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2080                                                    FunctionType::ExtInfo Info) {
2081   if (T->getExtInfo() == Info)
2082     return T;
2083 
2084   QualType Result;
2085   if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
2086     Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
2087   } else {
2088     const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2089     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2090     EPI.ExtInfo = Info;
2091     Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
2092   }
2093 
2094   return cast<FunctionType>(Result.getTypePtr());
2095 }
2096 
2097 void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2098                                                  QualType ResultType) {
2099   FD = FD->getMostRecentDecl();
2100   while (true) {
2101     const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2102     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2103     FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
2104     if (FunctionDecl *Next = FD->getPreviousDecl())
2105       FD = Next;
2106     else
2107       break;
2108   }
2109   if (ASTMutationListener *L = getASTMutationListener())
2110     L->DeducedReturnType(FD, ResultType);
2111 }
2112 
2113 /// getComplexType - Return the uniqued reference to the type for a complex
2114 /// number with the specified element type.
2115 QualType ASTContext::getComplexType(QualType T) const {
2116   // Unique pointers, to guarantee there is only one pointer of a particular
2117   // structure.
2118   llvm::FoldingSetNodeID ID;
2119   ComplexType::Profile(ID, T);
2120 
2121   void *InsertPos = 0;
2122   if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2123     return QualType(CT, 0);
2124 
2125   // If the pointee type isn't canonical, this won't be a canonical type either,
2126   // so fill in the canonical type field.
2127   QualType Canonical;
2128   if (!T.isCanonical()) {
2129     Canonical = getComplexType(getCanonicalType(T));
2130 
2131     // Get the new insert position for the node we care about.
2132     ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
2133     assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2134   }
2135   ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
2136   Types.push_back(New);
2137   ComplexTypes.InsertNode(New, InsertPos);
2138   return QualType(New, 0);
2139 }
2140 
2141 /// getPointerType - Return the uniqued reference to the type for a pointer to
2142 /// the specified type.
2143 QualType ASTContext::getPointerType(QualType T) const {
2144   // Unique pointers, to guarantee there is only one pointer of a particular
2145   // structure.
2146   llvm::FoldingSetNodeID ID;
2147   PointerType::Profile(ID, T);
2148 
2149   void *InsertPos = 0;
2150   if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2151     return QualType(PT, 0);
2152 
2153   // If the pointee type isn't canonical, this won't be a canonical type either,
2154   // so fill in the canonical type field.
2155   QualType Canonical;
2156   if (!T.isCanonical()) {
2157     Canonical = getPointerType(getCanonicalType(T));
2158 
2159     // Get the new insert position for the node we care about.
2160     PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2161     assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2162   }
2163   PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
2164   Types.push_back(New);
2165   PointerTypes.InsertNode(New, InsertPos);
2166   return QualType(New, 0);
2167 }
2168 
2169 QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2170   llvm::FoldingSetNodeID ID;
2171   AdjustedType::Profile(ID, Orig, New);
2172   void *InsertPos = 0;
2173   AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2174   if (AT)
2175     return QualType(AT, 0);
2176 
2177   QualType Canonical = getCanonicalType(New);
2178 
2179   // Get the new insert position for the node we care about.
2180   AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2181   assert(AT == 0 && "Shouldn't be in the map!");
2182 
2183   AT = new (*this, TypeAlignment)
2184       AdjustedType(Type::Adjusted, Orig, New, Canonical);
2185   Types.push_back(AT);
2186   AdjustedTypes.InsertNode(AT, InsertPos);
2187   return QualType(AT, 0);
2188 }
2189 
2190 QualType ASTContext::getDecayedType(QualType T) const {
2191   assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2192 
2193   QualType Decayed;
2194 
2195   // C99 6.7.5.3p7:
2196   //   A declaration of a parameter as "array of type" shall be
2197   //   adjusted to "qualified pointer to type", where the type
2198   //   qualifiers (if any) are those specified within the [ and ] of
2199   //   the array type derivation.
2200   if (T->isArrayType())
2201     Decayed = getArrayDecayedType(T);
2202 
2203   // C99 6.7.5.3p8:
2204   //   A declaration of a parameter as "function returning type"
2205   //   shall be adjusted to "pointer to function returning type", as
2206   //   in 6.3.2.1.
2207   if (T->isFunctionType())
2208     Decayed = getPointerType(T);
2209 
2210   llvm::FoldingSetNodeID ID;
2211   AdjustedType::Profile(ID, T, Decayed);
2212   void *InsertPos = 0;
2213   AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2214   if (AT)
2215     return QualType(AT, 0);
2216 
2217   QualType Canonical = getCanonicalType(Decayed);
2218 
2219   // Get the new insert position for the node we care about.
2220   AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2221   assert(AT == 0 && "Shouldn't be in the map!");
2222 
2223   AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2224   Types.push_back(AT);
2225   AdjustedTypes.InsertNode(AT, InsertPos);
2226   return QualType(AT, 0);
2227 }
2228 
2229 /// getBlockPointerType - Return the uniqued reference to the type for
2230 /// a pointer to the specified block.
2231 QualType ASTContext::getBlockPointerType(QualType T) const {
2232   assert(T->isFunctionType() && "block of function types only");
2233   // Unique pointers, to guarantee there is only one block of a particular
2234   // structure.
2235   llvm::FoldingSetNodeID ID;
2236   BlockPointerType::Profile(ID, T);
2237 
2238   void *InsertPos = 0;
2239   if (BlockPointerType *PT =
2240         BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2241     return QualType(PT, 0);
2242 
2243   // If the block pointee type isn't canonical, this won't be a canonical
2244   // type either so fill in the canonical type field.
2245   QualType Canonical;
2246   if (!T.isCanonical()) {
2247     Canonical = getBlockPointerType(getCanonicalType(T));
2248 
2249     // Get the new insert position for the node we care about.
2250     BlockPointerType *NewIP =
2251       BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2252     assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2253   }
2254   BlockPointerType *New
2255     = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
2256   Types.push_back(New);
2257   BlockPointerTypes.InsertNode(New, InsertPos);
2258   return QualType(New, 0);
2259 }
2260 
2261 /// getLValueReferenceType - Return the uniqued reference to the type for an
2262 /// lvalue reference to the specified type.
2263 QualType
2264 ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
2265   assert(getCanonicalType(T) != OverloadTy &&
2266          "Unresolved overloaded function type");
2267 
2268   // Unique pointers, to guarantee there is only one pointer of a particular
2269   // structure.
2270   llvm::FoldingSetNodeID ID;
2271   ReferenceType::Profile(ID, T, SpelledAsLValue);
2272 
2273   void *InsertPos = 0;
2274   if (LValueReferenceType *RT =
2275         LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2276     return QualType(RT, 0);
2277 
2278   const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2279 
2280   // If the referencee type isn't canonical, this won't be a canonical type
2281   // either, so fill in the canonical type field.
2282   QualType Canonical;
2283   if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2284     QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2285     Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
2286 
2287     // Get the new insert position for the node we care about.
2288     LValueReferenceType *NewIP =
2289       LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
2290     assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2291   }
2292 
2293   LValueReferenceType *New
2294     = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2295                                                      SpelledAsLValue);
2296   Types.push_back(New);
2297   LValueReferenceTypes.InsertNode(New, InsertPos);
2298 
2299   return QualType(New, 0);
2300 }
2301 
2302 /// getRValueReferenceType - Return the uniqued reference to the type for an
2303 /// rvalue reference to the specified type.
2304 QualType ASTContext::getRValueReferenceType(QualType T) const {
2305   // Unique pointers, to guarantee there is only one pointer of a particular
2306   // structure.
2307   llvm::FoldingSetNodeID ID;
2308   ReferenceType::Profile(ID, T, false);
2309 
2310   void *InsertPos = 0;
2311   if (RValueReferenceType *RT =
2312         RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2313     return QualType(RT, 0);
2314 
2315   const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2316 
2317   // If the referencee type isn't canonical, this won't be a canonical type
2318   // either, so fill in the canonical type field.
2319   QualType Canonical;
2320   if (InnerRef || !T.isCanonical()) {
2321     QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2322     Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
2323 
2324     // Get the new insert position for the node we care about.
2325     RValueReferenceType *NewIP =
2326       RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
2327     assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2328   }
2329 
2330   RValueReferenceType *New
2331     = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
2332   Types.push_back(New);
2333   RValueReferenceTypes.InsertNode(New, InsertPos);
2334   return QualType(New, 0);
2335 }
2336 
2337 /// getMemberPointerType - Return the uniqued reference to the type for a
2338 /// member pointer to the specified type, in the specified class.
2339 QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
2340   // Unique pointers, to guarantee there is only one pointer of a particular
2341   // structure.
2342   llvm::FoldingSetNodeID ID;
2343   MemberPointerType::Profile(ID, T, Cls);
2344 
2345   void *InsertPos = 0;
2346   if (MemberPointerType *PT =
2347       MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2348     return QualType(PT, 0);
2349 
2350   // If the pointee or class type isn't canonical, this won't be a canonical
2351   // type either, so fill in the canonical type field.
2352   QualType Canonical;
2353   if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
2354     Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2355 
2356     // Get the new insert position for the node we care about.
2357     MemberPointerType *NewIP =
2358       MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2359     assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2360   }
2361   MemberPointerType *New
2362     = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
2363   Types.push_back(New);
2364   MemberPointerTypes.InsertNode(New, InsertPos);
2365   return QualType(New, 0);
2366 }
2367 
2368 /// getConstantArrayType - Return the unique reference to the type for an
2369 /// array of the specified element type.
2370 QualType ASTContext::getConstantArrayType(QualType EltTy,
2371                                           const llvm::APInt &ArySizeIn,
2372                                           ArrayType::ArraySizeModifier ASM,
2373                                           unsigned IndexTypeQuals) const {
2374   assert((EltTy->isDependentType() ||
2375           EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
2376          "Constant array of VLAs is illegal!");
2377 
2378   // Convert the array size into a canonical width matching the pointer size for
2379   // the target.
2380   llvm::APInt ArySize(ArySizeIn);
2381   ArySize =
2382     ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
2383 
2384   llvm::FoldingSetNodeID ID;
2385   ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
2386 
2387   void *InsertPos = 0;
2388   if (ConstantArrayType *ATP =
2389       ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
2390     return QualType(ATP, 0);
2391 
2392   // If the element type isn't canonical or has qualifiers, this won't
2393   // be a canonical type either, so fill in the canonical type field.
2394   QualType Canon;
2395   if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2396     SplitQualType canonSplit = getCanonicalType(EltTy).split();
2397     Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
2398                                  ASM, IndexTypeQuals);
2399     Canon = getQualifiedType(Canon, canonSplit.Quals);
2400 
2401     // Get the new insert position for the node we care about.
2402     ConstantArrayType *NewIP =
2403       ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
2404     assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2405   }
2406 
2407   ConstantArrayType *New = new(*this,TypeAlignment)
2408     ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
2409   ConstantArrayTypes.InsertNode(New, InsertPos);
2410   Types.push_back(New);
2411   return QualType(New, 0);
2412 }
2413 
2414 /// getVariableArrayDecayedType - Turns the given type, which may be
2415 /// variably-modified, into the corresponding type with all the known
2416 /// sizes replaced with [*].
2417 QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2418   // Vastly most common case.
2419   if (!type->isVariablyModifiedType()) return type;
2420 
2421   QualType result;
2422 
2423   SplitQualType split = type.getSplitDesugaredType();
2424   const Type *ty = split.Ty;
2425   switch (ty->getTypeClass()) {
2426 #define TYPE(Class, Base)
2427 #define ABSTRACT_TYPE(Class, Base)
2428 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2429 #include "clang/AST/TypeNodes.def"
2430     llvm_unreachable("didn't desugar past all non-canonical types?");
2431 
2432   // These types should never be variably-modified.
2433   case Type::Builtin:
2434   case Type::Complex:
2435   case Type::Vector:
2436   case Type::ExtVector:
2437   case Type::DependentSizedExtVector:
2438   case Type::ObjCObject:
2439   case Type::ObjCInterface:
2440   case Type::ObjCObjectPointer:
2441   case Type::Record:
2442   case Type::Enum:
2443   case Type::UnresolvedUsing:
2444   case Type::TypeOfExpr:
2445   case Type::TypeOf:
2446   case Type::Decltype:
2447   case Type::UnaryTransform:
2448   case Type::DependentName:
2449   case Type::InjectedClassName:
2450   case Type::TemplateSpecialization:
2451   case Type::DependentTemplateSpecialization:
2452   case Type::TemplateTypeParm:
2453   case Type::SubstTemplateTypeParmPack:
2454   case Type::Auto:
2455   case Type::PackExpansion:
2456     llvm_unreachable("type should never be variably-modified");
2457 
2458   // These types can be variably-modified but should never need to
2459   // further decay.
2460   case Type::FunctionNoProto:
2461   case Type::FunctionProto:
2462   case Type::BlockPointer:
2463   case Type::MemberPointer:
2464     return type;
2465 
2466   // These types can be variably-modified.  All these modifications
2467   // preserve structure except as noted by comments.
2468   // TODO: if we ever care about optimizing VLAs, there are no-op
2469   // optimizations available here.
2470   case Type::Pointer:
2471     result = getPointerType(getVariableArrayDecayedType(
2472                               cast<PointerType>(ty)->getPointeeType()));
2473     break;
2474 
2475   case Type::LValueReference: {
2476     const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2477     result = getLValueReferenceType(
2478                  getVariableArrayDecayedType(lv->getPointeeType()),
2479                                     lv->isSpelledAsLValue());
2480     break;
2481   }
2482 
2483   case Type::RValueReference: {
2484     const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2485     result = getRValueReferenceType(
2486                  getVariableArrayDecayedType(lv->getPointeeType()));
2487     break;
2488   }
2489 
2490   case Type::Atomic: {
2491     const AtomicType *at = cast<AtomicType>(ty);
2492     result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2493     break;
2494   }
2495 
2496   case Type::ConstantArray: {
2497     const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2498     result = getConstantArrayType(
2499                  getVariableArrayDecayedType(cat->getElementType()),
2500                                   cat->getSize(),
2501                                   cat->getSizeModifier(),
2502                                   cat->getIndexTypeCVRQualifiers());
2503     break;
2504   }
2505 
2506   case Type::DependentSizedArray: {
2507     const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2508     result = getDependentSizedArrayType(
2509                  getVariableArrayDecayedType(dat->getElementType()),
2510                                         dat->getSizeExpr(),
2511                                         dat->getSizeModifier(),
2512                                         dat->getIndexTypeCVRQualifiers(),
2513                                         dat->getBracketsRange());
2514     break;
2515   }
2516 
2517   // Turn incomplete types into [*] types.
2518   case Type::IncompleteArray: {
2519     const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2520     result = getVariableArrayType(
2521                  getVariableArrayDecayedType(iat->getElementType()),
2522                                   /*size*/ 0,
2523                                   ArrayType::Normal,
2524                                   iat->getIndexTypeCVRQualifiers(),
2525                                   SourceRange());
2526     break;
2527   }
2528 
2529   // Turn VLA types into [*] types.
2530   case Type::VariableArray: {
2531     const VariableArrayType *vat = cast<VariableArrayType>(ty);
2532     result = getVariableArrayType(
2533                  getVariableArrayDecayedType(vat->getElementType()),
2534                                   /*size*/ 0,
2535                                   ArrayType::Star,
2536                                   vat->getIndexTypeCVRQualifiers(),
2537                                   vat->getBracketsRange());
2538     break;
2539   }
2540   }
2541 
2542   // Apply the top-level qualifiers from the original.
2543   return getQualifiedType(result, split.Quals);
2544 }
2545 
2546 /// getVariableArrayType - Returns a non-unique reference to the type for a
2547 /// variable array of the specified element type.
2548 QualType ASTContext::getVariableArrayType(QualType EltTy,
2549                                           Expr *NumElts,
2550                                           ArrayType::ArraySizeModifier ASM,
2551                                           unsigned IndexTypeQuals,
2552                                           SourceRange Brackets) const {
2553   // Since we don't unique expressions, it isn't possible to unique VLA's
2554   // that have an expression provided for their size.
2555   QualType Canon;
2556 
2557   // Be sure to pull qualifiers off the element type.
2558   if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2559     SplitQualType canonSplit = getCanonicalType(EltTy).split();
2560     Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
2561                                  IndexTypeQuals, Brackets);
2562     Canon = getQualifiedType(Canon, canonSplit.Quals);
2563   }
2564 
2565   VariableArrayType *New = new(*this, TypeAlignment)
2566     VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
2567 
2568   VariableArrayTypes.push_back(New);
2569   Types.push_back(New);
2570   return QualType(New, 0);
2571 }
2572 
2573 /// getDependentSizedArrayType - Returns a non-unique reference to
2574 /// the type for a dependently-sized array of the specified element
2575 /// type.
2576 QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2577                                                 Expr *numElements,
2578                                                 ArrayType::ArraySizeModifier ASM,
2579                                                 unsigned elementTypeQuals,
2580                                                 SourceRange brackets) const {
2581   assert((!numElements || numElements->isTypeDependent() ||
2582           numElements->isValueDependent()) &&
2583          "Size must be type- or value-dependent!");
2584 
2585   // Dependently-sized array types that do not have a specified number
2586   // of elements will have their sizes deduced from a dependent
2587   // initializer.  We do no canonicalization here at all, which is okay
2588   // because they can't be used in most locations.
2589   if (!numElements) {
2590     DependentSizedArrayType *newType
2591       = new (*this, TypeAlignment)
2592           DependentSizedArrayType(*this, elementType, QualType(),
2593                                   numElements, ASM, elementTypeQuals,
2594                                   brackets);
2595     Types.push_back(newType);
2596     return QualType(newType, 0);
2597   }
2598 
2599   // Otherwise, we actually build a new type every time, but we
2600   // also build a canonical type.
2601 
2602   SplitQualType canonElementType = getCanonicalType(elementType).split();
2603 
2604   void *insertPos = 0;
2605   llvm::FoldingSetNodeID ID;
2606   DependentSizedArrayType::Profile(ID, *this,
2607                                    QualType(canonElementType.Ty, 0),
2608                                    ASM, elementTypeQuals, numElements);
2609 
2610   // Look for an existing type with these properties.
2611   DependentSizedArrayType *canonTy =
2612     DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2613 
2614   // If we don't have one, build one.
2615   if (!canonTy) {
2616     canonTy = new (*this, TypeAlignment)
2617       DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
2618                               QualType(), numElements, ASM, elementTypeQuals,
2619                               brackets);
2620     DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2621     Types.push_back(canonTy);
2622   }
2623 
2624   // Apply qualifiers from the element type to the array.
2625   QualType canon = getQualifiedType(QualType(canonTy,0),
2626                                     canonElementType.Quals);
2627 
2628   // If we didn't need extra canonicalization for the element type,
2629   // then just use that as our result.
2630   if (QualType(canonElementType.Ty, 0) == elementType)
2631     return canon;
2632 
2633   // Otherwise, we need to build a type which follows the spelling
2634   // of the element type.
2635   DependentSizedArrayType *sugaredType
2636     = new (*this, TypeAlignment)
2637         DependentSizedArrayType(*this, elementType, canon, numElements,
2638                                 ASM, elementTypeQuals, brackets);
2639   Types.push_back(sugaredType);
2640   return QualType(sugaredType, 0);
2641 }
2642 
2643 QualType ASTContext::getIncompleteArrayType(QualType elementType,
2644                                             ArrayType::ArraySizeModifier ASM,
2645                                             unsigned elementTypeQuals) const {
2646   llvm::FoldingSetNodeID ID;
2647   IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
2648 
2649   void *insertPos = 0;
2650   if (IncompleteArrayType *iat =
2651        IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2652     return QualType(iat, 0);
2653 
2654   // If the element type isn't canonical, this won't be a canonical type
2655   // either, so fill in the canonical type field.  We also have to pull
2656   // qualifiers off the element type.
2657   QualType canon;
2658 
2659   if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2660     SplitQualType canonSplit = getCanonicalType(elementType).split();
2661     canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
2662                                    ASM, elementTypeQuals);
2663     canon = getQualifiedType(canon, canonSplit.Quals);
2664 
2665     // Get the new insert position for the node we care about.
2666     IncompleteArrayType *existing =
2667       IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2668     assert(!existing && "Shouldn't be in the map!"); (void) existing;
2669   }
2670 
2671   IncompleteArrayType *newType = new (*this, TypeAlignment)
2672     IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
2673 
2674   IncompleteArrayTypes.InsertNode(newType, insertPos);
2675   Types.push_back(newType);
2676   return QualType(newType, 0);
2677 }
2678 
2679 /// getVectorType - Return the unique reference to a vector type of
2680 /// the specified element type and size. VectorType must be a built-in type.
2681 QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
2682                                    VectorType::VectorKind VecKind) const {
2683   assert(vecType->isBuiltinType());
2684 
2685   // Check if we've already instantiated a vector of this type.
2686   llvm::FoldingSetNodeID ID;
2687   VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
2688 
2689   void *InsertPos = 0;
2690   if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2691     return QualType(VTP, 0);
2692 
2693   // If the element type isn't canonical, this won't be a canonical type either,
2694   // so fill in the canonical type field.
2695   QualType Canonical;
2696   if (!vecType.isCanonical()) {
2697     Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
2698 
2699     // Get the new insert position for the node we care about.
2700     VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2701     assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2702   }
2703   VectorType *New = new (*this, TypeAlignment)
2704     VectorType(vecType, NumElts, Canonical, VecKind);
2705   VectorTypes.InsertNode(New, InsertPos);
2706   Types.push_back(New);
2707   return QualType(New, 0);
2708 }
2709 
2710 /// getExtVectorType - Return the unique reference to an extended vector type of
2711 /// the specified element type and size. VectorType must be a built-in type.
2712 QualType
2713 ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
2714   assert(vecType->isBuiltinType() || vecType->isDependentType());
2715 
2716   // Check if we've already instantiated a vector of this type.
2717   llvm::FoldingSetNodeID ID;
2718   VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
2719                       VectorType::GenericVector);
2720   void *InsertPos = 0;
2721   if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2722     return QualType(VTP, 0);
2723 
2724   // If the element type isn't canonical, this won't be a canonical type either,
2725   // so fill in the canonical type field.
2726   QualType Canonical;
2727   if (!vecType.isCanonical()) {
2728     Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
2729 
2730     // Get the new insert position for the node we care about.
2731     VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2732     assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2733   }
2734   ExtVectorType *New = new (*this, TypeAlignment)
2735     ExtVectorType(vecType, NumElts, Canonical);
2736   VectorTypes.InsertNode(New, InsertPos);
2737   Types.push_back(New);
2738   return QualType(New, 0);
2739 }
2740 
2741 QualType
2742 ASTContext::getDependentSizedExtVectorType(QualType vecType,
2743                                            Expr *SizeExpr,
2744                                            SourceLocation AttrLoc) const {
2745   llvm::FoldingSetNodeID ID;
2746   DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
2747                                        SizeExpr);
2748 
2749   void *InsertPos = 0;
2750   DependentSizedExtVectorType *Canon
2751     = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2752   DependentSizedExtVectorType *New;
2753   if (Canon) {
2754     // We already have a canonical version of this array type; use it as
2755     // the canonical type for a newly-built type.
2756     New = new (*this, TypeAlignment)
2757       DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2758                                   SizeExpr, AttrLoc);
2759   } else {
2760     QualType CanonVecTy = getCanonicalType(vecType);
2761     if (CanonVecTy == vecType) {
2762       New = new (*this, TypeAlignment)
2763         DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2764                                     AttrLoc);
2765 
2766       DependentSizedExtVectorType *CanonCheck
2767         = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2768       assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2769       (void)CanonCheck;
2770       DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2771     } else {
2772       QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2773                                                       SourceLocation());
2774       New = new (*this, TypeAlignment)
2775         DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
2776     }
2777   }
2778 
2779   Types.push_back(New);
2780   return QualType(New, 0);
2781 }
2782 
2783 /// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
2784 ///
2785 QualType
2786 ASTContext::getFunctionNoProtoType(QualType ResultTy,
2787                                    const FunctionType::ExtInfo &Info) const {
2788   const CallingConv CallConv = Info.getCC();
2789 
2790   // Unique functions, to guarantee there is only one function of a particular
2791   // structure.
2792   llvm::FoldingSetNodeID ID;
2793   FunctionNoProtoType::Profile(ID, ResultTy, Info);
2794 
2795   void *InsertPos = 0;
2796   if (FunctionNoProtoType *FT =
2797         FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
2798     return QualType(FT, 0);
2799 
2800   QualType Canonical;
2801   if (!ResultTy.isCanonical()) {
2802     Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), Info);
2803 
2804     // Get the new insert position for the node we care about.
2805     FunctionNoProtoType *NewIP =
2806       FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
2807     assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2808   }
2809 
2810   FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
2811   FunctionNoProtoType *New = new (*this, TypeAlignment)
2812     FunctionNoProtoType(ResultTy, Canonical, newInfo);
2813   Types.push_back(New);
2814   FunctionNoProtoTypes.InsertNode(New, InsertPos);
2815   return QualType(New, 0);
2816 }
2817 
2818 /// \brief Determine whether \p T is canonical as the result type of a function.
2819 static bool isCanonicalResultType(QualType T) {
2820   return T.isCanonical() &&
2821          (T.getObjCLifetime() == Qualifiers::OCL_None ||
2822           T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
2823 }
2824 
2825 QualType
2826 ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
2827                             const FunctionProtoType::ExtProtoInfo &EPI) const {
2828   size_t NumArgs = ArgArray.size();
2829 
2830   // Unique functions, to guarantee there is only one function of a particular
2831   // structure.
2832   llvm::FoldingSetNodeID ID;
2833   FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
2834                              *this);
2835 
2836   void *InsertPos = 0;
2837   if (FunctionProtoType *FTP =
2838         FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
2839     return QualType(FTP, 0);
2840 
2841   // Determine whether the type being created is already canonical or not.
2842   bool isCanonical =
2843     EPI.ExceptionSpecType == EST_None && isCanonicalResultType(ResultTy) &&
2844     !EPI.HasTrailingReturn;
2845   for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
2846     if (!ArgArray[i].isCanonicalAsParam())
2847       isCanonical = false;
2848 
2849   // If this type isn't canonical, get the canonical version of it.
2850   // The exception spec is not part of the canonical type.
2851   QualType Canonical;
2852   if (!isCanonical) {
2853     SmallVector<QualType, 16> CanonicalArgs;
2854     CanonicalArgs.reserve(NumArgs);
2855     for (unsigned i = 0; i != NumArgs; ++i)
2856       CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
2857 
2858     FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
2859     CanonicalEPI.HasTrailingReturn = false;
2860     CanonicalEPI.ExceptionSpecType = EST_None;
2861     CanonicalEPI.NumExceptions = 0;
2862 
2863     // Result types do not have ARC lifetime qualifiers.
2864     QualType CanResultTy = getCanonicalType(ResultTy);
2865     if (ResultTy.getQualifiers().hasObjCLifetime()) {
2866       Qualifiers Qs = CanResultTy.getQualifiers();
2867       Qs.removeObjCLifetime();
2868       CanResultTy = getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
2869     }
2870 
2871     Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
2872 
2873     // Get the new insert position for the node we care about.
2874     FunctionProtoType *NewIP =
2875       FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
2876     assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2877   }
2878 
2879   // FunctionProtoType objects are allocated with extra bytes after
2880   // them for three variable size arrays at the end:
2881   //  - parameter types
2882   //  - exception types
2883   //  - consumed-arguments flags
2884   // Instead of the exception types, there could be a noexcept
2885   // expression, or information used to resolve the exception
2886   // specification.
2887   size_t Size = sizeof(FunctionProtoType) +
2888                 NumArgs * sizeof(QualType);
2889   if (EPI.ExceptionSpecType == EST_Dynamic) {
2890     Size += EPI.NumExceptions * sizeof(QualType);
2891   } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
2892     Size += sizeof(Expr*);
2893   } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
2894     Size += 2 * sizeof(FunctionDecl*);
2895   } else if (EPI.ExceptionSpecType == EST_Unevaluated) {
2896     Size += sizeof(FunctionDecl*);
2897   }
2898   if (EPI.ConsumedParameters)
2899     Size += NumArgs * sizeof(bool);
2900 
2901   FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
2902   FunctionProtoType::ExtProtoInfo newEPI = EPI;
2903   new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
2904   Types.push_back(FTP);
2905   FunctionProtoTypes.InsertNode(FTP, InsertPos);
2906   return QualType(FTP, 0);
2907 }
2908 
2909 #ifndef NDEBUG
2910 static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2911   if (!isa<CXXRecordDecl>(D)) return false;
2912   const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2913   if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2914     return true;
2915   if (RD->getDescribedClassTemplate() &&
2916       !isa<ClassTemplateSpecializationDecl>(RD))
2917     return true;
2918   return false;
2919 }
2920 #endif
2921 
2922 /// getInjectedClassNameType - Return the unique reference to the
2923 /// injected class name type for the specified templated declaration.
2924 QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
2925                                               QualType TST) const {
2926   assert(NeedsInjectedClassNameType(Decl));
2927   if (Decl->TypeForDecl) {
2928     assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2929   } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
2930     assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2931     Decl->TypeForDecl = PrevDecl->TypeForDecl;
2932     assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2933   } else {
2934     Type *newType =
2935       new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
2936     Decl->TypeForDecl = newType;
2937     Types.push_back(newType);
2938   }
2939   return QualType(Decl->TypeForDecl, 0);
2940 }
2941 
2942 /// getTypeDeclType - Return the unique reference to the type for the
2943 /// specified type declaration.
2944 QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
2945   assert(Decl && "Passed null for Decl param");
2946   assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
2947 
2948   if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
2949     return getTypedefType(Typedef);
2950 
2951   assert(!isa<TemplateTypeParmDecl>(Decl) &&
2952          "Template type parameter types are always available.");
2953 
2954   if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
2955     assert(Record->isFirstDecl() && "struct/union has previous declaration");
2956     assert(!NeedsInjectedClassNameType(Record));
2957     return getRecordType(Record);
2958   } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
2959     assert(Enum->isFirstDecl() && "enum has previous declaration");
2960     return getEnumType(Enum);
2961   } else if (const UnresolvedUsingTypenameDecl *Using =
2962                dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
2963     Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2964     Decl->TypeForDecl = newType;
2965     Types.push_back(newType);
2966   } else
2967     llvm_unreachable("TypeDecl without a type?");
2968 
2969   return QualType(Decl->TypeForDecl, 0);
2970 }
2971 
2972 /// getTypedefType - Return the unique reference to the type for the
2973 /// specified typedef name decl.
2974 QualType
2975 ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2976                            QualType Canonical) const {
2977   if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2978 
2979   if (Canonical.isNull())
2980     Canonical = getCanonicalType(Decl->getUnderlyingType());
2981   TypedefType *newType = new(*this, TypeAlignment)
2982     TypedefType(Type::Typedef, Decl, Canonical);
2983   Decl->TypeForDecl = newType;
2984   Types.push_back(newType);
2985   return QualType(newType, 0);
2986 }
2987 
2988 QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
2989   if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2990 
2991   if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
2992     if (PrevDecl->TypeForDecl)
2993       return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2994 
2995   RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2996   Decl->TypeForDecl = newType;
2997   Types.push_back(newType);
2998   return QualType(newType, 0);
2999 }
3000 
3001 QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
3002   if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3003 
3004   if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
3005     if (PrevDecl->TypeForDecl)
3006       return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3007 
3008   EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
3009   Decl->TypeForDecl = newType;
3010   Types.push_back(newType);
3011   return QualType(newType, 0);
3012 }
3013 
3014 QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
3015                                        QualType modifiedType,
3016                                        QualType equivalentType) {
3017   llvm::FoldingSetNodeID id;
3018   AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3019 
3020   void *insertPos = 0;
3021   AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3022   if (type) return QualType(type, 0);
3023 
3024   QualType canon = getCanonicalType(equivalentType);
3025   type = new (*this, TypeAlignment)
3026            AttributedType(canon, attrKind, modifiedType, equivalentType);
3027 
3028   Types.push_back(type);
3029   AttributedTypes.InsertNode(type, insertPos);
3030 
3031   return QualType(type, 0);
3032 }
3033 
3034 
3035 /// \brief Retrieve a substitution-result type.
3036 QualType
3037 ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
3038                                          QualType Replacement) const {
3039   assert(Replacement.isCanonical()
3040          && "replacement types must always be canonical");
3041 
3042   llvm::FoldingSetNodeID ID;
3043   SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
3044   void *InsertPos = 0;
3045   SubstTemplateTypeParmType *SubstParm
3046     = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3047 
3048   if (!SubstParm) {
3049     SubstParm = new (*this, TypeAlignment)
3050       SubstTemplateTypeParmType(Parm, Replacement);
3051     Types.push_back(SubstParm);
3052     SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3053   }
3054 
3055   return QualType(SubstParm, 0);
3056 }
3057 
3058 /// \brief Retrieve a
3059 QualType ASTContext::getSubstTemplateTypeParmPackType(
3060                                           const TemplateTypeParmType *Parm,
3061                                               const TemplateArgument &ArgPack) {
3062 #ifndef NDEBUG
3063   for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
3064                                     PEnd = ArgPack.pack_end();
3065        P != PEnd; ++P) {
3066     assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3067     assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
3068   }
3069 #endif
3070 
3071   llvm::FoldingSetNodeID ID;
3072   SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
3073   void *InsertPos = 0;
3074   if (SubstTemplateTypeParmPackType *SubstParm
3075         = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3076     return QualType(SubstParm, 0);
3077 
3078   QualType Canon;
3079   if (!Parm->isCanonicalUnqualified()) {
3080     Canon = getCanonicalType(QualType(Parm, 0));
3081     Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3082                                              ArgPack);
3083     SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3084   }
3085 
3086   SubstTemplateTypeParmPackType *SubstParm
3087     = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3088                                                                ArgPack);
3089   Types.push_back(SubstParm);
3090   SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3091   return QualType(SubstParm, 0);
3092 }
3093 
3094 /// \brief Retrieve the template type parameter type for a template
3095 /// parameter or parameter pack with the given depth, index, and (optionally)
3096 /// name.
3097 QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
3098                                              bool ParameterPack,
3099                                              TemplateTypeParmDecl *TTPDecl) const {
3100   llvm::FoldingSetNodeID ID;
3101   TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
3102   void *InsertPos = 0;
3103   TemplateTypeParmType *TypeParm
3104     = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3105 
3106   if (TypeParm)
3107     return QualType(TypeParm, 0);
3108 
3109   if (TTPDecl) {
3110     QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
3111     TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
3112 
3113     TemplateTypeParmType *TypeCheck
3114       = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3115     assert(!TypeCheck && "Template type parameter canonical type broken");
3116     (void)TypeCheck;
3117   } else
3118     TypeParm = new (*this, TypeAlignment)
3119       TemplateTypeParmType(Depth, Index, ParameterPack);
3120 
3121   Types.push_back(TypeParm);
3122   TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3123 
3124   return QualType(TypeParm, 0);
3125 }
3126 
3127 TypeSourceInfo *
3128 ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3129                                               SourceLocation NameLoc,
3130                                         const TemplateArgumentListInfo &Args,
3131                                               QualType Underlying) const {
3132   assert(!Name.getAsDependentTemplateName() &&
3133          "No dependent template names here!");
3134   QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
3135 
3136   TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
3137   TemplateSpecializationTypeLoc TL =
3138       DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
3139   TL.setTemplateKeywordLoc(SourceLocation());
3140   TL.setTemplateNameLoc(NameLoc);
3141   TL.setLAngleLoc(Args.getLAngleLoc());
3142   TL.setRAngleLoc(Args.getRAngleLoc());
3143   for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3144     TL.setArgLocInfo(i, Args[i].getLocInfo());
3145   return DI;
3146 }
3147 
3148 QualType
3149 ASTContext::getTemplateSpecializationType(TemplateName Template,
3150                                           const TemplateArgumentListInfo &Args,
3151                                           QualType Underlying) const {
3152   assert(!Template.getAsDependentTemplateName() &&
3153          "No dependent template names here!");
3154 
3155   unsigned NumArgs = Args.size();
3156 
3157   SmallVector<TemplateArgument, 4> ArgVec;
3158   ArgVec.reserve(NumArgs);
3159   for (unsigned i = 0; i != NumArgs; ++i)
3160     ArgVec.push_back(Args[i].getArgument());
3161 
3162   return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
3163                                        Underlying);
3164 }
3165 
3166 #ifndef NDEBUG
3167 static bool hasAnyPackExpansions(const TemplateArgument *Args,
3168                                  unsigned NumArgs) {
3169   for (unsigned I = 0; I != NumArgs; ++I)
3170     if (Args[I].isPackExpansion())
3171       return true;
3172 
3173   return true;
3174 }
3175 #endif
3176 
3177 QualType
3178 ASTContext::getTemplateSpecializationType(TemplateName Template,
3179                                           const TemplateArgument *Args,
3180                                           unsigned NumArgs,
3181                                           QualType Underlying) const {
3182   assert(!Template.getAsDependentTemplateName() &&
3183          "No dependent template names here!");
3184   // Look through qualified template names.
3185   if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3186     Template = TemplateName(QTN->getTemplateDecl());
3187 
3188   bool IsTypeAlias =
3189     Template.getAsTemplateDecl() &&
3190     isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
3191   QualType CanonType;
3192   if (!Underlying.isNull())
3193     CanonType = getCanonicalType(Underlying);
3194   else {
3195     // We can get here with an alias template when the specialization contains
3196     // a pack expansion that does not match up with a parameter pack.
3197     assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3198            "Caller must compute aliased type");
3199     IsTypeAlias = false;
3200     CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3201                                                        NumArgs);
3202   }
3203 
3204   // Allocate the (non-canonical) template specialization type, but don't
3205   // try to unique it: these types typically have location information that
3206   // we don't unique and don't want to lose.
3207   void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3208                        sizeof(TemplateArgument) * NumArgs +
3209                        (IsTypeAlias? sizeof(QualType) : 0),
3210                        TypeAlignment);
3211   TemplateSpecializationType *Spec
3212     = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3213                                          IsTypeAlias ? Underlying : QualType());
3214 
3215   Types.push_back(Spec);
3216   return QualType(Spec, 0);
3217 }
3218 
3219 QualType
3220 ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3221                                                    const TemplateArgument *Args,
3222                                                    unsigned NumArgs) const {
3223   assert(!Template.getAsDependentTemplateName() &&
3224          "No dependent template names here!");
3225 
3226   // Look through qualified template names.
3227   if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3228     Template = TemplateName(QTN->getTemplateDecl());
3229 
3230   // Build the canonical template specialization type.
3231   TemplateName CanonTemplate = getCanonicalTemplateName(Template);
3232   SmallVector<TemplateArgument, 4> CanonArgs;
3233   CanonArgs.reserve(NumArgs);
3234   for (unsigned I = 0; I != NumArgs; ++I)
3235     CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3236 
3237   // Determine whether this canonical template specialization type already
3238   // exists.
3239   llvm::FoldingSetNodeID ID;
3240   TemplateSpecializationType::Profile(ID, CanonTemplate,
3241                                       CanonArgs.data(), NumArgs, *this);
3242 
3243   void *InsertPos = 0;
3244   TemplateSpecializationType *Spec
3245     = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3246 
3247   if (!Spec) {
3248     // Allocate a new canonical template specialization type.
3249     void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3250                           sizeof(TemplateArgument) * NumArgs),
3251                          TypeAlignment);
3252     Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3253                                                 CanonArgs.data(), NumArgs,
3254                                                 QualType(), QualType());
3255     Types.push_back(Spec);
3256     TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3257   }
3258 
3259   assert(Spec->isDependentType() &&
3260          "Non-dependent template-id type must have a canonical type");
3261   return QualType(Spec, 0);
3262 }
3263 
3264 QualType
3265 ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3266                               NestedNameSpecifier *NNS,
3267                               QualType NamedType) const {
3268   llvm::FoldingSetNodeID ID;
3269   ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
3270 
3271   void *InsertPos = 0;
3272   ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3273   if (T)
3274     return QualType(T, 0);
3275 
3276   QualType Canon = NamedType;
3277   if (!Canon.isCanonical()) {
3278     Canon = getCanonicalType(NamedType);
3279     ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3280     assert(!CheckT && "Elaborated canonical type broken");
3281     (void)CheckT;
3282   }
3283 
3284   T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
3285   Types.push_back(T);
3286   ElaboratedTypes.InsertNode(T, InsertPos);
3287   return QualType(T, 0);
3288 }
3289 
3290 QualType
3291 ASTContext::getParenType(QualType InnerType) const {
3292   llvm::FoldingSetNodeID ID;
3293   ParenType::Profile(ID, InnerType);
3294 
3295   void *InsertPos = 0;
3296   ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3297   if (T)
3298     return QualType(T, 0);
3299 
3300   QualType Canon = InnerType;
3301   if (!Canon.isCanonical()) {
3302     Canon = getCanonicalType(InnerType);
3303     ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3304     assert(!CheckT && "Paren canonical type broken");
3305     (void)CheckT;
3306   }
3307 
3308   T = new (*this) ParenType(InnerType, Canon);
3309   Types.push_back(T);
3310   ParenTypes.InsertNode(T, InsertPos);
3311   return QualType(T, 0);
3312 }
3313 
3314 QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3315                                           NestedNameSpecifier *NNS,
3316                                           const IdentifierInfo *Name,
3317                                           QualType Canon) const {
3318   assert(NNS->isDependent() && "nested-name-specifier must be dependent");
3319 
3320   if (Canon.isNull()) {
3321     NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3322     ElaboratedTypeKeyword CanonKeyword = Keyword;
3323     if (Keyword == ETK_None)
3324       CanonKeyword = ETK_Typename;
3325 
3326     if (CanonNNS != NNS || CanonKeyword != Keyword)
3327       Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
3328   }
3329 
3330   llvm::FoldingSetNodeID ID;
3331   DependentNameType::Profile(ID, Keyword, NNS, Name);
3332 
3333   void *InsertPos = 0;
3334   DependentNameType *T
3335     = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
3336   if (T)
3337     return QualType(T, 0);
3338 
3339   T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
3340   Types.push_back(T);
3341   DependentNameTypes.InsertNode(T, InsertPos);
3342   return QualType(T, 0);
3343 }
3344 
3345 QualType
3346 ASTContext::getDependentTemplateSpecializationType(
3347                                  ElaboratedTypeKeyword Keyword,
3348                                  NestedNameSpecifier *NNS,
3349                                  const IdentifierInfo *Name,
3350                                  const TemplateArgumentListInfo &Args) const {
3351   // TODO: avoid this copy
3352   SmallVector<TemplateArgument, 16> ArgCopy;
3353   for (unsigned I = 0, E = Args.size(); I != E; ++I)
3354     ArgCopy.push_back(Args[I].getArgument());
3355   return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3356                                                 ArgCopy.size(),
3357                                                 ArgCopy.data());
3358 }
3359 
3360 QualType
3361 ASTContext::getDependentTemplateSpecializationType(
3362                                  ElaboratedTypeKeyword Keyword,
3363                                  NestedNameSpecifier *NNS,
3364                                  const IdentifierInfo *Name,
3365                                  unsigned NumArgs,
3366                                  const TemplateArgument *Args) const {
3367   assert((!NNS || NNS->isDependent()) &&
3368          "nested-name-specifier must be dependent");
3369 
3370   llvm::FoldingSetNodeID ID;
3371   DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3372                                                Name, NumArgs, Args);
3373 
3374   void *InsertPos = 0;
3375   DependentTemplateSpecializationType *T
3376     = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3377   if (T)
3378     return QualType(T, 0);
3379 
3380   NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3381 
3382   ElaboratedTypeKeyword CanonKeyword = Keyword;
3383   if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3384 
3385   bool AnyNonCanonArgs = false;
3386   SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
3387   for (unsigned I = 0; I != NumArgs; ++I) {
3388     CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3389     if (!CanonArgs[I].structurallyEquals(Args[I]))
3390       AnyNonCanonArgs = true;
3391   }
3392 
3393   QualType Canon;
3394   if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3395     Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3396                                                    Name, NumArgs,
3397                                                    CanonArgs.data());
3398 
3399     // Find the insert position again.
3400     DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3401   }
3402 
3403   void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3404                         sizeof(TemplateArgument) * NumArgs),
3405                        TypeAlignment);
3406   T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
3407                                                     Name, NumArgs, Args, Canon);
3408   Types.push_back(T);
3409   DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
3410   return QualType(T, 0);
3411 }
3412 
3413 QualType ASTContext::getPackExpansionType(QualType Pattern,
3414                                           Optional<unsigned> NumExpansions) {
3415   llvm::FoldingSetNodeID ID;
3416   PackExpansionType::Profile(ID, Pattern, NumExpansions);
3417 
3418   assert(Pattern->containsUnexpandedParameterPack() &&
3419          "Pack expansions must expand one or more parameter packs");
3420   void *InsertPos = 0;
3421   PackExpansionType *T
3422     = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3423   if (T)
3424     return QualType(T, 0);
3425 
3426   QualType Canon;
3427   if (!Pattern.isCanonical()) {
3428     Canon = getCanonicalType(Pattern);
3429     // The canonical type might not contain an unexpanded parameter pack, if it
3430     // contains an alias template specialization which ignores one of its
3431     // parameters.
3432     if (Canon->containsUnexpandedParameterPack()) {
3433       Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
3434 
3435       // Find the insert position again, in case we inserted an element into
3436       // PackExpansionTypes and invalidated our insert position.
3437       PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3438     }
3439   }
3440 
3441   T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
3442   Types.push_back(T);
3443   PackExpansionTypes.InsertNode(T, InsertPos);
3444   return QualType(T, 0);
3445 }
3446 
3447 /// CmpProtocolNames - Comparison predicate for sorting protocols
3448 /// alphabetically.
3449 static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
3450                             const ObjCProtocolDecl *RHS) {
3451   return LHS->getDeclName() < RHS->getDeclName();
3452 }
3453 
3454 static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
3455                                 unsigned NumProtocols) {
3456   if (NumProtocols == 0) return true;
3457 
3458   if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3459     return false;
3460 
3461   for (unsigned i = 1; i != NumProtocols; ++i)
3462     if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
3463         Protocols[i]->getCanonicalDecl() != Protocols[i])
3464       return false;
3465   return true;
3466 }
3467 
3468 static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
3469                                    unsigned &NumProtocols) {
3470   ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
3471 
3472   // Sort protocols, keyed by name.
3473   std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
3474 
3475   // Canonicalize.
3476   for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3477     Protocols[I] = Protocols[I]->getCanonicalDecl();
3478 
3479   // Remove duplicates.
3480   ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3481   NumProtocols = ProtocolsEnd-Protocols;
3482 }
3483 
3484 QualType ASTContext::getObjCObjectType(QualType BaseType,
3485                                        ObjCProtocolDecl * const *Protocols,
3486                                        unsigned NumProtocols) const {
3487   // If the base type is an interface and there aren't any protocols
3488   // to add, then the interface type will do just fine.
3489   if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3490     return BaseType;
3491 
3492   // Look in the folding set for an existing type.
3493   llvm::FoldingSetNodeID ID;
3494   ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
3495   void *InsertPos = 0;
3496   if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3497     return QualType(QT, 0);
3498 
3499   // Build the canonical type, which has the canonical base type and
3500   // a sorted-and-uniqued list of protocols.
3501   QualType Canonical;
3502   bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3503   if (!ProtocolsSorted || !BaseType.isCanonical()) {
3504     if (!ProtocolsSorted) {
3505       SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
3506                                                      Protocols + NumProtocols);
3507       unsigned UniqueCount = NumProtocols;
3508 
3509       SortAndUniqueProtocols(&Sorted[0], UniqueCount);
3510       Canonical = getObjCObjectType(getCanonicalType(BaseType),
3511                                     &Sorted[0], UniqueCount);
3512     } else {
3513       Canonical = getObjCObjectType(getCanonicalType(BaseType),
3514                                     Protocols, NumProtocols);
3515     }
3516 
3517     // Regenerate InsertPos.
3518     ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3519   }
3520 
3521   unsigned Size = sizeof(ObjCObjectTypeImpl);
3522   Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3523   void *Mem = Allocate(Size, TypeAlignment);
3524   ObjCObjectTypeImpl *T =
3525     new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3526 
3527   Types.push_back(T);
3528   ObjCObjectTypes.InsertNode(T, InsertPos);
3529   return QualType(T, 0);
3530 }
3531 
3532 /// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
3533 /// protocol list adopt all protocols in QT's qualified-id protocol
3534 /// list.
3535 bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
3536                                                 ObjCInterfaceDecl *IC) {
3537   if (!QT->isObjCQualifiedIdType())
3538     return false;
3539 
3540   if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) {
3541     // If both the right and left sides have qualifiers.
3542     for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3543          E = OPT->qual_end(); I != E; ++I) {
3544       ObjCProtocolDecl *Proto = *I;
3545       if (!IC->ClassImplementsProtocol(Proto, false))
3546         return false;
3547     }
3548     return true;
3549   }
3550   return false;
3551 }
3552 
3553 /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
3554 /// QT's qualified-id protocol list adopt all protocols in IDecl's list
3555 /// of protocols.
3556 bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
3557                                                 ObjCInterfaceDecl *IDecl) {
3558   if (!QT->isObjCQualifiedIdType())
3559     return false;
3560   const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
3561   if (!OPT)
3562     return false;
3563   if (!IDecl->hasDefinition())
3564     return false;
3565   llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
3566   CollectInheritedProtocols(IDecl, InheritedProtocols);
3567   if (InheritedProtocols.empty())
3568     return false;
3569 
3570   for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator PI =
3571        InheritedProtocols.begin(),
3572        E = InheritedProtocols.end(); PI != E; ++PI) {
3573     // If both the right and left sides have qualifiers.
3574     bool Adopts = false;
3575     for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3576          E = OPT->qual_end(); I != E; ++I) {
3577       ObjCProtocolDecl *Proto = *I;
3578       // return 'true' if '*PI' is in the inheritance hierarchy of Proto
3579       if ((Adopts = ProtocolCompatibleWithProtocol(*PI, Proto)))
3580         break;
3581     }
3582     if (!Adopts)
3583       return false;
3584   }
3585   return true;
3586 }
3587 
3588 /// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3589 /// the given object type.
3590 QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
3591   llvm::FoldingSetNodeID ID;
3592   ObjCObjectPointerType::Profile(ID, ObjectT);
3593 
3594   void *InsertPos = 0;
3595   if (ObjCObjectPointerType *QT =
3596               ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3597     return QualType(QT, 0);
3598 
3599   // Find the canonical object type.
3600   QualType Canonical;
3601   if (!ObjectT.isCanonical()) {
3602     Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3603 
3604     // Regenerate InsertPos.
3605     ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3606   }
3607 
3608   // No match.
3609   void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3610   ObjCObjectPointerType *QType =
3611     new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
3612 
3613   Types.push_back(QType);
3614   ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
3615   return QualType(QType, 0);
3616 }
3617 
3618 /// getObjCInterfaceType - Return the unique reference to the type for the
3619 /// specified ObjC interface decl. The list of protocols is optional.
3620 QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3621                                           ObjCInterfaceDecl *PrevDecl) const {
3622   if (Decl->TypeForDecl)
3623     return QualType(Decl->TypeForDecl, 0);
3624 
3625   if (PrevDecl) {
3626     assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3627     Decl->TypeForDecl = PrevDecl->TypeForDecl;
3628     return QualType(PrevDecl->TypeForDecl, 0);
3629   }
3630 
3631   // Prefer the definition, if there is one.
3632   if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3633     Decl = Def;
3634 
3635   void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3636   ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3637   Decl->TypeForDecl = T;
3638   Types.push_back(T);
3639   return QualType(T, 0);
3640 }
3641 
3642 /// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3643 /// TypeOfExprType AST's (since expression's are never shared). For example,
3644 /// multiple declarations that refer to "typeof(x)" all contain different
3645 /// DeclRefExpr's. This doesn't effect the type checker, since it operates
3646 /// on canonical type's (which are always unique).
3647 QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
3648   TypeOfExprType *toe;
3649   if (tofExpr->isTypeDependent()) {
3650     llvm::FoldingSetNodeID ID;
3651     DependentTypeOfExprType::Profile(ID, *this, tofExpr);
3652 
3653     void *InsertPos = 0;
3654     DependentTypeOfExprType *Canon
3655       = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3656     if (Canon) {
3657       // We already have a "canonical" version of an identical, dependent
3658       // typeof(expr) type. Use that as our canonical type.
3659       toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
3660                                           QualType((TypeOfExprType*)Canon, 0));
3661     } else {
3662       // Build a new, canonical typeof(expr) type.
3663       Canon
3664         = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
3665       DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3666       toe = Canon;
3667     }
3668   } else {
3669     QualType Canonical = getCanonicalType(tofExpr->getType());
3670     toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
3671   }
3672   Types.push_back(toe);
3673   return QualType(toe, 0);
3674 }
3675 
3676 /// getTypeOfType -  Unlike many "get<Type>" functions, we don't unique
3677 /// TypeOfType AST's. The only motivation to unique these nodes would be
3678 /// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
3679 /// an issue. This doesn't effect the type checker, since it operates
3680 /// on canonical type's (which are always unique).
3681 QualType ASTContext::getTypeOfType(QualType tofType) const {
3682   QualType Canonical = getCanonicalType(tofType);
3683   TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
3684   Types.push_back(tot);
3685   return QualType(tot, 0);
3686 }
3687 
3688 
3689 /// getDecltypeType -  Unlike many "get<Type>" functions, we don't unique
3690 /// DecltypeType AST's. The only motivation to unique these nodes would be
3691 /// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
3692 /// an issue. This doesn't effect the type checker, since it operates
3693 /// on canonical types (which are always unique).
3694 QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
3695   DecltypeType *dt;
3696 
3697   // C++0x [temp.type]p2:
3698   //   If an expression e involves a template parameter, decltype(e) denotes a
3699   //   unique dependent type. Two such decltype-specifiers refer to the same
3700   //   type only if their expressions are equivalent (14.5.6.1).
3701   if (e->isInstantiationDependent()) {
3702     llvm::FoldingSetNodeID ID;
3703     DependentDecltypeType::Profile(ID, *this, e);
3704 
3705     void *InsertPos = 0;
3706     DependentDecltypeType *Canon
3707       = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3708     if (Canon) {
3709       // We already have a "canonical" version of an equivalent, dependent
3710       // decltype type. Use that as our canonical type.
3711       dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3712                                        QualType((DecltypeType*)Canon, 0));
3713     } else {
3714       // Build a new, canonical typeof(expr) type.
3715       Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
3716       DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3717       dt = Canon;
3718     }
3719   } else {
3720     dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3721                                       getCanonicalType(UnderlyingType));
3722   }
3723   Types.push_back(dt);
3724   return QualType(dt, 0);
3725 }
3726 
3727 /// getUnaryTransformationType - We don't unique these, since the memory
3728 /// savings are minimal and these are rare.
3729 QualType ASTContext::getUnaryTransformType(QualType BaseType,
3730                                            QualType UnderlyingType,
3731                                            UnaryTransformType::UTTKind Kind)
3732     const {
3733   UnaryTransformType *Ty =
3734     new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3735                                                    Kind,
3736                                  UnderlyingType->isDependentType() ?
3737                                  QualType() : getCanonicalType(UnderlyingType));
3738   Types.push_back(Ty);
3739   return QualType(Ty, 0);
3740 }
3741 
3742 /// getAutoType - Return the uniqued reference to the 'auto' type which has been
3743 /// deduced to the given type, or to the canonical undeduced 'auto' type, or the
3744 /// canonical deduced-but-dependent 'auto' type.
3745 QualType ASTContext::getAutoType(QualType DeducedType, bool IsDecltypeAuto,
3746                                  bool IsDependent) const {
3747   if (DeducedType.isNull() && !IsDecltypeAuto && !IsDependent)
3748     return getAutoDeductType();
3749 
3750   // Look in the folding set for an existing type.
3751   void *InsertPos = 0;
3752   llvm::FoldingSetNodeID ID;
3753   AutoType::Profile(ID, DeducedType, IsDecltypeAuto, IsDependent);
3754   if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3755     return QualType(AT, 0);
3756 
3757   AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
3758                                                      IsDecltypeAuto,
3759                                                      IsDependent);
3760   Types.push_back(AT);
3761   if (InsertPos)
3762     AutoTypes.InsertNode(AT, InsertPos);
3763   return QualType(AT, 0);
3764 }
3765 
3766 /// getAtomicType - Return the uniqued reference to the atomic type for
3767 /// the given value type.
3768 QualType ASTContext::getAtomicType(QualType T) const {
3769   // Unique pointers, to guarantee there is only one pointer of a particular
3770   // structure.
3771   llvm::FoldingSetNodeID ID;
3772   AtomicType::Profile(ID, T);
3773 
3774   void *InsertPos = 0;
3775   if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3776     return QualType(AT, 0);
3777 
3778   // If the atomic value type isn't canonical, this won't be a canonical type
3779   // either, so fill in the canonical type field.
3780   QualType Canonical;
3781   if (!T.isCanonical()) {
3782     Canonical = getAtomicType(getCanonicalType(T));
3783 
3784     // Get the new insert position for the node we care about.
3785     AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3786     assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3787   }
3788   AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3789   Types.push_back(New);
3790   AtomicTypes.InsertNode(New, InsertPos);
3791   return QualType(New, 0);
3792 }
3793 
3794 /// getAutoDeductType - Get type pattern for deducing against 'auto'.
3795 QualType ASTContext::getAutoDeductType() const {
3796   if (AutoDeductTy.isNull())
3797     AutoDeductTy = QualType(
3798       new (*this, TypeAlignment) AutoType(QualType(), /*decltype(auto)*/false,
3799                                           /*dependent*/false),
3800       0);
3801   return AutoDeductTy;
3802 }
3803 
3804 /// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3805 QualType ASTContext::getAutoRRefDeductType() const {
3806   if (AutoRRefDeductTy.isNull())
3807     AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3808   assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3809   return AutoRRefDeductTy;
3810 }
3811 
3812 /// getTagDeclType - Return the unique reference to the type for the
3813 /// specified TagDecl (struct/union/class/enum) decl.
3814 QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
3815   assert (Decl);
3816   // FIXME: What is the design on getTagDeclType when it requires casting
3817   // away const?  mutable?
3818   return getTypeDeclType(const_cast<TagDecl*>(Decl));
3819 }
3820 
3821 /// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3822 /// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3823 /// needs to agree with the definition in <stddef.h>.
3824 CanQualType ASTContext::getSizeType() const {
3825   return getFromTargetType(Target->getSizeType());
3826 }
3827 
3828 /// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3829 CanQualType ASTContext::getIntMaxType() const {
3830   return getFromTargetType(Target->getIntMaxType());
3831 }
3832 
3833 /// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3834 CanQualType ASTContext::getUIntMaxType() const {
3835   return getFromTargetType(Target->getUIntMaxType());
3836 }
3837 
3838 /// getSignedWCharType - Return the type of "signed wchar_t".
3839 /// Used when in C++, as a GCC extension.
3840 QualType ASTContext::getSignedWCharType() const {
3841   // FIXME: derive from "Target" ?
3842   return WCharTy;
3843 }
3844 
3845 /// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3846 /// Used when in C++, as a GCC extension.
3847 QualType ASTContext::getUnsignedWCharType() const {
3848   // FIXME: derive from "Target" ?
3849   return UnsignedIntTy;
3850 }
3851 
3852 QualType ASTContext::getIntPtrType() const {
3853   return getFromTargetType(Target->getIntPtrType());
3854 }
3855 
3856 QualType ASTContext::getUIntPtrType() const {
3857   return getCorrespondingUnsignedType(getIntPtrType());
3858 }
3859 
3860 /// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
3861 /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3862 QualType ASTContext::getPointerDiffType() const {
3863   return getFromTargetType(Target->getPtrDiffType(0));
3864 }
3865 
3866 /// \brief Return the unique type for "pid_t" defined in
3867 /// <sys/types.h>. We need this to compute the correct type for vfork().
3868 QualType ASTContext::getProcessIDType() const {
3869   return getFromTargetType(Target->getProcessIDType());
3870 }
3871 
3872 //===----------------------------------------------------------------------===//
3873 //                              Type Operators
3874 //===----------------------------------------------------------------------===//
3875 
3876 CanQualType ASTContext::getCanonicalParamType(QualType T) const {
3877   // Push qualifiers into arrays, and then discard any remaining
3878   // qualifiers.
3879   T = getCanonicalType(T);
3880   T = getVariableArrayDecayedType(T);
3881   const Type *Ty = T.getTypePtr();
3882   QualType Result;
3883   if (isa<ArrayType>(Ty)) {
3884     Result = getArrayDecayedType(QualType(Ty,0));
3885   } else if (isa<FunctionType>(Ty)) {
3886     Result = getPointerType(QualType(Ty, 0));
3887   } else {
3888     Result = QualType(Ty, 0);
3889   }
3890 
3891   return CanQualType::CreateUnsafe(Result);
3892 }
3893 
3894 QualType ASTContext::getUnqualifiedArrayType(QualType type,
3895                                              Qualifiers &quals) {
3896   SplitQualType splitType = type.getSplitUnqualifiedType();
3897 
3898   // FIXME: getSplitUnqualifiedType() actually walks all the way to
3899   // the unqualified desugared type and then drops it on the floor.
3900   // We then have to strip that sugar back off with
3901   // getUnqualifiedDesugaredType(), which is silly.
3902   const ArrayType *AT =
3903     dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
3904 
3905   // If we don't have an array, just use the results in splitType.
3906   if (!AT) {
3907     quals = splitType.Quals;
3908     return QualType(splitType.Ty, 0);
3909   }
3910 
3911   // Otherwise, recurse on the array's element type.
3912   QualType elementType = AT->getElementType();
3913   QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3914 
3915   // If that didn't change the element type, AT has no qualifiers, so we
3916   // can just use the results in splitType.
3917   if (elementType == unqualElementType) {
3918     assert(quals.empty()); // from the recursive call
3919     quals = splitType.Quals;
3920     return QualType(splitType.Ty, 0);
3921   }
3922 
3923   // Otherwise, add in the qualifiers from the outermost type, then
3924   // build the type back up.
3925   quals.addConsistentQualifiers(splitType.Quals);
3926 
3927   if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
3928     return getConstantArrayType(unqualElementType, CAT->getSize(),
3929                                 CAT->getSizeModifier(), 0);
3930   }
3931 
3932   if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
3933     return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
3934   }
3935 
3936   if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
3937     return getVariableArrayType(unqualElementType,
3938                                 VAT->getSizeExpr(),
3939                                 VAT->getSizeModifier(),
3940                                 VAT->getIndexTypeCVRQualifiers(),
3941                                 VAT->getBracketsRange());
3942   }
3943 
3944   const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
3945   return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
3946                                     DSAT->getSizeModifier(), 0,
3947                                     SourceRange());
3948 }
3949 
3950 /// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types  that
3951 /// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3952 /// they point to and return true. If T1 and T2 aren't pointer types
3953 /// or pointer-to-member types, or if they are not similar at this
3954 /// level, returns false and leaves T1 and T2 unchanged. Top-level
3955 /// qualifiers on T1 and T2 are ignored. This function will typically
3956 /// be called in a loop that successively "unwraps" pointer and
3957 /// pointer-to-member types to compare them at each level.
3958 bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3959   const PointerType *T1PtrType = T1->getAs<PointerType>(),
3960                     *T2PtrType = T2->getAs<PointerType>();
3961   if (T1PtrType && T2PtrType) {
3962     T1 = T1PtrType->getPointeeType();
3963     T2 = T2PtrType->getPointeeType();
3964     return true;
3965   }
3966 
3967   const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3968                           *T2MPType = T2->getAs<MemberPointerType>();
3969   if (T1MPType && T2MPType &&
3970       hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3971                              QualType(T2MPType->getClass(), 0))) {
3972     T1 = T1MPType->getPointeeType();
3973     T2 = T2MPType->getPointeeType();
3974     return true;
3975   }
3976 
3977   if (getLangOpts().ObjC1) {
3978     const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3979                                 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3980     if (T1OPType && T2OPType) {
3981       T1 = T1OPType->getPointeeType();
3982       T2 = T2OPType->getPointeeType();
3983       return true;
3984     }
3985   }
3986 
3987   // FIXME: Block pointers, too?
3988 
3989   return false;
3990 }
3991 
3992 DeclarationNameInfo
3993 ASTContext::getNameForTemplate(TemplateName Name,
3994                                SourceLocation NameLoc) const {
3995   switch (Name.getKind()) {
3996   case TemplateName::QualifiedTemplate:
3997   case TemplateName::Template:
3998     // DNInfo work in progress: CHECKME: what about DNLoc?
3999     return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
4000                                NameLoc);
4001 
4002   case TemplateName::OverloadedTemplate: {
4003     OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
4004     // DNInfo work in progress: CHECKME: what about DNLoc?
4005     return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
4006   }
4007 
4008   case TemplateName::DependentTemplate: {
4009     DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4010     DeclarationName DName;
4011     if (DTN->isIdentifier()) {
4012       DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
4013       return DeclarationNameInfo(DName, NameLoc);
4014     } else {
4015       DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
4016       // DNInfo work in progress: FIXME: source locations?
4017       DeclarationNameLoc DNLoc;
4018       DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
4019       DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
4020       return DeclarationNameInfo(DName, NameLoc, DNLoc);
4021     }
4022   }
4023 
4024   case TemplateName::SubstTemplateTemplateParm: {
4025     SubstTemplateTemplateParmStorage *subst
4026       = Name.getAsSubstTemplateTemplateParm();
4027     return DeclarationNameInfo(subst->getParameter()->getDeclName(),
4028                                NameLoc);
4029   }
4030 
4031   case TemplateName::SubstTemplateTemplateParmPack: {
4032     SubstTemplateTemplateParmPackStorage *subst
4033       = Name.getAsSubstTemplateTemplateParmPack();
4034     return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
4035                                NameLoc);
4036   }
4037   }
4038 
4039   llvm_unreachable("bad template name kind!");
4040 }
4041 
4042 TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
4043   switch (Name.getKind()) {
4044   case TemplateName::QualifiedTemplate:
4045   case TemplateName::Template: {
4046     TemplateDecl *Template = Name.getAsTemplateDecl();
4047     if (TemplateTemplateParmDecl *TTP
4048           = dyn_cast<TemplateTemplateParmDecl>(Template))
4049       Template = getCanonicalTemplateTemplateParmDecl(TTP);
4050 
4051     // The canonical template name is the canonical template declaration.
4052     return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
4053   }
4054 
4055   case TemplateName::OverloadedTemplate:
4056     llvm_unreachable("cannot canonicalize overloaded template");
4057 
4058   case TemplateName::DependentTemplate: {
4059     DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4060     assert(DTN && "Non-dependent template names must refer to template decls.");
4061     return DTN->CanonicalTemplateName;
4062   }
4063 
4064   case TemplateName::SubstTemplateTemplateParm: {
4065     SubstTemplateTemplateParmStorage *subst
4066       = Name.getAsSubstTemplateTemplateParm();
4067     return getCanonicalTemplateName(subst->getReplacement());
4068   }
4069 
4070   case TemplateName::SubstTemplateTemplateParmPack: {
4071     SubstTemplateTemplateParmPackStorage *subst
4072                                   = Name.getAsSubstTemplateTemplateParmPack();
4073     TemplateTemplateParmDecl *canonParameter
4074       = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
4075     TemplateArgument canonArgPack
4076       = getCanonicalTemplateArgument(subst->getArgumentPack());
4077     return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
4078   }
4079   }
4080 
4081   llvm_unreachable("bad template name!");
4082 }
4083 
4084 bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
4085   X = getCanonicalTemplateName(X);
4086   Y = getCanonicalTemplateName(Y);
4087   return X.getAsVoidPointer() == Y.getAsVoidPointer();
4088 }
4089 
4090 TemplateArgument
4091 ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
4092   switch (Arg.getKind()) {
4093     case TemplateArgument::Null:
4094       return Arg;
4095 
4096     case TemplateArgument::Expression:
4097       return Arg;
4098 
4099     case TemplateArgument::Declaration: {
4100       ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
4101       return TemplateArgument(D, Arg.isDeclForReferenceParam());
4102     }
4103 
4104     case TemplateArgument::NullPtr:
4105       return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4106                               /*isNullPtr*/true);
4107 
4108     case TemplateArgument::Template:
4109       return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
4110 
4111     case TemplateArgument::TemplateExpansion:
4112       return TemplateArgument(getCanonicalTemplateName(
4113                                          Arg.getAsTemplateOrTemplatePattern()),
4114                               Arg.getNumTemplateExpansions());
4115 
4116     case TemplateArgument::Integral:
4117       return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
4118 
4119     case TemplateArgument::Type:
4120       return TemplateArgument(getCanonicalType(Arg.getAsType()));
4121 
4122     case TemplateArgument::Pack: {
4123       if (Arg.pack_size() == 0)
4124         return Arg;
4125 
4126       TemplateArgument *CanonArgs
4127         = new (*this) TemplateArgument[Arg.pack_size()];
4128       unsigned Idx = 0;
4129       for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
4130                                         AEnd = Arg.pack_end();
4131            A != AEnd; (void)++A, ++Idx)
4132         CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
4133 
4134       return TemplateArgument(CanonArgs, Arg.pack_size());
4135     }
4136   }
4137 
4138   // Silence GCC warning
4139   llvm_unreachable("Unhandled template argument kind");
4140 }
4141 
4142 NestedNameSpecifier *
4143 ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
4144   if (!NNS)
4145     return 0;
4146 
4147   switch (NNS->getKind()) {
4148   case NestedNameSpecifier::Identifier:
4149     // Canonicalize the prefix but keep the identifier the same.
4150     return NestedNameSpecifier::Create(*this,
4151                          getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4152                                        NNS->getAsIdentifier());
4153 
4154   case NestedNameSpecifier::Namespace:
4155     // A namespace is canonical; build a nested-name-specifier with
4156     // this namespace and no prefix.
4157     return NestedNameSpecifier::Create(*this, 0,
4158                                  NNS->getAsNamespace()->getOriginalNamespace());
4159 
4160   case NestedNameSpecifier::NamespaceAlias:
4161     // A namespace is canonical; build a nested-name-specifier with
4162     // this namespace and no prefix.
4163     return NestedNameSpecifier::Create(*this, 0,
4164                                     NNS->getAsNamespaceAlias()->getNamespace()
4165                                                       ->getOriginalNamespace());
4166 
4167   case NestedNameSpecifier::TypeSpec:
4168   case NestedNameSpecifier::TypeSpecWithTemplate: {
4169     QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
4170 
4171     // If we have some kind of dependent-named type (e.g., "typename T::type"),
4172     // break it apart into its prefix and identifier, then reconsititute those
4173     // as the canonical nested-name-specifier. This is required to canonicalize
4174     // a dependent nested-name-specifier involving typedefs of dependent-name
4175     // types, e.g.,
4176     //   typedef typename T::type T1;
4177     //   typedef typename T1::type T2;
4178     if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4179       return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
4180                            const_cast<IdentifierInfo *>(DNT->getIdentifier()));
4181 
4182     // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4183     // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4184     // first place?
4185     return NestedNameSpecifier::Create(*this, 0, false,
4186                                        const_cast<Type*>(T.getTypePtr()));
4187   }
4188 
4189   case NestedNameSpecifier::Global:
4190     // The global specifier is canonical and unique.
4191     return NNS;
4192   }
4193 
4194   llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
4195 }
4196 
4197 
4198 const ArrayType *ASTContext::getAsArrayType(QualType T) const {
4199   // Handle the non-qualified case efficiently.
4200   if (!T.hasLocalQualifiers()) {
4201     // Handle the common positive case fast.
4202     if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4203       return AT;
4204   }
4205 
4206   // Handle the common negative case fast.
4207   if (!isa<ArrayType>(T.getCanonicalType()))
4208     return 0;
4209 
4210   // Apply any qualifiers from the array type to the element type.  This
4211   // implements C99 6.7.3p8: "If the specification of an array type includes
4212   // any type qualifiers, the element type is so qualified, not the array type."
4213 
4214   // If we get here, we either have type qualifiers on the type, or we have
4215   // sugar such as a typedef in the way.  If we have type qualifiers on the type
4216   // we must propagate them down into the element type.
4217 
4218   SplitQualType split = T.getSplitDesugaredType();
4219   Qualifiers qs = split.Quals;
4220 
4221   // If we have a simple case, just return now.
4222   const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
4223   if (ATy == 0 || qs.empty())
4224     return ATy;
4225 
4226   // Otherwise, we have an array and we have qualifiers on it.  Push the
4227   // qualifiers into the array element type and return a new array type.
4228   QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
4229 
4230   if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4231     return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4232                                                 CAT->getSizeModifier(),
4233                                            CAT->getIndexTypeCVRQualifiers()));
4234   if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4235     return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4236                                                   IAT->getSizeModifier(),
4237                                            IAT->getIndexTypeCVRQualifiers()));
4238 
4239   if (const DependentSizedArrayType *DSAT
4240         = dyn_cast<DependentSizedArrayType>(ATy))
4241     return cast<ArrayType>(
4242                      getDependentSizedArrayType(NewEltTy,
4243                                                 DSAT->getSizeExpr(),
4244                                                 DSAT->getSizeModifier(),
4245                                               DSAT->getIndexTypeCVRQualifiers(),
4246                                                 DSAT->getBracketsRange()));
4247 
4248   const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
4249   return cast<ArrayType>(getVariableArrayType(NewEltTy,
4250                                               VAT->getSizeExpr(),
4251                                               VAT->getSizeModifier(),
4252                                               VAT->getIndexTypeCVRQualifiers(),
4253                                               VAT->getBracketsRange()));
4254 }
4255 
4256 QualType ASTContext::getAdjustedParameterType(QualType T) const {
4257   if (T->isArrayType() || T->isFunctionType())
4258     return getDecayedType(T);
4259   return T;
4260 }
4261 
4262 QualType ASTContext::getSignatureParameterType(QualType T) const {
4263   T = getVariableArrayDecayedType(T);
4264   T = getAdjustedParameterType(T);
4265   return T.getUnqualifiedType();
4266 }
4267 
4268 /// getArrayDecayedType - Return the properly qualified result of decaying the
4269 /// specified array type to a pointer.  This operation is non-trivial when
4270 /// handling typedefs etc.  The canonical type of "T" must be an array type,
4271 /// this returns a pointer to a properly qualified element of the array.
4272 ///
4273 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
4274 QualType ASTContext::getArrayDecayedType(QualType Ty) const {
4275   // Get the element type with 'getAsArrayType' so that we don't lose any
4276   // typedefs in the element type of the array.  This also handles propagation
4277   // of type qualifiers from the array type into the element type if present
4278   // (C99 6.7.3p8).
4279   const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4280   assert(PrettyArrayType && "Not an array type!");
4281 
4282   QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
4283 
4284   // int x[restrict 4] ->  int *restrict
4285   return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
4286 }
4287 
4288 QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4289   return getBaseElementType(array->getElementType());
4290 }
4291 
4292 QualType ASTContext::getBaseElementType(QualType type) const {
4293   Qualifiers qs;
4294   while (true) {
4295     SplitQualType split = type.getSplitDesugaredType();
4296     const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
4297     if (!array) break;
4298 
4299     type = array->getElementType();
4300     qs.addConsistentQualifiers(split.Quals);
4301   }
4302 
4303   return getQualifiedType(type, qs);
4304 }
4305 
4306 /// getConstantArrayElementCount - Returns number of constant array elements.
4307 uint64_t
4308 ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA)  const {
4309   uint64_t ElementCount = 1;
4310   do {
4311     ElementCount *= CA->getSize().getZExtValue();
4312     CA = dyn_cast_or_null<ConstantArrayType>(
4313       CA->getElementType()->getAsArrayTypeUnsafe());
4314   } while (CA);
4315   return ElementCount;
4316 }
4317 
4318 /// getFloatingRank - Return a relative rank for floating point types.
4319 /// This routine will assert if passed a built-in type that isn't a float.
4320 static FloatingRank getFloatingRank(QualType T) {
4321   if (const ComplexType *CT = T->getAs<ComplexType>())
4322     return getFloatingRank(CT->getElementType());
4323 
4324   assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4325   switch (T->getAs<BuiltinType>()->getKind()) {
4326   default: llvm_unreachable("getFloatingRank(): not a floating type");
4327   case BuiltinType::Half:       return HalfRank;
4328   case BuiltinType::Float:      return FloatRank;
4329   case BuiltinType::Double:     return DoubleRank;
4330   case BuiltinType::LongDouble: return LongDoubleRank;
4331   }
4332 }
4333 
4334 /// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4335 /// point or a complex type (based on typeDomain/typeSize).
4336 /// 'typeDomain' is a real floating point or complex type.
4337 /// 'typeSize' is a real floating point or complex type.
4338 QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4339                                                        QualType Domain) const {
4340   FloatingRank EltRank = getFloatingRank(Size);
4341   if (Domain->isComplexType()) {
4342     switch (EltRank) {
4343     case HalfRank: llvm_unreachable("Complex half is not supported");
4344     case FloatRank:      return FloatComplexTy;
4345     case DoubleRank:     return DoubleComplexTy;
4346     case LongDoubleRank: return LongDoubleComplexTy;
4347     }
4348   }
4349 
4350   assert(Domain->isRealFloatingType() && "Unknown domain!");
4351   switch (EltRank) {
4352   case HalfRank:       return HalfTy;
4353   case FloatRank:      return FloatTy;
4354   case DoubleRank:     return DoubleTy;
4355   case LongDoubleRank: return LongDoubleTy;
4356   }
4357   llvm_unreachable("getFloatingRank(): illegal value for rank");
4358 }
4359 
4360 /// getFloatingTypeOrder - Compare the rank of the two specified floating
4361 /// point types, ignoring the domain of the type (i.e. 'double' ==
4362 /// '_Complex double').  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
4363 /// LHS < RHS, return -1.
4364 int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
4365   FloatingRank LHSR = getFloatingRank(LHS);
4366   FloatingRank RHSR = getFloatingRank(RHS);
4367 
4368   if (LHSR == RHSR)
4369     return 0;
4370   if (LHSR > RHSR)
4371     return 1;
4372   return -1;
4373 }
4374 
4375 /// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4376 /// routine will assert if passed a built-in type that isn't an integer or enum,
4377 /// or if it is not canonicalized.
4378 unsigned ASTContext::getIntegerRank(const Type *T) const {
4379   assert(T->isCanonicalUnqualified() && "T should be canonicalized");
4380 
4381   switch (cast<BuiltinType>(T)->getKind()) {
4382   default: llvm_unreachable("getIntegerRank(): not a built-in integer");
4383   case BuiltinType::Bool:
4384     return 1 + (getIntWidth(BoolTy) << 3);
4385   case BuiltinType::Char_S:
4386   case BuiltinType::Char_U:
4387   case BuiltinType::SChar:
4388   case BuiltinType::UChar:
4389     return 2 + (getIntWidth(CharTy) << 3);
4390   case BuiltinType::Short:
4391   case BuiltinType::UShort:
4392     return 3 + (getIntWidth(ShortTy) << 3);
4393   case BuiltinType::Int:
4394   case BuiltinType::UInt:
4395     return 4 + (getIntWidth(IntTy) << 3);
4396   case BuiltinType::Long:
4397   case BuiltinType::ULong:
4398     return 5 + (getIntWidth(LongTy) << 3);
4399   case BuiltinType::LongLong:
4400   case BuiltinType::ULongLong:
4401     return 6 + (getIntWidth(LongLongTy) << 3);
4402   case BuiltinType::Int128:
4403   case BuiltinType::UInt128:
4404     return 7 + (getIntWidth(Int128Ty) << 3);
4405   }
4406 }
4407 
4408 /// \brief Whether this is a promotable bitfield reference according
4409 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4410 ///
4411 /// \returns the type this bit-field will promote to, or NULL if no
4412 /// promotion occurs.
4413 QualType ASTContext::isPromotableBitField(Expr *E) const {
4414   if (E->isTypeDependent() || E->isValueDependent())
4415     return QualType();
4416 
4417   FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
4418   if (!Field)
4419     return QualType();
4420 
4421   QualType FT = Field->getType();
4422 
4423   uint64_t BitWidth = Field->getBitWidthValue(*this);
4424   uint64_t IntSize = getTypeSize(IntTy);
4425   // GCC extension compatibility: if the bit-field size is less than or equal
4426   // to the size of int, it gets promoted no matter what its type is.
4427   // For instance, unsigned long bf : 4 gets promoted to signed int.
4428   if (BitWidth < IntSize)
4429     return IntTy;
4430 
4431   if (BitWidth == IntSize)
4432     return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4433 
4434   // Types bigger than int are not subject to promotions, and therefore act
4435   // like the base type.
4436   // FIXME: This doesn't quite match what gcc does, but what gcc does here
4437   // is ridiculous.
4438   return QualType();
4439 }
4440 
4441 /// getPromotedIntegerType - Returns the type that Promotable will
4442 /// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4443 /// integer type.
4444 QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
4445   assert(!Promotable.isNull());
4446   assert(Promotable->isPromotableIntegerType());
4447   if (const EnumType *ET = Promotable->getAs<EnumType>())
4448     return ET->getDecl()->getPromotionType();
4449 
4450   if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4451     // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4452     // (3.9.1) can be converted to a prvalue of the first of the following
4453     // types that can represent all the values of its underlying type:
4454     // int, unsigned int, long int, unsigned long int, long long int, or
4455     // unsigned long long int [...]
4456     // FIXME: Is there some better way to compute this?
4457     if (BT->getKind() == BuiltinType::WChar_S ||
4458         BT->getKind() == BuiltinType::WChar_U ||
4459         BT->getKind() == BuiltinType::Char16 ||
4460         BT->getKind() == BuiltinType::Char32) {
4461       bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4462       uint64_t FromSize = getTypeSize(BT);
4463       QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4464                                   LongLongTy, UnsignedLongLongTy };
4465       for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4466         uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4467         if (FromSize < ToSize ||
4468             (FromSize == ToSize &&
4469              FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4470           return PromoteTypes[Idx];
4471       }
4472       llvm_unreachable("char type should fit into long long");
4473     }
4474   }
4475 
4476   // At this point, we should have a signed or unsigned integer type.
4477   if (Promotable->isSignedIntegerType())
4478     return IntTy;
4479   uint64_t PromotableSize = getIntWidth(Promotable);
4480   uint64_t IntSize = getIntWidth(IntTy);
4481   assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4482   return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4483 }
4484 
4485 /// \brief Recurses in pointer/array types until it finds an objc retainable
4486 /// type and returns its ownership.
4487 Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4488   while (!T.isNull()) {
4489     if (T.getObjCLifetime() != Qualifiers::OCL_None)
4490       return T.getObjCLifetime();
4491     if (T->isArrayType())
4492       T = getBaseElementType(T);
4493     else if (const PointerType *PT = T->getAs<PointerType>())
4494       T = PT->getPointeeType();
4495     else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4496       T = RT->getPointeeType();
4497     else
4498       break;
4499   }
4500 
4501   return Qualifiers::OCL_None;
4502 }
4503 
4504 static const Type *getIntegerTypeForEnum(const EnumType *ET) {
4505   // Incomplete enum types are not treated as integer types.
4506   // FIXME: In C++, enum types are never integer types.
4507   if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
4508     return ET->getDecl()->getIntegerType().getTypePtr();
4509   return NULL;
4510 }
4511 
4512 /// getIntegerTypeOrder - Returns the highest ranked integer type:
4513 /// C99 6.3.1.8p1.  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
4514 /// LHS < RHS, return -1.
4515 int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
4516   const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4517   const Type *RHSC = getCanonicalType(RHS).getTypePtr();
4518 
4519   // Unwrap enums to their underlying type.
4520   if (const EnumType *ET = dyn_cast<EnumType>(LHSC))
4521     LHSC = getIntegerTypeForEnum(ET);
4522   if (const EnumType *ET = dyn_cast<EnumType>(RHSC))
4523     RHSC = getIntegerTypeForEnum(ET);
4524 
4525   if (LHSC == RHSC) return 0;
4526 
4527   bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4528   bool RHSUnsigned = RHSC->isUnsignedIntegerType();
4529 
4530   unsigned LHSRank = getIntegerRank(LHSC);
4531   unsigned RHSRank = getIntegerRank(RHSC);
4532 
4533   if (LHSUnsigned == RHSUnsigned) {  // Both signed or both unsigned.
4534     if (LHSRank == RHSRank) return 0;
4535     return LHSRank > RHSRank ? 1 : -1;
4536   }
4537 
4538   // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4539   if (LHSUnsigned) {
4540     // If the unsigned [LHS] type is larger, return it.
4541     if (LHSRank >= RHSRank)
4542       return 1;
4543 
4544     // If the signed type can represent all values of the unsigned type, it
4545     // wins.  Because we are dealing with 2's complement and types that are
4546     // powers of two larger than each other, this is always safe.
4547     return -1;
4548   }
4549 
4550   // If the unsigned [RHS] type is larger, return it.
4551   if (RHSRank >= LHSRank)
4552     return -1;
4553 
4554   // If the signed type can represent all values of the unsigned type, it
4555   // wins.  Because we are dealing with 2's complement and types that are
4556   // powers of two larger than each other, this is always safe.
4557   return 1;
4558 }
4559 
4560 // getCFConstantStringType - Return the type used for constant CFStrings.
4561 QualType ASTContext::getCFConstantStringType() const {
4562   if (!CFConstantStringTypeDecl) {
4563     CFConstantStringTypeDecl = buildImplicitRecord("NSConstantString");
4564     CFConstantStringTypeDecl->startDefinition();
4565 
4566     QualType FieldTypes[4];
4567 
4568     // const int *isa;
4569     FieldTypes[0] = getPointerType(IntTy.withConst());
4570     // int flags;
4571     FieldTypes[1] = IntTy;
4572     // const char *str;
4573     FieldTypes[2] = getPointerType(CharTy.withConst());
4574     // long length;
4575     FieldTypes[3] = LongTy;
4576 
4577     // Create fields
4578     for (unsigned i = 0; i < 4; ++i) {
4579       FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
4580                                            SourceLocation(),
4581                                            SourceLocation(), 0,
4582                                            FieldTypes[i], /*TInfo=*/0,
4583                                            /*BitWidth=*/0,
4584                                            /*Mutable=*/false,
4585                                            ICIS_NoInit);
4586       Field->setAccess(AS_public);
4587       CFConstantStringTypeDecl->addDecl(Field);
4588     }
4589 
4590     CFConstantStringTypeDecl->completeDefinition();
4591   }
4592 
4593   return getTagDeclType(CFConstantStringTypeDecl);
4594 }
4595 
4596 QualType ASTContext::getObjCSuperType() const {
4597   if (ObjCSuperType.isNull()) {
4598     RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
4599     TUDecl->addDecl(ObjCSuperTypeDecl);
4600     ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4601   }
4602   return ObjCSuperType;
4603 }
4604 
4605 void ASTContext::setCFConstantStringType(QualType T) {
4606   const RecordType *Rec = T->getAs<RecordType>();
4607   assert(Rec && "Invalid CFConstantStringType");
4608   CFConstantStringTypeDecl = Rec->getDecl();
4609 }
4610 
4611 QualType ASTContext::getBlockDescriptorType() const {
4612   if (BlockDescriptorType)
4613     return getTagDeclType(BlockDescriptorType);
4614 
4615   RecordDecl *RD;
4616   // FIXME: Needs the FlagAppleBlock bit.
4617   RD = buildImplicitRecord("__block_descriptor");
4618   RD->startDefinition();
4619 
4620   QualType FieldTypes[] = {
4621     UnsignedLongTy,
4622     UnsignedLongTy,
4623   };
4624 
4625   static const char *const FieldNames[] = {
4626     "reserved",
4627     "Size"
4628   };
4629 
4630   for (size_t i = 0; i < 2; ++i) {
4631     FieldDecl *Field = FieldDecl::Create(
4632         *this, RD, SourceLocation(), SourceLocation(),
4633         &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/0,
4634         /*BitWidth=*/0, /*Mutable=*/false, ICIS_NoInit);
4635     Field->setAccess(AS_public);
4636     RD->addDecl(Field);
4637   }
4638 
4639   RD->completeDefinition();
4640 
4641   BlockDescriptorType = RD;
4642 
4643   return getTagDeclType(BlockDescriptorType);
4644 }
4645 
4646 QualType ASTContext::getBlockDescriptorExtendedType() const {
4647   if (BlockDescriptorExtendedType)
4648     return getTagDeclType(BlockDescriptorExtendedType);
4649 
4650   RecordDecl *RD;
4651   // FIXME: Needs the FlagAppleBlock bit.
4652   RD = buildImplicitRecord("__block_descriptor_withcopydispose");
4653   RD->startDefinition();
4654 
4655   QualType FieldTypes[] = {
4656     UnsignedLongTy,
4657     UnsignedLongTy,
4658     getPointerType(VoidPtrTy),
4659     getPointerType(VoidPtrTy)
4660   };
4661 
4662   static const char *const FieldNames[] = {
4663     "reserved",
4664     "Size",
4665     "CopyFuncPtr",
4666     "DestroyFuncPtr"
4667   };
4668 
4669   for (size_t i = 0; i < 4; ++i) {
4670     FieldDecl *Field = FieldDecl::Create(
4671         *this, RD, SourceLocation(), SourceLocation(),
4672         &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/0,
4673         /*BitWidth=*/0,
4674         /*Mutable=*/false, ICIS_NoInit);
4675     Field->setAccess(AS_public);
4676     RD->addDecl(Field);
4677   }
4678 
4679   RD->completeDefinition();
4680 
4681   BlockDescriptorExtendedType = RD;
4682   return getTagDeclType(BlockDescriptorExtendedType);
4683 }
4684 
4685 /// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4686 /// requires copy/dispose. Note that this must match the logic
4687 /// in buildByrefHelpers.
4688 bool ASTContext::BlockRequiresCopying(QualType Ty,
4689                                       const VarDecl *D) {
4690   if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4691     const Expr *copyExpr = getBlockVarCopyInits(D);
4692     if (!copyExpr && record->hasTrivialDestructor()) return false;
4693 
4694     return true;
4695   }
4696 
4697   if (!Ty->isObjCRetainableType()) return false;
4698 
4699   Qualifiers qs = Ty.getQualifiers();
4700 
4701   // If we have lifetime, that dominates.
4702   if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4703     assert(getLangOpts().ObjCAutoRefCount);
4704 
4705     switch (lifetime) {
4706       case Qualifiers::OCL_None: llvm_unreachable("impossible");
4707 
4708       // These are just bits as far as the runtime is concerned.
4709       case Qualifiers::OCL_ExplicitNone:
4710       case Qualifiers::OCL_Autoreleasing:
4711         return false;
4712 
4713       // Tell the runtime that this is ARC __weak, called by the
4714       // byref routines.
4715       case Qualifiers::OCL_Weak:
4716       // ARC __strong __block variables need to be retained.
4717       case Qualifiers::OCL_Strong:
4718         return true;
4719     }
4720     llvm_unreachable("fell out of lifetime switch!");
4721   }
4722   return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4723           Ty->isObjCObjectPointerType());
4724 }
4725 
4726 bool ASTContext::getByrefLifetime(QualType Ty,
4727                               Qualifiers::ObjCLifetime &LifeTime,
4728                               bool &HasByrefExtendedLayout) const {
4729 
4730   if (!getLangOpts().ObjC1 ||
4731       getLangOpts().getGC() != LangOptions::NonGC)
4732     return false;
4733 
4734   HasByrefExtendedLayout = false;
4735   if (Ty->isRecordType()) {
4736     HasByrefExtendedLayout = true;
4737     LifeTime = Qualifiers::OCL_None;
4738   }
4739   else if (getLangOpts().ObjCAutoRefCount)
4740     LifeTime = Ty.getObjCLifetime();
4741   // MRR.
4742   else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4743     LifeTime = Qualifiers::OCL_ExplicitNone;
4744   else
4745     LifeTime = Qualifiers::OCL_None;
4746   return true;
4747 }
4748 
4749 TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4750   if (!ObjCInstanceTypeDecl)
4751     ObjCInstanceTypeDecl =
4752         buildImplicitTypedef(getObjCIdType(), "instancetype");
4753   return ObjCInstanceTypeDecl;
4754 }
4755 
4756 // This returns true if a type has been typedefed to BOOL:
4757 // typedef <type> BOOL;
4758 static bool isTypeTypedefedAsBOOL(QualType T) {
4759   if (const TypedefType *TT = dyn_cast<TypedefType>(T))
4760     if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4761       return II->isStr("BOOL");
4762 
4763   return false;
4764 }
4765 
4766 /// getObjCEncodingTypeSize returns size of type for objective-c encoding
4767 /// purpose.
4768 CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
4769   if (!type->isIncompleteArrayType() && type->isIncompleteType())
4770     return CharUnits::Zero();
4771 
4772   CharUnits sz = getTypeSizeInChars(type);
4773 
4774   // Make all integer and enum types at least as large as an int
4775   if (sz.isPositive() && type->isIntegralOrEnumerationType())
4776     sz = std::max(sz, getTypeSizeInChars(IntTy));
4777   // Treat arrays as pointers, since that's how they're passed in.
4778   else if (type->isArrayType())
4779     sz = getTypeSizeInChars(VoidPtrTy);
4780   return sz;
4781 }
4782 
4783 static inline
4784 std::string charUnitsToString(const CharUnits &CU) {
4785   return llvm::itostr(CU.getQuantity());
4786 }
4787 
4788 /// getObjCEncodingForBlock - Return the encoded type for this block
4789 /// declaration.
4790 std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4791   std::string S;
4792 
4793   const BlockDecl *Decl = Expr->getBlockDecl();
4794   QualType BlockTy =
4795       Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4796   // Encode result type.
4797   if (getLangOpts().EncodeExtendedBlockSig)
4798     getObjCEncodingForMethodParameter(
4799         Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
4800         true /*Extended*/);
4801   else
4802     getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
4803   // Compute size of all parameters.
4804   // Start with computing size of a pointer in number of bytes.
4805   // FIXME: There might(should) be a better way of doing this computation!
4806   SourceLocation Loc;
4807   CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4808   CharUnits ParmOffset = PtrSize;
4809   for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
4810        E = Decl->param_end(); PI != E; ++PI) {
4811     QualType PType = (*PI)->getType();
4812     CharUnits sz = getObjCEncodingTypeSize(PType);
4813     if (sz.isZero())
4814       continue;
4815     assert (sz.isPositive() && "BlockExpr - Incomplete param type");
4816     ParmOffset += sz;
4817   }
4818   // Size of the argument frame
4819   S += charUnitsToString(ParmOffset);
4820   // Block pointer and offset.
4821   S += "@?0";
4822 
4823   // Argument types.
4824   ParmOffset = PtrSize;
4825   for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4826        Decl->param_end(); PI != E; ++PI) {
4827     ParmVarDecl *PVDecl = *PI;
4828     QualType PType = PVDecl->getOriginalType();
4829     if (const ArrayType *AT =
4830           dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4831       // Use array's original type only if it has known number of
4832       // elements.
4833       if (!isa<ConstantArrayType>(AT))
4834         PType = PVDecl->getType();
4835     } else if (PType->isFunctionType())
4836       PType = PVDecl->getType();
4837     if (getLangOpts().EncodeExtendedBlockSig)
4838       getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
4839                                       S, true /*Extended*/);
4840     else
4841       getObjCEncodingForType(PType, S);
4842     S += charUnitsToString(ParmOffset);
4843     ParmOffset += getObjCEncodingTypeSize(PType);
4844   }
4845 
4846   return S;
4847 }
4848 
4849 bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
4850                                                 std::string& S) {
4851   // Encode result type.
4852   getObjCEncodingForType(Decl->getReturnType(), S);
4853   CharUnits ParmOffset;
4854   // Compute size of all parameters.
4855   for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4856        E = Decl->param_end(); PI != E; ++PI) {
4857     QualType PType = (*PI)->getType();
4858     CharUnits sz = getObjCEncodingTypeSize(PType);
4859     if (sz.isZero())
4860       continue;
4861 
4862     assert (sz.isPositive() &&
4863         "getObjCEncodingForFunctionDecl - Incomplete param type");
4864     ParmOffset += sz;
4865   }
4866   S += charUnitsToString(ParmOffset);
4867   ParmOffset = CharUnits::Zero();
4868 
4869   // Argument types.
4870   for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4871        E = Decl->param_end(); PI != E; ++PI) {
4872     ParmVarDecl *PVDecl = *PI;
4873     QualType PType = PVDecl->getOriginalType();
4874     if (const ArrayType *AT =
4875           dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4876       // Use array's original type only if it has known number of
4877       // elements.
4878       if (!isa<ConstantArrayType>(AT))
4879         PType = PVDecl->getType();
4880     } else if (PType->isFunctionType())
4881       PType = PVDecl->getType();
4882     getObjCEncodingForType(PType, S);
4883     S += charUnitsToString(ParmOffset);
4884     ParmOffset += getObjCEncodingTypeSize(PType);
4885   }
4886 
4887   return false;
4888 }
4889 
4890 /// getObjCEncodingForMethodParameter - Return the encoded type for a single
4891 /// method parameter or return type. If Extended, include class names and
4892 /// block object types.
4893 void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4894                                                    QualType T, std::string& S,
4895                                                    bool Extended) const {
4896   // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4897   getObjCEncodingForTypeQualifier(QT, S);
4898   // Encode parameter type.
4899   getObjCEncodingForTypeImpl(T, S, true, true, 0,
4900                              true     /*OutermostType*/,
4901                              false    /*EncodingProperty*/,
4902                              false    /*StructField*/,
4903                              Extended /*EncodeBlockParameters*/,
4904                              Extended /*EncodeClassNames*/);
4905 }
4906 
4907 /// getObjCEncodingForMethodDecl - Return the encoded type for this method
4908 /// declaration.
4909 bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
4910                                               std::string& S,
4911                                               bool Extended) const {
4912   // FIXME: This is not very efficient.
4913   // Encode return type.
4914   getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4915                                     Decl->getReturnType(), S, Extended);
4916   // Compute size of all parameters.
4917   // Start with computing size of a pointer in number of bytes.
4918   // FIXME: There might(should) be a better way of doing this computation!
4919   SourceLocation Loc;
4920   CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4921   // The first two arguments (self and _cmd) are pointers; account for
4922   // their size.
4923   CharUnits ParmOffset = 2 * PtrSize;
4924   for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
4925        E = Decl->sel_param_end(); PI != E; ++PI) {
4926     QualType PType = (*PI)->getType();
4927     CharUnits sz = getObjCEncodingTypeSize(PType);
4928     if (sz.isZero())
4929       continue;
4930 
4931     assert (sz.isPositive() &&
4932         "getObjCEncodingForMethodDecl - Incomplete param type");
4933     ParmOffset += sz;
4934   }
4935   S += charUnitsToString(ParmOffset);
4936   S += "@0:";
4937   S += charUnitsToString(PtrSize);
4938 
4939   // Argument types.
4940   ParmOffset = 2 * PtrSize;
4941   for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
4942        E = Decl->sel_param_end(); PI != E; ++PI) {
4943     const ParmVarDecl *PVDecl = *PI;
4944     QualType PType = PVDecl->getOriginalType();
4945     if (const ArrayType *AT =
4946           dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4947       // Use array's original type only if it has known number of
4948       // elements.
4949       if (!isa<ConstantArrayType>(AT))
4950         PType = PVDecl->getType();
4951     } else if (PType->isFunctionType())
4952       PType = PVDecl->getType();
4953     getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4954                                       PType, S, Extended);
4955     S += charUnitsToString(ParmOffset);
4956     ParmOffset += getObjCEncodingTypeSize(PType);
4957   }
4958 
4959   return false;
4960 }
4961 
4962 ObjCPropertyImplDecl *
4963 ASTContext::getObjCPropertyImplDeclForPropertyDecl(
4964                                       const ObjCPropertyDecl *PD,
4965                                       const Decl *Container) const {
4966   if (!Container)
4967     return 0;
4968   if (const ObjCCategoryImplDecl *CID =
4969       dyn_cast<ObjCCategoryImplDecl>(Container)) {
4970     for (ObjCCategoryImplDecl::propimpl_iterator
4971          i = CID->propimpl_begin(), e = CID->propimpl_end();
4972          i != e; ++i) {
4973       ObjCPropertyImplDecl *PID = *i;
4974         if (PID->getPropertyDecl() == PD)
4975           return PID;
4976       }
4977     } else {
4978       const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
4979       for (ObjCCategoryImplDecl::propimpl_iterator
4980            i = OID->propimpl_begin(), e = OID->propimpl_end();
4981            i != e; ++i) {
4982         ObjCPropertyImplDecl *PID = *i;
4983         if (PID->getPropertyDecl() == PD)
4984           return PID;
4985       }
4986     }
4987   return 0;
4988 }
4989 
4990 /// getObjCEncodingForPropertyDecl - Return the encoded type for this
4991 /// property declaration. If non-NULL, Container must be either an
4992 /// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4993 /// NULL when getting encodings for protocol properties.
4994 /// Property attributes are stored as a comma-delimited C string. The simple
4995 /// attributes readonly and bycopy are encoded as single characters. The
4996 /// parametrized attributes, getter=name, setter=name, and ivar=name, are
4997 /// encoded as single characters, followed by an identifier. Property types
4998 /// are also encoded as a parametrized attribute. The characters used to encode
4999 /// these attributes are defined by the following enumeration:
5000 /// @code
5001 /// enum PropertyAttributes {
5002 /// kPropertyReadOnly = 'R',   // property is read-only.
5003 /// kPropertyBycopy = 'C',     // property is a copy of the value last assigned
5004 /// kPropertyByref = '&',  // property is a reference to the value last assigned
5005 /// kPropertyDynamic = 'D',    // property is dynamic
5006 /// kPropertyGetter = 'G',     // followed by getter selector name
5007 /// kPropertySetter = 'S',     // followed by setter selector name
5008 /// kPropertyInstanceVariable = 'V'  // followed by instance variable  name
5009 /// kPropertyType = 'T'              // followed by old-style type encoding.
5010 /// kPropertyWeak = 'W'              // 'weak' property
5011 /// kPropertyStrong = 'P'            // property GC'able
5012 /// kPropertyNonAtomic = 'N'         // property non-atomic
5013 /// };
5014 /// @endcode
5015 void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
5016                                                 const Decl *Container,
5017                                                 std::string& S) const {
5018   // Collect information from the property implementation decl(s).
5019   bool Dynamic = false;
5020   ObjCPropertyImplDecl *SynthesizePID = 0;
5021 
5022   if (ObjCPropertyImplDecl *PropertyImpDecl =
5023       getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
5024     if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5025       Dynamic = true;
5026     else
5027       SynthesizePID = PropertyImpDecl;
5028   }
5029 
5030   // FIXME: This is not very efficient.
5031   S = "T";
5032 
5033   // Encode result type.
5034   // GCC has some special rules regarding encoding of properties which
5035   // closely resembles encoding of ivars.
5036   getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
5037                              true /* outermost type */,
5038                              true /* encoding for property */);
5039 
5040   if (PD->isReadOnly()) {
5041     S += ",R";
5042     if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
5043       S += ",C";
5044     if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
5045       S += ",&";
5046   } else {
5047     switch (PD->getSetterKind()) {
5048     case ObjCPropertyDecl::Assign: break;
5049     case ObjCPropertyDecl::Copy:   S += ",C"; break;
5050     case ObjCPropertyDecl::Retain: S += ",&"; break;
5051     case ObjCPropertyDecl::Weak:   S += ",W"; break;
5052     }
5053   }
5054 
5055   // It really isn't clear at all what this means, since properties
5056   // are "dynamic by default".
5057   if (Dynamic)
5058     S += ",D";
5059 
5060   if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
5061     S += ",N";
5062 
5063   if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
5064     S += ",G";
5065     S += PD->getGetterName().getAsString();
5066   }
5067 
5068   if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
5069     S += ",S";
5070     S += PD->getSetterName().getAsString();
5071   }
5072 
5073   if (SynthesizePID) {
5074     const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
5075     S += ",V";
5076     S += OID->getNameAsString();
5077   }
5078 
5079   // FIXME: OBJCGC: weak & strong
5080 }
5081 
5082 /// getLegacyIntegralTypeEncoding -
5083 /// Another legacy compatibility encoding: 32-bit longs are encoded as
5084 /// 'l' or 'L' , but not always.  For typedefs, we need to use
5085 /// 'i' or 'I' instead if encoding a struct field, or a pointer!
5086 ///
5087 void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
5088   if (isa<TypedefType>(PointeeTy.getTypePtr())) {
5089     if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
5090       if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
5091         PointeeTy = UnsignedIntTy;
5092       else
5093         if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
5094           PointeeTy = IntTy;
5095     }
5096   }
5097 }
5098 
5099 void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
5100                                         const FieldDecl *Field) const {
5101   // We follow the behavior of gcc, expanding structures which are
5102   // directly pointed to, and expanding embedded structures. Note that
5103   // these rules are sufficient to prevent recursive encoding of the
5104   // same type.
5105   getObjCEncodingForTypeImpl(T, S, true, true, Field,
5106                              true /* outermost type */);
5107 }
5108 
5109 static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5110                                             BuiltinType::Kind kind) {
5111     switch (kind) {
5112     case BuiltinType::Void:       return 'v';
5113     case BuiltinType::Bool:       return 'B';
5114     case BuiltinType::Char_U:
5115     case BuiltinType::UChar:      return 'C';
5116     case BuiltinType::Char16:
5117     case BuiltinType::UShort:     return 'S';
5118     case BuiltinType::Char32:
5119     case BuiltinType::UInt:       return 'I';
5120     case BuiltinType::ULong:
5121         return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
5122     case BuiltinType::UInt128:    return 'T';
5123     case BuiltinType::ULongLong:  return 'Q';
5124     case BuiltinType::Char_S:
5125     case BuiltinType::SChar:      return 'c';
5126     case BuiltinType::Short:      return 's';
5127     case BuiltinType::WChar_S:
5128     case BuiltinType::WChar_U:
5129     case BuiltinType::Int:        return 'i';
5130     case BuiltinType::Long:
5131       return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
5132     case BuiltinType::LongLong:   return 'q';
5133     case BuiltinType::Int128:     return 't';
5134     case BuiltinType::Float:      return 'f';
5135     case BuiltinType::Double:     return 'd';
5136     case BuiltinType::LongDouble: return 'D';
5137     case BuiltinType::NullPtr:    return '*'; // like char*
5138 
5139     case BuiltinType::Half:
5140       // FIXME: potentially need @encodes for these!
5141       return ' ';
5142 
5143     case BuiltinType::ObjCId:
5144     case BuiltinType::ObjCClass:
5145     case BuiltinType::ObjCSel:
5146       llvm_unreachable("@encoding ObjC primitive type");
5147 
5148     // OpenCL and placeholder types don't need @encodings.
5149     case BuiltinType::OCLImage1d:
5150     case BuiltinType::OCLImage1dArray:
5151     case BuiltinType::OCLImage1dBuffer:
5152     case BuiltinType::OCLImage2d:
5153     case BuiltinType::OCLImage2dArray:
5154     case BuiltinType::OCLImage3d:
5155     case BuiltinType::OCLEvent:
5156     case BuiltinType::OCLSampler:
5157     case BuiltinType::Dependent:
5158 #define BUILTIN_TYPE(KIND, ID)
5159 #define PLACEHOLDER_TYPE(KIND, ID) \
5160     case BuiltinType::KIND:
5161 #include "clang/AST/BuiltinTypes.def"
5162       llvm_unreachable("invalid builtin type for @encode");
5163     }
5164     llvm_unreachable("invalid BuiltinType::Kind value");
5165 }
5166 
5167 static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5168   EnumDecl *Enum = ET->getDecl();
5169 
5170   // The encoding of an non-fixed enum type is always 'i', regardless of size.
5171   if (!Enum->isFixed())
5172     return 'i';
5173 
5174   // The encoding of a fixed enum type matches its fixed underlying type.
5175   const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5176   return getObjCEncodingForPrimitiveKind(C, BT->getKind());
5177 }
5178 
5179 static void EncodeBitField(const ASTContext *Ctx, std::string& S,
5180                            QualType T, const FieldDecl *FD) {
5181   assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
5182   S += 'b';
5183   // The NeXT runtime encodes bit fields as b followed by the number of bits.
5184   // The GNU runtime requires more information; bitfields are encoded as b,
5185   // then the offset (in bits) of the first element, then the type of the
5186   // bitfield, then the size in bits.  For example, in this structure:
5187   //
5188   // struct
5189   // {
5190   //    int integer;
5191   //    int flags:2;
5192   // };
5193   // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5194   // runtime, but b32i2 for the GNU runtime.  The reason for this extra
5195   // information is not especially sensible, but we're stuck with it for
5196   // compatibility with GCC, although providing it breaks anything that
5197   // actually uses runtime introspection and wants to work on both runtimes...
5198   if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
5199     const RecordDecl *RD = FD->getParent();
5200     const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
5201     S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
5202     if (const EnumType *ET = T->getAs<EnumType>())
5203       S += ObjCEncodingForEnumType(Ctx, ET);
5204     else {
5205       const BuiltinType *BT = T->castAs<BuiltinType>();
5206       S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5207     }
5208   }
5209   S += llvm::utostr(FD->getBitWidthValue(*Ctx));
5210 }
5211 
5212 // FIXME: Use SmallString for accumulating string.
5213 void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5214                                             bool ExpandPointedToStructures,
5215                                             bool ExpandStructures,
5216                                             const FieldDecl *FD,
5217                                             bool OutermostType,
5218                                             bool EncodingProperty,
5219                                             bool StructField,
5220                                             bool EncodeBlockParameters,
5221                                             bool EncodeClassNames,
5222                                             bool EncodePointerToObjCTypedef) const {
5223   CanQualType CT = getCanonicalType(T);
5224   switch (CT->getTypeClass()) {
5225   case Type::Builtin:
5226   case Type::Enum:
5227     if (FD && FD->isBitField())
5228       return EncodeBitField(this, S, T, FD);
5229     if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5230       S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5231     else
5232       S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
5233     return;
5234 
5235   case Type::Complex: {
5236     const ComplexType *CT = T->castAs<ComplexType>();
5237     S += 'j';
5238     getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
5239                                false);
5240     return;
5241   }
5242 
5243   case Type::Atomic: {
5244     const AtomicType *AT = T->castAs<AtomicType>();
5245     S += 'A';
5246     getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, 0,
5247                                false, false);
5248     return;
5249   }
5250 
5251   // encoding for pointer or reference types.
5252   case Type::Pointer:
5253   case Type::LValueReference:
5254   case Type::RValueReference: {
5255     QualType PointeeTy;
5256     if (isa<PointerType>(CT)) {
5257       const PointerType *PT = T->castAs<PointerType>();
5258       if (PT->isObjCSelType()) {
5259         S += ':';
5260         return;
5261       }
5262       PointeeTy = PT->getPointeeType();
5263     } else {
5264       PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5265     }
5266 
5267     bool isReadOnly = false;
5268     // For historical/compatibility reasons, the read-only qualifier of the
5269     // pointee gets emitted _before_ the '^'.  The read-only qualifier of
5270     // the pointer itself gets ignored, _unless_ we are looking at a typedef!
5271     // Also, do not emit the 'r' for anything but the outermost type!
5272     if (isa<TypedefType>(T.getTypePtr())) {
5273       if (OutermostType && T.isConstQualified()) {
5274         isReadOnly = true;
5275         S += 'r';
5276       }
5277     } else if (OutermostType) {
5278       QualType P = PointeeTy;
5279       while (P->getAs<PointerType>())
5280         P = P->getAs<PointerType>()->getPointeeType();
5281       if (P.isConstQualified()) {
5282         isReadOnly = true;
5283         S += 'r';
5284       }
5285     }
5286     if (isReadOnly) {
5287       // Another legacy compatibility encoding. Some ObjC qualifier and type
5288       // combinations need to be rearranged.
5289       // Rewrite "in const" from "nr" to "rn"
5290       if (StringRef(S).endswith("nr"))
5291         S.replace(S.end()-2, S.end(), "rn");
5292     }
5293 
5294     if (PointeeTy->isCharType()) {
5295       // char pointer types should be encoded as '*' unless it is a
5296       // type that has been typedef'd to 'BOOL'.
5297       if (!isTypeTypedefedAsBOOL(PointeeTy)) {
5298         S += '*';
5299         return;
5300       }
5301     } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
5302       // GCC binary compat: Need to convert "struct objc_class *" to "#".
5303       if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5304         S += '#';
5305         return;
5306       }
5307       // GCC binary compat: Need to convert "struct objc_object *" to "@".
5308       if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5309         S += '@';
5310         return;
5311       }
5312       // fall through...
5313     }
5314     S += '^';
5315     getLegacyIntegralTypeEncoding(PointeeTy);
5316 
5317     getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
5318                                NULL);
5319     return;
5320   }
5321 
5322   case Type::ConstantArray:
5323   case Type::IncompleteArray:
5324   case Type::VariableArray: {
5325     const ArrayType *AT = cast<ArrayType>(CT);
5326 
5327     if (isa<IncompleteArrayType>(AT) && !StructField) {
5328       // Incomplete arrays are encoded as a pointer to the array element.
5329       S += '^';
5330 
5331       getObjCEncodingForTypeImpl(AT->getElementType(), S,
5332                                  false, ExpandStructures, FD);
5333     } else {
5334       S += '[';
5335 
5336       if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
5337         S += llvm::utostr(CAT->getSize().getZExtValue());
5338       else {
5339         //Variable length arrays are encoded as a regular array with 0 elements.
5340         assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5341                "Unknown array type!");
5342         S += '0';
5343       }
5344 
5345       getObjCEncodingForTypeImpl(AT->getElementType(), S,
5346                                  false, ExpandStructures, FD);
5347       S += ']';
5348     }
5349     return;
5350   }
5351 
5352   case Type::FunctionNoProto:
5353   case Type::FunctionProto:
5354     S += '?';
5355     return;
5356 
5357   case Type::Record: {
5358     RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
5359     S += RDecl->isUnion() ? '(' : '{';
5360     // Anonymous structures print as '?'
5361     if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5362       S += II->getName();
5363       if (ClassTemplateSpecializationDecl *Spec
5364           = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5365         const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
5366         llvm::raw_string_ostream OS(S);
5367         TemplateSpecializationType::PrintTemplateArgumentList(OS,
5368                                             TemplateArgs.data(),
5369                                             TemplateArgs.size(),
5370                                             (*this).getPrintingPolicy());
5371       }
5372     } else {
5373       S += '?';
5374     }
5375     if (ExpandStructures) {
5376       S += '=';
5377       if (!RDecl->isUnion()) {
5378         getObjCEncodingForStructureImpl(RDecl, S, FD);
5379       } else {
5380         for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5381                                      FieldEnd = RDecl->field_end();
5382              Field != FieldEnd; ++Field) {
5383           if (FD) {
5384             S += '"';
5385             S += Field->getNameAsString();
5386             S += '"';
5387           }
5388 
5389           // Special case bit-fields.
5390           if (Field->isBitField()) {
5391             getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
5392                                        *Field);
5393           } else {
5394             QualType qt = Field->getType();
5395             getLegacyIntegralTypeEncoding(qt);
5396             getObjCEncodingForTypeImpl(qt, S, false, true,
5397                                        FD, /*OutermostType*/false,
5398                                        /*EncodingProperty*/false,
5399                                        /*StructField*/true);
5400           }
5401         }
5402       }
5403     }
5404     S += RDecl->isUnion() ? ')' : '}';
5405     return;
5406   }
5407 
5408   case Type::BlockPointer: {
5409     const BlockPointerType *BT = T->castAs<BlockPointerType>();
5410     S += "@?"; // Unlike a pointer-to-function, which is "^?".
5411     if (EncodeBlockParameters) {
5412       const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
5413 
5414       S += '<';
5415       // Block return type
5416       getObjCEncodingForTypeImpl(
5417           FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
5418           FD, false /* OutermostType */, EncodingProperty,
5419           false /* StructField */, EncodeBlockParameters, EncodeClassNames);
5420       // Block self
5421       S += "@?";
5422       // Block parameters
5423       if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
5424         for (FunctionProtoType::param_type_iterator I = FPT->param_type_begin(),
5425                                                     E = FPT->param_type_end();
5426              I && (I != E); ++I) {
5427           getObjCEncodingForTypeImpl(*I, S,
5428                                      ExpandPointedToStructures,
5429                                      ExpandStructures,
5430                                      FD,
5431                                      false /* OutermostType */,
5432                                      EncodingProperty,
5433                                      false /* StructField */,
5434                                      EncodeBlockParameters,
5435                                      EncodeClassNames);
5436         }
5437       }
5438       S += '>';
5439     }
5440     return;
5441   }
5442 
5443   case Type::ObjCObject: {
5444     // hack to match legacy encoding of *id and *Class
5445     QualType Ty = getObjCObjectPointerType(CT);
5446     if (Ty->isObjCIdType()) {
5447       S += "{objc_object=}";
5448       return;
5449     }
5450     else if (Ty->isObjCClassType()) {
5451       S += "{objc_class=}";
5452       return;
5453     }
5454   }
5455 
5456   case Type::ObjCInterface: {
5457     // Ignore protocol qualifiers when mangling at this level.
5458     T = T->castAs<ObjCObjectType>()->getBaseType();
5459 
5460     // The assumption seems to be that this assert will succeed
5461     // because nested levels will have filtered out 'id' and 'Class'.
5462     const ObjCInterfaceType *OIT = T->castAs<ObjCInterfaceType>();
5463     // @encode(class_name)
5464     ObjCInterfaceDecl *OI = OIT->getDecl();
5465     S += '{';
5466     const IdentifierInfo *II = OI->getIdentifier();
5467     S += II->getName();
5468     S += '=';
5469     SmallVector<const ObjCIvarDecl*, 32> Ivars;
5470     DeepCollectObjCIvars(OI, true, Ivars);
5471     for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5472       const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
5473       if (Field->isBitField())
5474         getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
5475       else
5476         getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5477                                    false, false, false, false, false,
5478                                    EncodePointerToObjCTypedef);
5479     }
5480     S += '}';
5481     return;
5482   }
5483 
5484   case Type::ObjCObjectPointer: {
5485     const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
5486     if (OPT->isObjCIdType()) {
5487       S += '@';
5488       return;
5489     }
5490 
5491     if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5492       // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5493       // Since this is a binary compatibility issue, need to consult with runtime
5494       // folks. Fortunately, this is a *very* obsure construct.
5495       S += '#';
5496       return;
5497     }
5498 
5499     if (OPT->isObjCQualifiedIdType()) {
5500       getObjCEncodingForTypeImpl(getObjCIdType(), S,
5501                                  ExpandPointedToStructures,
5502                                  ExpandStructures, FD);
5503       if (FD || EncodingProperty || EncodeClassNames) {
5504         // Note that we do extended encoding of protocol qualifer list
5505         // Only when doing ivar or property encoding.
5506         S += '"';
5507         for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5508              E = OPT->qual_end(); I != E; ++I) {
5509           S += '<';
5510           S += (*I)->getNameAsString();
5511           S += '>';
5512         }
5513         S += '"';
5514       }
5515       return;
5516     }
5517 
5518     QualType PointeeTy = OPT->getPointeeType();
5519     if (!EncodingProperty &&
5520         isa<TypedefType>(PointeeTy.getTypePtr()) &&
5521         !EncodePointerToObjCTypedef) {
5522       // Another historical/compatibility reason.
5523       // We encode the underlying type which comes out as
5524       // {...};
5525       S += '^';
5526       if (FD && OPT->getInterfaceDecl()) {
5527         // Prevent recursive encoding of fields in some rare cases.
5528         ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
5529         SmallVector<const ObjCIvarDecl*, 32> Ivars;
5530         DeepCollectObjCIvars(OI, true, Ivars);
5531         for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5532           if (cast<FieldDecl>(Ivars[i]) == FD) {
5533             S += '{';
5534             S += OI->getIdentifier()->getName();
5535             S += '}';
5536             return;
5537           }
5538         }
5539       }
5540       getObjCEncodingForTypeImpl(PointeeTy, S,
5541                                  false, ExpandPointedToStructures,
5542                                  NULL,
5543                                  false, false, false, false, false,
5544                                  /*EncodePointerToObjCTypedef*/true);
5545       return;
5546     }
5547 
5548     S += '@';
5549     if (OPT->getInterfaceDecl() &&
5550         (FD || EncodingProperty || EncodeClassNames)) {
5551       S += '"';
5552       S += OPT->getInterfaceDecl()->getIdentifier()->getName();
5553       for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5554            E = OPT->qual_end(); I != E; ++I) {
5555         S += '<';
5556         S += (*I)->getNameAsString();
5557         S += '>';
5558       }
5559       S += '"';
5560     }
5561     return;
5562   }
5563 
5564   // gcc just blithely ignores member pointers.
5565   // FIXME: we shoul do better than that.  'M' is available.
5566   case Type::MemberPointer:
5567     return;
5568 
5569   case Type::Vector:
5570   case Type::ExtVector:
5571     // This matches gcc's encoding, even though technically it is
5572     // insufficient.
5573     // FIXME. We should do a better job than gcc.
5574     return;
5575 
5576   case Type::Auto:
5577     // We could see an undeduced auto type here during error recovery.
5578     // Just ignore it.
5579     return;
5580 
5581 #define ABSTRACT_TYPE(KIND, BASE)
5582 #define TYPE(KIND, BASE)
5583 #define DEPENDENT_TYPE(KIND, BASE) \
5584   case Type::KIND:
5585 #define NON_CANONICAL_TYPE(KIND, BASE) \
5586   case Type::KIND:
5587 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5588   case Type::KIND:
5589 #include "clang/AST/TypeNodes.def"
5590     llvm_unreachable("@encode for dependent type!");
5591   }
5592   llvm_unreachable("bad type kind!");
5593 }
5594 
5595 void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5596                                                  std::string &S,
5597                                                  const FieldDecl *FD,
5598                                                  bool includeVBases) const {
5599   assert(RDecl && "Expected non-null RecordDecl");
5600   assert(!RDecl->isUnion() && "Should not be called for unions");
5601   if (!RDecl->getDefinition())
5602     return;
5603 
5604   CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5605   std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5606   const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5607 
5608   if (CXXRec) {
5609     for (CXXRecordDecl::base_class_iterator
5610            BI = CXXRec->bases_begin(),
5611            BE = CXXRec->bases_end(); BI != BE; ++BI) {
5612       if (!BI->isVirtual()) {
5613         CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
5614         if (base->isEmpty())
5615           continue;
5616         uint64_t offs = toBits(layout.getBaseClassOffset(base));
5617         FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5618                                   std::make_pair(offs, base));
5619       }
5620     }
5621   }
5622 
5623   unsigned i = 0;
5624   for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5625                                FieldEnd = RDecl->field_end();
5626        Field != FieldEnd; ++Field, ++i) {
5627     uint64_t offs = layout.getFieldOffset(i);
5628     FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5629                               std::make_pair(offs, *Field));
5630   }
5631 
5632   if (CXXRec && includeVBases) {
5633     for (CXXRecordDecl::base_class_iterator
5634            BI = CXXRec->vbases_begin(),
5635            BE = CXXRec->vbases_end(); BI != BE; ++BI) {
5636       CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
5637       if (base->isEmpty())
5638         continue;
5639       uint64_t offs = toBits(layout.getVBaseClassOffset(base));
5640       if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
5641           FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
5642         FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5643                                   std::make_pair(offs, base));
5644     }
5645   }
5646 
5647   CharUnits size;
5648   if (CXXRec) {
5649     size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5650   } else {
5651     size = layout.getSize();
5652   }
5653 
5654 #ifndef NDEBUG
5655   uint64_t CurOffs = 0;
5656 #endif
5657   std::multimap<uint64_t, NamedDecl *>::iterator
5658     CurLayObj = FieldOrBaseOffsets.begin();
5659 
5660   if (CXXRec && CXXRec->isDynamicClass() &&
5661       (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
5662     if (FD) {
5663       S += "\"_vptr$";
5664       std::string recname = CXXRec->getNameAsString();
5665       if (recname.empty()) recname = "?";
5666       S += recname;
5667       S += '"';
5668     }
5669     S += "^^?";
5670 #ifndef NDEBUG
5671     CurOffs += getTypeSize(VoidPtrTy);
5672 #endif
5673   }
5674 
5675   if (!RDecl->hasFlexibleArrayMember()) {
5676     // Mark the end of the structure.
5677     uint64_t offs = toBits(size);
5678     FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5679                               std::make_pair(offs, (NamedDecl*)0));
5680   }
5681 
5682   for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
5683 #ifndef NDEBUG
5684     assert(CurOffs <= CurLayObj->first);
5685     if (CurOffs < CurLayObj->first) {
5686       uint64_t padding = CurLayObj->first - CurOffs;
5687       // FIXME: There doesn't seem to be a way to indicate in the encoding that
5688       // packing/alignment of members is different that normal, in which case
5689       // the encoding will be out-of-sync with the real layout.
5690       // If the runtime switches to just consider the size of types without
5691       // taking into account alignment, we could make padding explicit in the
5692       // encoding (e.g. using arrays of chars). The encoding strings would be
5693       // longer then though.
5694       CurOffs += padding;
5695     }
5696 #endif
5697 
5698     NamedDecl *dcl = CurLayObj->second;
5699     if (dcl == 0)
5700       break; // reached end of structure.
5701 
5702     if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5703       // We expand the bases without their virtual bases since those are going
5704       // in the initial structure. Note that this differs from gcc which
5705       // expands virtual bases each time one is encountered in the hierarchy,
5706       // making the encoding type bigger than it really is.
5707       getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
5708       assert(!base->isEmpty());
5709 #ifndef NDEBUG
5710       CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
5711 #endif
5712     } else {
5713       FieldDecl *field = cast<FieldDecl>(dcl);
5714       if (FD) {
5715         S += '"';
5716         S += field->getNameAsString();
5717         S += '"';
5718       }
5719 
5720       if (field->isBitField()) {
5721         EncodeBitField(this, S, field->getType(), field);
5722 #ifndef NDEBUG
5723         CurOffs += field->getBitWidthValue(*this);
5724 #endif
5725       } else {
5726         QualType qt = field->getType();
5727         getLegacyIntegralTypeEncoding(qt);
5728         getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5729                                    /*OutermostType*/false,
5730                                    /*EncodingProperty*/false,
5731                                    /*StructField*/true);
5732 #ifndef NDEBUG
5733         CurOffs += getTypeSize(field->getType());
5734 #endif
5735       }
5736     }
5737   }
5738 }
5739 
5740 void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
5741                                                  std::string& S) const {
5742   if (QT & Decl::OBJC_TQ_In)
5743     S += 'n';
5744   if (QT & Decl::OBJC_TQ_Inout)
5745     S += 'N';
5746   if (QT & Decl::OBJC_TQ_Out)
5747     S += 'o';
5748   if (QT & Decl::OBJC_TQ_Bycopy)
5749     S += 'O';
5750   if (QT & Decl::OBJC_TQ_Byref)
5751     S += 'R';
5752   if (QT & Decl::OBJC_TQ_Oneway)
5753     S += 'V';
5754 }
5755 
5756 TypedefDecl *ASTContext::getObjCIdDecl() const {
5757   if (!ObjCIdDecl) {
5758     QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
5759     T = getObjCObjectPointerType(T);
5760     ObjCIdDecl = buildImplicitTypedef(T, "id");
5761   }
5762   return ObjCIdDecl;
5763 }
5764 
5765 TypedefDecl *ASTContext::getObjCSelDecl() const {
5766   if (!ObjCSelDecl) {
5767     QualType T = getPointerType(ObjCBuiltinSelTy);
5768     ObjCSelDecl = buildImplicitTypedef(T, "SEL");
5769   }
5770   return ObjCSelDecl;
5771 }
5772 
5773 TypedefDecl *ASTContext::getObjCClassDecl() const {
5774   if (!ObjCClassDecl) {
5775     QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5776     T = getObjCObjectPointerType(T);
5777     ObjCClassDecl = buildImplicitTypedef(T, "Class");
5778   }
5779   return ObjCClassDecl;
5780 }
5781 
5782 ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5783   if (!ObjCProtocolClassDecl) {
5784     ObjCProtocolClassDecl
5785       = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5786                                   SourceLocation(),
5787                                   &Idents.get("Protocol"),
5788                                   /*PrevDecl=*/0,
5789                                   SourceLocation(), true);
5790   }
5791 
5792   return ObjCProtocolClassDecl;
5793 }
5794 
5795 //===----------------------------------------------------------------------===//
5796 // __builtin_va_list Construction Functions
5797 //===----------------------------------------------------------------------===//
5798 
5799 static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5800   // typedef char* __builtin_va_list;
5801   QualType T = Context->getPointerType(Context->CharTy);
5802   return Context->buildImplicitTypedef(T, "__builtin_va_list");
5803 }
5804 
5805 static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5806   // typedef void* __builtin_va_list;
5807   QualType T = Context->getPointerType(Context->VoidTy);
5808   return Context->buildImplicitTypedef(T, "__builtin_va_list");
5809 }
5810 
5811 static TypedefDecl *
5812 CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
5813   // struct __va_list
5814   RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
5815   if (Context->getLangOpts().CPlusPlus) {
5816     // namespace std { struct __va_list {
5817     NamespaceDecl *NS;
5818     NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5819                                Context->getTranslationUnitDecl(),
5820                                /*Inline*/false, SourceLocation(),
5821                                SourceLocation(), &Context->Idents.get("std"),
5822                                /*PrevDecl*/0);
5823     NS->setImplicit();
5824     VaListTagDecl->setDeclContext(NS);
5825   }
5826 
5827   VaListTagDecl->startDefinition();
5828 
5829   const size_t NumFields = 5;
5830   QualType FieldTypes[NumFields];
5831   const char *FieldNames[NumFields];
5832 
5833   // void *__stack;
5834   FieldTypes[0] = Context->getPointerType(Context->VoidTy);
5835   FieldNames[0] = "__stack";
5836 
5837   // void *__gr_top;
5838   FieldTypes[1] = Context->getPointerType(Context->VoidTy);
5839   FieldNames[1] = "__gr_top";
5840 
5841   // void *__vr_top;
5842   FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5843   FieldNames[2] = "__vr_top";
5844 
5845   // int __gr_offs;
5846   FieldTypes[3] = Context->IntTy;
5847   FieldNames[3] = "__gr_offs";
5848 
5849   // int __vr_offs;
5850   FieldTypes[4] = Context->IntTy;
5851   FieldNames[4] = "__vr_offs";
5852 
5853   // Create fields
5854   for (unsigned i = 0; i < NumFields; ++i) {
5855     FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5856                                          VaListTagDecl,
5857                                          SourceLocation(),
5858                                          SourceLocation(),
5859                                          &Context->Idents.get(FieldNames[i]),
5860                                          FieldTypes[i], /*TInfo=*/0,
5861                                          /*BitWidth=*/0,
5862                                          /*Mutable=*/false,
5863                                          ICIS_NoInit);
5864     Field->setAccess(AS_public);
5865     VaListTagDecl->addDecl(Field);
5866   }
5867   VaListTagDecl->completeDefinition();
5868   QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5869   Context->VaListTagTy = VaListTagType;
5870 
5871   // } __builtin_va_list;
5872   return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
5873 }
5874 
5875 static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5876   // typedef struct __va_list_tag {
5877   RecordDecl *VaListTagDecl;
5878 
5879   VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
5880   VaListTagDecl->startDefinition();
5881 
5882   const size_t NumFields = 5;
5883   QualType FieldTypes[NumFields];
5884   const char *FieldNames[NumFields];
5885 
5886   //   unsigned char gpr;
5887   FieldTypes[0] = Context->UnsignedCharTy;
5888   FieldNames[0] = "gpr";
5889 
5890   //   unsigned char fpr;
5891   FieldTypes[1] = Context->UnsignedCharTy;
5892   FieldNames[1] = "fpr";
5893 
5894   //   unsigned short reserved;
5895   FieldTypes[2] = Context->UnsignedShortTy;
5896   FieldNames[2] = "reserved";
5897 
5898   //   void* overflow_arg_area;
5899   FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5900   FieldNames[3] = "overflow_arg_area";
5901 
5902   //   void* reg_save_area;
5903   FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5904   FieldNames[4] = "reg_save_area";
5905 
5906   // Create fields
5907   for (unsigned i = 0; i < NumFields; ++i) {
5908     FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5909                                          SourceLocation(),
5910                                          SourceLocation(),
5911                                          &Context->Idents.get(FieldNames[i]),
5912                                          FieldTypes[i], /*TInfo=*/0,
5913                                          /*BitWidth=*/0,
5914                                          /*Mutable=*/false,
5915                                          ICIS_NoInit);
5916     Field->setAccess(AS_public);
5917     VaListTagDecl->addDecl(Field);
5918   }
5919   VaListTagDecl->completeDefinition();
5920   QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5921   Context->VaListTagTy = VaListTagType;
5922 
5923   // } __va_list_tag;
5924   TypedefDecl *VaListTagTypedefDecl =
5925       Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
5926 
5927   QualType VaListTagTypedefType =
5928     Context->getTypedefType(VaListTagTypedefDecl);
5929 
5930   // typedef __va_list_tag __builtin_va_list[1];
5931   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5932   QualType VaListTagArrayType
5933     = Context->getConstantArrayType(VaListTagTypedefType,
5934                                     Size, ArrayType::Normal, 0);
5935   return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
5936 }
5937 
5938 static TypedefDecl *
5939 CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5940   // typedef struct __va_list_tag {
5941   RecordDecl *VaListTagDecl;
5942   VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
5943   VaListTagDecl->startDefinition();
5944 
5945   const size_t NumFields = 4;
5946   QualType FieldTypes[NumFields];
5947   const char *FieldNames[NumFields];
5948 
5949   //   unsigned gp_offset;
5950   FieldTypes[0] = Context->UnsignedIntTy;
5951   FieldNames[0] = "gp_offset";
5952 
5953   //   unsigned fp_offset;
5954   FieldTypes[1] = Context->UnsignedIntTy;
5955   FieldNames[1] = "fp_offset";
5956 
5957   //   void* overflow_arg_area;
5958   FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5959   FieldNames[2] = "overflow_arg_area";
5960 
5961   //   void* reg_save_area;
5962   FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5963   FieldNames[3] = "reg_save_area";
5964 
5965   // Create fields
5966   for (unsigned i = 0; i < NumFields; ++i) {
5967     FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5968                                          VaListTagDecl,
5969                                          SourceLocation(),
5970                                          SourceLocation(),
5971                                          &Context->Idents.get(FieldNames[i]),
5972                                          FieldTypes[i], /*TInfo=*/0,
5973                                          /*BitWidth=*/0,
5974                                          /*Mutable=*/false,
5975                                          ICIS_NoInit);
5976     Field->setAccess(AS_public);
5977     VaListTagDecl->addDecl(Field);
5978   }
5979   VaListTagDecl->completeDefinition();
5980   QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5981   Context->VaListTagTy = VaListTagType;
5982 
5983   // } __va_list_tag;
5984   TypedefDecl *VaListTagTypedefDecl =
5985       Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
5986 
5987   QualType VaListTagTypedefType =
5988     Context->getTypedefType(VaListTagTypedefDecl);
5989 
5990   // typedef __va_list_tag __builtin_va_list[1];
5991   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5992   QualType VaListTagArrayType
5993     = Context->getConstantArrayType(VaListTagTypedefType,
5994                                       Size, ArrayType::Normal,0);
5995   return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
5996 }
5997 
5998 static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5999   // typedef int __builtin_va_list[4];
6000   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
6001   QualType IntArrayType
6002     = Context->getConstantArrayType(Context->IntTy,
6003 				    Size, ArrayType::Normal, 0);
6004   return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
6005 }
6006 
6007 static TypedefDecl *
6008 CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
6009   // struct __va_list
6010   RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
6011   if (Context->getLangOpts().CPlusPlus) {
6012     // namespace std { struct __va_list {
6013     NamespaceDecl *NS;
6014     NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6015                                Context->getTranslationUnitDecl(),
6016                                /*Inline*/false, SourceLocation(),
6017                                SourceLocation(), &Context->Idents.get("std"),
6018                                /*PrevDecl*/0);
6019     NS->setImplicit();
6020     VaListDecl->setDeclContext(NS);
6021   }
6022 
6023   VaListDecl->startDefinition();
6024 
6025   // void * __ap;
6026   FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6027                                        VaListDecl,
6028                                        SourceLocation(),
6029                                        SourceLocation(),
6030                                        &Context->Idents.get("__ap"),
6031                                        Context->getPointerType(Context->VoidTy),
6032                                        /*TInfo=*/0,
6033                                        /*BitWidth=*/0,
6034                                        /*Mutable=*/false,
6035                                        ICIS_NoInit);
6036   Field->setAccess(AS_public);
6037   VaListDecl->addDecl(Field);
6038 
6039   // };
6040   VaListDecl->completeDefinition();
6041 
6042   // typedef struct __va_list __builtin_va_list;
6043   QualType T = Context->getRecordType(VaListDecl);
6044   return Context->buildImplicitTypedef(T, "__builtin_va_list");
6045 }
6046 
6047 static TypedefDecl *
6048 CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
6049   // typedef struct __va_list_tag {
6050   RecordDecl *VaListTagDecl;
6051   VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
6052   VaListTagDecl->startDefinition();
6053 
6054   const size_t NumFields = 4;
6055   QualType FieldTypes[NumFields];
6056   const char *FieldNames[NumFields];
6057 
6058   //   long __gpr;
6059   FieldTypes[0] = Context->LongTy;
6060   FieldNames[0] = "__gpr";
6061 
6062   //   long __fpr;
6063   FieldTypes[1] = Context->LongTy;
6064   FieldNames[1] = "__fpr";
6065 
6066   //   void *__overflow_arg_area;
6067   FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6068   FieldNames[2] = "__overflow_arg_area";
6069 
6070   //   void *__reg_save_area;
6071   FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6072   FieldNames[3] = "__reg_save_area";
6073 
6074   // Create fields
6075   for (unsigned i = 0; i < NumFields; ++i) {
6076     FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6077                                          VaListTagDecl,
6078                                          SourceLocation(),
6079                                          SourceLocation(),
6080                                          &Context->Idents.get(FieldNames[i]),
6081                                          FieldTypes[i], /*TInfo=*/0,
6082                                          /*BitWidth=*/0,
6083                                          /*Mutable=*/false,
6084                                          ICIS_NoInit);
6085     Field->setAccess(AS_public);
6086     VaListTagDecl->addDecl(Field);
6087   }
6088   VaListTagDecl->completeDefinition();
6089   QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6090   Context->VaListTagTy = VaListTagType;
6091 
6092   // } __va_list_tag;
6093   TypedefDecl *VaListTagTypedefDecl =
6094       Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
6095   QualType VaListTagTypedefType =
6096     Context->getTypedefType(VaListTagTypedefDecl);
6097 
6098   // typedef __va_list_tag __builtin_va_list[1];
6099   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6100   QualType VaListTagArrayType
6101     = Context->getConstantArrayType(VaListTagTypedefType,
6102                                       Size, ArrayType::Normal,0);
6103 
6104   return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
6105 }
6106 
6107 static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6108                                      TargetInfo::BuiltinVaListKind Kind) {
6109   switch (Kind) {
6110   case TargetInfo::CharPtrBuiltinVaList:
6111     return CreateCharPtrBuiltinVaListDecl(Context);
6112   case TargetInfo::VoidPtrBuiltinVaList:
6113     return CreateVoidPtrBuiltinVaListDecl(Context);
6114   case TargetInfo::AArch64ABIBuiltinVaList:
6115     return CreateAArch64ABIBuiltinVaListDecl(Context);
6116   case TargetInfo::PowerABIBuiltinVaList:
6117     return CreatePowerABIBuiltinVaListDecl(Context);
6118   case TargetInfo::X86_64ABIBuiltinVaList:
6119     return CreateX86_64ABIBuiltinVaListDecl(Context);
6120   case TargetInfo::PNaClABIBuiltinVaList:
6121     return CreatePNaClABIBuiltinVaListDecl(Context);
6122   case TargetInfo::AAPCSABIBuiltinVaList:
6123     return CreateAAPCSABIBuiltinVaListDecl(Context);
6124   case TargetInfo::SystemZBuiltinVaList:
6125     return CreateSystemZBuiltinVaListDecl(Context);
6126   }
6127 
6128   llvm_unreachable("Unhandled __builtin_va_list type kind");
6129 }
6130 
6131 TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
6132   if (!BuiltinVaListDecl) {
6133     BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
6134     assert(BuiltinVaListDecl->isImplicit());
6135   }
6136 
6137   return BuiltinVaListDecl;
6138 }
6139 
6140 QualType ASTContext::getVaListTagType() const {
6141   // Force the creation of VaListTagTy by building the __builtin_va_list
6142   // declaration.
6143   if (VaListTagTy.isNull())
6144     (void) getBuiltinVaListDecl();
6145 
6146   return VaListTagTy;
6147 }
6148 
6149 void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
6150   assert(ObjCConstantStringType.isNull() &&
6151          "'NSConstantString' type already set!");
6152 
6153   ObjCConstantStringType = getObjCInterfaceType(Decl);
6154 }
6155 
6156 /// \brief Retrieve the template name that corresponds to a non-empty
6157 /// lookup.
6158 TemplateName
6159 ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6160                                       UnresolvedSetIterator End) const {
6161   unsigned size = End - Begin;
6162   assert(size > 1 && "set is not overloaded!");
6163 
6164   void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6165                           size * sizeof(FunctionTemplateDecl*));
6166   OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6167 
6168   NamedDecl **Storage = OT->getStorage();
6169   for (UnresolvedSetIterator I = Begin; I != End; ++I) {
6170     NamedDecl *D = *I;
6171     assert(isa<FunctionTemplateDecl>(D) ||
6172            (isa<UsingShadowDecl>(D) &&
6173             isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6174     *Storage++ = D;
6175   }
6176 
6177   return TemplateName(OT);
6178 }
6179 
6180 /// \brief Retrieve the template name that represents a qualified
6181 /// template name such as \c std::vector.
6182 TemplateName
6183 ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6184                                      bool TemplateKeyword,
6185                                      TemplateDecl *Template) const {
6186   assert(NNS && "Missing nested-name-specifier in qualified template name");
6187 
6188   // FIXME: Canonicalization?
6189   llvm::FoldingSetNodeID ID;
6190   QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6191 
6192   void *InsertPos = 0;
6193   QualifiedTemplateName *QTN =
6194     QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6195   if (!QTN) {
6196     QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6197         QualifiedTemplateName(NNS, TemplateKeyword, Template);
6198     QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6199   }
6200 
6201   return TemplateName(QTN);
6202 }
6203 
6204 /// \brief Retrieve the template name that represents a dependent
6205 /// template name such as \c MetaFun::template apply.
6206 TemplateName
6207 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6208                                      const IdentifierInfo *Name) const {
6209   assert((!NNS || NNS->isDependent()) &&
6210          "Nested name specifier must be dependent");
6211 
6212   llvm::FoldingSetNodeID ID;
6213   DependentTemplateName::Profile(ID, NNS, Name);
6214 
6215   void *InsertPos = 0;
6216   DependentTemplateName *QTN =
6217     DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6218 
6219   if (QTN)
6220     return TemplateName(QTN);
6221 
6222   NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6223   if (CanonNNS == NNS) {
6224     QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6225         DependentTemplateName(NNS, Name);
6226   } else {
6227     TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
6228     QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6229         DependentTemplateName(NNS, Name, Canon);
6230     DependentTemplateName *CheckQTN =
6231       DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6232     assert(!CheckQTN && "Dependent type name canonicalization broken");
6233     (void)CheckQTN;
6234   }
6235 
6236   DependentTemplateNames.InsertNode(QTN, InsertPos);
6237   return TemplateName(QTN);
6238 }
6239 
6240 /// \brief Retrieve the template name that represents a dependent
6241 /// template name such as \c MetaFun::template operator+.
6242 TemplateName
6243 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6244                                      OverloadedOperatorKind Operator) const {
6245   assert((!NNS || NNS->isDependent()) &&
6246          "Nested name specifier must be dependent");
6247 
6248   llvm::FoldingSetNodeID ID;
6249   DependentTemplateName::Profile(ID, NNS, Operator);
6250 
6251   void *InsertPos = 0;
6252   DependentTemplateName *QTN
6253     = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6254 
6255   if (QTN)
6256     return TemplateName(QTN);
6257 
6258   NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6259   if (CanonNNS == NNS) {
6260     QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6261         DependentTemplateName(NNS, Operator);
6262   } else {
6263     TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
6264     QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6265         DependentTemplateName(NNS, Operator, Canon);
6266 
6267     DependentTemplateName *CheckQTN
6268       = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6269     assert(!CheckQTN && "Dependent template name canonicalization broken");
6270     (void)CheckQTN;
6271   }
6272 
6273   DependentTemplateNames.InsertNode(QTN, InsertPos);
6274   return TemplateName(QTN);
6275 }
6276 
6277 TemplateName
6278 ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6279                                          TemplateName replacement) const {
6280   llvm::FoldingSetNodeID ID;
6281   SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
6282 
6283   void *insertPos = 0;
6284   SubstTemplateTemplateParmStorage *subst
6285     = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6286 
6287   if (!subst) {
6288     subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6289     SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6290   }
6291 
6292   return TemplateName(subst);
6293 }
6294 
6295 TemplateName
6296 ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6297                                        const TemplateArgument &ArgPack) const {
6298   ASTContext &Self = const_cast<ASTContext &>(*this);
6299   llvm::FoldingSetNodeID ID;
6300   SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
6301 
6302   void *InsertPos = 0;
6303   SubstTemplateTemplateParmPackStorage *Subst
6304     = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6305 
6306   if (!Subst) {
6307     Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
6308                                                            ArgPack.pack_size(),
6309                                                          ArgPack.pack_begin());
6310     SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6311   }
6312 
6313   return TemplateName(Subst);
6314 }
6315 
6316 /// getFromTargetType - Given one of the integer types provided by
6317 /// TargetInfo, produce the corresponding type. The unsigned @p Type
6318 /// is actually a value of type @c TargetInfo::IntType.
6319 CanQualType ASTContext::getFromTargetType(unsigned Type) const {
6320   switch (Type) {
6321   case TargetInfo::NoInt: return CanQualType();
6322   case TargetInfo::SignedChar: return SignedCharTy;
6323   case TargetInfo::UnsignedChar: return UnsignedCharTy;
6324   case TargetInfo::SignedShort: return ShortTy;
6325   case TargetInfo::UnsignedShort: return UnsignedShortTy;
6326   case TargetInfo::SignedInt: return IntTy;
6327   case TargetInfo::UnsignedInt: return UnsignedIntTy;
6328   case TargetInfo::SignedLong: return LongTy;
6329   case TargetInfo::UnsignedLong: return UnsignedLongTy;
6330   case TargetInfo::SignedLongLong: return LongLongTy;
6331   case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6332   }
6333 
6334   llvm_unreachable("Unhandled TargetInfo::IntType value");
6335 }
6336 
6337 //===----------------------------------------------------------------------===//
6338 //                        Type Predicates.
6339 //===----------------------------------------------------------------------===//
6340 
6341 /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6342 /// garbage collection attribute.
6343 ///
6344 Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
6345   if (getLangOpts().getGC() == LangOptions::NonGC)
6346     return Qualifiers::GCNone;
6347 
6348   assert(getLangOpts().ObjC1);
6349   Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6350 
6351   // Default behaviour under objective-C's gc is for ObjC pointers
6352   // (or pointers to them) be treated as though they were declared
6353   // as __strong.
6354   if (GCAttrs == Qualifiers::GCNone) {
6355     if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6356       return Qualifiers::Strong;
6357     else if (Ty->isPointerType())
6358       return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6359   } else {
6360     // It's not valid to set GC attributes on anything that isn't a
6361     // pointer.
6362 #ifndef NDEBUG
6363     QualType CT = Ty->getCanonicalTypeInternal();
6364     while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6365       CT = AT->getElementType();
6366     assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6367 #endif
6368   }
6369   return GCAttrs;
6370 }
6371 
6372 //===----------------------------------------------------------------------===//
6373 //                        Type Compatibility Testing
6374 //===----------------------------------------------------------------------===//
6375 
6376 /// areCompatVectorTypes - Return true if the two specified vector types are
6377 /// compatible.
6378 static bool areCompatVectorTypes(const VectorType *LHS,
6379                                  const VectorType *RHS) {
6380   assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
6381   return LHS->getElementType() == RHS->getElementType() &&
6382          LHS->getNumElements() == RHS->getNumElements();
6383 }
6384 
6385 bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6386                                           QualType SecondVec) {
6387   assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6388   assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6389 
6390   if (hasSameUnqualifiedType(FirstVec, SecondVec))
6391     return true;
6392 
6393   // Treat Neon vector types and most AltiVec vector types as if they are the
6394   // equivalent GCC vector types.
6395   const VectorType *First = FirstVec->getAs<VectorType>();
6396   const VectorType *Second = SecondVec->getAs<VectorType>();
6397   if (First->getNumElements() == Second->getNumElements() &&
6398       hasSameType(First->getElementType(), Second->getElementType()) &&
6399       First->getVectorKind() != VectorType::AltiVecPixel &&
6400       First->getVectorKind() != VectorType::AltiVecBool &&
6401       Second->getVectorKind() != VectorType::AltiVecPixel &&
6402       Second->getVectorKind() != VectorType::AltiVecBool)
6403     return true;
6404 
6405   return false;
6406 }
6407 
6408 //===----------------------------------------------------------------------===//
6409 // ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6410 //===----------------------------------------------------------------------===//
6411 
6412 /// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6413 /// inheritance hierarchy of 'rProto'.
6414 bool
6415 ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6416                                            ObjCProtocolDecl *rProto) const {
6417   if (declaresSameEntity(lProto, rProto))
6418     return true;
6419   for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
6420        E = rProto->protocol_end(); PI != E; ++PI)
6421     if (ProtocolCompatibleWithProtocol(lProto, *PI))
6422       return true;
6423   return false;
6424 }
6425 
6426 /// ObjCQualifiedClassTypesAreCompatible - compare  Class<pr,...> and
6427 /// Class<pr1, ...>.
6428 bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6429                                                       QualType rhs) {
6430   const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6431   const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6432   assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6433 
6434   for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6435        E = lhsQID->qual_end(); I != E; ++I) {
6436     bool match = false;
6437     ObjCProtocolDecl *lhsProto = *I;
6438     for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6439          E = rhsOPT->qual_end(); J != E; ++J) {
6440       ObjCProtocolDecl *rhsProto = *J;
6441       if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6442         match = true;
6443         break;
6444       }
6445     }
6446     if (!match)
6447       return false;
6448   }
6449   return true;
6450 }
6451 
6452 /// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6453 /// ObjCQualifiedIDType.
6454 bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6455                                                    bool compare) {
6456   // Allow id<P..> and an 'id' or void* type in all cases.
6457   if (lhs->isVoidPointerType() ||
6458       lhs->isObjCIdType() || lhs->isObjCClassType())
6459     return true;
6460   else if (rhs->isVoidPointerType() ||
6461            rhs->isObjCIdType() || rhs->isObjCClassType())
6462     return true;
6463 
6464   if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
6465     const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6466 
6467     if (!rhsOPT) return false;
6468 
6469     if (rhsOPT->qual_empty()) {
6470       // If the RHS is a unqualified interface pointer "NSString*",
6471       // make sure we check the class hierarchy.
6472       if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6473         for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6474              E = lhsQID->qual_end(); I != E; ++I) {
6475           // when comparing an id<P> on lhs with a static type on rhs,
6476           // see if static class implements all of id's protocols, directly or
6477           // through its super class and categories.
6478           if (!rhsID->ClassImplementsProtocol(*I, true))
6479             return false;
6480         }
6481       }
6482       // If there are no qualifiers and no interface, we have an 'id'.
6483       return true;
6484     }
6485     // Both the right and left sides have qualifiers.
6486     for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6487          E = lhsQID->qual_end(); I != E; ++I) {
6488       ObjCProtocolDecl *lhsProto = *I;
6489       bool match = false;
6490 
6491       // when comparing an id<P> on lhs with a static type on rhs,
6492       // see if static class implements all of id's protocols, directly or
6493       // through its super class and categories.
6494       for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6495            E = rhsOPT->qual_end(); J != E; ++J) {
6496         ObjCProtocolDecl *rhsProto = *J;
6497         if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6498             (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6499           match = true;
6500           break;
6501         }
6502       }
6503       // If the RHS is a qualified interface pointer "NSString<P>*",
6504       // make sure we check the class hierarchy.
6505       if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6506         for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6507              E = lhsQID->qual_end(); I != E; ++I) {
6508           // when comparing an id<P> on lhs with a static type on rhs,
6509           // see if static class implements all of id's protocols, directly or
6510           // through its super class and categories.
6511           if (rhsID->ClassImplementsProtocol(*I, true)) {
6512             match = true;
6513             break;
6514           }
6515         }
6516       }
6517       if (!match)
6518         return false;
6519     }
6520 
6521     return true;
6522   }
6523 
6524   const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6525   assert(rhsQID && "One of the LHS/RHS should be id<x>");
6526 
6527   if (const ObjCObjectPointerType *lhsOPT =
6528         lhs->getAsObjCInterfacePointerType()) {
6529     // If both the right and left sides have qualifiers.
6530     for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
6531          E = lhsOPT->qual_end(); I != E; ++I) {
6532       ObjCProtocolDecl *lhsProto = *I;
6533       bool match = false;
6534 
6535       // when comparing an id<P> on rhs with a static type on lhs,
6536       // see if static class implements all of id's protocols, directly or
6537       // through its super class and categories.
6538       // First, lhs protocols in the qualifier list must be found, direct
6539       // or indirect in rhs's qualifier list or it is a mismatch.
6540       for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6541            E = rhsQID->qual_end(); J != E; ++J) {
6542         ObjCProtocolDecl *rhsProto = *J;
6543         if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6544             (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6545           match = true;
6546           break;
6547         }
6548       }
6549       if (!match)
6550         return false;
6551     }
6552 
6553     // Static class's protocols, or its super class or category protocols
6554     // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6555     if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6556       llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6557       CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6558       // This is rather dubious but matches gcc's behavior. If lhs has
6559       // no type qualifier and its class has no static protocol(s)
6560       // assume that it is mismatch.
6561       if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6562         return false;
6563       for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6564            LHSInheritedProtocols.begin(),
6565            E = LHSInheritedProtocols.end(); I != E; ++I) {
6566         bool match = false;
6567         ObjCProtocolDecl *lhsProto = (*I);
6568         for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6569              E = rhsQID->qual_end(); J != E; ++J) {
6570           ObjCProtocolDecl *rhsProto = *J;
6571           if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6572               (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6573             match = true;
6574             break;
6575           }
6576         }
6577         if (!match)
6578           return false;
6579       }
6580     }
6581     return true;
6582   }
6583   return false;
6584 }
6585 
6586 /// canAssignObjCInterfaces - Return true if the two interface types are
6587 /// compatible for assignment from RHS to LHS.  This handles validation of any
6588 /// protocol qualifiers on the LHS or RHS.
6589 ///
6590 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6591                                          const ObjCObjectPointerType *RHSOPT) {
6592   const ObjCObjectType* LHS = LHSOPT->getObjectType();
6593   const ObjCObjectType* RHS = RHSOPT->getObjectType();
6594 
6595   // If either type represents the built-in 'id' or 'Class' types, return true.
6596   if (LHS->isObjCUnqualifiedIdOrClass() ||
6597       RHS->isObjCUnqualifiedIdOrClass())
6598     return true;
6599 
6600   if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
6601     return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6602                                              QualType(RHSOPT,0),
6603                                              false);
6604 
6605   if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
6606     return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6607                                                 QualType(RHSOPT,0));
6608 
6609   // If we have 2 user-defined types, fall into that path.
6610   if (LHS->getInterface() && RHS->getInterface())
6611     return canAssignObjCInterfaces(LHS, RHS);
6612 
6613   return false;
6614 }
6615 
6616 /// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
6617 /// for providing type-safety for objective-c pointers used to pass/return
6618 /// arguments in block literals. When passed as arguments, passing 'A*' where
6619 /// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6620 /// not OK. For the return type, the opposite is not OK.
6621 bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6622                                          const ObjCObjectPointerType *LHSOPT,
6623                                          const ObjCObjectPointerType *RHSOPT,
6624                                          bool BlockReturnType) {
6625   if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
6626     return true;
6627 
6628   if (LHSOPT->isObjCBuiltinType()) {
6629     return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
6630   }
6631 
6632   if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
6633     return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6634                                              QualType(RHSOPT,0),
6635                                              false);
6636 
6637   const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6638   const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6639   if (LHS && RHS)  { // We have 2 user-defined types.
6640     if (LHS != RHS) {
6641       if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
6642         return BlockReturnType;
6643       if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
6644         return !BlockReturnType;
6645     }
6646     else
6647       return true;
6648   }
6649   return false;
6650 }
6651 
6652 /// getIntersectionOfProtocols - This routine finds the intersection of set
6653 /// of protocols inherited from two distinct objective-c pointer objects.
6654 /// It is used to build composite qualifier list of the composite type of
6655 /// the conditional expression involving two objective-c pointer objects.
6656 static
6657 void getIntersectionOfProtocols(ASTContext &Context,
6658                                 const ObjCObjectPointerType *LHSOPT,
6659                                 const ObjCObjectPointerType *RHSOPT,
6660       SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
6661 
6662   const ObjCObjectType* LHS = LHSOPT->getObjectType();
6663   const ObjCObjectType* RHS = RHSOPT->getObjectType();
6664   assert(LHS->getInterface() && "LHS must have an interface base");
6665   assert(RHS->getInterface() && "RHS must have an interface base");
6666 
6667   llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
6668   unsigned LHSNumProtocols = LHS->getNumProtocols();
6669   if (LHSNumProtocols > 0)
6670     InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
6671   else {
6672     llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6673     Context.CollectInheritedProtocols(LHS->getInterface(),
6674                                       LHSInheritedProtocols);
6675     InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
6676                                 LHSInheritedProtocols.end());
6677   }
6678 
6679   unsigned RHSNumProtocols = RHS->getNumProtocols();
6680   if (RHSNumProtocols > 0) {
6681     ObjCProtocolDecl **RHSProtocols =
6682       const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
6683     for (unsigned i = 0; i < RHSNumProtocols; ++i)
6684       if (InheritedProtocolSet.count(RHSProtocols[i]))
6685         IntersectionOfProtocols.push_back(RHSProtocols[i]);
6686   } else {
6687     llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
6688     Context.CollectInheritedProtocols(RHS->getInterface(),
6689                                       RHSInheritedProtocols);
6690     for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6691          RHSInheritedProtocols.begin(),
6692          E = RHSInheritedProtocols.end(); I != E; ++I)
6693       if (InheritedProtocolSet.count((*I)))
6694         IntersectionOfProtocols.push_back((*I));
6695   }
6696 }
6697 
6698 /// areCommonBaseCompatible - Returns common base class of the two classes if
6699 /// one found. Note that this is O'2 algorithm. But it will be called as the
6700 /// last type comparison in a ?-exp of ObjC pointer types before a
6701 /// warning is issued. So, its invokation is extremely rare.
6702 QualType ASTContext::areCommonBaseCompatible(
6703                                           const ObjCObjectPointerType *Lptr,
6704                                           const ObjCObjectPointerType *Rptr) {
6705   const ObjCObjectType *LHS = Lptr->getObjectType();
6706   const ObjCObjectType *RHS = Rptr->getObjectType();
6707   const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6708   const ObjCInterfaceDecl* RDecl = RHS->getInterface();
6709   if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
6710     return QualType();
6711 
6712   do {
6713     LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
6714     if (canAssignObjCInterfaces(LHS, RHS)) {
6715       SmallVector<ObjCProtocolDecl *, 8> Protocols;
6716       getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6717 
6718       QualType Result = QualType(LHS, 0);
6719       if (!Protocols.empty())
6720         Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6721       Result = getObjCObjectPointerType(Result);
6722       return Result;
6723     }
6724   } while ((LDecl = LDecl->getSuperClass()));
6725 
6726   return QualType();
6727 }
6728 
6729 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6730                                          const ObjCObjectType *RHS) {
6731   assert(LHS->getInterface() && "LHS is not an interface type");
6732   assert(RHS->getInterface() && "RHS is not an interface type");
6733 
6734   // Verify that the base decls are compatible: the RHS must be a subclass of
6735   // the LHS.
6736   if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
6737     return false;
6738 
6739   // RHS must have a superset of the protocols in the LHS.  If the LHS is not
6740   // protocol qualified at all, then we are good.
6741   if (LHS->getNumProtocols() == 0)
6742     return true;
6743 
6744   // Okay, we know the LHS has protocol qualifiers.  If the RHS doesn't,
6745   // more detailed analysis is required.
6746   if (RHS->getNumProtocols() == 0) {
6747     // OK, if LHS is a superclass of RHS *and*
6748     // this superclass is assignment compatible with LHS.
6749     // false otherwise.
6750     bool IsSuperClass =
6751       LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6752     if (IsSuperClass) {
6753       // OK if conversion of LHS to SuperClass results in narrowing of types
6754       // ; i.e., SuperClass may implement at least one of the protocols
6755       // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6756       // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6757       llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
6758       CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
6759       // If super class has no protocols, it is not a match.
6760       if (SuperClassInheritedProtocols.empty())
6761         return false;
6762 
6763       for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6764            LHSPE = LHS->qual_end();
6765            LHSPI != LHSPE; LHSPI++) {
6766         bool SuperImplementsProtocol = false;
6767         ObjCProtocolDecl *LHSProto = (*LHSPI);
6768 
6769         for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6770              SuperClassInheritedProtocols.begin(),
6771              E = SuperClassInheritedProtocols.end(); I != E; ++I) {
6772           ObjCProtocolDecl *SuperClassProto = (*I);
6773           if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6774             SuperImplementsProtocol = true;
6775             break;
6776           }
6777         }
6778         if (!SuperImplementsProtocol)
6779           return false;
6780       }
6781       return true;
6782     }
6783     return false;
6784   }
6785 
6786   for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6787                                      LHSPE = LHS->qual_end();
6788        LHSPI != LHSPE; LHSPI++) {
6789     bool RHSImplementsProtocol = false;
6790 
6791     // If the RHS doesn't implement the protocol on the left, the types
6792     // are incompatible.
6793     for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
6794                                        RHSPE = RHS->qual_end();
6795          RHSPI != RHSPE; RHSPI++) {
6796       if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
6797         RHSImplementsProtocol = true;
6798         break;
6799       }
6800     }
6801     // FIXME: For better diagnostics, consider passing back the protocol name.
6802     if (!RHSImplementsProtocol)
6803       return false;
6804   }
6805   // The RHS implements all protocols listed on the LHS.
6806   return true;
6807 }
6808 
6809 bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6810   // get the "pointed to" types
6811   const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6812   const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
6813 
6814   if (!LHSOPT || !RHSOPT)
6815     return false;
6816 
6817   return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6818          canAssignObjCInterfaces(RHSOPT, LHSOPT);
6819 }
6820 
6821 bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6822   return canAssignObjCInterfaces(
6823                 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6824                 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6825 }
6826 
6827 /// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
6828 /// both shall have the identically qualified version of a compatible type.
6829 /// C99 6.2.7p1: Two types have compatible types if their types are the
6830 /// same. See 6.7.[2,3,5] for additional rules.
6831 bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6832                                     bool CompareUnqualified) {
6833   if (getLangOpts().CPlusPlus)
6834     return hasSameType(LHS, RHS);
6835 
6836   return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
6837 }
6838 
6839 bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
6840   return typesAreCompatible(LHS, RHS);
6841 }
6842 
6843 bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6844   return !mergeTypes(LHS, RHS, true).isNull();
6845 }
6846 
6847 /// mergeTransparentUnionType - if T is a transparent union type and a member
6848 /// of T is compatible with SubType, return the merged type, else return
6849 /// QualType()
6850 QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6851                                                bool OfBlockPointer,
6852                                                bool Unqualified) {
6853   if (const RecordType *UT = T->getAsUnionType()) {
6854     RecordDecl *UD = UT->getDecl();
6855     if (UD->hasAttr<TransparentUnionAttr>()) {
6856       for (RecordDecl::field_iterator it = UD->field_begin(),
6857            itend = UD->field_end(); it != itend; ++it) {
6858         QualType ET = it->getType().getUnqualifiedType();
6859         QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6860         if (!MT.isNull())
6861           return MT;
6862       }
6863     }
6864   }
6865 
6866   return QualType();
6867 }
6868 
6869 /// mergeFunctionParameterTypes - merge two types which appear as function
6870 /// parameter types
6871 QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
6872                                                  bool OfBlockPointer,
6873                                                  bool Unqualified) {
6874   // GNU extension: two types are compatible if they appear as a function
6875   // argument, one of the types is a transparent union type and the other
6876   // type is compatible with a union member
6877   QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6878                                               Unqualified);
6879   if (!lmerge.isNull())
6880     return lmerge;
6881 
6882   QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6883                                               Unqualified);
6884   if (!rmerge.isNull())
6885     return rmerge;
6886 
6887   return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6888 }
6889 
6890 QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
6891                                         bool OfBlockPointer,
6892                                         bool Unqualified) {
6893   const FunctionType *lbase = lhs->getAs<FunctionType>();
6894   const FunctionType *rbase = rhs->getAs<FunctionType>();
6895   const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6896   const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
6897   bool allLTypes = true;
6898   bool allRTypes = true;
6899 
6900   // Check return type
6901   QualType retType;
6902   if (OfBlockPointer) {
6903     QualType RHS = rbase->getReturnType();
6904     QualType LHS = lbase->getReturnType();
6905     bool UnqualifiedResult = Unqualified;
6906     if (!UnqualifiedResult)
6907       UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
6908     retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
6909   }
6910   else
6911     retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
6912                          Unqualified);
6913   if (retType.isNull()) return QualType();
6914 
6915   if (Unqualified)
6916     retType = retType.getUnqualifiedType();
6917 
6918   CanQualType LRetType = getCanonicalType(lbase->getReturnType());
6919   CanQualType RRetType = getCanonicalType(rbase->getReturnType());
6920   if (Unqualified) {
6921     LRetType = LRetType.getUnqualifiedType();
6922     RRetType = RRetType.getUnqualifiedType();
6923   }
6924 
6925   if (getCanonicalType(retType) != LRetType)
6926     allLTypes = false;
6927   if (getCanonicalType(retType) != RRetType)
6928     allRTypes = false;
6929 
6930   // FIXME: double check this
6931   // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6932   //                           rbase->getRegParmAttr() != 0 &&
6933   //                           lbase->getRegParmAttr() != rbase->getRegParmAttr()?
6934   FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6935   FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
6936 
6937   // Compatible functions must have compatible calling conventions
6938   if (lbaseInfo.getCC() != rbaseInfo.getCC())
6939     return QualType();
6940 
6941   // Regparm is part of the calling convention.
6942   if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6943     return QualType();
6944   if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6945     return QualType();
6946 
6947   if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6948     return QualType();
6949 
6950   // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6951   bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
6952 
6953   if (lbaseInfo.getNoReturn() != NoReturn)
6954     allLTypes = false;
6955   if (rbaseInfo.getNoReturn() != NoReturn)
6956     allRTypes = false;
6957 
6958   FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
6959 
6960   if (lproto && rproto) { // two C99 style function prototypes
6961     assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6962            "C++ shouldn't be here");
6963     // Compatible functions must have the same number of parameters
6964     if (lproto->getNumParams() != rproto->getNumParams())
6965       return QualType();
6966 
6967     // Variadic and non-variadic functions aren't compatible
6968     if (lproto->isVariadic() != rproto->isVariadic())
6969       return QualType();
6970 
6971     if (lproto->getTypeQuals() != rproto->getTypeQuals())
6972       return QualType();
6973 
6974     if (LangOpts.ObjCAutoRefCount &&
6975         !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6976       return QualType();
6977 
6978     // Check parameter type compatibility
6979     SmallVector<QualType, 10> types;
6980     for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
6981       QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
6982       QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
6983       QualType paramType = mergeFunctionParameterTypes(
6984           lParamType, rParamType, OfBlockPointer, Unqualified);
6985       if (paramType.isNull())
6986         return QualType();
6987 
6988       if (Unqualified)
6989         paramType = paramType.getUnqualifiedType();
6990 
6991       types.push_back(paramType);
6992       if (Unqualified) {
6993         lParamType = lParamType.getUnqualifiedType();
6994         rParamType = rParamType.getUnqualifiedType();
6995       }
6996 
6997       if (getCanonicalType(paramType) != getCanonicalType(lParamType))
6998         allLTypes = false;
6999       if (getCanonicalType(paramType) != getCanonicalType(rParamType))
7000         allRTypes = false;
7001     }
7002 
7003     if (allLTypes) return lhs;
7004     if (allRTypes) return rhs;
7005 
7006     FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
7007     EPI.ExtInfo = einfo;
7008     return getFunctionType(retType, types, EPI);
7009   }
7010 
7011   if (lproto) allRTypes = false;
7012   if (rproto) allLTypes = false;
7013 
7014   const FunctionProtoType *proto = lproto ? lproto : rproto;
7015   if (proto) {
7016     assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
7017     if (proto->isVariadic()) return QualType();
7018     // Check that the types are compatible with the types that
7019     // would result from default argument promotions (C99 6.7.5.3p15).
7020     // The only types actually affected are promotable integer
7021     // types and floats, which would be passed as a different
7022     // type depending on whether the prototype is visible.
7023     for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
7024       QualType paramTy = proto->getParamType(i);
7025 
7026       // Look at the converted type of enum types, since that is the type used
7027       // to pass enum values.
7028       if (const EnumType *Enum = paramTy->getAs<EnumType>()) {
7029         paramTy = Enum->getDecl()->getIntegerType();
7030         if (paramTy.isNull())
7031           return QualType();
7032       }
7033 
7034       if (paramTy->isPromotableIntegerType() ||
7035           getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
7036         return QualType();
7037     }
7038 
7039     if (allLTypes) return lhs;
7040     if (allRTypes) return rhs;
7041 
7042     FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7043     EPI.ExtInfo = einfo;
7044     return getFunctionType(retType, proto->getParamTypes(), EPI);
7045   }
7046 
7047   if (allLTypes) return lhs;
7048   if (allRTypes) return rhs;
7049   return getFunctionNoProtoType(retType, einfo);
7050 }
7051 
7052 /// Given that we have an enum type and a non-enum type, try to merge them.
7053 static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7054                                      QualType other, bool isBlockReturnType) {
7055   // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7056   // a signed integer type, or an unsigned integer type.
7057   // Compatibility is based on the underlying type, not the promotion
7058   // type.
7059   QualType underlyingType = ET->getDecl()->getIntegerType();
7060   if (underlyingType.isNull()) return QualType();
7061   if (Context.hasSameType(underlyingType, other))
7062     return other;
7063 
7064   // In block return types, we're more permissive and accept any
7065   // integral type of the same size.
7066   if (isBlockReturnType && other->isIntegerType() &&
7067       Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7068     return other;
7069 
7070   return QualType();
7071 }
7072 
7073 QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
7074                                 bool OfBlockPointer,
7075                                 bool Unqualified, bool BlockReturnType) {
7076   // C++ [expr]: If an expression initially has the type "reference to T", the
7077   // type is adjusted to "T" prior to any further analysis, the expression
7078   // designates the object or function denoted by the reference, and the
7079   // expression is an lvalue unless the reference is an rvalue reference and
7080   // the expression is a function call (possibly inside parentheses).
7081   assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7082   assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
7083 
7084   if (Unqualified) {
7085     LHS = LHS.getUnqualifiedType();
7086     RHS = RHS.getUnqualifiedType();
7087   }
7088 
7089   QualType LHSCan = getCanonicalType(LHS),
7090            RHSCan = getCanonicalType(RHS);
7091 
7092   // If two types are identical, they are compatible.
7093   if (LHSCan == RHSCan)
7094     return LHS;
7095 
7096   // If the qualifiers are different, the types aren't compatible... mostly.
7097   Qualifiers LQuals = LHSCan.getLocalQualifiers();
7098   Qualifiers RQuals = RHSCan.getLocalQualifiers();
7099   if (LQuals != RQuals) {
7100     // If any of these qualifiers are different, we have a type
7101     // mismatch.
7102     if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7103         LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7104         LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
7105       return QualType();
7106 
7107     // Exactly one GC qualifier difference is allowed: __strong is
7108     // okay if the other type has no GC qualifier but is an Objective
7109     // C object pointer (i.e. implicitly strong by default).  We fix
7110     // this by pretending that the unqualified type was actually
7111     // qualified __strong.
7112     Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7113     Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7114     assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7115 
7116     if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7117       return QualType();
7118 
7119     if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7120       return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7121     }
7122     if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7123       return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7124     }
7125     return QualType();
7126   }
7127 
7128   // Okay, qualifiers are equal.
7129 
7130   Type::TypeClass LHSClass = LHSCan->getTypeClass();
7131   Type::TypeClass RHSClass = RHSCan->getTypeClass();
7132 
7133   // We want to consider the two function types to be the same for these
7134   // comparisons, just force one to the other.
7135   if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7136   if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
7137 
7138   // Same as above for arrays
7139   if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7140     LHSClass = Type::ConstantArray;
7141   if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7142     RHSClass = Type::ConstantArray;
7143 
7144   // ObjCInterfaces are just specialized ObjCObjects.
7145   if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7146   if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7147 
7148   // Canonicalize ExtVector -> Vector.
7149   if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7150   if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
7151 
7152   // If the canonical type classes don't match.
7153   if (LHSClass != RHSClass) {
7154     // Note that we only have special rules for turning block enum
7155     // returns into block int returns, not vice-versa.
7156     if (const EnumType* ETy = LHS->getAs<EnumType>()) {
7157       return mergeEnumWithInteger(*this, ETy, RHS, false);
7158     }
7159     if (const EnumType* ETy = RHS->getAs<EnumType>()) {
7160       return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
7161     }
7162     // allow block pointer type to match an 'id' type.
7163     if (OfBlockPointer && !BlockReturnType) {
7164        if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7165          return LHS;
7166       if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7167         return RHS;
7168     }
7169 
7170     return QualType();
7171   }
7172 
7173   // The canonical type classes match.
7174   switch (LHSClass) {
7175 #define TYPE(Class, Base)
7176 #define ABSTRACT_TYPE(Class, Base)
7177 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
7178 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7179 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
7180 #include "clang/AST/TypeNodes.def"
7181     llvm_unreachable("Non-canonical and dependent types shouldn't get here");
7182 
7183   case Type::Auto:
7184   case Type::LValueReference:
7185   case Type::RValueReference:
7186   case Type::MemberPointer:
7187     llvm_unreachable("C++ should never be in mergeTypes");
7188 
7189   case Type::ObjCInterface:
7190   case Type::IncompleteArray:
7191   case Type::VariableArray:
7192   case Type::FunctionProto:
7193   case Type::ExtVector:
7194     llvm_unreachable("Types are eliminated above");
7195 
7196   case Type::Pointer:
7197   {
7198     // Merge two pointer types, while trying to preserve typedef info
7199     QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7200     QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
7201     if (Unqualified) {
7202       LHSPointee = LHSPointee.getUnqualifiedType();
7203       RHSPointee = RHSPointee.getUnqualifiedType();
7204     }
7205     QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7206                                      Unqualified);
7207     if (ResultType.isNull()) return QualType();
7208     if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7209       return LHS;
7210     if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7211       return RHS;
7212     return getPointerType(ResultType);
7213   }
7214   case Type::BlockPointer:
7215   {
7216     // Merge two block pointer types, while trying to preserve typedef info
7217     QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7218     QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
7219     if (Unqualified) {
7220       LHSPointee = LHSPointee.getUnqualifiedType();
7221       RHSPointee = RHSPointee.getUnqualifiedType();
7222     }
7223     QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7224                                      Unqualified);
7225     if (ResultType.isNull()) return QualType();
7226     if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7227       return LHS;
7228     if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7229       return RHS;
7230     return getBlockPointerType(ResultType);
7231   }
7232   case Type::Atomic:
7233   {
7234     // Merge two pointer types, while trying to preserve typedef info
7235     QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7236     QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7237     if (Unqualified) {
7238       LHSValue = LHSValue.getUnqualifiedType();
7239       RHSValue = RHSValue.getUnqualifiedType();
7240     }
7241     QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7242                                      Unqualified);
7243     if (ResultType.isNull()) return QualType();
7244     if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7245       return LHS;
7246     if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7247       return RHS;
7248     return getAtomicType(ResultType);
7249   }
7250   case Type::ConstantArray:
7251   {
7252     const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7253     const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7254     if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7255       return QualType();
7256 
7257     QualType LHSElem = getAsArrayType(LHS)->getElementType();
7258     QualType RHSElem = getAsArrayType(RHS)->getElementType();
7259     if (Unqualified) {
7260       LHSElem = LHSElem.getUnqualifiedType();
7261       RHSElem = RHSElem.getUnqualifiedType();
7262     }
7263 
7264     QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
7265     if (ResultType.isNull()) return QualType();
7266     if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7267       return LHS;
7268     if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7269       return RHS;
7270     if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7271                                           ArrayType::ArraySizeModifier(), 0);
7272     if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7273                                           ArrayType::ArraySizeModifier(), 0);
7274     const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7275     const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
7276     if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7277       return LHS;
7278     if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7279       return RHS;
7280     if (LVAT) {
7281       // FIXME: This isn't correct! But tricky to implement because
7282       // the array's size has to be the size of LHS, but the type
7283       // has to be different.
7284       return LHS;
7285     }
7286     if (RVAT) {
7287       // FIXME: This isn't correct! But tricky to implement because
7288       // the array's size has to be the size of RHS, but the type
7289       // has to be different.
7290       return RHS;
7291     }
7292     if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7293     if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
7294     return getIncompleteArrayType(ResultType,
7295                                   ArrayType::ArraySizeModifier(), 0);
7296   }
7297   case Type::FunctionNoProto:
7298     return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
7299   case Type::Record:
7300   case Type::Enum:
7301     return QualType();
7302   case Type::Builtin:
7303     // Only exactly equal builtin types are compatible, which is tested above.
7304     return QualType();
7305   case Type::Complex:
7306     // Distinct complex types are incompatible.
7307     return QualType();
7308   case Type::Vector:
7309     // FIXME: The merged type should be an ExtVector!
7310     if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7311                              RHSCan->getAs<VectorType>()))
7312       return LHS;
7313     return QualType();
7314   case Type::ObjCObject: {
7315     // Check if the types are assignment compatible.
7316     // FIXME: This should be type compatibility, e.g. whether
7317     // "LHS x; RHS x;" at global scope is legal.
7318     const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7319     const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7320     if (canAssignObjCInterfaces(LHSIface, RHSIface))
7321       return LHS;
7322 
7323     return QualType();
7324   }
7325   case Type::ObjCObjectPointer: {
7326     if (OfBlockPointer) {
7327       if (canAssignObjCInterfacesInBlockPointer(
7328                                           LHS->getAs<ObjCObjectPointerType>(),
7329                                           RHS->getAs<ObjCObjectPointerType>(),
7330                                           BlockReturnType))
7331         return LHS;
7332       return QualType();
7333     }
7334     if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7335                                 RHS->getAs<ObjCObjectPointerType>()))
7336       return LHS;
7337 
7338     return QualType();
7339   }
7340   }
7341 
7342   llvm_unreachable("Invalid Type::Class!");
7343 }
7344 
7345 bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7346                    const FunctionProtoType *FromFunctionType,
7347                    const FunctionProtoType *ToFunctionType) {
7348   if (FromFunctionType->hasAnyConsumedParams() !=
7349       ToFunctionType->hasAnyConsumedParams())
7350     return false;
7351   FunctionProtoType::ExtProtoInfo FromEPI =
7352     FromFunctionType->getExtProtoInfo();
7353   FunctionProtoType::ExtProtoInfo ToEPI =
7354     ToFunctionType->getExtProtoInfo();
7355   if (FromEPI.ConsumedParameters && ToEPI.ConsumedParameters)
7356     for (unsigned i = 0, n = FromFunctionType->getNumParams(); i != n; ++i) {
7357       if (FromEPI.ConsumedParameters[i] != ToEPI.ConsumedParameters[i])
7358         return false;
7359     }
7360   return true;
7361 }
7362 
7363 /// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7364 /// 'RHS' attributes and returns the merged version; including for function
7365 /// return types.
7366 QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7367   QualType LHSCan = getCanonicalType(LHS),
7368   RHSCan = getCanonicalType(RHS);
7369   // If two types are identical, they are compatible.
7370   if (LHSCan == RHSCan)
7371     return LHS;
7372   if (RHSCan->isFunctionType()) {
7373     if (!LHSCan->isFunctionType())
7374       return QualType();
7375     QualType OldReturnType =
7376         cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
7377     QualType NewReturnType =
7378         cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
7379     QualType ResReturnType =
7380       mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7381     if (ResReturnType.isNull())
7382       return QualType();
7383     if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7384       // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7385       // In either case, use OldReturnType to build the new function type.
7386       const FunctionType *F = LHS->getAs<FunctionType>();
7387       if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
7388         FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7389         EPI.ExtInfo = getFunctionExtInfo(LHS);
7390         QualType ResultType =
7391             getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
7392         return ResultType;
7393       }
7394     }
7395     return QualType();
7396   }
7397 
7398   // If the qualifiers are different, the types can still be merged.
7399   Qualifiers LQuals = LHSCan.getLocalQualifiers();
7400   Qualifiers RQuals = RHSCan.getLocalQualifiers();
7401   if (LQuals != RQuals) {
7402     // If any of these qualifiers are different, we have a type mismatch.
7403     if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7404         LQuals.getAddressSpace() != RQuals.getAddressSpace())
7405       return QualType();
7406 
7407     // Exactly one GC qualifier difference is allowed: __strong is
7408     // okay if the other type has no GC qualifier but is an Objective
7409     // C object pointer (i.e. implicitly strong by default).  We fix
7410     // this by pretending that the unqualified type was actually
7411     // qualified __strong.
7412     Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7413     Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7414     assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7415 
7416     if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7417       return QualType();
7418 
7419     if (GC_L == Qualifiers::Strong)
7420       return LHS;
7421     if (GC_R == Qualifiers::Strong)
7422       return RHS;
7423     return QualType();
7424   }
7425 
7426   if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7427     QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7428     QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7429     QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7430     if (ResQT == LHSBaseQT)
7431       return LHS;
7432     if (ResQT == RHSBaseQT)
7433       return RHS;
7434   }
7435   return QualType();
7436 }
7437 
7438 //===----------------------------------------------------------------------===//
7439 //                         Integer Predicates
7440 //===----------------------------------------------------------------------===//
7441 
7442 unsigned ASTContext::getIntWidth(QualType T) const {
7443   if (const EnumType *ET = T->getAs<EnumType>())
7444     T = ET->getDecl()->getIntegerType();
7445   if (T->isBooleanType())
7446     return 1;
7447   // For builtin types, just use the standard type sizing method
7448   return (unsigned)getTypeSize(T);
7449 }
7450 
7451 QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
7452   assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
7453 
7454   // Turn <4 x signed int> -> <4 x unsigned int>
7455   if (const VectorType *VTy = T->getAs<VectorType>())
7456     return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
7457                          VTy->getNumElements(), VTy->getVectorKind());
7458 
7459   // For enums, we return the unsigned version of the base type.
7460   if (const EnumType *ETy = T->getAs<EnumType>())
7461     T = ETy->getDecl()->getIntegerType();
7462 
7463   const BuiltinType *BTy = T->getAs<BuiltinType>();
7464   assert(BTy && "Unexpected signed integer type");
7465   switch (BTy->getKind()) {
7466   case BuiltinType::Char_S:
7467   case BuiltinType::SChar:
7468     return UnsignedCharTy;
7469   case BuiltinType::Short:
7470     return UnsignedShortTy;
7471   case BuiltinType::Int:
7472     return UnsignedIntTy;
7473   case BuiltinType::Long:
7474     return UnsignedLongTy;
7475   case BuiltinType::LongLong:
7476     return UnsignedLongLongTy;
7477   case BuiltinType::Int128:
7478     return UnsignedInt128Ty;
7479   default:
7480     llvm_unreachable("Unexpected signed integer type");
7481   }
7482 }
7483 
7484 ASTMutationListener::~ASTMutationListener() { }
7485 
7486 void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
7487                                             QualType ReturnType) {}
7488 
7489 //===----------------------------------------------------------------------===//
7490 //                          Builtin Type Computation
7491 //===----------------------------------------------------------------------===//
7492 
7493 /// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
7494 /// pointer over the consumed characters.  This returns the resultant type.  If
7495 /// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7496 /// types.  This allows "v2i*" to be parsed as a pointer to a v2i instead of
7497 /// a vector of "i*".
7498 ///
7499 /// RequiresICE is filled in on return to indicate whether the value is required
7500 /// to be an Integer Constant Expression.
7501 static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
7502                                   ASTContext::GetBuiltinTypeError &Error,
7503                                   bool &RequiresICE,
7504                                   bool AllowTypeModifiers) {
7505   // Modifiers.
7506   int HowLong = 0;
7507   bool Signed = false, Unsigned = false;
7508   RequiresICE = false;
7509 
7510   // Read the prefixed modifiers first.
7511   bool Done = false;
7512   while (!Done) {
7513     switch (*Str++) {
7514     default: Done = true; --Str; break;
7515     case 'I':
7516       RequiresICE = true;
7517       break;
7518     case 'S':
7519       assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7520       assert(!Signed && "Can't use 'S' modifier multiple times!");
7521       Signed = true;
7522       break;
7523     case 'U':
7524       assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
7525       assert(!Unsigned && "Can't use 'S' modifier multiple times!");
7526       Unsigned = true;
7527       break;
7528     case 'L':
7529       assert(HowLong <= 2 && "Can't have LLLL modifier");
7530       ++HowLong;
7531       break;
7532     }
7533   }
7534 
7535   QualType Type;
7536 
7537   // Read the base type.
7538   switch (*Str++) {
7539   default: llvm_unreachable("Unknown builtin type letter!");
7540   case 'v':
7541     assert(HowLong == 0 && !Signed && !Unsigned &&
7542            "Bad modifiers used with 'v'!");
7543     Type = Context.VoidTy;
7544     break;
7545   case 'h':
7546     assert(HowLong == 0 && !Signed && !Unsigned &&
7547            "Bad modifiers used with 'f'!");
7548     Type = Context.HalfTy;
7549     break;
7550   case 'f':
7551     assert(HowLong == 0 && !Signed && !Unsigned &&
7552            "Bad modifiers used with 'f'!");
7553     Type = Context.FloatTy;
7554     break;
7555   case 'd':
7556     assert(HowLong < 2 && !Signed && !Unsigned &&
7557            "Bad modifiers used with 'd'!");
7558     if (HowLong)
7559       Type = Context.LongDoubleTy;
7560     else
7561       Type = Context.DoubleTy;
7562     break;
7563   case 's':
7564     assert(HowLong == 0 && "Bad modifiers used with 's'!");
7565     if (Unsigned)
7566       Type = Context.UnsignedShortTy;
7567     else
7568       Type = Context.ShortTy;
7569     break;
7570   case 'i':
7571     if (HowLong == 3)
7572       Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
7573     else if (HowLong == 2)
7574       Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
7575     else if (HowLong == 1)
7576       Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
7577     else
7578       Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
7579     break;
7580   case 'c':
7581     assert(HowLong == 0 && "Bad modifiers used with 'c'!");
7582     if (Signed)
7583       Type = Context.SignedCharTy;
7584     else if (Unsigned)
7585       Type = Context.UnsignedCharTy;
7586     else
7587       Type = Context.CharTy;
7588     break;
7589   case 'b': // boolean
7590     assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
7591     Type = Context.BoolTy;
7592     break;
7593   case 'z':  // size_t.
7594     assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
7595     Type = Context.getSizeType();
7596     break;
7597   case 'F':
7598     Type = Context.getCFConstantStringType();
7599     break;
7600   case 'G':
7601     Type = Context.getObjCIdType();
7602     break;
7603   case 'H':
7604     Type = Context.getObjCSelType();
7605     break;
7606   case 'M':
7607     Type = Context.getObjCSuperType();
7608     break;
7609   case 'a':
7610     Type = Context.getBuiltinVaListType();
7611     assert(!Type.isNull() && "builtin va list type not initialized!");
7612     break;
7613   case 'A':
7614     // This is a "reference" to a va_list; however, what exactly
7615     // this means depends on how va_list is defined. There are two
7616     // different kinds of va_list: ones passed by value, and ones
7617     // passed by reference.  An example of a by-value va_list is
7618     // x86, where va_list is a char*. An example of by-ref va_list
7619     // is x86-64, where va_list is a __va_list_tag[1]. For x86,
7620     // we want this argument to be a char*&; for x86-64, we want
7621     // it to be a __va_list_tag*.
7622     Type = Context.getBuiltinVaListType();
7623     assert(!Type.isNull() && "builtin va list type not initialized!");
7624     if (Type->isArrayType())
7625       Type = Context.getArrayDecayedType(Type);
7626     else
7627       Type = Context.getLValueReferenceType(Type);
7628     break;
7629   case 'V': {
7630     char *End;
7631     unsigned NumElements = strtoul(Str, &End, 10);
7632     assert(End != Str && "Missing vector size");
7633     Str = End;
7634 
7635     QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
7636                                              RequiresICE, false);
7637     assert(!RequiresICE && "Can't require vector ICE");
7638 
7639     // TODO: No way to make AltiVec vectors in builtins yet.
7640     Type = Context.getVectorType(ElementType, NumElements,
7641                                  VectorType::GenericVector);
7642     break;
7643   }
7644   case 'E': {
7645     char *End;
7646 
7647     unsigned NumElements = strtoul(Str, &End, 10);
7648     assert(End != Str && "Missing vector size");
7649 
7650     Str = End;
7651 
7652     QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7653                                              false);
7654     Type = Context.getExtVectorType(ElementType, NumElements);
7655     break;
7656   }
7657   case 'X': {
7658     QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7659                                              false);
7660     assert(!RequiresICE && "Can't require complex ICE");
7661     Type = Context.getComplexType(ElementType);
7662     break;
7663   }
7664   case 'Y' : {
7665     Type = Context.getPointerDiffType();
7666     break;
7667   }
7668   case 'P':
7669     Type = Context.getFILEType();
7670     if (Type.isNull()) {
7671       Error = ASTContext::GE_Missing_stdio;
7672       return QualType();
7673     }
7674     break;
7675   case 'J':
7676     if (Signed)
7677       Type = Context.getsigjmp_bufType();
7678     else
7679       Type = Context.getjmp_bufType();
7680 
7681     if (Type.isNull()) {
7682       Error = ASTContext::GE_Missing_setjmp;
7683       return QualType();
7684     }
7685     break;
7686   case 'K':
7687     assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
7688     Type = Context.getucontext_tType();
7689 
7690     if (Type.isNull()) {
7691       Error = ASTContext::GE_Missing_ucontext;
7692       return QualType();
7693     }
7694     break;
7695   case 'p':
7696     Type = Context.getProcessIDType();
7697     break;
7698   }
7699 
7700   // If there are modifiers and if we're allowed to parse them, go for it.
7701   Done = !AllowTypeModifiers;
7702   while (!Done) {
7703     switch (char c = *Str++) {
7704     default: Done = true; --Str; break;
7705     case '*':
7706     case '&': {
7707       // Both pointers and references can have their pointee types
7708       // qualified with an address space.
7709       char *End;
7710       unsigned AddrSpace = strtoul(Str, &End, 10);
7711       if (End != Str && AddrSpace != 0) {
7712         Type = Context.getAddrSpaceQualType(Type, AddrSpace);
7713         Str = End;
7714       }
7715       if (c == '*')
7716         Type = Context.getPointerType(Type);
7717       else
7718         Type = Context.getLValueReferenceType(Type);
7719       break;
7720     }
7721     // FIXME: There's no way to have a built-in with an rvalue ref arg.
7722     case 'C':
7723       Type = Type.withConst();
7724       break;
7725     case 'D':
7726       Type = Context.getVolatileType(Type);
7727       break;
7728     case 'R':
7729       Type = Type.withRestrict();
7730       break;
7731     }
7732   }
7733 
7734   assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
7735          "Integer constant 'I' type must be an integer");
7736 
7737   return Type;
7738 }
7739 
7740 /// GetBuiltinType - Return the type for the specified builtin.
7741 QualType ASTContext::GetBuiltinType(unsigned Id,
7742                                     GetBuiltinTypeError &Error,
7743                                     unsigned *IntegerConstantArgs) const {
7744   const char *TypeStr = BuiltinInfo.GetTypeString(Id);
7745 
7746   SmallVector<QualType, 8> ArgTypes;
7747 
7748   bool RequiresICE = false;
7749   Error = GE_None;
7750   QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7751                                        RequiresICE, true);
7752   if (Error != GE_None)
7753     return QualType();
7754 
7755   assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7756 
7757   while (TypeStr[0] && TypeStr[0] != '.') {
7758     QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
7759     if (Error != GE_None)
7760       return QualType();
7761 
7762     // If this argument is required to be an IntegerConstantExpression and the
7763     // caller cares, fill in the bitmask we return.
7764     if (RequiresICE && IntegerConstantArgs)
7765       *IntegerConstantArgs |= 1 << ArgTypes.size();
7766 
7767     // Do array -> pointer decay.  The builtin should use the decayed type.
7768     if (Ty->isArrayType())
7769       Ty = getArrayDecayedType(Ty);
7770 
7771     ArgTypes.push_back(Ty);
7772   }
7773 
7774   assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7775          "'.' should only occur at end of builtin type list!");
7776 
7777   FunctionType::ExtInfo EI(CC_C);
7778   if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7779 
7780   bool Variadic = (TypeStr[0] == '.');
7781 
7782   // We really shouldn't be making a no-proto type here, especially in C++.
7783   if (ArgTypes.empty() && Variadic)
7784     return getFunctionNoProtoType(ResType, EI);
7785 
7786   FunctionProtoType::ExtProtoInfo EPI;
7787   EPI.ExtInfo = EI;
7788   EPI.Variadic = Variadic;
7789 
7790   return getFunctionType(ResType, ArgTypes, EPI);
7791 }
7792 
7793 GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
7794   if (!FD->isExternallyVisible())
7795     return GVA_Internal;
7796 
7797   GVALinkage External = GVA_StrongExternal;
7798   switch (FD->getTemplateSpecializationKind()) {
7799   case TSK_Undeclared:
7800   case TSK_ExplicitSpecialization:
7801     External = GVA_StrongExternal;
7802     break;
7803 
7804   case TSK_ExplicitInstantiationDefinition:
7805     return GVA_ExplicitTemplateInstantiation;
7806 
7807   case TSK_ExplicitInstantiationDeclaration:
7808   case TSK_ImplicitInstantiation:
7809     External = GVA_TemplateInstantiation;
7810     break;
7811   }
7812 
7813   if (!FD->isInlined())
7814     return External;
7815 
7816   if ((!getLangOpts().CPlusPlus && !getLangOpts().MSVCCompat) ||
7817       FD->hasAttr<GNUInlineAttr>()) {
7818     // GNU or C99 inline semantics. Determine whether this symbol should be
7819     // externally visible.
7820     if (FD->isInlineDefinitionExternallyVisible())
7821       return External;
7822 
7823     // C99 inline semantics, where the symbol is not externally visible.
7824     return GVA_C99Inline;
7825   }
7826 
7827   // C++0x [temp.explicit]p9:
7828   //   [ Note: The intent is that an inline function that is the subject of
7829   //   an explicit instantiation declaration will still be implicitly
7830   //   instantiated when used so that the body can be considered for
7831   //   inlining, but that no out-of-line copy of the inline function would be
7832   //   generated in the translation unit. -- end note ]
7833   if (FD->getTemplateSpecializationKind()
7834                                        == TSK_ExplicitInstantiationDeclaration)
7835     return GVA_C99Inline;
7836 
7837   return GVA_CXXInline;
7838 }
7839 
7840 GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
7841   if (!VD->isExternallyVisible())
7842     return GVA_Internal;
7843 
7844   switch (VD->getTemplateSpecializationKind()) {
7845   case TSK_Undeclared:
7846   case TSK_ExplicitSpecialization:
7847     return GVA_StrongExternal;
7848 
7849   case TSK_ExplicitInstantiationDeclaration:
7850     llvm_unreachable("Variable should not be instantiated");
7851   // Fall through to treat this like any other instantiation.
7852 
7853   case TSK_ExplicitInstantiationDefinition:
7854     return GVA_ExplicitTemplateInstantiation;
7855 
7856   case TSK_ImplicitInstantiation:
7857     return GVA_TemplateInstantiation;
7858   }
7859 
7860   llvm_unreachable("Invalid Linkage!");
7861 }
7862 
7863 bool ASTContext::DeclMustBeEmitted(const Decl *D) {
7864   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7865     if (!VD->isFileVarDecl())
7866       return false;
7867   } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7868     // We never need to emit an uninstantiated function template.
7869     if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
7870       return false;
7871   } else
7872     return false;
7873 
7874   // If this is a member of a class template, we do not need to emit it.
7875   if (D->getDeclContext()->isDependentContext())
7876     return false;
7877 
7878   // Weak references don't produce any output by themselves.
7879   if (D->hasAttr<WeakRefAttr>())
7880     return false;
7881 
7882   // Aliases and used decls are required.
7883   if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7884     return true;
7885 
7886   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7887     // Forward declarations aren't required.
7888     if (!FD->doesThisDeclarationHaveABody())
7889       return FD->doesDeclarationForceExternallyVisibleDefinition();
7890 
7891     // Constructors and destructors are required.
7892     if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7893       return true;
7894 
7895     // The key function for a class is required.  This rule only comes
7896     // into play when inline functions can be key functions, though.
7897     if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7898       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7899         const CXXRecordDecl *RD = MD->getParent();
7900         if (MD->isOutOfLine() && RD->isDynamicClass()) {
7901           const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
7902           if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7903             return true;
7904         }
7905       }
7906     }
7907 
7908     GVALinkage Linkage = GetGVALinkageForFunction(FD);
7909 
7910     // static, static inline, always_inline, and extern inline functions can
7911     // always be deferred.  Normal inline functions can be deferred in C99/C++.
7912     // Implicit template instantiations can also be deferred in C++.
7913     if (Linkage == GVA_Internal  || Linkage == GVA_C99Inline ||
7914         Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
7915       return false;
7916     return true;
7917   }
7918 
7919   const VarDecl *VD = cast<VarDecl>(D);
7920   assert(VD->isFileVarDecl() && "Expected file scoped var");
7921 
7922   if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7923     return false;
7924 
7925   // Variables that can be needed in other TUs are required.
7926   GVALinkage L = GetGVALinkageForVariable(VD);
7927   if (L != GVA_Internal && L != GVA_TemplateInstantiation)
7928     return true;
7929 
7930   // Variables that have destruction with side-effects are required.
7931   if (VD->getType().isDestructedType())
7932     return true;
7933 
7934   // Variables that have initialization with side-effects are required.
7935   if (VD->getInit() && VD->getInit()->HasSideEffects(*this))
7936     return true;
7937 
7938   return false;
7939 }
7940 
7941 CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
7942                                                     bool IsCXXMethod) const {
7943   // Pass through to the C++ ABI object
7944   if (IsCXXMethod)
7945     return ABI->getDefaultMethodCallConv(IsVariadic);
7946 
7947   return (LangOpts.MRTD && !IsVariadic) ? CC_X86StdCall : CC_C;
7948 }
7949 
7950 bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
7951   // Pass through to the C++ ABI object
7952   return ABI->isNearlyEmpty(RD);
7953 }
7954 
7955 MangleContext *ASTContext::createMangleContext() {
7956   switch (Target->getCXXABI().getKind()) {
7957   case TargetCXXABI::GenericAArch64:
7958   case TargetCXXABI::GenericItanium:
7959   case TargetCXXABI::GenericARM:
7960   case TargetCXXABI::iOS:
7961     return ItaniumMangleContext::create(*this, getDiagnostics());
7962   case TargetCXXABI::Microsoft:
7963     return MicrosoftMangleContext::create(*this, getDiagnostics());
7964   }
7965   llvm_unreachable("Unsupported ABI");
7966 }
7967 
7968 CXXABI::~CXXABI() {}
7969 
7970 size_t ASTContext::getSideTableAllocatedMemory() const {
7971   return ASTRecordLayouts.getMemorySize() +
7972          llvm::capacity_in_bytes(ObjCLayouts) +
7973          llvm::capacity_in_bytes(KeyFunctions) +
7974          llvm::capacity_in_bytes(ObjCImpls) +
7975          llvm::capacity_in_bytes(BlockVarCopyInits) +
7976          llvm::capacity_in_bytes(DeclAttrs) +
7977          llvm::capacity_in_bytes(TemplateOrInstantiation) +
7978          llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
7979          llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
7980          llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
7981          llvm::capacity_in_bytes(OverriddenMethods) +
7982          llvm::capacity_in_bytes(Types) +
7983          llvm::capacity_in_bytes(VariableArrayTypes) +
7984          llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
7985 }
7986 
7987 /// getIntTypeForBitwidth -
7988 /// sets integer QualTy according to specified details:
7989 /// bitwidth, signed/unsigned.
7990 /// Returns empty type if there is no appropriate target types.
7991 QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
7992                                            unsigned Signed) const {
7993   TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
7994   CanQualType QualTy = getFromTargetType(Ty);
7995   if (!QualTy && DestWidth == 128)
7996     return Signed ? Int128Ty : UnsignedInt128Ty;
7997   return QualTy;
7998 }
7999 
8000 /// getRealTypeForBitwidth -
8001 /// sets floating point QualTy according to specified bitwidth.
8002 /// Returns empty type if there is no appropriate target types.
8003 QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
8004   TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
8005   switch (Ty) {
8006   case TargetInfo::Float:
8007     return FloatTy;
8008   case TargetInfo::Double:
8009     return DoubleTy;
8010   case TargetInfo::LongDouble:
8011     return LongDoubleTy;
8012   case TargetInfo::NoFloat:
8013     return QualType();
8014   }
8015 
8016   llvm_unreachable("Unhandled TargetInfo::RealType value");
8017 }
8018 
8019 void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
8020   if (Number > 1)
8021     MangleNumbers[ND] = Number;
8022 }
8023 
8024 unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
8025   llvm::DenseMap<const NamedDecl *, unsigned>::const_iterator I =
8026     MangleNumbers.find(ND);
8027   return I != MangleNumbers.end() ? I->second : 1;
8028 }
8029 
8030 MangleNumberingContext &
8031 ASTContext::getManglingNumberContext(const DeclContext *DC) {
8032   assert(LangOpts.CPlusPlus);  // We don't need mangling numbers for plain C.
8033   MangleNumberingContext *&MCtx = MangleNumberingContexts[DC];
8034   if (!MCtx)
8035     MCtx = createMangleNumberingContext();
8036   return *MCtx;
8037 }
8038 
8039 MangleNumberingContext *ASTContext::createMangleNumberingContext() const {
8040   return ABI->createMangleNumberingContext();
8041 }
8042 
8043 void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
8044   ParamIndices[D] = index;
8045 }
8046 
8047 unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
8048   ParameterIndexTable::const_iterator I = ParamIndices.find(D);
8049   assert(I != ParamIndices.end() &&
8050          "ParmIndices lacks entry set by ParmVarDecl");
8051   return I->second;
8052 }
8053 
8054 APValue *
8055 ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
8056                                           bool MayCreate) {
8057   assert(E && E->getStorageDuration() == SD_Static &&
8058          "don't need to cache the computed value for this temporary");
8059   if (MayCreate)
8060     return &MaterializedTemporaryValues[E];
8061 
8062   llvm::DenseMap<const MaterializeTemporaryExpr *, APValue>::iterator I =
8063       MaterializedTemporaryValues.find(E);
8064   return I == MaterializedTemporaryValues.end() ? 0 : &I->second;
8065 }
8066 
8067 bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
8068   const llvm::Triple &T = getTargetInfo().getTriple();
8069   if (!T.isOSDarwin())
8070     return false;
8071 
8072   if (!(T.isiOS() && T.isOSVersionLT(7)) &&
8073       !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
8074     return false;
8075 
8076   QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
8077   CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
8078   uint64_t Size = sizeChars.getQuantity();
8079   CharUnits alignChars = getTypeAlignInChars(AtomicTy);
8080   unsigned Align = alignChars.getQuantity();
8081   unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
8082   return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
8083 }
8084 
8085 namespace {
8086 
8087   /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
8088   /// parents as defined by the \c RecursiveASTVisitor.
8089   ///
8090   /// Note that the relationship described here is purely in terms of AST
8091   /// traversal - there are other relationships (for example declaration context)
8092   /// in the AST that are better modeled by special matchers.
8093   ///
8094   /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
8095   class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
8096 
8097   public:
8098     /// \brief Builds and returns the translation unit's parent map.
8099     ///
8100     ///  The caller takes ownership of the returned \c ParentMap.
8101     static ASTContext::ParentMap *buildMap(TranslationUnitDecl &TU) {
8102       ParentMapASTVisitor Visitor(new ASTContext::ParentMap);
8103       Visitor.TraverseDecl(&TU);
8104       return Visitor.Parents;
8105     }
8106 
8107   private:
8108     typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
8109 
8110     ParentMapASTVisitor(ASTContext::ParentMap *Parents) : Parents(Parents) {
8111     }
8112 
8113     bool shouldVisitTemplateInstantiations() const {
8114       return true;
8115     }
8116     bool shouldVisitImplicitCode() const {
8117       return true;
8118     }
8119     // Disables data recursion. We intercept Traverse* methods in the RAV, which
8120     // are not triggered during data recursion.
8121     bool shouldUseDataRecursionFor(clang::Stmt *S) const {
8122       return false;
8123     }
8124 
8125     template <typename T>
8126     bool TraverseNode(T *Node, bool(VisitorBase:: *traverse) (T *)) {
8127       if (Node == NULL)
8128         return true;
8129       if (ParentStack.size() > 0)
8130         // FIXME: Currently we add the same parent multiple times, for example
8131         // when we visit all subexpressions of template instantiations; this is
8132         // suboptimal, bug benign: the only way to visit those is with
8133         // hasAncestor / hasParent, and those do not create new matches.
8134         // The plan is to enable DynTypedNode to be storable in a map or hash
8135         // map. The main problem there is to implement hash functions /
8136         // comparison operators for all types that DynTypedNode supports that
8137         // do not have pointer identity.
8138         (*Parents)[Node].push_back(ParentStack.back());
8139       ParentStack.push_back(ast_type_traits::DynTypedNode::create(*Node));
8140       bool Result = (this ->* traverse) (Node);
8141       ParentStack.pop_back();
8142       return Result;
8143     }
8144 
8145     bool TraverseDecl(Decl *DeclNode) {
8146       return TraverseNode(DeclNode, &VisitorBase::TraverseDecl);
8147     }
8148 
8149     bool TraverseStmt(Stmt *StmtNode) {
8150       return TraverseNode(StmtNode, &VisitorBase::TraverseStmt);
8151     }
8152 
8153     ASTContext::ParentMap *Parents;
8154     llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
8155 
8156     friend class RecursiveASTVisitor<ParentMapASTVisitor>;
8157   };
8158 
8159 } // end namespace
8160 
8161 ASTContext::ParentVector
8162 ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
8163   assert(Node.getMemoizationData() &&
8164          "Invariant broken: only nodes that support memoization may be "
8165          "used in the parent map.");
8166   if (!AllParents) {
8167     // We always need to run over the whole translation unit, as
8168     // hasAncestor can escape any subtree.
8169     AllParents.reset(
8170         ParentMapASTVisitor::buildMap(*getTranslationUnitDecl()));
8171   }
8172   ParentMap::const_iterator I = AllParents->find(Node.getMemoizationData());
8173   if (I == AllParents->end()) {
8174     return ParentVector();
8175   }
8176   return I->second;
8177 }
8178 
8179 bool
8180 ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
8181                                 const ObjCMethodDecl *MethodImpl) {
8182   // No point trying to match an unavailable/deprecated mothod.
8183   if (MethodDecl->hasAttr<UnavailableAttr>()
8184       || MethodDecl->hasAttr<DeprecatedAttr>())
8185     return false;
8186   if (MethodDecl->getObjCDeclQualifier() !=
8187       MethodImpl->getObjCDeclQualifier())
8188     return false;
8189   if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
8190     return false;
8191 
8192   if (MethodDecl->param_size() != MethodImpl->param_size())
8193     return false;
8194 
8195   for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
8196        IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
8197        EF = MethodDecl->param_end();
8198        IM != EM && IF != EF; ++IM, ++IF) {
8199     const ParmVarDecl *DeclVar = (*IF);
8200     const ParmVarDecl *ImplVar = (*IM);
8201     if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
8202       return false;
8203     if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
8204       return false;
8205   }
8206   return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
8207 
8208 }
8209