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