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