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