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