1 //===- ASTContext.cpp - Context to hold long-lived AST nodes --------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements the ASTContext interface.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "clang/AST/ASTContext.h"
14 #include "CXXABI.h"
15 #include "Interp/Context.h"
16 #include "clang/AST/APValue.h"
17 #include "clang/AST/ASTConcept.h"
18 #include "clang/AST/ASTMutationListener.h"
19 #include "clang/AST/ASTTypeTraits.h"
20 #include "clang/AST/Attr.h"
21 #include "clang/AST/AttrIterator.h"
22 #include "clang/AST/CharUnits.h"
23 #include "clang/AST/Comment.h"
24 #include "clang/AST/Decl.h"
25 #include "clang/AST/DeclBase.h"
26 #include "clang/AST/DeclCXX.h"
27 #include "clang/AST/DeclContextInternals.h"
28 #include "clang/AST/DeclObjC.h"
29 #include "clang/AST/DeclOpenMP.h"
30 #include "clang/AST/DeclTemplate.h"
31 #include "clang/AST/DeclarationName.h"
32 #include "clang/AST/DependenceFlags.h"
33 #include "clang/AST/Expr.h"
34 #include "clang/AST/ExprCXX.h"
35 #include "clang/AST/ExprConcepts.h"
36 #include "clang/AST/ExternalASTSource.h"
37 #include "clang/AST/Mangle.h"
38 #include "clang/AST/MangleNumberingContext.h"
39 #include "clang/AST/NestedNameSpecifier.h"
40 #include "clang/AST/ParentMapContext.h"
41 #include "clang/AST/RawCommentList.h"
42 #include "clang/AST/RecordLayout.h"
43 #include "clang/AST/Stmt.h"
44 #include "clang/AST/TemplateBase.h"
45 #include "clang/AST/TemplateName.h"
46 #include "clang/AST/Type.h"
47 #include "clang/AST/TypeLoc.h"
48 #include "clang/AST/UnresolvedSet.h"
49 #include "clang/AST/VTableBuilder.h"
50 #include "clang/Basic/AddressSpaces.h"
51 #include "clang/Basic/Builtins.h"
52 #include "clang/Basic/CommentOptions.h"
53 #include "clang/Basic/ExceptionSpecificationType.h"
54 #include "clang/Basic/IdentifierTable.h"
55 #include "clang/Basic/LLVM.h"
56 #include "clang/Basic/LangOptions.h"
57 #include "clang/Basic/Linkage.h"
58 #include "clang/Basic/Module.h"
59 #include "clang/Basic/ObjCRuntime.h"
60 #include "clang/Basic/SanitizerBlacklist.h"
61 #include "clang/Basic/SourceLocation.h"
62 #include "clang/Basic/SourceManager.h"
63 #include "clang/Basic/Specifiers.h"
64 #include "clang/Basic/TargetCXXABI.h"
65 #include "clang/Basic/TargetInfo.h"
66 #include "clang/Basic/XRayLists.h"
67 #include "llvm/ADT/APFixedPoint.h"
68 #include "llvm/ADT/APInt.h"
69 #include "llvm/ADT/APSInt.h"
70 #include "llvm/ADT/ArrayRef.h"
71 #include "llvm/ADT/DenseMap.h"
72 #include "llvm/ADT/DenseSet.h"
73 #include "llvm/ADT/FoldingSet.h"
74 #include "llvm/ADT/None.h"
75 #include "llvm/ADT/Optional.h"
76 #include "llvm/ADT/PointerUnion.h"
77 #include "llvm/ADT/STLExtras.h"
78 #include "llvm/ADT/SmallPtrSet.h"
79 #include "llvm/ADT/SmallVector.h"
80 #include "llvm/ADT/StringExtras.h"
81 #include "llvm/ADT/StringRef.h"
82 #include "llvm/ADT/Triple.h"
83 #include "llvm/Support/Capacity.h"
84 #include "llvm/Support/Casting.h"
85 #include "llvm/Support/Compiler.h"
86 #include "llvm/Support/ErrorHandling.h"
87 #include "llvm/Support/MathExtras.h"
88 #include "llvm/Support/raw_ostream.h"
89 #include <algorithm>
90 #include <cassert>
91 #include <cstddef>
92 #include <cstdint>
93 #include <cstdlib>
94 #include <map>
95 #include <memory>
96 #include <string>
97 #include <tuple>
98 #include <utility>
99 
100 using namespace clang;
101 
102 enum FloatingRank {
103   BFloat16Rank, Float16Rank, HalfRank, FloatRank, DoubleRank, LongDoubleRank, Float128Rank
104 };
105 
106 /// \returns location that is relevant when searching for Doc comments related
107 /// to \p D.
108 static SourceLocation getDeclLocForCommentSearch(const Decl *D,
109                                                  SourceManager &SourceMgr) {
110   assert(D);
111 
112   // User can not attach documentation to implicit declarations.
113   if (D->isImplicit())
114     return {};
115 
116   // User can not attach documentation to implicit instantiations.
117   if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
118     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
119       return {};
120   }
121 
122   if (const auto *VD = dyn_cast<VarDecl>(D)) {
123     if (VD->isStaticDataMember() &&
124         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
125       return {};
126   }
127 
128   if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) {
129     if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
130       return {};
131   }
132 
133   if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
134     TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
135     if (TSK == TSK_ImplicitInstantiation ||
136         TSK == TSK_Undeclared)
137       return {};
138   }
139 
140   if (const auto *ED = dyn_cast<EnumDecl>(D)) {
141     if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
142       return {};
143   }
144   if (const auto *TD = dyn_cast<TagDecl>(D)) {
145     // When tag declaration (but not definition!) is part of the
146     // decl-specifier-seq of some other declaration, it doesn't get comment
147     if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
148       return {};
149   }
150   // TODO: handle comments for function parameters properly.
151   if (isa<ParmVarDecl>(D))
152     return {};
153 
154   // TODO: we could look up template parameter documentation in the template
155   // documentation.
156   if (isa<TemplateTypeParmDecl>(D) ||
157       isa<NonTypeTemplateParmDecl>(D) ||
158       isa<TemplateTemplateParmDecl>(D))
159     return {};
160 
161   // Find declaration location.
162   // For Objective-C declarations we generally don't expect to have multiple
163   // declarators, thus use declaration starting location as the "declaration
164   // location".
165   // For all other declarations multiple declarators are used quite frequently,
166   // so we use the location of the identifier as the "declaration location".
167   if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
168       isa<ObjCPropertyDecl>(D) ||
169       isa<RedeclarableTemplateDecl>(D) ||
170       isa<ClassTemplateSpecializationDecl>(D) ||
171       // Allow association with Y across {} in `typedef struct X {} Y`.
172       isa<TypedefDecl>(D))
173     return D->getBeginLoc();
174   else {
175     const SourceLocation DeclLoc = D->getLocation();
176     if (DeclLoc.isMacroID()) {
177       if (isa<TypedefDecl>(D)) {
178         // If location of the typedef name is in a macro, it is because being
179         // declared via a macro. Try using declaration's starting location as
180         // the "declaration location".
181         return D->getBeginLoc();
182       } else if (const auto *TD = dyn_cast<TagDecl>(D)) {
183         // If location of the tag decl is inside a macro, but the spelling of
184         // the tag name comes from a macro argument, it looks like a special
185         // macro like NS_ENUM is being used to define the tag decl.  In that
186         // case, adjust the source location to the expansion loc so that we can
187         // attach the comment to the tag decl.
188         if (SourceMgr.isMacroArgExpansion(DeclLoc) &&
189             TD->isCompleteDefinition())
190           return SourceMgr.getExpansionLoc(DeclLoc);
191       }
192     }
193     return DeclLoc;
194   }
195 
196   return {};
197 }
198 
199 RawComment *ASTContext::getRawCommentForDeclNoCacheImpl(
200     const Decl *D, const SourceLocation RepresentativeLocForDecl,
201     const std::map<unsigned, RawComment *> &CommentsInTheFile) const {
202   // If the declaration doesn't map directly to a location in a file, we
203   // can't find the comment.
204   if (RepresentativeLocForDecl.isInvalid() ||
205       !RepresentativeLocForDecl.isFileID())
206     return nullptr;
207 
208   // If there are no comments anywhere, we won't find anything.
209   if (CommentsInTheFile.empty())
210     return nullptr;
211 
212   // Decompose the location for the declaration and find the beginning of the
213   // file buffer.
214   const std::pair<FileID, unsigned> DeclLocDecomp =
215       SourceMgr.getDecomposedLoc(RepresentativeLocForDecl);
216 
217   // Slow path.
218   auto OffsetCommentBehindDecl =
219       CommentsInTheFile.lower_bound(DeclLocDecomp.second);
220 
221   // First check whether we have a trailing comment.
222   if (OffsetCommentBehindDecl != CommentsInTheFile.end()) {
223     RawComment *CommentBehindDecl = OffsetCommentBehindDecl->second;
224     if ((CommentBehindDecl->isDocumentation() ||
225          LangOpts.CommentOpts.ParseAllComments) &&
226         CommentBehindDecl->isTrailingComment() &&
227         (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
228          isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
229 
230       // Check that Doxygen trailing comment comes after the declaration, starts
231       // on the same line and in the same file as the declaration.
232       if (SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second) ==
233           Comments.getCommentBeginLine(CommentBehindDecl, DeclLocDecomp.first,
234                                        OffsetCommentBehindDecl->first)) {
235         return CommentBehindDecl;
236       }
237     }
238   }
239 
240   // The comment just after the declaration was not a trailing comment.
241   // Let's look at the previous comment.
242   if (OffsetCommentBehindDecl == CommentsInTheFile.begin())
243     return nullptr;
244 
245   auto OffsetCommentBeforeDecl = --OffsetCommentBehindDecl;
246   RawComment *CommentBeforeDecl = OffsetCommentBeforeDecl->second;
247 
248   // Check that we actually have a non-member Doxygen comment.
249   if (!(CommentBeforeDecl->isDocumentation() ||
250         LangOpts.CommentOpts.ParseAllComments) ||
251       CommentBeforeDecl->isTrailingComment())
252     return nullptr;
253 
254   // Decompose the end of the comment.
255   const unsigned CommentEndOffset =
256       Comments.getCommentEndOffset(CommentBeforeDecl);
257 
258   // Get the corresponding buffer.
259   bool Invalid = false;
260   const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
261                                                &Invalid).data();
262   if (Invalid)
263     return nullptr;
264 
265   // Extract text between the comment and declaration.
266   StringRef Text(Buffer + CommentEndOffset,
267                  DeclLocDecomp.second - CommentEndOffset);
268 
269   // There should be no other declarations or preprocessor directives between
270   // comment and declaration.
271   if (Text.find_first_of(";{}#@") != StringRef::npos)
272     return nullptr;
273 
274   return CommentBeforeDecl;
275 }
276 
277 RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
278   const SourceLocation DeclLoc = getDeclLocForCommentSearch(D, SourceMgr);
279 
280   // If the declaration doesn't map directly to a location in a file, we
281   // can't find the comment.
282   if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
283     return nullptr;
284 
285   if (ExternalSource && !CommentsLoaded) {
286     ExternalSource->ReadComments();
287     CommentsLoaded = true;
288   }
289 
290   if (Comments.empty())
291     return nullptr;
292 
293   const FileID File = SourceMgr.getDecomposedLoc(DeclLoc).first;
294   const auto CommentsInThisFile = Comments.getCommentsInFile(File);
295   if (!CommentsInThisFile || CommentsInThisFile->empty())
296     return nullptr;
297 
298   return getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile);
299 }
300 
301 void ASTContext::addComment(const RawComment &RC) {
302   assert(LangOpts.RetainCommentsFromSystemHeaders ||
303          !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin()));
304   Comments.addComment(RC, LangOpts.CommentOpts, BumpAlloc);
305 }
306 
307 /// If we have a 'templated' declaration for a template, adjust 'D' to
308 /// refer to the actual template.
309 /// If we have an implicit instantiation, adjust 'D' to refer to template.
310 static const Decl &adjustDeclToTemplate(const Decl &D) {
311   if (const auto *FD = dyn_cast<FunctionDecl>(&D)) {
312     // Is this function declaration part of a function template?
313     if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
314       return *FTD;
315 
316     // Nothing to do if function is not an implicit instantiation.
317     if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
318       return D;
319 
320     // Function is an implicit instantiation of a function template?
321     if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
322       return *FTD;
323 
324     // Function is instantiated from a member definition of a class template?
325     if (const FunctionDecl *MemberDecl =
326             FD->getInstantiatedFromMemberFunction())
327       return *MemberDecl;
328 
329     return D;
330   }
331   if (const auto *VD = dyn_cast<VarDecl>(&D)) {
332     // Static data member is instantiated from a member definition of a class
333     // template?
334     if (VD->isStaticDataMember())
335       if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
336         return *MemberDecl;
337 
338     return D;
339   }
340   if (const auto *CRD = dyn_cast<CXXRecordDecl>(&D)) {
341     // Is this class declaration part of a class template?
342     if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
343       return *CTD;
344 
345     // Class is an implicit instantiation of a class template or partial
346     // specialization?
347     if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
348       if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
349         return D;
350       llvm::PointerUnion<ClassTemplateDecl *,
351                          ClassTemplatePartialSpecializationDecl *>
352           PU = CTSD->getSpecializedTemplateOrPartial();
353       return PU.is<ClassTemplateDecl *>()
354                  ? *static_cast<const Decl *>(PU.get<ClassTemplateDecl *>())
355                  : *static_cast<const Decl *>(
356                        PU.get<ClassTemplatePartialSpecializationDecl *>());
357     }
358 
359     // Class is instantiated from a member definition of a class template?
360     if (const MemberSpecializationInfo *Info =
361             CRD->getMemberSpecializationInfo())
362       return *Info->getInstantiatedFrom();
363 
364     return D;
365   }
366   if (const auto *ED = dyn_cast<EnumDecl>(&D)) {
367     // Enum is instantiated from a member definition of a class template?
368     if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
369       return *MemberDecl;
370 
371     return D;
372   }
373   // FIXME: Adjust alias templates?
374   return D;
375 }
376 
377 const RawComment *ASTContext::getRawCommentForAnyRedecl(
378                                                 const Decl *D,
379                                                 const Decl **OriginalDecl) const {
380   if (!D) {
381     if (OriginalDecl)
382       OriginalDecl = nullptr;
383     return nullptr;
384   }
385 
386   D = &adjustDeclToTemplate(*D);
387 
388   // Any comment directly attached to D?
389   {
390     auto DeclComment = DeclRawComments.find(D);
391     if (DeclComment != DeclRawComments.end()) {
392       if (OriginalDecl)
393         *OriginalDecl = D;
394       return DeclComment->second;
395     }
396   }
397 
398   // Any comment attached to any redeclaration of D?
399   const Decl *CanonicalD = D->getCanonicalDecl();
400   if (!CanonicalD)
401     return nullptr;
402 
403   {
404     auto RedeclComment = RedeclChainComments.find(CanonicalD);
405     if (RedeclComment != RedeclChainComments.end()) {
406       if (OriginalDecl)
407         *OriginalDecl = RedeclComment->second;
408       auto CommentAtRedecl = DeclRawComments.find(RedeclComment->second);
409       assert(CommentAtRedecl != DeclRawComments.end() &&
410              "This decl is supposed to have comment attached.");
411       return CommentAtRedecl->second;
412     }
413   }
414 
415   // Any redeclarations of D that we haven't checked for comments yet?
416   // We can't use DenseMap::iterator directly since it'd get invalid.
417   auto LastCheckedRedecl = [this, CanonicalD]() -> const Decl * {
418     auto LookupRes = CommentlessRedeclChains.find(CanonicalD);
419     if (LookupRes != CommentlessRedeclChains.end())
420       return LookupRes->second;
421     return nullptr;
422   }();
423 
424   for (const auto Redecl : D->redecls()) {
425     assert(Redecl);
426     // Skip all redeclarations that have been checked previously.
427     if (LastCheckedRedecl) {
428       if (LastCheckedRedecl == Redecl) {
429         LastCheckedRedecl = nullptr;
430       }
431       continue;
432     }
433     const RawComment *RedeclComment = getRawCommentForDeclNoCache(Redecl);
434     if (RedeclComment) {
435       cacheRawCommentForDecl(*Redecl, *RedeclComment);
436       if (OriginalDecl)
437         *OriginalDecl = Redecl;
438       return RedeclComment;
439     }
440     CommentlessRedeclChains[CanonicalD] = Redecl;
441   }
442 
443   if (OriginalDecl)
444     *OriginalDecl = nullptr;
445   return nullptr;
446 }
447 
448 void ASTContext::cacheRawCommentForDecl(const Decl &OriginalD,
449                                         const RawComment &Comment) const {
450   assert(Comment.isDocumentation() || LangOpts.CommentOpts.ParseAllComments);
451   DeclRawComments.try_emplace(&OriginalD, &Comment);
452   const Decl *const CanonicalDecl = OriginalD.getCanonicalDecl();
453   RedeclChainComments.try_emplace(CanonicalDecl, &OriginalD);
454   CommentlessRedeclChains.erase(CanonicalDecl);
455 }
456 
457 static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
458                    SmallVectorImpl<const NamedDecl *> &Redeclared) {
459   const DeclContext *DC = ObjCMethod->getDeclContext();
460   if (const auto *IMD = dyn_cast<ObjCImplDecl>(DC)) {
461     const ObjCInterfaceDecl *ID = IMD->getClassInterface();
462     if (!ID)
463       return;
464     // Add redeclared method here.
465     for (const auto *Ext : ID->known_extensions()) {
466       if (ObjCMethodDecl *RedeclaredMethod =
467             Ext->getMethod(ObjCMethod->getSelector(),
468                                   ObjCMethod->isInstanceMethod()))
469         Redeclared.push_back(RedeclaredMethod);
470     }
471   }
472 }
473 
474 void ASTContext::attachCommentsToJustParsedDecls(ArrayRef<Decl *> Decls,
475                                                  const Preprocessor *PP) {
476   if (Comments.empty() || Decls.empty())
477     return;
478 
479   FileID File;
480   for (Decl *D : Decls) {
481     SourceLocation Loc = D->getLocation();
482     if (Loc.isValid()) {
483       // See if there are any new comments that are not attached to a decl.
484       // The location doesn't have to be precise - we care only about the file.
485       File = SourceMgr.getDecomposedLoc(Loc).first;
486       break;
487     }
488   }
489 
490   if (File.isInvalid())
491     return;
492 
493   auto CommentsInThisFile = Comments.getCommentsInFile(File);
494   if (!CommentsInThisFile || CommentsInThisFile->empty() ||
495       CommentsInThisFile->rbegin()->second->isAttached())
496     return;
497 
498   // There is at least one comment not attached to a decl.
499   // Maybe it should be attached to one of Decls?
500   //
501   // Note that this way we pick up not only comments that precede the
502   // declaration, but also comments that *follow* the declaration -- thanks to
503   // the lookahead in the lexer: we've consumed the semicolon and looked
504   // ahead through comments.
505 
506   for (const Decl *D : Decls) {
507     assert(D);
508     if (D->isInvalidDecl())
509       continue;
510 
511     D = &adjustDeclToTemplate(*D);
512 
513     const SourceLocation DeclLoc = getDeclLocForCommentSearch(D, SourceMgr);
514 
515     if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
516       continue;
517 
518     if (DeclRawComments.count(D) > 0)
519       continue;
520 
521     if (RawComment *const DocComment =
522             getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile)) {
523       cacheRawCommentForDecl(*D, *DocComment);
524       comments::FullComment *FC = DocComment->parse(*this, PP, D);
525       ParsedComments[D->getCanonicalDecl()] = FC;
526     }
527   }
528 }
529 
530 comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
531                                                     const Decl *D) const {
532   auto *ThisDeclInfo = new (*this) comments::DeclInfo;
533   ThisDeclInfo->CommentDecl = D;
534   ThisDeclInfo->IsFilled = false;
535   ThisDeclInfo->fill();
536   ThisDeclInfo->CommentDecl = FC->getDecl();
537   if (!ThisDeclInfo->TemplateParameters)
538     ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
539   comments::FullComment *CFC =
540     new (*this) comments::FullComment(FC->getBlocks(),
541                                       ThisDeclInfo);
542   return CFC;
543 }
544 
545 comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
546   const RawComment *RC = getRawCommentForDeclNoCache(D);
547   return RC ? RC->parse(*this, nullptr, D) : nullptr;
548 }
549 
550 comments::FullComment *ASTContext::getCommentForDecl(
551                                               const Decl *D,
552                                               const Preprocessor *PP) const {
553   if (!D || D->isInvalidDecl())
554     return nullptr;
555   D = &adjustDeclToTemplate(*D);
556 
557   const Decl *Canonical = D->getCanonicalDecl();
558   llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
559       ParsedComments.find(Canonical);
560 
561   if (Pos != ParsedComments.end()) {
562     if (Canonical != D) {
563       comments::FullComment *FC = Pos->second;
564       comments::FullComment *CFC = cloneFullComment(FC, D);
565       return CFC;
566     }
567     return Pos->second;
568   }
569 
570   const Decl *OriginalDecl = nullptr;
571 
572   const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
573   if (!RC) {
574     if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
575       SmallVector<const NamedDecl*, 8> Overridden;
576       const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
577       if (OMD && OMD->isPropertyAccessor())
578         if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
579           if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
580             return cloneFullComment(FC, D);
581       if (OMD)
582         addRedeclaredMethods(OMD, Overridden);
583       getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
584       for (unsigned i = 0, e = Overridden.size(); i < e; i++)
585         if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
586           return cloneFullComment(FC, D);
587     }
588     else if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
589       // Attach any tag type's documentation to its typedef if latter
590       // does not have one of its own.
591       QualType QT = TD->getUnderlyingType();
592       if (const auto *TT = QT->getAs<TagType>())
593         if (const Decl *TD = TT->getDecl())
594           if (comments::FullComment *FC = getCommentForDecl(TD, PP))
595             return cloneFullComment(FC, D);
596     }
597     else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
598       while (IC->getSuperClass()) {
599         IC = IC->getSuperClass();
600         if (comments::FullComment *FC = getCommentForDecl(IC, PP))
601           return cloneFullComment(FC, D);
602       }
603     }
604     else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(D)) {
605       if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
606         if (comments::FullComment *FC = getCommentForDecl(IC, PP))
607           return cloneFullComment(FC, D);
608     }
609     else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
610       if (!(RD = RD->getDefinition()))
611         return nullptr;
612       // Check non-virtual bases.
613       for (const auto &I : RD->bases()) {
614         if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
615           continue;
616         QualType Ty = I.getType();
617         if (Ty.isNull())
618           continue;
619         if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
620           if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
621             continue;
622 
623           if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
624             return cloneFullComment(FC, D);
625         }
626       }
627       // Check virtual bases.
628       for (const auto &I : RD->vbases()) {
629         if (I.getAccessSpecifier() != AS_public)
630           continue;
631         QualType Ty = I.getType();
632         if (Ty.isNull())
633           continue;
634         if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
635           if (!(VirtualBase= VirtualBase->getDefinition()))
636             continue;
637           if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
638             return cloneFullComment(FC, D);
639         }
640       }
641     }
642     return nullptr;
643   }
644 
645   // If the RawComment was attached to other redeclaration of this Decl, we
646   // should parse the comment in context of that other Decl.  This is important
647   // because comments can contain references to parameter names which can be
648   // different across redeclarations.
649   if (D != OriginalDecl && OriginalDecl)
650     return getCommentForDecl(OriginalDecl, PP);
651 
652   comments::FullComment *FC = RC->parse(*this, PP, D);
653   ParsedComments[Canonical] = FC;
654   return FC;
655 }
656 
657 void
658 ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
659                                                    const ASTContext &C,
660                                                TemplateTemplateParmDecl *Parm) {
661   ID.AddInteger(Parm->getDepth());
662   ID.AddInteger(Parm->getPosition());
663   ID.AddBoolean(Parm->isParameterPack());
664 
665   TemplateParameterList *Params = Parm->getTemplateParameters();
666   ID.AddInteger(Params->size());
667   for (TemplateParameterList::const_iterator P = Params->begin(),
668                                           PEnd = Params->end();
669        P != PEnd; ++P) {
670     if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
671       ID.AddInteger(0);
672       ID.AddBoolean(TTP->isParameterPack());
673       const TypeConstraint *TC = TTP->getTypeConstraint();
674       ID.AddBoolean(TC != nullptr);
675       if (TC)
676         TC->getImmediatelyDeclaredConstraint()->Profile(ID, C,
677                                                         /*Canonical=*/true);
678       if (TTP->isExpandedParameterPack()) {
679         ID.AddBoolean(true);
680         ID.AddInteger(TTP->getNumExpansionParameters());
681       } else
682         ID.AddBoolean(false);
683       continue;
684     }
685 
686     if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
687       ID.AddInteger(1);
688       ID.AddBoolean(NTTP->isParameterPack());
689       ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
690       if (NTTP->isExpandedParameterPack()) {
691         ID.AddBoolean(true);
692         ID.AddInteger(NTTP->getNumExpansionTypes());
693         for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
694           QualType T = NTTP->getExpansionType(I);
695           ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
696         }
697       } else
698         ID.AddBoolean(false);
699       continue;
700     }
701 
702     auto *TTP = cast<TemplateTemplateParmDecl>(*P);
703     ID.AddInteger(2);
704     Profile(ID, C, TTP);
705   }
706   Expr *RequiresClause = Parm->getTemplateParameters()->getRequiresClause();
707   ID.AddBoolean(RequiresClause != nullptr);
708   if (RequiresClause)
709     RequiresClause->Profile(ID, C, /*Canonical=*/true);
710 }
711 
712 static Expr *
713 canonicalizeImmediatelyDeclaredConstraint(const ASTContext &C, Expr *IDC,
714                                           QualType ConstrainedType) {
715   // This is a bit ugly - we need to form a new immediately-declared
716   // constraint that references the new parameter; this would ideally
717   // require semantic analysis (e.g. template<C T> struct S {}; - the
718   // converted arguments of C<T> could be an argument pack if C is
719   // declared as template<typename... T> concept C = ...).
720   // We don't have semantic analysis here so we dig deep into the
721   // ready-made constraint expr and change the thing manually.
722   ConceptSpecializationExpr *CSE;
723   if (const auto *Fold = dyn_cast<CXXFoldExpr>(IDC))
724     CSE = cast<ConceptSpecializationExpr>(Fold->getLHS());
725   else
726     CSE = cast<ConceptSpecializationExpr>(IDC);
727   ArrayRef<TemplateArgument> OldConverted = CSE->getTemplateArguments();
728   SmallVector<TemplateArgument, 3> NewConverted;
729   NewConverted.reserve(OldConverted.size());
730   if (OldConverted.front().getKind() == TemplateArgument::Pack) {
731     // The case:
732     // template<typename... T> concept C = true;
733     // template<C<int> T> struct S; -> constraint is C<{T, int}>
734     NewConverted.push_back(ConstrainedType);
735     for (auto &Arg : OldConverted.front().pack_elements().drop_front(1))
736       NewConverted.push_back(Arg);
737     TemplateArgument NewPack(NewConverted);
738 
739     NewConverted.clear();
740     NewConverted.push_back(NewPack);
741     assert(OldConverted.size() == 1 &&
742            "Template parameter pack should be the last parameter");
743   } else {
744     assert(OldConverted.front().getKind() == TemplateArgument::Type &&
745            "Unexpected first argument kind for immediately-declared "
746            "constraint");
747     NewConverted.push_back(ConstrainedType);
748     for (auto &Arg : OldConverted.drop_front(1))
749       NewConverted.push_back(Arg);
750   }
751   Expr *NewIDC = ConceptSpecializationExpr::Create(
752       C, CSE->getNamedConcept(), NewConverted, nullptr,
753       CSE->isInstantiationDependent(), CSE->containsUnexpandedParameterPack());
754 
755   if (auto *OrigFold = dyn_cast<CXXFoldExpr>(IDC))
756     NewIDC = new (C) CXXFoldExpr(
757         OrigFold->getType(), /*Callee*/nullptr, SourceLocation(), NewIDC,
758         BinaryOperatorKind::BO_LAnd, SourceLocation(), /*RHS=*/nullptr,
759         SourceLocation(), /*NumExpansions=*/None);
760   return NewIDC;
761 }
762 
763 TemplateTemplateParmDecl *
764 ASTContext::getCanonicalTemplateTemplateParmDecl(
765                                           TemplateTemplateParmDecl *TTP) const {
766   // Check if we already have a canonical template template parameter.
767   llvm::FoldingSetNodeID ID;
768   CanonicalTemplateTemplateParm::Profile(ID, *this, TTP);
769   void *InsertPos = nullptr;
770   CanonicalTemplateTemplateParm *Canonical
771     = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
772   if (Canonical)
773     return Canonical->getParam();
774 
775   // Build a canonical template parameter list.
776   TemplateParameterList *Params = TTP->getTemplateParameters();
777   SmallVector<NamedDecl *, 4> CanonParams;
778   CanonParams.reserve(Params->size());
779   for (TemplateParameterList::const_iterator P = Params->begin(),
780                                           PEnd = Params->end();
781        P != PEnd; ++P) {
782     if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
783       TemplateTypeParmDecl *NewTTP = TemplateTypeParmDecl::Create(*this,
784           getTranslationUnitDecl(), SourceLocation(), SourceLocation(),
785           TTP->getDepth(), TTP->getIndex(), nullptr, false,
786           TTP->isParameterPack(), TTP->hasTypeConstraint(),
787           TTP->isExpandedParameterPack() ?
788           llvm::Optional<unsigned>(TTP->getNumExpansionParameters()) : None);
789       if (const auto *TC = TTP->getTypeConstraint()) {
790         QualType ParamAsArgument(NewTTP->getTypeForDecl(), 0);
791         Expr *NewIDC = canonicalizeImmediatelyDeclaredConstraint(
792                 *this, TC->getImmediatelyDeclaredConstraint(),
793                 ParamAsArgument);
794         TemplateArgumentListInfo CanonArgsAsWritten;
795         if (auto *Args = TC->getTemplateArgsAsWritten())
796           for (const auto &ArgLoc : Args->arguments())
797             CanonArgsAsWritten.addArgument(
798                 TemplateArgumentLoc(ArgLoc.getArgument(),
799                                     TemplateArgumentLocInfo()));
800         NewTTP->setTypeConstraint(
801             NestedNameSpecifierLoc(),
802             DeclarationNameInfo(TC->getNamedConcept()->getDeclName(),
803                                 SourceLocation()), /*FoundDecl=*/nullptr,
804             // Actually canonicalizing a TemplateArgumentLoc is difficult so we
805             // simply omit the ArgsAsWritten
806             TC->getNamedConcept(), /*ArgsAsWritten=*/nullptr, NewIDC);
807       }
808       CanonParams.push_back(NewTTP);
809     } else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
810       QualType T = getCanonicalType(NTTP->getType());
811       TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
812       NonTypeTemplateParmDecl *Param;
813       if (NTTP->isExpandedParameterPack()) {
814         SmallVector<QualType, 2> ExpandedTypes;
815         SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
816         for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
817           ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
818           ExpandedTInfos.push_back(
819                                 getTrivialTypeSourceInfo(ExpandedTypes.back()));
820         }
821 
822         Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
823                                                 SourceLocation(),
824                                                 SourceLocation(),
825                                                 NTTP->getDepth(),
826                                                 NTTP->getPosition(), nullptr,
827                                                 T,
828                                                 TInfo,
829                                                 ExpandedTypes,
830                                                 ExpandedTInfos);
831       } else {
832         Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
833                                                 SourceLocation(),
834                                                 SourceLocation(),
835                                                 NTTP->getDepth(),
836                                                 NTTP->getPosition(), nullptr,
837                                                 T,
838                                                 NTTP->isParameterPack(),
839                                                 TInfo);
840       }
841       if (AutoType *AT = T->getContainedAutoType()) {
842         if (AT->isConstrained()) {
843           Param->setPlaceholderTypeConstraint(
844               canonicalizeImmediatelyDeclaredConstraint(
845                   *this, NTTP->getPlaceholderTypeConstraint(), T));
846         }
847       }
848       CanonParams.push_back(Param);
849 
850     } else
851       CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
852                                            cast<TemplateTemplateParmDecl>(*P)));
853   }
854 
855   Expr *CanonRequiresClause = nullptr;
856   if (Expr *RequiresClause = TTP->getTemplateParameters()->getRequiresClause())
857     CanonRequiresClause = RequiresClause;
858 
859   TemplateTemplateParmDecl *CanonTTP
860     = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
861                                        SourceLocation(), TTP->getDepth(),
862                                        TTP->getPosition(),
863                                        TTP->isParameterPack(),
864                                        nullptr,
865                          TemplateParameterList::Create(*this, SourceLocation(),
866                                                        SourceLocation(),
867                                                        CanonParams,
868                                                        SourceLocation(),
869                                                        CanonRequiresClause));
870 
871   // Get the new insert position for the node we care about.
872   Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
873   assert(!Canonical && "Shouldn't be in the map!");
874   (void)Canonical;
875 
876   // Create the canonical template template parameter entry.
877   Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
878   CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
879   return CanonTTP;
880 }
881 
882 CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
883   if (!LangOpts.CPlusPlus) return nullptr;
884 
885   switch (T.getCXXABI().getKind()) {
886   case TargetCXXABI::AppleARM64:
887   case TargetCXXABI::Fuchsia:
888   case TargetCXXABI::GenericARM: // Same as Itanium at this level
889   case TargetCXXABI::iOS:
890   case TargetCXXABI::WatchOS:
891   case TargetCXXABI::GenericAArch64:
892   case TargetCXXABI::GenericMIPS:
893   case TargetCXXABI::GenericItanium:
894   case TargetCXXABI::WebAssembly:
895   case TargetCXXABI::XL:
896     return CreateItaniumCXXABI(*this);
897   case TargetCXXABI::Microsoft:
898     return CreateMicrosoftCXXABI(*this);
899   }
900   llvm_unreachable("Invalid CXXABI type!");
901 }
902 
903 interp::Context &ASTContext::getInterpContext() {
904   if (!InterpContext) {
905     InterpContext.reset(new interp::Context(*this));
906   }
907   return *InterpContext.get();
908 }
909 
910 ParentMapContext &ASTContext::getParentMapContext() {
911   if (!ParentMapCtx)
912     ParentMapCtx.reset(new ParentMapContext(*this));
913   return *ParentMapCtx.get();
914 }
915 
916 static const LangASMap *getAddressSpaceMap(const TargetInfo &T,
917                                            const LangOptions &LOpts) {
918   if (LOpts.FakeAddressSpaceMap) {
919     // The fake address space map must have a distinct entry for each
920     // language-specific address space.
921     static const unsigned FakeAddrSpaceMap[] = {
922         0,  // Default
923         1,  // opencl_global
924         3,  // opencl_local
925         2,  // opencl_constant
926         0,  // opencl_private
927         4,  // opencl_generic
928         5,  // opencl_global_device
929         6,  // opencl_global_host
930         7,  // cuda_device
931         8,  // cuda_constant
932         9,  // cuda_shared
933         10, // ptr32_sptr
934         11, // ptr32_uptr
935         12  // ptr64
936     };
937     return &FakeAddrSpaceMap;
938   } else {
939     return &T.getAddressSpaceMap();
940   }
941 }
942 
943 static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
944                                           const LangOptions &LangOpts) {
945   switch (LangOpts.getAddressSpaceMapMangling()) {
946   case LangOptions::ASMM_Target:
947     return TI.useAddressSpaceMapMangling();
948   case LangOptions::ASMM_On:
949     return true;
950   case LangOptions::ASMM_Off:
951     return false;
952   }
953   llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
954 }
955 
956 ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
957                        IdentifierTable &idents, SelectorTable &sels,
958                        Builtin::Context &builtins)
959     : ConstantArrayTypes(this_()), FunctionProtoTypes(this_()),
960       TemplateSpecializationTypes(this_()),
961       DependentTemplateSpecializationTypes(this_()), AutoTypes(this_()),
962       SubstTemplateTemplateParmPacks(this_()),
963       CanonTemplateTemplateParms(this_()), SourceMgr(SM), LangOpts(LOpts),
964       SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFiles, SM)),
965       XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
966                                         LangOpts.XRayNeverInstrumentFiles,
967                                         LangOpts.XRayAttrListFiles, SM)),
968       ProfList(new ProfileList(LangOpts.ProfileListFiles, SM)),
969       PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
970       BuiltinInfo(builtins), DeclarationNames(*this), Comments(SM),
971       CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
972       CompCategories(this_()), LastSDM(nullptr, 0) {
973   TUDecl = TranslationUnitDecl::Create(*this);
974   TraversalScope = {TUDecl};
975 }
976 
977 ASTContext::~ASTContext() {
978   // Release the DenseMaps associated with DeclContext objects.
979   // FIXME: Is this the ideal solution?
980   ReleaseDeclContextMaps();
981 
982   // Call all of the deallocation functions on all of their targets.
983   for (auto &Pair : Deallocations)
984     (Pair.first)(Pair.second);
985 
986   // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
987   // because they can contain DenseMaps.
988   for (llvm::DenseMap<const ObjCContainerDecl*,
989        const ASTRecordLayout*>::iterator
990        I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
991     // Increment in loop to prevent using deallocated memory.
992     if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
993       R->Destroy(*this);
994 
995   for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
996        I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
997     // Increment in loop to prevent using deallocated memory.
998     if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
999       R->Destroy(*this);
1000   }
1001 
1002   for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
1003                                                     AEnd = DeclAttrs.end();
1004        A != AEnd; ++A)
1005     A->second->~AttrVec();
1006 
1007   for (const auto &Value : ModuleInitializers)
1008     Value.second->~PerModuleInitializers();
1009 }
1010 
1011 void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) {
1012   TraversalScope = TopLevelDecls;
1013   getParentMapContext().clear();
1014 }
1015 
1016 void ASTContext::AddDeallocation(void (*Callback)(void *), void *Data) const {
1017   Deallocations.push_back({Callback, Data});
1018 }
1019 
1020 void
1021 ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
1022   ExternalSource = std::move(Source);
1023 }
1024 
1025 void ASTContext::PrintStats() const {
1026   llvm::errs() << "\n*** AST Context Stats:\n";
1027   llvm::errs() << "  " << Types.size() << " types total.\n";
1028 
1029   unsigned counts[] = {
1030 #define TYPE(Name, Parent) 0,
1031 #define ABSTRACT_TYPE(Name, Parent)
1032 #include "clang/AST/TypeNodes.inc"
1033     0 // Extra
1034   };
1035 
1036   for (unsigned i = 0, e = Types.size(); i != e; ++i) {
1037     Type *T = Types[i];
1038     counts[(unsigned)T->getTypeClass()]++;
1039   }
1040 
1041   unsigned Idx = 0;
1042   unsigned TotalBytes = 0;
1043 #define TYPE(Name, Parent)                                              \
1044   if (counts[Idx])                                                      \
1045     llvm::errs() << "    " << counts[Idx] << " " << #Name               \
1046                  << " types, " << sizeof(Name##Type) << " each "        \
1047                  << "(" << counts[Idx] * sizeof(Name##Type)             \
1048                  << " bytes)\n";                                        \
1049   TotalBytes += counts[Idx] * sizeof(Name##Type);                       \
1050   ++Idx;
1051 #define ABSTRACT_TYPE(Name, Parent)
1052 #include "clang/AST/TypeNodes.inc"
1053 
1054   llvm::errs() << "Total bytes = " << TotalBytes << "\n";
1055 
1056   // Implicit special member functions.
1057   llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
1058                << NumImplicitDefaultConstructors
1059                << " implicit default constructors created\n";
1060   llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
1061                << NumImplicitCopyConstructors
1062                << " implicit copy constructors created\n";
1063   if (getLangOpts().CPlusPlus)
1064     llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
1065                  << NumImplicitMoveConstructors
1066                  << " implicit move constructors created\n";
1067   llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
1068                << NumImplicitCopyAssignmentOperators
1069                << " implicit copy assignment operators created\n";
1070   if (getLangOpts().CPlusPlus)
1071     llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
1072                  << NumImplicitMoveAssignmentOperators
1073                  << " implicit move assignment operators created\n";
1074   llvm::errs() << NumImplicitDestructorsDeclared << "/"
1075                << NumImplicitDestructors
1076                << " implicit destructors created\n";
1077 
1078   if (ExternalSource) {
1079     llvm::errs() << "\n";
1080     ExternalSource->PrintStats();
1081   }
1082 
1083   BumpAlloc.PrintStats();
1084 }
1085 
1086 void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
1087                                            bool NotifyListeners) {
1088   if (NotifyListeners)
1089     if (auto *Listener = getASTMutationListener())
1090       Listener->RedefinedHiddenDefinition(ND, M);
1091 
1092   MergedDefModules[cast<NamedDecl>(ND->getCanonicalDecl())].push_back(M);
1093 }
1094 
1095 void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
1096   auto It = MergedDefModules.find(cast<NamedDecl>(ND->getCanonicalDecl()));
1097   if (It == MergedDefModules.end())
1098     return;
1099 
1100   auto &Merged = It->second;
1101   llvm::DenseSet<Module*> Found;
1102   for (Module *&M : Merged)
1103     if (!Found.insert(M).second)
1104       M = nullptr;
1105   Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end());
1106 }
1107 
1108 ArrayRef<Module *>
1109 ASTContext::getModulesWithMergedDefinition(const NamedDecl *Def) {
1110   auto MergedIt =
1111       MergedDefModules.find(cast<NamedDecl>(Def->getCanonicalDecl()));
1112   if (MergedIt == MergedDefModules.end())
1113     return None;
1114   return MergedIt->second;
1115 }
1116 
1117 void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
1118   if (LazyInitializers.empty())
1119     return;
1120 
1121   auto *Source = Ctx.getExternalSource();
1122   assert(Source && "lazy initializers but no external source");
1123 
1124   auto LazyInits = std::move(LazyInitializers);
1125   LazyInitializers.clear();
1126 
1127   for (auto ID : LazyInits)
1128     Initializers.push_back(Source->GetExternalDecl(ID));
1129 
1130   assert(LazyInitializers.empty() &&
1131          "GetExternalDecl for lazy module initializer added more inits");
1132 }
1133 
1134 void ASTContext::addModuleInitializer(Module *M, Decl *D) {
1135   // One special case: if we add a module initializer that imports another
1136   // module, and that module's only initializer is an ImportDecl, simplify.
1137   if (const auto *ID = dyn_cast<ImportDecl>(D)) {
1138     auto It = ModuleInitializers.find(ID->getImportedModule());
1139 
1140     // Maybe the ImportDecl does nothing at all. (Common case.)
1141     if (It == ModuleInitializers.end())
1142       return;
1143 
1144     // Maybe the ImportDecl only imports another ImportDecl.
1145     auto &Imported = *It->second;
1146     if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
1147       Imported.resolve(*this);
1148       auto *OnlyDecl = Imported.Initializers.front();
1149       if (isa<ImportDecl>(OnlyDecl))
1150         D = OnlyDecl;
1151     }
1152   }
1153 
1154   auto *&Inits = ModuleInitializers[M];
1155   if (!Inits)
1156     Inits = new (*this) PerModuleInitializers;
1157   Inits->Initializers.push_back(D);
1158 }
1159 
1160 void ASTContext::addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs) {
1161   auto *&Inits = ModuleInitializers[M];
1162   if (!Inits)
1163     Inits = new (*this) PerModuleInitializers;
1164   Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
1165                                  IDs.begin(), IDs.end());
1166 }
1167 
1168 ArrayRef<Decl *> ASTContext::getModuleInitializers(Module *M) {
1169   auto It = ModuleInitializers.find(M);
1170   if (It == ModuleInitializers.end())
1171     return None;
1172 
1173   auto *Inits = It->second;
1174   Inits->resolve(*this);
1175   return Inits->Initializers;
1176 }
1177 
1178 ExternCContextDecl *ASTContext::getExternCContextDecl() const {
1179   if (!ExternCContext)
1180     ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
1181 
1182   return ExternCContext;
1183 }
1184 
1185 BuiltinTemplateDecl *
1186 ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
1187                                      const IdentifierInfo *II) const {
1188   auto *BuiltinTemplate = BuiltinTemplateDecl::Create(*this, TUDecl, II, BTK);
1189   BuiltinTemplate->setImplicit();
1190   TUDecl->addDecl(BuiltinTemplate);
1191 
1192   return BuiltinTemplate;
1193 }
1194 
1195 BuiltinTemplateDecl *
1196 ASTContext::getMakeIntegerSeqDecl() const {
1197   if (!MakeIntegerSeqDecl)
1198     MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq,
1199                                                   getMakeIntegerSeqName());
1200   return MakeIntegerSeqDecl;
1201 }
1202 
1203 BuiltinTemplateDecl *
1204 ASTContext::getTypePackElementDecl() const {
1205   if (!TypePackElementDecl)
1206     TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element,
1207                                                    getTypePackElementName());
1208   return TypePackElementDecl;
1209 }
1210 
1211 RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
1212                                             RecordDecl::TagKind TK) const {
1213   SourceLocation Loc;
1214   RecordDecl *NewDecl;
1215   if (getLangOpts().CPlusPlus)
1216     NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1217                                     Loc, &Idents.get(Name));
1218   else
1219     NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1220                                  &Idents.get(Name));
1221   NewDecl->setImplicit();
1222   NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1223       const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
1224   return NewDecl;
1225 }
1226 
1227 TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
1228                                               StringRef Name) const {
1229   TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
1230   TypedefDecl *NewDecl = TypedefDecl::Create(
1231       const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1232       SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1233   NewDecl->setImplicit();
1234   return NewDecl;
1235 }
1236 
1237 TypedefDecl *ASTContext::getInt128Decl() const {
1238   if (!Int128Decl)
1239     Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
1240   return Int128Decl;
1241 }
1242 
1243 TypedefDecl *ASTContext::getUInt128Decl() const {
1244   if (!UInt128Decl)
1245     UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
1246   return UInt128Decl;
1247 }
1248 
1249 void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
1250   auto *Ty = new (*this, TypeAlignment) BuiltinType(K);
1251   R = CanQualType::CreateUnsafe(QualType(Ty, 0));
1252   Types.push_back(Ty);
1253 }
1254 
1255 void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
1256                                   const TargetInfo *AuxTarget) {
1257   assert((!this->Target || this->Target == &Target) &&
1258          "Incorrect target reinitialization");
1259   assert(VoidTy.isNull() && "Context reinitialized?");
1260 
1261   this->Target = &Target;
1262   this->AuxTarget = AuxTarget;
1263 
1264   ABI.reset(createCXXABI(Target));
1265   AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
1266   AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
1267 
1268   // C99 6.2.5p19.
1269   InitBuiltinType(VoidTy,              BuiltinType::Void);
1270 
1271   // C99 6.2.5p2.
1272   InitBuiltinType(BoolTy,              BuiltinType::Bool);
1273   // C99 6.2.5p3.
1274   if (LangOpts.CharIsSigned)
1275     InitBuiltinType(CharTy,            BuiltinType::Char_S);
1276   else
1277     InitBuiltinType(CharTy,            BuiltinType::Char_U);
1278   // C99 6.2.5p4.
1279   InitBuiltinType(SignedCharTy,        BuiltinType::SChar);
1280   InitBuiltinType(ShortTy,             BuiltinType::Short);
1281   InitBuiltinType(IntTy,               BuiltinType::Int);
1282   InitBuiltinType(LongTy,              BuiltinType::Long);
1283   InitBuiltinType(LongLongTy,          BuiltinType::LongLong);
1284 
1285   // C99 6.2.5p6.
1286   InitBuiltinType(UnsignedCharTy,      BuiltinType::UChar);
1287   InitBuiltinType(UnsignedShortTy,     BuiltinType::UShort);
1288   InitBuiltinType(UnsignedIntTy,       BuiltinType::UInt);
1289   InitBuiltinType(UnsignedLongTy,      BuiltinType::ULong);
1290   InitBuiltinType(UnsignedLongLongTy,  BuiltinType::ULongLong);
1291 
1292   // C99 6.2.5p10.
1293   InitBuiltinType(FloatTy,             BuiltinType::Float);
1294   InitBuiltinType(DoubleTy,            BuiltinType::Double);
1295   InitBuiltinType(LongDoubleTy,        BuiltinType::LongDouble);
1296 
1297   // GNU extension, __float128 for IEEE quadruple precision
1298   InitBuiltinType(Float128Ty,          BuiltinType::Float128);
1299 
1300   // C11 extension ISO/IEC TS 18661-3
1301   InitBuiltinType(Float16Ty,           BuiltinType::Float16);
1302 
1303   // ISO/IEC JTC1 SC22 WG14 N1169 Extension
1304   InitBuiltinType(ShortAccumTy,            BuiltinType::ShortAccum);
1305   InitBuiltinType(AccumTy,                 BuiltinType::Accum);
1306   InitBuiltinType(LongAccumTy,             BuiltinType::LongAccum);
1307   InitBuiltinType(UnsignedShortAccumTy,    BuiltinType::UShortAccum);
1308   InitBuiltinType(UnsignedAccumTy,         BuiltinType::UAccum);
1309   InitBuiltinType(UnsignedLongAccumTy,     BuiltinType::ULongAccum);
1310   InitBuiltinType(ShortFractTy,            BuiltinType::ShortFract);
1311   InitBuiltinType(FractTy,                 BuiltinType::Fract);
1312   InitBuiltinType(LongFractTy,             BuiltinType::LongFract);
1313   InitBuiltinType(UnsignedShortFractTy,    BuiltinType::UShortFract);
1314   InitBuiltinType(UnsignedFractTy,         BuiltinType::UFract);
1315   InitBuiltinType(UnsignedLongFractTy,     BuiltinType::ULongFract);
1316   InitBuiltinType(SatShortAccumTy,         BuiltinType::SatShortAccum);
1317   InitBuiltinType(SatAccumTy,              BuiltinType::SatAccum);
1318   InitBuiltinType(SatLongAccumTy,          BuiltinType::SatLongAccum);
1319   InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum);
1320   InitBuiltinType(SatUnsignedAccumTy,      BuiltinType::SatUAccum);
1321   InitBuiltinType(SatUnsignedLongAccumTy,  BuiltinType::SatULongAccum);
1322   InitBuiltinType(SatShortFractTy,         BuiltinType::SatShortFract);
1323   InitBuiltinType(SatFractTy,              BuiltinType::SatFract);
1324   InitBuiltinType(SatLongFractTy,          BuiltinType::SatLongFract);
1325   InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract);
1326   InitBuiltinType(SatUnsignedFractTy,      BuiltinType::SatUFract);
1327   InitBuiltinType(SatUnsignedLongFractTy,  BuiltinType::SatULongFract);
1328 
1329   // GNU extension, 128-bit integers.
1330   InitBuiltinType(Int128Ty,            BuiltinType::Int128);
1331   InitBuiltinType(UnsignedInt128Ty,    BuiltinType::UInt128);
1332 
1333   // C++ 3.9.1p5
1334   if (TargetInfo::isTypeSigned(Target.getWCharType()))
1335     InitBuiltinType(WCharTy,           BuiltinType::WChar_S);
1336   else  // -fshort-wchar makes wchar_t be unsigned.
1337     InitBuiltinType(WCharTy,           BuiltinType::WChar_U);
1338   if (LangOpts.CPlusPlus && LangOpts.WChar)
1339     WideCharTy = WCharTy;
1340   else {
1341     // C99 (or C++ using -fno-wchar).
1342     WideCharTy = getFromTargetType(Target.getWCharType());
1343   }
1344 
1345   WIntTy = getFromTargetType(Target.getWIntType());
1346 
1347   // C++20 (proposed)
1348   InitBuiltinType(Char8Ty,              BuiltinType::Char8);
1349 
1350   if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1351     InitBuiltinType(Char16Ty,           BuiltinType::Char16);
1352   else // C99
1353     Char16Ty = getFromTargetType(Target.getChar16Type());
1354 
1355   if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1356     InitBuiltinType(Char32Ty,           BuiltinType::Char32);
1357   else // C99
1358     Char32Ty = getFromTargetType(Target.getChar32Type());
1359 
1360   // Placeholder type for type-dependent expressions whose type is
1361   // completely unknown. No code should ever check a type against
1362   // DependentTy and users should never see it; however, it is here to
1363   // help diagnose failures to properly check for type-dependent
1364   // expressions.
1365   InitBuiltinType(DependentTy,         BuiltinType::Dependent);
1366 
1367   // Placeholder type for functions.
1368   InitBuiltinType(OverloadTy,          BuiltinType::Overload);
1369 
1370   // Placeholder type for bound members.
1371   InitBuiltinType(BoundMemberTy,       BuiltinType::BoundMember);
1372 
1373   // Placeholder type for pseudo-objects.
1374   InitBuiltinType(PseudoObjectTy,      BuiltinType::PseudoObject);
1375 
1376   // "any" type; useful for debugger-like clients.
1377   InitBuiltinType(UnknownAnyTy,        BuiltinType::UnknownAny);
1378 
1379   // Placeholder type for unbridged ARC casts.
1380   InitBuiltinType(ARCUnbridgedCastTy,  BuiltinType::ARCUnbridgedCast);
1381 
1382   // Placeholder type for builtin functions.
1383   InitBuiltinType(BuiltinFnTy,  BuiltinType::BuiltinFn);
1384 
1385   // Placeholder type for OMP array sections.
1386   if (LangOpts.OpenMP) {
1387     InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
1388     InitBuiltinType(OMPArrayShapingTy, BuiltinType::OMPArrayShaping);
1389     InitBuiltinType(OMPIteratorTy, BuiltinType::OMPIterator);
1390   }
1391   if (LangOpts.MatrixTypes)
1392     InitBuiltinType(IncompleteMatrixIdxTy, BuiltinType::IncompleteMatrixIdx);
1393 
1394   // C99 6.2.5p11.
1395   FloatComplexTy      = getComplexType(FloatTy);
1396   DoubleComplexTy     = getComplexType(DoubleTy);
1397   LongDoubleComplexTy = getComplexType(LongDoubleTy);
1398   Float128ComplexTy   = getComplexType(Float128Ty);
1399 
1400   // Builtin types for 'id', 'Class', and 'SEL'.
1401   InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1402   InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
1403   InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
1404 
1405   if (LangOpts.OpenCL) {
1406 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1407     InitBuiltinType(SingletonId, BuiltinType::Id);
1408 #include "clang/Basic/OpenCLImageTypes.def"
1409 
1410     InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
1411     InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
1412     InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1413     InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
1414     InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
1415 
1416 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1417     InitBuiltinType(Id##Ty, BuiltinType::Id);
1418 #include "clang/Basic/OpenCLExtensionTypes.def"
1419   }
1420 
1421   if (Target.hasAArch64SVETypes()) {
1422 #define SVE_TYPE(Name, Id, SingletonId) \
1423     InitBuiltinType(SingletonId, BuiltinType::Id);
1424 #include "clang/Basic/AArch64SVEACLETypes.def"
1425   }
1426 
1427   if (Target.getTriple().isPPC64() &&
1428       Target.hasFeature("paired-vector-memops")) {
1429     if (Target.hasFeature("mma")) {
1430 #define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \
1431       InitBuiltinType(Id##Ty, BuiltinType::Id);
1432 #include "clang/Basic/PPCTypes.def"
1433     }
1434 #define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \
1435     InitBuiltinType(Id##Ty, BuiltinType::Id);
1436 #include "clang/Basic/PPCTypes.def"
1437   }
1438 
1439   if (Target.hasRISCVVTypes()) {
1440 #define RVV_TYPE(Name, Id, SingletonId)                                        \
1441   InitBuiltinType(SingletonId, BuiltinType::Id);
1442 #include "clang/Basic/RISCVVTypes.def"
1443   }
1444 
1445   // Builtin type for __objc_yes and __objc_no
1446   ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1447                        SignedCharTy : BoolTy);
1448 
1449   ObjCConstantStringType = QualType();
1450 
1451   ObjCSuperType = QualType();
1452 
1453   // void * type
1454   if (LangOpts.OpenCLGenericAddressSpace) {
1455     auto Q = VoidTy.getQualifiers();
1456     Q.setAddressSpace(LangAS::opencl_generic);
1457     VoidPtrTy = getPointerType(getCanonicalType(
1458         getQualifiedType(VoidTy.getUnqualifiedType(), Q)));
1459   } else {
1460     VoidPtrTy = getPointerType(VoidTy);
1461   }
1462 
1463   // nullptr type (C++0x 2.14.7)
1464   InitBuiltinType(NullPtrTy,           BuiltinType::NullPtr);
1465 
1466   // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1467   InitBuiltinType(HalfTy, BuiltinType::Half);
1468 
1469   InitBuiltinType(BFloat16Ty, BuiltinType::BFloat16);
1470 
1471   // Builtin type used to help define __builtin_va_list.
1472   VaListTagDecl = nullptr;
1473 
1474   // MSVC predeclares struct _GUID, and we need it to create MSGuidDecls.
1475   if (LangOpts.MicrosoftExt || LangOpts.Borland) {
1476     MSGuidTagDecl = buildImplicitRecord("_GUID");
1477     TUDecl->addDecl(MSGuidTagDecl);
1478   }
1479 }
1480 
1481 DiagnosticsEngine &ASTContext::getDiagnostics() const {
1482   return SourceMgr.getDiagnostics();
1483 }
1484 
1485 AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1486   AttrVec *&Result = DeclAttrs[D];
1487   if (!Result) {
1488     void *Mem = Allocate(sizeof(AttrVec));
1489     Result = new (Mem) AttrVec;
1490   }
1491 
1492   return *Result;
1493 }
1494 
1495 /// Erase the attributes corresponding to the given declaration.
1496 void ASTContext::eraseDeclAttrs(const Decl *D) {
1497   llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1498   if (Pos != DeclAttrs.end()) {
1499     Pos->second->~AttrVec();
1500     DeclAttrs.erase(Pos);
1501   }
1502 }
1503 
1504 // FIXME: Remove ?
1505 MemberSpecializationInfo *
1506 ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
1507   assert(Var->isStaticDataMember() && "Not a static data member");
1508   return getTemplateOrSpecializationInfo(Var)
1509       .dyn_cast<MemberSpecializationInfo *>();
1510 }
1511 
1512 ASTContext::TemplateOrSpecializationInfo
1513 ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1514   llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1515       TemplateOrInstantiation.find(Var);
1516   if (Pos == TemplateOrInstantiation.end())
1517     return {};
1518 
1519   return Pos->second;
1520 }
1521 
1522 void
1523 ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
1524                                                 TemplateSpecializationKind TSK,
1525                                           SourceLocation PointOfInstantiation) {
1526   assert(Inst->isStaticDataMember() && "Not a static data member");
1527   assert(Tmpl->isStaticDataMember() && "Not a static data member");
1528   setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1529                                             Tmpl, TSK, PointOfInstantiation));
1530 }
1531 
1532 void
1533 ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1534                                             TemplateOrSpecializationInfo TSI) {
1535   assert(!TemplateOrInstantiation[Inst] &&
1536          "Already noted what the variable was instantiated from");
1537   TemplateOrInstantiation[Inst] = TSI;
1538 }
1539 
1540 NamedDecl *
1541 ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) {
1542   auto Pos = InstantiatedFromUsingDecl.find(UUD);
1543   if (Pos == InstantiatedFromUsingDecl.end())
1544     return nullptr;
1545 
1546   return Pos->second;
1547 }
1548 
1549 void
1550 ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) {
1551   assert((isa<UsingDecl>(Pattern) ||
1552           isa<UnresolvedUsingValueDecl>(Pattern) ||
1553           isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1554          "pattern decl is not a using decl");
1555   assert((isa<UsingDecl>(Inst) ||
1556           isa<UnresolvedUsingValueDecl>(Inst) ||
1557           isa<UnresolvedUsingTypenameDecl>(Inst)) &&
1558          "instantiation did not produce a using decl");
1559   assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1560   InstantiatedFromUsingDecl[Inst] = Pattern;
1561 }
1562 
1563 UsingShadowDecl *
1564 ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1565   llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1566     = InstantiatedFromUsingShadowDecl.find(Inst);
1567   if (Pos == InstantiatedFromUsingShadowDecl.end())
1568     return nullptr;
1569 
1570   return Pos->second;
1571 }
1572 
1573 void
1574 ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1575                                                UsingShadowDecl *Pattern) {
1576   assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1577   InstantiatedFromUsingShadowDecl[Inst] = Pattern;
1578 }
1579 
1580 FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1581   llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1582     = InstantiatedFromUnnamedFieldDecl.find(Field);
1583   if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1584     return nullptr;
1585 
1586   return Pos->second;
1587 }
1588 
1589 void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1590                                                      FieldDecl *Tmpl) {
1591   assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1592   assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1593   assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1594          "Already noted what unnamed field was instantiated from");
1595 
1596   InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1597 }
1598 
1599 ASTContext::overridden_cxx_method_iterator
1600 ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1601   return overridden_methods(Method).begin();
1602 }
1603 
1604 ASTContext::overridden_cxx_method_iterator
1605 ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1606   return overridden_methods(Method).end();
1607 }
1608 
1609 unsigned
1610 ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1611   auto Range = overridden_methods(Method);
1612   return Range.end() - Range.begin();
1613 }
1614 
1615 ASTContext::overridden_method_range
1616 ASTContext::overridden_methods(const CXXMethodDecl *Method) const {
1617   llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1618       OverriddenMethods.find(Method->getCanonicalDecl());
1619   if (Pos == OverriddenMethods.end())
1620     return overridden_method_range(nullptr, nullptr);
1621   return overridden_method_range(Pos->second.begin(), Pos->second.end());
1622 }
1623 
1624 void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1625                                      const CXXMethodDecl *Overridden) {
1626   assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
1627   OverriddenMethods[Method].push_back(Overridden);
1628 }
1629 
1630 void ASTContext::getOverriddenMethods(
1631                       const NamedDecl *D,
1632                       SmallVectorImpl<const NamedDecl *> &Overridden) const {
1633   assert(D);
1634 
1635   if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
1636     Overridden.append(overridden_methods_begin(CXXMethod),
1637                       overridden_methods_end(CXXMethod));
1638     return;
1639   }
1640 
1641   const auto *Method = dyn_cast<ObjCMethodDecl>(D);
1642   if (!Method)
1643     return;
1644 
1645   SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1646   Method->getOverriddenMethods(OverDecls);
1647   Overridden.append(OverDecls.begin(), OverDecls.end());
1648 }
1649 
1650 void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1651   assert(!Import->getNextLocalImport() &&
1652          "Import declaration already in the chain");
1653   assert(!Import->isFromASTFile() && "Non-local import declaration");
1654   if (!FirstLocalImport) {
1655     FirstLocalImport = Import;
1656     LastLocalImport = Import;
1657     return;
1658   }
1659 
1660   LastLocalImport->setNextLocalImport(Import);
1661   LastLocalImport = Import;
1662 }
1663 
1664 //===----------------------------------------------------------------------===//
1665 //                         Type Sizing and Analysis
1666 //===----------------------------------------------------------------------===//
1667 
1668 /// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1669 /// scalar floating point type.
1670 const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
1671   switch (T->castAs<BuiltinType>()->getKind()) {
1672   default:
1673     llvm_unreachable("Not a floating point type!");
1674   case BuiltinType::BFloat16:
1675     return Target->getBFloat16Format();
1676   case BuiltinType::Float16:
1677   case BuiltinType::Half:
1678     return Target->getHalfFormat();
1679   case BuiltinType::Float:      return Target->getFloatFormat();
1680   case BuiltinType::Double:     return Target->getDoubleFormat();
1681   case BuiltinType::LongDouble:
1682     if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice)
1683       return AuxTarget->getLongDoubleFormat();
1684     return Target->getLongDoubleFormat();
1685   case BuiltinType::Float128:
1686     if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice)
1687       return AuxTarget->getFloat128Format();
1688     return Target->getFloat128Format();
1689   }
1690 }
1691 
1692 CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
1693   unsigned Align = Target->getCharWidth();
1694 
1695   bool UseAlignAttrOnly = false;
1696   if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1697     Align = AlignFromAttr;
1698 
1699     // __attribute__((aligned)) can increase or decrease alignment
1700     // *except* on a struct or struct member, where it only increases
1701     // alignment unless 'packed' is also specified.
1702     //
1703     // It is an error for alignas to decrease alignment, so we can
1704     // ignore that possibility;  Sema should diagnose it.
1705     if (isa<FieldDecl>(D)) {
1706       UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1707         cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1708     } else {
1709       UseAlignAttrOnly = true;
1710     }
1711   }
1712   else if (isa<FieldDecl>(D))
1713       UseAlignAttrOnly =
1714         D->hasAttr<PackedAttr>() ||
1715         cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1716 
1717   // If we're using the align attribute only, just ignore everything
1718   // else about the declaration and its type.
1719   if (UseAlignAttrOnly) {
1720     // do nothing
1721   } else if (const auto *VD = dyn_cast<ValueDecl>(D)) {
1722     QualType T = VD->getType();
1723     if (const auto *RT = T->getAs<ReferenceType>()) {
1724       if (ForAlignof)
1725         T = RT->getPointeeType();
1726       else
1727         T = getPointerType(RT->getPointeeType());
1728     }
1729     QualType BaseT = getBaseElementType(T);
1730     if (T->isFunctionType())
1731       Align = getTypeInfoImpl(T.getTypePtr()).Align;
1732     else if (!BaseT->isIncompleteType()) {
1733       // Adjust alignments of declarations with array type by the
1734       // large-array alignment on the target.
1735       if (const ArrayType *arrayType = getAsArrayType(T)) {
1736         unsigned MinWidth = Target->getLargeArrayMinWidth();
1737         if (!ForAlignof && MinWidth) {
1738           if (isa<VariableArrayType>(arrayType))
1739             Align = std::max(Align, Target->getLargeArrayAlign());
1740           else if (isa<ConstantArrayType>(arrayType) &&
1741                    MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1742             Align = std::max(Align, Target->getLargeArrayAlign());
1743         }
1744       }
1745       Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
1746       if (BaseT.getQualifiers().hasUnaligned())
1747         Align = Target->getCharWidth();
1748       if (const auto *VD = dyn_cast<VarDecl>(D)) {
1749         if (VD->hasGlobalStorage() && !ForAlignof) {
1750           uint64_t TypeSize = getTypeSize(T.getTypePtr());
1751           Align = std::max(Align, getTargetInfo().getMinGlobalAlign(TypeSize));
1752         }
1753       }
1754     }
1755 
1756     // Fields can be subject to extra alignment constraints, like if
1757     // the field is packed, the struct is packed, or the struct has a
1758     // a max-field-alignment constraint (#pragma pack).  So calculate
1759     // the actual alignment of the field within the struct, and then
1760     // (as we're expected to) constrain that by the alignment of the type.
1761     if (const auto *Field = dyn_cast<FieldDecl>(VD)) {
1762       const RecordDecl *Parent = Field->getParent();
1763       // We can only produce a sensible answer if the record is valid.
1764       if (!Parent->isInvalidDecl()) {
1765         const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
1766 
1767         // Start with the record's overall alignment.
1768         unsigned FieldAlign = toBits(Layout.getAlignment());
1769 
1770         // Use the GCD of that and the offset within the record.
1771         uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1772         if (Offset > 0) {
1773           // Alignment is always a power of 2, so the GCD will be a power of 2,
1774           // which means we get to do this crazy thing instead of Euclid's.
1775           uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1776           if (LowBitOfOffset < FieldAlign)
1777             FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1778         }
1779 
1780         Align = std::min(Align, FieldAlign);
1781       }
1782     }
1783   }
1784 
1785   return toCharUnitsFromBits(Align);
1786 }
1787 
1788 CharUnits ASTContext::getExnObjectAlignment() const {
1789   return toCharUnitsFromBits(Target->getExnObjectAlignment());
1790 }
1791 
1792 // getTypeInfoDataSizeInChars - Return the size of a type, in
1793 // chars. If the type is a record, its data size is returned.  This is
1794 // the size of the memcpy that's performed when assigning this type
1795 // using a trivial copy/move assignment operator.
1796 TypeInfoChars ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1797   TypeInfoChars Info = getTypeInfoInChars(T);
1798 
1799   // In C++, objects can sometimes be allocated into the tail padding
1800   // of a base-class subobject.  We decide whether that's possible
1801   // during class layout, so here we can just trust the layout results.
1802   if (getLangOpts().CPlusPlus) {
1803     if (const auto *RT = T->getAs<RecordType>()) {
1804       const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1805       Info.Width = layout.getDataSize();
1806     }
1807   }
1808 
1809   return Info;
1810 }
1811 
1812 /// getConstantArrayInfoInChars - Performing the computation in CharUnits
1813 /// instead of in bits prevents overflowing the uint64_t for some large arrays.
1814 TypeInfoChars
1815 static getConstantArrayInfoInChars(const ASTContext &Context,
1816                                    const ConstantArrayType *CAT) {
1817   TypeInfoChars EltInfo = Context.getTypeInfoInChars(CAT->getElementType());
1818   uint64_t Size = CAT->getSize().getZExtValue();
1819   assert((Size == 0 || static_cast<uint64_t>(EltInfo.Width.getQuantity()) <=
1820               (uint64_t)(-1)/Size) &&
1821          "Overflow in array type char size evaluation");
1822   uint64_t Width = EltInfo.Width.getQuantity() * Size;
1823   unsigned Align = EltInfo.Align.getQuantity();
1824   if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1825       Context.getTargetInfo().getPointerWidth(0) == 64)
1826     Width = llvm::alignTo(Width, Align);
1827   return TypeInfoChars(CharUnits::fromQuantity(Width),
1828                        CharUnits::fromQuantity(Align),
1829                        EltInfo.AlignIsRequired);
1830 }
1831 
1832 TypeInfoChars ASTContext::getTypeInfoInChars(const Type *T) const {
1833   if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
1834     return getConstantArrayInfoInChars(*this, CAT);
1835   TypeInfo Info = getTypeInfo(T);
1836   return TypeInfoChars(toCharUnitsFromBits(Info.Width),
1837                        toCharUnitsFromBits(Info.Align),
1838                        Info.AlignIsRequired);
1839 }
1840 
1841 TypeInfoChars ASTContext::getTypeInfoInChars(QualType T) const {
1842   return getTypeInfoInChars(T.getTypePtr());
1843 }
1844 
1845 bool ASTContext::isAlignmentRequired(const Type *T) const {
1846   return getTypeInfo(T).AlignIsRequired;
1847 }
1848 
1849 bool ASTContext::isAlignmentRequired(QualType T) const {
1850   return isAlignmentRequired(T.getTypePtr());
1851 }
1852 
1853 unsigned ASTContext::getTypeAlignIfKnown(QualType T,
1854                                          bool NeedsPreferredAlignment) const {
1855   // An alignment on a typedef overrides anything else.
1856   if (const auto *TT = T->getAs<TypedefType>())
1857     if (unsigned Align = TT->getDecl()->getMaxAlignment())
1858       return Align;
1859 
1860   // If we have an (array of) complete type, we're done.
1861   T = getBaseElementType(T);
1862   if (!T->isIncompleteType())
1863     return NeedsPreferredAlignment ? getPreferredTypeAlign(T) : getTypeAlign(T);
1864 
1865   // If we had an array type, its element type might be a typedef
1866   // type with an alignment attribute.
1867   if (const auto *TT = T->getAs<TypedefType>())
1868     if (unsigned Align = TT->getDecl()->getMaxAlignment())
1869       return Align;
1870 
1871   // Otherwise, see if the declaration of the type had an attribute.
1872   if (const auto *TT = T->getAs<TagType>())
1873     return TT->getDecl()->getMaxAlignment();
1874 
1875   return 0;
1876 }
1877 
1878 TypeInfo ASTContext::getTypeInfo(const Type *T) const {
1879   TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1880   if (I != MemoizedTypeInfo.end())
1881     return I->second;
1882 
1883   // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1884   TypeInfo TI = getTypeInfoImpl(T);
1885   MemoizedTypeInfo[T] = TI;
1886   return TI;
1887 }
1888 
1889 /// getTypeInfoImpl - Return the size of the specified type, in bits.  This
1890 /// method does not work on incomplete types.
1891 ///
1892 /// FIXME: Pointers into different addr spaces could have different sizes and
1893 /// alignment requirements: getPointerInfo should take an AddrSpace, this
1894 /// should take a QualType, &c.
1895 TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1896   uint64_t Width = 0;
1897   unsigned Align = 8;
1898   bool AlignIsRequired = false;
1899   unsigned AS = 0;
1900   switch (T->getTypeClass()) {
1901 #define TYPE(Class, Base)
1902 #define ABSTRACT_TYPE(Class, Base)
1903 #define NON_CANONICAL_TYPE(Class, Base)
1904 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1905 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)                       \
1906   case Type::Class:                                                            \
1907   assert(!T->isDependentType() && "should not see dependent types here");      \
1908   return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
1909 #include "clang/AST/TypeNodes.inc"
1910     llvm_unreachable("Should not see dependent types");
1911 
1912   case Type::FunctionNoProto:
1913   case Type::FunctionProto:
1914     // GCC extension: alignof(function) = 32 bits
1915     Width = 0;
1916     Align = 32;
1917     break;
1918 
1919   case Type::IncompleteArray:
1920   case Type::VariableArray:
1921   case Type::ConstantArray: {
1922     // Model non-constant sized arrays as size zero, but track the alignment.
1923     uint64_t Size = 0;
1924     if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
1925       Size = CAT->getSize().getZExtValue();
1926 
1927     TypeInfo EltInfo = getTypeInfo(cast<ArrayType>(T)->getElementType());
1928     assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
1929            "Overflow in array type bit size evaluation");
1930     Width = EltInfo.Width * Size;
1931     Align = EltInfo.Align;
1932     AlignIsRequired = EltInfo.AlignIsRequired;
1933     if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1934         getTargetInfo().getPointerWidth(0) == 64)
1935       Width = llvm::alignTo(Width, Align);
1936     break;
1937   }
1938 
1939   case Type::ExtVector:
1940   case Type::Vector: {
1941     const auto *VT = cast<VectorType>(T);
1942     TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1943     Width = EltInfo.Width * VT->getNumElements();
1944     Align = Width;
1945     // If the alignment is not a power of 2, round up to the next power of 2.
1946     // This happens for non-power-of-2 length vectors.
1947     if (Align & (Align-1)) {
1948       Align = llvm::NextPowerOf2(Align);
1949       Width = llvm::alignTo(Width, Align);
1950     }
1951     // Adjust the alignment based on the target max.
1952     uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1953     if (TargetVectorAlign && TargetVectorAlign < Align)
1954       Align = TargetVectorAlign;
1955     if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector)
1956       // Adjust the alignment for fixed-length SVE vectors. This is important
1957       // for non-power-of-2 vector lengths.
1958       Align = 128;
1959     else if (VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector)
1960       // Adjust the alignment for fixed-length SVE predicates.
1961       Align = 16;
1962     break;
1963   }
1964 
1965   case Type::ConstantMatrix: {
1966     const auto *MT = cast<ConstantMatrixType>(T);
1967     TypeInfo ElementInfo = getTypeInfo(MT->getElementType());
1968     // The internal layout of a matrix value is implementation defined.
1969     // Initially be ABI compatible with arrays with respect to alignment and
1970     // size.
1971     Width = ElementInfo.Width * MT->getNumRows() * MT->getNumColumns();
1972     Align = ElementInfo.Align;
1973     break;
1974   }
1975 
1976   case Type::Builtin:
1977     switch (cast<BuiltinType>(T)->getKind()) {
1978     default: llvm_unreachable("Unknown builtin type!");
1979     case BuiltinType::Void:
1980       // GCC extension: alignof(void) = 8 bits.
1981       Width = 0;
1982       Align = 8;
1983       break;
1984     case BuiltinType::Bool:
1985       Width = Target->getBoolWidth();
1986       Align = Target->getBoolAlign();
1987       break;
1988     case BuiltinType::Char_S:
1989     case BuiltinType::Char_U:
1990     case BuiltinType::UChar:
1991     case BuiltinType::SChar:
1992     case BuiltinType::Char8:
1993       Width = Target->getCharWidth();
1994       Align = Target->getCharAlign();
1995       break;
1996     case BuiltinType::WChar_S:
1997     case BuiltinType::WChar_U:
1998       Width = Target->getWCharWidth();
1999       Align = Target->getWCharAlign();
2000       break;
2001     case BuiltinType::Char16:
2002       Width = Target->getChar16Width();
2003       Align = Target->getChar16Align();
2004       break;
2005     case BuiltinType::Char32:
2006       Width = Target->getChar32Width();
2007       Align = Target->getChar32Align();
2008       break;
2009     case BuiltinType::UShort:
2010     case BuiltinType::Short:
2011       Width = Target->getShortWidth();
2012       Align = Target->getShortAlign();
2013       break;
2014     case BuiltinType::UInt:
2015     case BuiltinType::Int:
2016       Width = Target->getIntWidth();
2017       Align = Target->getIntAlign();
2018       break;
2019     case BuiltinType::ULong:
2020     case BuiltinType::Long:
2021       Width = Target->getLongWidth();
2022       Align = Target->getLongAlign();
2023       break;
2024     case BuiltinType::ULongLong:
2025     case BuiltinType::LongLong:
2026       Width = Target->getLongLongWidth();
2027       Align = Target->getLongLongAlign();
2028       break;
2029     case BuiltinType::Int128:
2030     case BuiltinType::UInt128:
2031       Width = 128;
2032       Align = 128; // int128_t is 128-bit aligned on all targets.
2033       break;
2034     case BuiltinType::ShortAccum:
2035     case BuiltinType::UShortAccum:
2036     case BuiltinType::SatShortAccum:
2037     case BuiltinType::SatUShortAccum:
2038       Width = Target->getShortAccumWidth();
2039       Align = Target->getShortAccumAlign();
2040       break;
2041     case BuiltinType::Accum:
2042     case BuiltinType::UAccum:
2043     case BuiltinType::SatAccum:
2044     case BuiltinType::SatUAccum:
2045       Width = Target->getAccumWidth();
2046       Align = Target->getAccumAlign();
2047       break;
2048     case BuiltinType::LongAccum:
2049     case BuiltinType::ULongAccum:
2050     case BuiltinType::SatLongAccum:
2051     case BuiltinType::SatULongAccum:
2052       Width = Target->getLongAccumWidth();
2053       Align = Target->getLongAccumAlign();
2054       break;
2055     case BuiltinType::ShortFract:
2056     case BuiltinType::UShortFract:
2057     case BuiltinType::SatShortFract:
2058     case BuiltinType::SatUShortFract:
2059       Width = Target->getShortFractWidth();
2060       Align = Target->getShortFractAlign();
2061       break;
2062     case BuiltinType::Fract:
2063     case BuiltinType::UFract:
2064     case BuiltinType::SatFract:
2065     case BuiltinType::SatUFract:
2066       Width = Target->getFractWidth();
2067       Align = Target->getFractAlign();
2068       break;
2069     case BuiltinType::LongFract:
2070     case BuiltinType::ULongFract:
2071     case BuiltinType::SatLongFract:
2072     case BuiltinType::SatULongFract:
2073       Width = Target->getLongFractWidth();
2074       Align = Target->getLongFractAlign();
2075       break;
2076     case BuiltinType::BFloat16:
2077       Width = Target->getBFloat16Width();
2078       Align = Target->getBFloat16Align();
2079       break;
2080     case BuiltinType::Float16:
2081     case BuiltinType::Half:
2082       if (Target->hasFloat16Type() || !getLangOpts().OpenMP ||
2083           !getLangOpts().OpenMPIsDevice) {
2084         Width = Target->getHalfWidth();
2085         Align = Target->getHalfAlign();
2086       } else {
2087         assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
2088                "Expected OpenMP device compilation.");
2089         Width = AuxTarget->getHalfWidth();
2090         Align = AuxTarget->getHalfAlign();
2091       }
2092       break;
2093     case BuiltinType::Float:
2094       Width = Target->getFloatWidth();
2095       Align = Target->getFloatAlign();
2096       break;
2097     case BuiltinType::Double:
2098       Width = Target->getDoubleWidth();
2099       Align = Target->getDoubleAlign();
2100       break;
2101     case BuiltinType::LongDouble:
2102       if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
2103           (Target->getLongDoubleWidth() != AuxTarget->getLongDoubleWidth() ||
2104            Target->getLongDoubleAlign() != AuxTarget->getLongDoubleAlign())) {
2105         Width = AuxTarget->getLongDoubleWidth();
2106         Align = AuxTarget->getLongDoubleAlign();
2107       } else {
2108         Width = Target->getLongDoubleWidth();
2109         Align = Target->getLongDoubleAlign();
2110       }
2111       break;
2112     case BuiltinType::Float128:
2113       if (Target->hasFloat128Type() || !getLangOpts().OpenMP ||
2114           !getLangOpts().OpenMPIsDevice) {
2115         Width = Target->getFloat128Width();
2116         Align = Target->getFloat128Align();
2117       } else {
2118         assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
2119                "Expected OpenMP device compilation.");
2120         Width = AuxTarget->getFloat128Width();
2121         Align = AuxTarget->getFloat128Align();
2122       }
2123       break;
2124     case BuiltinType::NullPtr:
2125       Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
2126       Align = Target->getPointerAlign(0); //   == sizeof(void*)
2127       break;
2128     case BuiltinType::ObjCId:
2129     case BuiltinType::ObjCClass:
2130     case BuiltinType::ObjCSel:
2131       Width = Target->getPointerWidth(0);
2132       Align = Target->getPointerAlign(0);
2133       break;
2134     case BuiltinType::OCLSampler:
2135     case BuiltinType::OCLEvent:
2136     case BuiltinType::OCLClkEvent:
2137     case BuiltinType::OCLQueue:
2138     case BuiltinType::OCLReserveID:
2139 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2140     case BuiltinType::Id:
2141 #include "clang/Basic/OpenCLImageTypes.def"
2142 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2143   case BuiltinType::Id:
2144 #include "clang/Basic/OpenCLExtensionTypes.def"
2145       AS = getTargetAddressSpace(
2146           Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T)));
2147       Width = Target->getPointerWidth(AS);
2148       Align = Target->getPointerAlign(AS);
2149       break;
2150     // The SVE types are effectively target-specific.  The length of an
2151     // SVE_VECTOR_TYPE is only known at runtime, but it is always a multiple
2152     // of 128 bits.  There is one predicate bit for each vector byte, so the
2153     // length of an SVE_PREDICATE_TYPE is always a multiple of 16 bits.
2154     //
2155     // Because the length is only known at runtime, we use a dummy value
2156     // of 0 for the static length.  The alignment values are those defined
2157     // by the Procedure Call Standard for the Arm Architecture.
2158 #define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId, NumEls, ElBits,    \
2159                         IsSigned, IsFP, IsBF)                                  \
2160   case BuiltinType::Id:                                                        \
2161     Width = 0;                                                                 \
2162     Align = 128;                                                               \
2163     break;
2164 #define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId, NumEls)         \
2165   case BuiltinType::Id:                                                        \
2166     Width = 0;                                                                 \
2167     Align = 16;                                                                \
2168     break;
2169 #include "clang/Basic/AArch64SVEACLETypes.def"
2170 #define PPC_VECTOR_TYPE(Name, Id, Size)                                        \
2171   case BuiltinType::Id:                                                        \
2172     Width = Size;                                                              \
2173     Align = Size;                                                              \
2174     break;
2175 #include "clang/Basic/PPCTypes.def"
2176 #define RVV_VECTOR_TYPE(Name, Id, SingletonId, ElKind, ElBits, NF, IsSigned,   \
2177                         IsFP)                                                  \
2178   case BuiltinType::Id:                                                        \
2179     Width = 0;                                                                 \
2180     Align = ElBits;                                                            \
2181     break;
2182 #define RVV_PREDICATE_TYPE(Name, Id, SingletonId, ElKind)                      \
2183   case BuiltinType::Id:                                                        \
2184     Width = 0;                                                                 \
2185     Align = 8;                                                                 \
2186     break;
2187 #include "clang/Basic/RISCVVTypes.def"
2188     }
2189     break;
2190   case Type::ObjCObjectPointer:
2191     Width = Target->getPointerWidth(0);
2192     Align = Target->getPointerAlign(0);
2193     break;
2194   case Type::BlockPointer:
2195     AS = getTargetAddressSpace(cast<BlockPointerType>(T)->getPointeeType());
2196     Width = Target->getPointerWidth(AS);
2197     Align = Target->getPointerAlign(AS);
2198     break;
2199   case Type::LValueReference:
2200   case Type::RValueReference:
2201     // alignof and sizeof should never enter this code path here, so we go
2202     // the pointer route.
2203     AS = getTargetAddressSpace(cast<ReferenceType>(T)->getPointeeType());
2204     Width = Target->getPointerWidth(AS);
2205     Align = Target->getPointerAlign(AS);
2206     break;
2207   case Type::Pointer:
2208     AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
2209     Width = Target->getPointerWidth(AS);
2210     Align = Target->getPointerAlign(AS);
2211     break;
2212   case Type::MemberPointer: {
2213     const auto *MPT = cast<MemberPointerType>(T);
2214     CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT);
2215     Width = MPI.Width;
2216     Align = MPI.Align;
2217     break;
2218   }
2219   case Type::Complex: {
2220     // Complex types have the same alignment as their elements, but twice the
2221     // size.
2222     TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
2223     Width = EltInfo.Width * 2;
2224     Align = EltInfo.Align;
2225     break;
2226   }
2227   case Type::ObjCObject:
2228     return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
2229   case Type::Adjusted:
2230   case Type::Decayed:
2231     return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
2232   case Type::ObjCInterface: {
2233     const auto *ObjCI = cast<ObjCInterfaceType>(T);
2234     if (ObjCI->getDecl()->isInvalidDecl()) {
2235       Width = 8;
2236       Align = 8;
2237       break;
2238     }
2239     const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2240     Width = toBits(Layout.getSize());
2241     Align = toBits(Layout.getAlignment());
2242     break;
2243   }
2244   case Type::ExtInt: {
2245     const auto *EIT = cast<ExtIntType>(T);
2246     Align =
2247         std::min(static_cast<unsigned>(std::max(
2248                      getCharWidth(), llvm::PowerOf2Ceil(EIT->getNumBits()))),
2249                  Target->getLongLongAlign());
2250     Width = llvm::alignTo(EIT->getNumBits(), Align);
2251     break;
2252   }
2253   case Type::Record:
2254   case Type::Enum: {
2255     const auto *TT = cast<TagType>(T);
2256 
2257     if (TT->getDecl()->isInvalidDecl()) {
2258       Width = 8;
2259       Align = 8;
2260       break;
2261     }
2262 
2263     if (const auto *ET = dyn_cast<EnumType>(TT)) {
2264       const EnumDecl *ED = ET->getDecl();
2265       TypeInfo Info =
2266           getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
2267       if (unsigned AttrAlign = ED->getMaxAlignment()) {
2268         Info.Align = AttrAlign;
2269         Info.AlignIsRequired = true;
2270       }
2271       return Info;
2272     }
2273 
2274     const auto *RT = cast<RecordType>(TT);
2275     const RecordDecl *RD = RT->getDecl();
2276     const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2277     Width = toBits(Layout.getSize());
2278     Align = toBits(Layout.getAlignment());
2279     AlignIsRequired = RD->hasAttr<AlignedAttr>();
2280     break;
2281   }
2282 
2283   case Type::SubstTemplateTypeParm:
2284     return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
2285                        getReplacementType().getTypePtr());
2286 
2287   case Type::Auto:
2288   case Type::DeducedTemplateSpecialization: {
2289     const auto *A = cast<DeducedType>(T);
2290     assert(!A->getDeducedType().isNull() &&
2291            "cannot request the size of an undeduced or dependent auto type");
2292     return getTypeInfo(A->getDeducedType().getTypePtr());
2293   }
2294 
2295   case Type::Paren:
2296     return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
2297 
2298   case Type::MacroQualified:
2299     return getTypeInfo(
2300         cast<MacroQualifiedType>(T)->getUnderlyingType().getTypePtr());
2301 
2302   case Type::ObjCTypeParam:
2303     return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
2304 
2305   case Type::Typedef: {
2306     const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
2307     TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
2308     // If the typedef has an aligned attribute on it, it overrides any computed
2309     // alignment we have.  This violates the GCC documentation (which says that
2310     // attribute(aligned) can only round up) but matches its implementation.
2311     if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
2312       Align = AttrAlign;
2313       AlignIsRequired = true;
2314     } else {
2315       Align = Info.Align;
2316       AlignIsRequired = Info.AlignIsRequired;
2317     }
2318     Width = Info.Width;
2319     break;
2320   }
2321 
2322   case Type::Elaborated:
2323     return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
2324 
2325   case Type::Attributed:
2326     return getTypeInfo(
2327                   cast<AttributedType>(T)->getEquivalentType().getTypePtr());
2328 
2329   case Type::Atomic: {
2330     // Start with the base type information.
2331     TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
2332     Width = Info.Width;
2333     Align = Info.Align;
2334 
2335     if (!Width) {
2336       // An otherwise zero-sized type should still generate an
2337       // atomic operation.
2338       Width = Target->getCharWidth();
2339       assert(Align);
2340     } else if (Width <= Target->getMaxAtomicPromoteWidth()) {
2341       // If the size of the type doesn't exceed the platform's max
2342       // atomic promotion width, make the size and alignment more
2343       // favorable to atomic operations:
2344 
2345       // Round the size up to a power of 2.
2346       if (!llvm::isPowerOf2_64(Width))
2347         Width = llvm::NextPowerOf2(Width);
2348 
2349       // Set the alignment equal to the size.
2350       Align = static_cast<unsigned>(Width);
2351     }
2352   }
2353   break;
2354 
2355   case Type::Pipe:
2356     Width = Target->getPointerWidth(getTargetAddressSpace(LangAS::opencl_global));
2357     Align = Target->getPointerAlign(getTargetAddressSpace(LangAS::opencl_global));
2358     break;
2359   }
2360 
2361   assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
2362   return TypeInfo(Width, Align, AlignIsRequired);
2363 }
2364 
2365 unsigned ASTContext::getTypeUnadjustedAlign(const Type *T) const {
2366   UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T);
2367   if (I != MemoizedUnadjustedAlign.end())
2368     return I->second;
2369 
2370   unsigned UnadjustedAlign;
2371   if (const auto *RT = T->getAs<RecordType>()) {
2372     const RecordDecl *RD = RT->getDecl();
2373     const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2374     UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2375   } else if (const auto *ObjCI = T->getAs<ObjCInterfaceType>()) {
2376     const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2377     UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2378   } else {
2379     UnadjustedAlign = getTypeAlign(T->getUnqualifiedDesugaredType());
2380   }
2381 
2382   MemoizedUnadjustedAlign[T] = UnadjustedAlign;
2383   return UnadjustedAlign;
2384 }
2385 
2386 unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
2387   unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
2388   return SimdAlign;
2389 }
2390 
2391 /// toCharUnitsFromBits - Convert a size in bits to a size in characters.
2392 CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
2393   return CharUnits::fromQuantity(BitSize / getCharWidth());
2394 }
2395 
2396 /// toBits - Convert a size in characters to a size in characters.
2397 int64_t ASTContext::toBits(CharUnits CharSize) const {
2398   return CharSize.getQuantity() * getCharWidth();
2399 }
2400 
2401 /// getTypeSizeInChars - Return the size of the specified type, in characters.
2402 /// This method does not work on incomplete types.
2403 CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
2404   return getTypeInfoInChars(T).Width;
2405 }
2406 CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
2407   return getTypeInfoInChars(T).Width;
2408 }
2409 
2410 /// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
2411 /// characters. This method does not work on incomplete types.
2412 CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
2413   return toCharUnitsFromBits(getTypeAlign(T));
2414 }
2415 CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
2416   return toCharUnitsFromBits(getTypeAlign(T));
2417 }
2418 
2419 /// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a
2420 /// type, in characters, before alignment adustments. This method does
2421 /// not work on incomplete types.
2422 CharUnits ASTContext::getTypeUnadjustedAlignInChars(QualType T) const {
2423   return toCharUnitsFromBits(getTypeUnadjustedAlign(T));
2424 }
2425 CharUnits ASTContext::getTypeUnadjustedAlignInChars(const Type *T) const {
2426   return toCharUnitsFromBits(getTypeUnadjustedAlign(T));
2427 }
2428 
2429 /// getPreferredTypeAlign - Return the "preferred" alignment of the specified
2430 /// type for the current target in bits.  This can be different than the ABI
2431 /// alignment in cases where it is beneficial for performance or backwards
2432 /// compatibility preserving to overalign a data type. (Note: despite the name,
2433 /// the preferred alignment is ABI-impacting, and not an optimization.)
2434 unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
2435   TypeInfo TI = getTypeInfo(T);
2436   unsigned ABIAlign = TI.Align;
2437 
2438   T = T->getBaseElementTypeUnsafe();
2439 
2440   // The preferred alignment of member pointers is that of a pointer.
2441   if (T->isMemberPointerType())
2442     return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
2443 
2444   if (!Target->allowsLargerPreferedTypeAlignment())
2445     return ABIAlign;
2446 
2447   if (const auto *RT = T->getAs<RecordType>()) {
2448     if (TI.AlignIsRequired || RT->getDecl()->isInvalidDecl())
2449       return ABIAlign;
2450 
2451     unsigned PreferredAlign = static_cast<unsigned>(
2452         toBits(getASTRecordLayout(RT->getDecl()).PreferredAlignment));
2453     assert(PreferredAlign >= ABIAlign &&
2454            "PreferredAlign should be at least as large as ABIAlign.");
2455     return PreferredAlign;
2456   }
2457 
2458   // Double (and, for targets supporting AIX `power` alignment, long double) and
2459   // long long should be naturally aligned (despite requiring less alignment) if
2460   // possible.
2461   if (const auto *CT = T->getAs<ComplexType>())
2462     T = CT->getElementType().getTypePtr();
2463   if (const auto *ET = T->getAs<EnumType>())
2464     T = ET->getDecl()->getIntegerType().getTypePtr();
2465   if (T->isSpecificBuiltinType(BuiltinType::Double) ||
2466       T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2467       T->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2468       (T->isSpecificBuiltinType(BuiltinType::LongDouble) &&
2469        Target->defaultsToAIXPowerAlignment()))
2470     // Don't increase the alignment if an alignment attribute was specified on a
2471     // typedef declaration.
2472     if (!TI.AlignIsRequired)
2473       return std::max(ABIAlign, (unsigned)getTypeSize(T));
2474 
2475   return ABIAlign;
2476 }
2477 
2478 /// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2479 /// for __attribute__((aligned)) on this target, to be used if no alignment
2480 /// value is specified.
2481 unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const {
2482   return getTargetInfo().getDefaultAlignForAttributeAligned();
2483 }
2484 
2485 /// getAlignOfGlobalVar - Return the alignment in bits that should be given
2486 /// to a global variable of the specified type.
2487 unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
2488   uint64_t TypeSize = getTypeSize(T.getTypePtr());
2489   return std::max(getPreferredTypeAlign(T),
2490                   getTargetInfo().getMinGlobalAlign(TypeSize));
2491 }
2492 
2493 /// getAlignOfGlobalVarInChars - Return the alignment in characters that
2494 /// should be given to a global variable of the specified type.
2495 CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
2496   return toCharUnitsFromBits(getAlignOfGlobalVar(T));
2497 }
2498 
2499 CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
2500   CharUnits Offset = CharUnits::Zero();
2501   const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2502   while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2503     Offset += Layout->getBaseClassOffset(Base);
2504     Layout = &getASTRecordLayout(Base);
2505   }
2506   return Offset;
2507 }
2508 
2509 CharUnits ASTContext::getMemberPointerPathAdjustment(const APValue &MP) const {
2510   const ValueDecl *MPD = MP.getMemberPointerDecl();
2511   CharUnits ThisAdjustment = CharUnits::Zero();
2512   ArrayRef<const CXXRecordDecl*> Path = MP.getMemberPointerPath();
2513   bool DerivedMember = MP.isMemberPointerToDerivedMember();
2514   const CXXRecordDecl *RD = cast<CXXRecordDecl>(MPD->getDeclContext());
2515   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
2516     const CXXRecordDecl *Base = RD;
2517     const CXXRecordDecl *Derived = Path[I];
2518     if (DerivedMember)
2519       std::swap(Base, Derived);
2520     ThisAdjustment += getASTRecordLayout(Derived).getBaseClassOffset(Base);
2521     RD = Path[I];
2522   }
2523   if (DerivedMember)
2524     ThisAdjustment = -ThisAdjustment;
2525   return ThisAdjustment;
2526 }
2527 
2528 /// DeepCollectObjCIvars -
2529 /// This routine first collects all declared, but not synthesized, ivars in
2530 /// super class and then collects all ivars, including those synthesized for
2531 /// current class. This routine is used for implementation of current class
2532 /// when all ivars, declared and synthesized are known.
2533 void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
2534                                       bool leafClass,
2535                             SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
2536   if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2537     DeepCollectObjCIvars(SuperClass, false, Ivars);
2538   if (!leafClass) {
2539     for (const auto *I : OI->ivars())
2540       Ivars.push_back(I);
2541   } else {
2542     auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
2543     for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
2544          Iv= Iv->getNextIvar())
2545       Ivars.push_back(Iv);
2546   }
2547 }
2548 
2549 /// CollectInheritedProtocols - Collect all protocols in current class and
2550 /// those inherited by it.
2551 void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
2552                           llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
2553   if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
2554     // We can use protocol_iterator here instead of
2555     // all_referenced_protocol_iterator since we are walking all categories.
2556     for (auto *Proto : OI->all_referenced_protocols()) {
2557       CollectInheritedProtocols(Proto, Protocols);
2558     }
2559 
2560     // Categories of this Interface.
2561     for (const auto *Cat : OI->visible_categories())
2562       CollectInheritedProtocols(Cat, Protocols);
2563 
2564     if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2565       while (SD) {
2566         CollectInheritedProtocols(SD, Protocols);
2567         SD = SD->getSuperClass();
2568       }
2569   } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
2570     for (auto *Proto : OC->protocols()) {
2571       CollectInheritedProtocols(Proto, Protocols);
2572     }
2573   } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
2574     // Insert the protocol.
2575     if (!Protocols.insert(
2576           const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2577       return;
2578 
2579     for (auto *Proto : OP->protocols())
2580       CollectInheritedProtocols(Proto, Protocols);
2581   }
2582 }
2583 
2584 static bool unionHasUniqueObjectRepresentations(const ASTContext &Context,
2585                                                 const RecordDecl *RD) {
2586   assert(RD->isUnion() && "Must be union type");
2587   CharUnits UnionSize = Context.getTypeSizeInChars(RD->getTypeForDecl());
2588 
2589   for (const auto *Field : RD->fields()) {
2590     if (!Context.hasUniqueObjectRepresentations(Field->getType()))
2591       return false;
2592     CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType());
2593     if (FieldSize != UnionSize)
2594       return false;
2595   }
2596   return !RD->field_empty();
2597 }
2598 
2599 static bool isStructEmpty(QualType Ty) {
2600   const RecordDecl *RD = Ty->castAs<RecordType>()->getDecl();
2601 
2602   if (!RD->field_empty())
2603     return false;
2604 
2605   if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD))
2606     return ClassDecl->isEmpty();
2607 
2608   return true;
2609 }
2610 
2611 static llvm::Optional<int64_t>
2612 structHasUniqueObjectRepresentations(const ASTContext &Context,
2613                                      const RecordDecl *RD) {
2614   assert(!RD->isUnion() && "Must be struct/class type");
2615   const auto &Layout = Context.getASTRecordLayout(RD);
2616 
2617   int64_t CurOffsetInBits = 0;
2618   if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) {
2619     if (ClassDecl->isDynamicClass())
2620       return llvm::None;
2621 
2622     SmallVector<std::pair<QualType, int64_t>, 4> Bases;
2623     for (const auto &Base : ClassDecl->bases()) {
2624       // Empty types can be inherited from, and non-empty types can potentially
2625       // have tail padding, so just make sure there isn't an error.
2626       if (!isStructEmpty(Base.getType())) {
2627         llvm::Optional<int64_t> Size = structHasUniqueObjectRepresentations(
2628             Context, Base.getType()->castAs<RecordType>()->getDecl());
2629         if (!Size)
2630           return llvm::None;
2631         Bases.emplace_back(Base.getType(), Size.getValue());
2632       }
2633     }
2634 
2635     llvm::sort(Bases, [&](const std::pair<QualType, int64_t> &L,
2636                           const std::pair<QualType, int64_t> &R) {
2637       return Layout.getBaseClassOffset(L.first->getAsCXXRecordDecl()) <
2638              Layout.getBaseClassOffset(R.first->getAsCXXRecordDecl());
2639     });
2640 
2641     for (const auto &Base : Bases) {
2642       int64_t BaseOffset = Context.toBits(
2643           Layout.getBaseClassOffset(Base.first->getAsCXXRecordDecl()));
2644       int64_t BaseSize = Base.second;
2645       if (BaseOffset != CurOffsetInBits)
2646         return llvm::None;
2647       CurOffsetInBits = BaseOffset + BaseSize;
2648     }
2649   }
2650 
2651   for (const auto *Field : RD->fields()) {
2652     if (!Field->getType()->isReferenceType() &&
2653         !Context.hasUniqueObjectRepresentations(Field->getType()))
2654       return llvm::None;
2655 
2656     int64_t FieldSizeInBits =
2657         Context.toBits(Context.getTypeSizeInChars(Field->getType()));
2658     if (Field->isBitField()) {
2659       int64_t BitfieldSize = Field->getBitWidthValue(Context);
2660 
2661       if (BitfieldSize > FieldSizeInBits)
2662         return llvm::None;
2663       FieldSizeInBits = BitfieldSize;
2664     }
2665 
2666     int64_t FieldOffsetInBits = Context.getFieldOffset(Field);
2667 
2668     if (FieldOffsetInBits != CurOffsetInBits)
2669       return llvm::None;
2670 
2671     CurOffsetInBits = FieldSizeInBits + FieldOffsetInBits;
2672   }
2673 
2674   return CurOffsetInBits;
2675 }
2676 
2677 bool ASTContext::hasUniqueObjectRepresentations(QualType Ty) const {
2678   // C++17 [meta.unary.prop]:
2679   //   The predicate condition for a template specialization
2680   //   has_unique_object_representations<T> shall be
2681   //   satisfied if and only if:
2682   //     (9.1) - T is trivially copyable, and
2683   //     (9.2) - any two objects of type T with the same value have the same
2684   //     object representation, where two objects
2685   //   of array or non-union class type are considered to have the same value
2686   //   if their respective sequences of
2687   //   direct subobjects have the same values, and two objects of union type
2688   //   are considered to have the same
2689   //   value if they have the same active member and the corresponding members
2690   //   have the same value.
2691   //   The set of scalar types for which this condition holds is
2692   //   implementation-defined. [ Note: If a type has padding
2693   //   bits, the condition does not hold; otherwise, the condition holds true
2694   //   for unsigned integral types. -- end note ]
2695   assert(!Ty.isNull() && "Null QualType sent to unique object rep check");
2696 
2697   // Arrays are unique only if their element type is unique.
2698   if (Ty->isArrayType())
2699     return hasUniqueObjectRepresentations(getBaseElementType(Ty));
2700 
2701   // (9.1) - T is trivially copyable...
2702   if (!Ty.isTriviallyCopyableType(*this))
2703     return false;
2704 
2705   // All integrals and enums are unique.
2706   if (Ty->isIntegralOrEnumerationType())
2707     return true;
2708 
2709   // All other pointers are unique.
2710   if (Ty->isPointerType())
2711     return true;
2712 
2713   if (Ty->isMemberPointerType()) {
2714     const auto *MPT = Ty->getAs<MemberPointerType>();
2715     return !ABI->getMemberPointerInfo(MPT).HasPadding;
2716   }
2717 
2718   if (Ty->isRecordType()) {
2719     const RecordDecl *Record = Ty->castAs<RecordType>()->getDecl();
2720 
2721     if (Record->isInvalidDecl())
2722       return false;
2723 
2724     if (Record->isUnion())
2725       return unionHasUniqueObjectRepresentations(*this, Record);
2726 
2727     Optional<int64_t> StructSize =
2728         structHasUniqueObjectRepresentations(*this, Record);
2729 
2730     return StructSize &&
2731            StructSize.getValue() == static_cast<int64_t>(getTypeSize(Ty));
2732   }
2733 
2734   // FIXME: More cases to handle here (list by rsmith):
2735   // vectors (careful about, eg, vector of 3 foo)
2736   // _Complex int and friends
2737   // _Atomic T
2738   // Obj-C block pointers
2739   // Obj-C object pointers
2740   // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t,
2741   // clk_event_t, queue_t, reserve_id_t)
2742   // There're also Obj-C class types and the Obj-C selector type, but I think it
2743   // makes sense for those to return false here.
2744 
2745   return false;
2746 }
2747 
2748 unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
2749   unsigned count = 0;
2750   // Count ivars declared in class extension.
2751   for (const auto *Ext : OI->known_extensions())
2752     count += Ext->ivar_size();
2753 
2754   // Count ivar defined in this class's implementation.  This
2755   // includes synthesized ivars.
2756   if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
2757     count += ImplDecl->ivar_size();
2758 
2759   return count;
2760 }
2761 
2762 bool ASTContext::isSentinelNullExpr(const Expr *E) {
2763   if (!E)
2764     return false;
2765 
2766   // nullptr_t is always treated as null.
2767   if (E->getType()->isNullPtrType()) return true;
2768 
2769   if (E->getType()->isAnyPointerType() &&
2770       E->IgnoreParenCasts()->isNullPointerConstant(*this,
2771                                                 Expr::NPC_ValueDependentIsNull))
2772     return true;
2773 
2774   // Unfortunately, __null has type 'int'.
2775   if (isa<GNUNullExpr>(E)) return true;
2776 
2777   return false;
2778 }
2779 
2780 /// Get the implementation of ObjCInterfaceDecl, or nullptr if none
2781 /// exists.
2782 ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
2783   llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2784     I = ObjCImpls.find(D);
2785   if (I != ObjCImpls.end())
2786     return cast<ObjCImplementationDecl>(I->second);
2787   return nullptr;
2788 }
2789 
2790 /// Get the implementation of ObjCCategoryDecl, or nullptr if none
2791 /// exists.
2792 ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
2793   llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2794     I = ObjCImpls.find(D);
2795   if (I != ObjCImpls.end())
2796     return cast<ObjCCategoryImplDecl>(I->second);
2797   return nullptr;
2798 }
2799 
2800 /// Set the implementation of ObjCInterfaceDecl.
2801 void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2802                            ObjCImplementationDecl *ImplD) {
2803   assert(IFaceD && ImplD && "Passed null params");
2804   ObjCImpls[IFaceD] = ImplD;
2805 }
2806 
2807 /// Set the implementation of ObjCCategoryDecl.
2808 void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
2809                            ObjCCategoryImplDecl *ImplD) {
2810   assert(CatD && ImplD && "Passed null params");
2811   ObjCImpls[CatD] = ImplD;
2812 }
2813 
2814 const ObjCMethodDecl *
2815 ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const {
2816   return ObjCMethodRedecls.lookup(MD);
2817 }
2818 
2819 void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2820                                             const ObjCMethodDecl *Redecl) {
2821   assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
2822   ObjCMethodRedecls[MD] = Redecl;
2823 }
2824 
2825 const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
2826                                               const NamedDecl *ND) const {
2827   if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
2828     return ID;
2829   if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
2830     return CD->getClassInterface();
2831   if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
2832     return IMD->getClassInterface();
2833 
2834   return nullptr;
2835 }
2836 
2837 /// Get the copy initialization expression of VarDecl, or nullptr if
2838 /// none exists.
2839 BlockVarCopyInit ASTContext::getBlockVarCopyInit(const VarDecl *VD) const {
2840   assert(VD && "Passed null params");
2841   assert(VD->hasAttr<BlocksAttr>() &&
2842          "getBlockVarCopyInits - not __block var");
2843   auto I = BlockVarCopyInits.find(VD);
2844   if (I != BlockVarCopyInits.end())
2845     return I->second;
2846   return {nullptr, false};
2847 }
2848 
2849 /// Set the copy initialization expression of a block var decl.
2850 void ASTContext::setBlockVarCopyInit(const VarDecl*VD, Expr *CopyExpr,
2851                                      bool CanThrow) {
2852   assert(VD && CopyExpr && "Passed null params");
2853   assert(VD->hasAttr<BlocksAttr>() &&
2854          "setBlockVarCopyInits - not __block var");
2855   BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow);
2856 }
2857 
2858 TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
2859                                                  unsigned DataSize) const {
2860   if (!DataSize)
2861     DataSize = TypeLoc::getFullDataSizeForType(T);
2862   else
2863     assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
2864            "incorrect data size provided to CreateTypeSourceInfo!");
2865 
2866   auto *TInfo =
2867     (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2868   new (TInfo) TypeSourceInfo(T);
2869   return TInfo;
2870 }
2871 
2872 TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
2873                                                      SourceLocation L) const {
2874   TypeSourceInfo *DI = CreateTypeSourceInfo(T);
2875   DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
2876   return DI;
2877 }
2878 
2879 const ASTRecordLayout &
2880 ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
2881   return getObjCLayout(D, nullptr);
2882 }
2883 
2884 const ASTRecordLayout &
2885 ASTContext::getASTObjCImplementationLayout(
2886                                         const ObjCImplementationDecl *D) const {
2887   return getObjCLayout(D->getClassInterface(), D);
2888 }
2889 
2890 //===----------------------------------------------------------------------===//
2891 //                   Type creation/memoization methods
2892 //===----------------------------------------------------------------------===//
2893 
2894 QualType
2895 ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2896   unsigned fastQuals = quals.getFastQualifiers();
2897   quals.removeFastQualifiers();
2898 
2899   // Check if we've already instantiated this type.
2900   llvm::FoldingSetNodeID ID;
2901   ExtQuals::Profile(ID, baseType, quals);
2902   void *insertPos = nullptr;
2903   if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2904     assert(eq->getQualifiers() == quals);
2905     return QualType(eq, fastQuals);
2906   }
2907 
2908   // If the base type is not canonical, make the appropriate canonical type.
2909   QualType canon;
2910   if (!baseType->isCanonicalUnqualified()) {
2911     SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
2912     canonSplit.Quals.addConsistentQualifiers(quals);
2913     canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
2914 
2915     // Re-find the insert position.
2916     (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2917   }
2918 
2919   auto *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2920   ExtQualNodes.InsertNode(eq, insertPos);
2921   return QualType(eq, fastQuals);
2922 }
2923 
2924 QualType ASTContext::getAddrSpaceQualType(QualType T,
2925                                           LangAS AddressSpace) const {
2926   QualType CanT = getCanonicalType(T);
2927   if (CanT.getAddressSpace() == AddressSpace)
2928     return T;
2929 
2930   // If we are composing extended qualifiers together, merge together
2931   // into one ExtQuals node.
2932   QualifierCollector Quals;
2933   const Type *TypeNode = Quals.strip(T);
2934 
2935   // If this type already has an address space specified, it cannot get
2936   // another one.
2937   assert(!Quals.hasAddressSpace() &&
2938          "Type cannot be in multiple addr spaces!");
2939   Quals.addAddressSpace(AddressSpace);
2940 
2941   return getExtQualType(TypeNode, Quals);
2942 }
2943 
2944 QualType ASTContext::removeAddrSpaceQualType(QualType T) const {
2945   // If the type is not qualified with an address space, just return it
2946   // immediately.
2947   if (!T.hasAddressSpace())
2948     return T;
2949 
2950   // If we are composing extended qualifiers together, merge together
2951   // into one ExtQuals node.
2952   QualifierCollector Quals;
2953   const Type *TypeNode;
2954 
2955   while (T.hasAddressSpace()) {
2956     TypeNode = Quals.strip(T);
2957 
2958     // If the type no longer has an address space after stripping qualifiers,
2959     // jump out.
2960     if (!QualType(TypeNode, 0).hasAddressSpace())
2961       break;
2962 
2963     // There might be sugar in the way. Strip it and try again.
2964     T = T.getSingleStepDesugaredType(*this);
2965   }
2966 
2967   Quals.removeAddressSpace();
2968 
2969   // Removal of the address space can mean there are no longer any
2970   // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
2971   // or required.
2972   if (Quals.hasNonFastQualifiers())
2973     return getExtQualType(TypeNode, Quals);
2974   else
2975     return QualType(TypeNode, Quals.getFastQualifiers());
2976 }
2977 
2978 QualType ASTContext::getObjCGCQualType(QualType T,
2979                                        Qualifiers::GC GCAttr) const {
2980   QualType CanT = getCanonicalType(T);
2981   if (CanT.getObjCGCAttr() == GCAttr)
2982     return T;
2983 
2984   if (const auto *ptr = T->getAs<PointerType>()) {
2985     QualType Pointee = ptr->getPointeeType();
2986     if (Pointee->isAnyPointerType()) {
2987       QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2988       return getPointerType(ResultType);
2989     }
2990   }
2991 
2992   // If we are composing extended qualifiers together, merge together
2993   // into one ExtQuals node.
2994   QualifierCollector Quals;
2995   const Type *TypeNode = Quals.strip(T);
2996 
2997   // If this type already has an ObjCGC specified, it cannot get
2998   // another one.
2999   assert(!Quals.hasObjCGCAttr() &&
3000          "Type cannot have multiple ObjCGCs!");
3001   Quals.addObjCGCAttr(GCAttr);
3002 
3003   return getExtQualType(TypeNode, Quals);
3004 }
3005 
3006 QualType ASTContext::removePtrSizeAddrSpace(QualType T) const {
3007   if (const PointerType *Ptr = T->getAs<PointerType>()) {
3008     QualType Pointee = Ptr->getPointeeType();
3009     if (isPtrSizeAddressSpace(Pointee.getAddressSpace())) {
3010       return getPointerType(removeAddrSpaceQualType(Pointee));
3011     }
3012   }
3013   return T;
3014 }
3015 
3016 const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
3017                                                    FunctionType::ExtInfo Info) {
3018   if (T->getExtInfo() == Info)
3019     return T;
3020 
3021   QualType Result;
3022   if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
3023     Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
3024   } else {
3025     const auto *FPT = cast<FunctionProtoType>(T);
3026     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
3027     EPI.ExtInfo = Info;
3028     Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
3029   }
3030 
3031   return cast<FunctionType>(Result.getTypePtr());
3032 }
3033 
3034 void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
3035                                                  QualType ResultType) {
3036   FD = FD->getMostRecentDecl();
3037   while (true) {
3038     const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
3039     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
3040     FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
3041     if (FunctionDecl *Next = FD->getPreviousDecl())
3042       FD = Next;
3043     else
3044       break;
3045   }
3046   if (ASTMutationListener *L = getASTMutationListener())
3047     L->DeducedReturnType(FD, ResultType);
3048 }
3049 
3050 /// Get a function type and produce the equivalent function type with the
3051 /// specified exception specification. Type sugar that can be present on a
3052 /// declaration of a function with an exception specification is permitted
3053 /// and preserved. Other type sugar (for instance, typedefs) is not.
3054 QualType ASTContext::getFunctionTypeWithExceptionSpec(
3055     QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) {
3056   // Might have some parens.
3057   if (const auto *PT = dyn_cast<ParenType>(Orig))
3058     return getParenType(
3059         getFunctionTypeWithExceptionSpec(PT->getInnerType(), ESI));
3060 
3061   // Might be wrapped in a macro qualified type.
3062   if (const auto *MQT = dyn_cast<MacroQualifiedType>(Orig))
3063     return getMacroQualifiedType(
3064         getFunctionTypeWithExceptionSpec(MQT->getUnderlyingType(), ESI),
3065         MQT->getMacroIdentifier());
3066 
3067   // Might have a calling-convention attribute.
3068   if (const auto *AT = dyn_cast<AttributedType>(Orig))
3069     return getAttributedType(
3070         AT->getAttrKind(),
3071         getFunctionTypeWithExceptionSpec(AT->getModifiedType(), ESI),
3072         getFunctionTypeWithExceptionSpec(AT->getEquivalentType(), ESI));
3073 
3074   // Anything else must be a function type. Rebuild it with the new exception
3075   // specification.
3076   const auto *Proto = Orig->castAs<FunctionProtoType>();
3077   return getFunctionType(
3078       Proto->getReturnType(), Proto->getParamTypes(),
3079       Proto->getExtProtoInfo().withExceptionSpec(ESI));
3080 }
3081 
3082 bool ASTContext::hasSameFunctionTypeIgnoringExceptionSpec(QualType T,
3083                                                           QualType U) {
3084   return hasSameType(T, U) ||
3085          (getLangOpts().CPlusPlus17 &&
3086           hasSameType(getFunctionTypeWithExceptionSpec(T, EST_None),
3087                       getFunctionTypeWithExceptionSpec(U, EST_None)));
3088 }
3089 
3090 QualType ASTContext::getFunctionTypeWithoutPtrSizes(QualType T) {
3091   if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3092     QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3093     SmallVector<QualType, 16> Args(Proto->param_types());
3094     for (unsigned i = 0, n = Args.size(); i != n; ++i)
3095       Args[i] = removePtrSizeAddrSpace(Args[i]);
3096     return getFunctionType(RetTy, Args, Proto->getExtProtoInfo());
3097   }
3098 
3099   if (const FunctionNoProtoType *Proto = T->getAs<FunctionNoProtoType>()) {
3100     QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3101     return getFunctionNoProtoType(RetTy, Proto->getExtInfo());
3102   }
3103 
3104   return T;
3105 }
3106 
3107 bool ASTContext::hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U) {
3108   return hasSameType(T, U) ||
3109          hasSameType(getFunctionTypeWithoutPtrSizes(T),
3110                      getFunctionTypeWithoutPtrSizes(U));
3111 }
3112 
3113 void ASTContext::adjustExceptionSpec(
3114     FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
3115     bool AsWritten) {
3116   // Update the type.
3117   QualType Updated =
3118       getFunctionTypeWithExceptionSpec(FD->getType(), ESI);
3119   FD->setType(Updated);
3120 
3121   if (!AsWritten)
3122     return;
3123 
3124   // Update the type in the type source information too.
3125   if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
3126     // If the type and the type-as-written differ, we may need to update
3127     // the type-as-written too.
3128     if (TSInfo->getType() != FD->getType())
3129       Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI);
3130 
3131     // FIXME: When we get proper type location information for exceptions,
3132     // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
3133     // up the TypeSourceInfo;
3134     assert(TypeLoc::getFullDataSizeForType(Updated) ==
3135                TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
3136            "TypeLoc size mismatch from updating exception specification");
3137     TSInfo->overrideType(Updated);
3138   }
3139 }
3140 
3141 /// getComplexType - Return the uniqued reference to the type for a complex
3142 /// number with the specified element type.
3143 QualType ASTContext::getComplexType(QualType T) const {
3144   // Unique pointers, to guarantee there is only one pointer of a particular
3145   // structure.
3146   llvm::FoldingSetNodeID ID;
3147   ComplexType::Profile(ID, T);
3148 
3149   void *InsertPos = nullptr;
3150   if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
3151     return QualType(CT, 0);
3152 
3153   // If the pointee type isn't canonical, this won't be a canonical type either,
3154   // so fill in the canonical type field.
3155   QualType Canonical;
3156   if (!T.isCanonical()) {
3157     Canonical = getComplexType(getCanonicalType(T));
3158 
3159     // Get the new insert position for the node we care about.
3160     ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
3161     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3162   }
3163   auto *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
3164   Types.push_back(New);
3165   ComplexTypes.InsertNode(New, InsertPos);
3166   return QualType(New, 0);
3167 }
3168 
3169 /// getPointerType - Return the uniqued reference to the type for a pointer to
3170 /// the specified type.
3171 QualType ASTContext::getPointerType(QualType T) const {
3172   // Unique pointers, to guarantee there is only one pointer of a particular
3173   // structure.
3174   llvm::FoldingSetNodeID ID;
3175   PointerType::Profile(ID, T);
3176 
3177   void *InsertPos = nullptr;
3178   if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3179     return QualType(PT, 0);
3180 
3181   // If the pointee type isn't canonical, this won't be a canonical type either,
3182   // so fill in the canonical type field.
3183   QualType Canonical;
3184   if (!T.isCanonical()) {
3185     Canonical = getPointerType(getCanonicalType(T));
3186 
3187     // Get the new insert position for the node we care about.
3188     PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3189     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3190   }
3191   auto *New = new (*this, TypeAlignment) PointerType(T, Canonical);
3192   Types.push_back(New);
3193   PointerTypes.InsertNode(New, InsertPos);
3194   return QualType(New, 0);
3195 }
3196 
3197 QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
3198   llvm::FoldingSetNodeID ID;
3199   AdjustedType::Profile(ID, Orig, New);
3200   void *InsertPos = nullptr;
3201   AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3202   if (AT)
3203     return QualType(AT, 0);
3204 
3205   QualType Canonical = getCanonicalType(New);
3206 
3207   // Get the new insert position for the node we care about.
3208   AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3209   assert(!AT && "Shouldn't be in the map!");
3210 
3211   AT = new (*this, TypeAlignment)
3212       AdjustedType(Type::Adjusted, Orig, New, Canonical);
3213   Types.push_back(AT);
3214   AdjustedTypes.InsertNode(AT, InsertPos);
3215   return QualType(AT, 0);
3216 }
3217 
3218 QualType ASTContext::getDecayedType(QualType T) const {
3219   assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
3220 
3221   QualType Decayed;
3222 
3223   // C99 6.7.5.3p7:
3224   //   A declaration of a parameter as "array of type" shall be
3225   //   adjusted to "qualified pointer to type", where the type
3226   //   qualifiers (if any) are those specified within the [ and ] of
3227   //   the array type derivation.
3228   if (T->isArrayType())
3229     Decayed = getArrayDecayedType(T);
3230 
3231   // C99 6.7.5.3p8:
3232   //   A declaration of a parameter as "function returning type"
3233   //   shall be adjusted to "pointer to function returning type", as
3234   //   in 6.3.2.1.
3235   if (T->isFunctionType())
3236     Decayed = getPointerType(T);
3237 
3238   llvm::FoldingSetNodeID ID;
3239   AdjustedType::Profile(ID, T, Decayed);
3240   void *InsertPos = nullptr;
3241   AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3242   if (AT)
3243     return QualType(AT, 0);
3244 
3245   QualType Canonical = getCanonicalType(Decayed);
3246 
3247   // Get the new insert position for the node we care about.
3248   AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3249   assert(!AT && "Shouldn't be in the map!");
3250 
3251   AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
3252   Types.push_back(AT);
3253   AdjustedTypes.InsertNode(AT, InsertPos);
3254   return QualType(AT, 0);
3255 }
3256 
3257 /// getBlockPointerType - Return the uniqued reference to the type for
3258 /// a pointer to the specified block.
3259 QualType ASTContext::getBlockPointerType(QualType T) const {
3260   assert(T->isFunctionType() && "block of function types only");
3261   // Unique pointers, to guarantee there is only one block of a particular
3262   // structure.
3263   llvm::FoldingSetNodeID ID;
3264   BlockPointerType::Profile(ID, T);
3265 
3266   void *InsertPos = nullptr;
3267   if (BlockPointerType *PT =
3268         BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3269     return QualType(PT, 0);
3270 
3271   // If the block pointee type isn't canonical, this won't be a canonical
3272   // type either so fill in the canonical type field.
3273   QualType Canonical;
3274   if (!T.isCanonical()) {
3275     Canonical = getBlockPointerType(getCanonicalType(T));
3276 
3277     // Get the new insert position for the node we care about.
3278     BlockPointerType *NewIP =
3279       BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3280     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3281   }
3282   auto *New = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
3283   Types.push_back(New);
3284   BlockPointerTypes.InsertNode(New, InsertPos);
3285   return QualType(New, 0);
3286 }
3287 
3288 /// getLValueReferenceType - Return the uniqued reference to the type for an
3289 /// lvalue reference to the specified type.
3290 QualType
3291 ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
3292   assert(getCanonicalType(T) != OverloadTy &&
3293          "Unresolved overloaded function type");
3294 
3295   // Unique pointers, to guarantee there is only one pointer of a particular
3296   // structure.
3297   llvm::FoldingSetNodeID ID;
3298   ReferenceType::Profile(ID, T, SpelledAsLValue);
3299 
3300   void *InsertPos = nullptr;
3301   if (LValueReferenceType *RT =
3302         LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
3303     return QualType(RT, 0);
3304 
3305   const auto *InnerRef = T->getAs<ReferenceType>();
3306 
3307   // If the referencee type isn't canonical, this won't be a canonical type
3308   // either, so fill in the canonical type field.
3309   QualType Canonical;
3310   if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
3311     QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
3312     Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
3313 
3314     // Get the new insert position for the node we care about.
3315     LValueReferenceType *NewIP =
3316       LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
3317     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3318   }
3319 
3320   auto *New = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
3321                                                              SpelledAsLValue);
3322   Types.push_back(New);
3323   LValueReferenceTypes.InsertNode(New, InsertPos);
3324 
3325   return QualType(New, 0);
3326 }
3327 
3328 /// getRValueReferenceType - Return the uniqued reference to the type for an
3329 /// rvalue reference to the specified type.
3330 QualType ASTContext::getRValueReferenceType(QualType T) const {
3331   // Unique pointers, to guarantee there is only one pointer of a particular
3332   // structure.
3333   llvm::FoldingSetNodeID ID;
3334   ReferenceType::Profile(ID, T, false);
3335 
3336   void *InsertPos = nullptr;
3337   if (RValueReferenceType *RT =
3338         RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
3339     return QualType(RT, 0);
3340 
3341   const auto *InnerRef = T->getAs<ReferenceType>();
3342 
3343   // If the referencee type isn't canonical, this won't be a canonical type
3344   // either, so fill in the canonical type field.
3345   QualType Canonical;
3346   if (InnerRef || !T.isCanonical()) {
3347     QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
3348     Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
3349 
3350     // Get the new insert position for the node we care about.
3351     RValueReferenceType *NewIP =
3352       RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
3353     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3354   }
3355 
3356   auto *New = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
3357   Types.push_back(New);
3358   RValueReferenceTypes.InsertNode(New, InsertPos);
3359   return QualType(New, 0);
3360 }
3361 
3362 /// getMemberPointerType - Return the uniqued reference to the type for a
3363 /// member pointer to the specified type, in the specified class.
3364 QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
3365   // Unique pointers, to guarantee there is only one pointer of a particular
3366   // structure.
3367   llvm::FoldingSetNodeID ID;
3368   MemberPointerType::Profile(ID, T, Cls);
3369 
3370   void *InsertPos = nullptr;
3371   if (MemberPointerType *PT =
3372       MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3373     return QualType(PT, 0);
3374 
3375   // If the pointee or class type isn't canonical, this won't be a canonical
3376   // type either, so fill in the canonical type field.
3377   QualType Canonical;
3378   if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
3379     Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
3380 
3381     // Get the new insert position for the node we care about.
3382     MemberPointerType *NewIP =
3383       MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3384     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3385   }
3386   auto *New = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
3387   Types.push_back(New);
3388   MemberPointerTypes.InsertNode(New, InsertPos);
3389   return QualType(New, 0);
3390 }
3391 
3392 /// getConstantArrayType - Return the unique reference to the type for an
3393 /// array of the specified element type.
3394 QualType ASTContext::getConstantArrayType(QualType EltTy,
3395                                           const llvm::APInt &ArySizeIn,
3396                                           const Expr *SizeExpr,
3397                                           ArrayType::ArraySizeModifier ASM,
3398                                           unsigned IndexTypeQuals) const {
3399   assert((EltTy->isDependentType() ||
3400           EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
3401          "Constant array of VLAs is illegal!");
3402 
3403   // We only need the size as part of the type if it's instantiation-dependent.
3404   if (SizeExpr && !SizeExpr->isInstantiationDependent())
3405     SizeExpr = nullptr;
3406 
3407   // Convert the array size into a canonical width matching the pointer size for
3408   // the target.
3409   llvm::APInt ArySize(ArySizeIn);
3410   ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
3411 
3412   llvm::FoldingSetNodeID ID;
3413   ConstantArrayType::Profile(ID, *this, EltTy, ArySize, SizeExpr, ASM,
3414                              IndexTypeQuals);
3415 
3416   void *InsertPos = nullptr;
3417   if (ConstantArrayType *ATP =
3418       ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
3419     return QualType(ATP, 0);
3420 
3421   // If the element type isn't canonical or has qualifiers, or the array bound
3422   // is instantiation-dependent, this won't be a canonical type either, so fill
3423   // in the canonical type field.
3424   QualType Canon;
3425   if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers() || SizeExpr) {
3426     SplitQualType canonSplit = getCanonicalType(EltTy).split();
3427     Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize, nullptr,
3428                                  ASM, IndexTypeQuals);
3429     Canon = getQualifiedType(Canon, canonSplit.Quals);
3430 
3431     // Get the new insert position for the node we care about.
3432     ConstantArrayType *NewIP =
3433       ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
3434     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3435   }
3436 
3437   void *Mem = Allocate(
3438       ConstantArrayType::totalSizeToAlloc<const Expr *>(SizeExpr ? 1 : 0),
3439       TypeAlignment);
3440   auto *New = new (Mem)
3441     ConstantArrayType(EltTy, Canon, ArySize, SizeExpr, ASM, IndexTypeQuals);
3442   ConstantArrayTypes.InsertNode(New, InsertPos);
3443   Types.push_back(New);
3444   return QualType(New, 0);
3445 }
3446 
3447 /// getVariableArrayDecayedType - Turns the given type, which may be
3448 /// variably-modified, into the corresponding type with all the known
3449 /// sizes replaced with [*].
3450 QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
3451   // Vastly most common case.
3452   if (!type->isVariablyModifiedType()) return type;
3453 
3454   QualType result;
3455 
3456   SplitQualType split = type.getSplitDesugaredType();
3457   const Type *ty = split.Ty;
3458   switch (ty->getTypeClass()) {
3459 #define TYPE(Class, Base)
3460 #define ABSTRACT_TYPE(Class, Base)
3461 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3462 #include "clang/AST/TypeNodes.inc"
3463     llvm_unreachable("didn't desugar past all non-canonical types?");
3464 
3465   // These types should never be variably-modified.
3466   case Type::Builtin:
3467   case Type::Complex:
3468   case Type::Vector:
3469   case Type::DependentVector:
3470   case Type::ExtVector:
3471   case Type::DependentSizedExtVector:
3472   case Type::ConstantMatrix:
3473   case Type::DependentSizedMatrix:
3474   case Type::DependentAddressSpace:
3475   case Type::ObjCObject:
3476   case Type::ObjCInterface:
3477   case Type::ObjCObjectPointer:
3478   case Type::Record:
3479   case Type::Enum:
3480   case Type::UnresolvedUsing:
3481   case Type::TypeOfExpr:
3482   case Type::TypeOf:
3483   case Type::Decltype:
3484   case Type::UnaryTransform:
3485   case Type::DependentName:
3486   case Type::InjectedClassName:
3487   case Type::TemplateSpecialization:
3488   case Type::DependentTemplateSpecialization:
3489   case Type::TemplateTypeParm:
3490   case Type::SubstTemplateTypeParmPack:
3491   case Type::Auto:
3492   case Type::DeducedTemplateSpecialization:
3493   case Type::PackExpansion:
3494   case Type::ExtInt:
3495   case Type::DependentExtInt:
3496     llvm_unreachable("type should never be variably-modified");
3497 
3498   // These types can be variably-modified but should never need to
3499   // further decay.
3500   case Type::FunctionNoProto:
3501   case Type::FunctionProto:
3502   case Type::BlockPointer:
3503   case Type::MemberPointer:
3504   case Type::Pipe:
3505     return type;
3506 
3507   // These types can be variably-modified.  All these modifications
3508   // preserve structure except as noted by comments.
3509   // TODO: if we ever care about optimizing VLAs, there are no-op
3510   // optimizations available here.
3511   case Type::Pointer:
3512     result = getPointerType(getVariableArrayDecayedType(
3513                               cast<PointerType>(ty)->getPointeeType()));
3514     break;
3515 
3516   case Type::LValueReference: {
3517     const auto *lv = cast<LValueReferenceType>(ty);
3518     result = getLValueReferenceType(
3519                  getVariableArrayDecayedType(lv->getPointeeType()),
3520                                     lv->isSpelledAsLValue());
3521     break;
3522   }
3523 
3524   case Type::RValueReference: {
3525     const auto *lv = cast<RValueReferenceType>(ty);
3526     result = getRValueReferenceType(
3527                  getVariableArrayDecayedType(lv->getPointeeType()));
3528     break;
3529   }
3530 
3531   case Type::Atomic: {
3532     const auto *at = cast<AtomicType>(ty);
3533     result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
3534     break;
3535   }
3536 
3537   case Type::ConstantArray: {
3538     const auto *cat = cast<ConstantArrayType>(ty);
3539     result = getConstantArrayType(
3540                  getVariableArrayDecayedType(cat->getElementType()),
3541                                   cat->getSize(),
3542                                   cat->getSizeExpr(),
3543                                   cat->getSizeModifier(),
3544                                   cat->getIndexTypeCVRQualifiers());
3545     break;
3546   }
3547 
3548   case Type::DependentSizedArray: {
3549     const auto *dat = cast<DependentSizedArrayType>(ty);
3550     result = getDependentSizedArrayType(
3551                  getVariableArrayDecayedType(dat->getElementType()),
3552                                         dat->getSizeExpr(),
3553                                         dat->getSizeModifier(),
3554                                         dat->getIndexTypeCVRQualifiers(),
3555                                         dat->getBracketsRange());
3556     break;
3557   }
3558 
3559   // Turn incomplete types into [*] types.
3560   case Type::IncompleteArray: {
3561     const auto *iat = cast<IncompleteArrayType>(ty);
3562     result = getVariableArrayType(
3563                  getVariableArrayDecayedType(iat->getElementType()),
3564                                   /*size*/ nullptr,
3565                                   ArrayType::Normal,
3566                                   iat->getIndexTypeCVRQualifiers(),
3567                                   SourceRange());
3568     break;
3569   }
3570 
3571   // Turn VLA types into [*] types.
3572   case Type::VariableArray: {
3573     const auto *vat = cast<VariableArrayType>(ty);
3574     result = getVariableArrayType(
3575                  getVariableArrayDecayedType(vat->getElementType()),
3576                                   /*size*/ nullptr,
3577                                   ArrayType::Star,
3578                                   vat->getIndexTypeCVRQualifiers(),
3579                                   vat->getBracketsRange());
3580     break;
3581   }
3582   }
3583 
3584   // Apply the top-level qualifiers from the original.
3585   return getQualifiedType(result, split.Quals);
3586 }
3587 
3588 /// getVariableArrayType - Returns a non-unique reference to the type for a
3589 /// variable array of the specified element type.
3590 QualType ASTContext::getVariableArrayType(QualType EltTy,
3591                                           Expr *NumElts,
3592                                           ArrayType::ArraySizeModifier ASM,
3593                                           unsigned IndexTypeQuals,
3594                                           SourceRange Brackets) const {
3595   // Since we don't unique expressions, it isn't possible to unique VLA's
3596   // that have an expression provided for their size.
3597   QualType Canon;
3598 
3599   // Be sure to pull qualifiers off the element type.
3600   if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
3601     SplitQualType canonSplit = getCanonicalType(EltTy).split();
3602     Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
3603                                  IndexTypeQuals, Brackets);
3604     Canon = getQualifiedType(Canon, canonSplit.Quals);
3605   }
3606 
3607   auto *New = new (*this, TypeAlignment)
3608     VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
3609 
3610   VariableArrayTypes.push_back(New);
3611   Types.push_back(New);
3612   return QualType(New, 0);
3613 }
3614 
3615 /// getDependentSizedArrayType - Returns a non-unique reference to
3616 /// the type for a dependently-sized array of the specified element
3617 /// type.
3618 QualType ASTContext::getDependentSizedArrayType(QualType elementType,
3619                                                 Expr *numElements,
3620                                                 ArrayType::ArraySizeModifier ASM,
3621                                                 unsigned elementTypeQuals,
3622                                                 SourceRange brackets) const {
3623   assert((!numElements || numElements->isTypeDependent() ||
3624           numElements->isValueDependent()) &&
3625          "Size must be type- or value-dependent!");
3626 
3627   // Dependently-sized array types that do not have a specified number
3628   // of elements will have their sizes deduced from a dependent
3629   // initializer.  We do no canonicalization here at all, which is okay
3630   // because they can't be used in most locations.
3631   if (!numElements) {
3632     auto *newType
3633       = new (*this, TypeAlignment)
3634           DependentSizedArrayType(*this, elementType, QualType(),
3635                                   numElements, ASM, elementTypeQuals,
3636                                   brackets);
3637     Types.push_back(newType);
3638     return QualType(newType, 0);
3639   }
3640 
3641   // Otherwise, we actually build a new type every time, but we
3642   // also build a canonical type.
3643 
3644   SplitQualType canonElementType = getCanonicalType(elementType).split();
3645 
3646   void *insertPos = nullptr;
3647   llvm::FoldingSetNodeID ID;
3648   DependentSizedArrayType::Profile(ID, *this,
3649                                    QualType(canonElementType.Ty, 0),
3650                                    ASM, elementTypeQuals, numElements);
3651 
3652   // Look for an existing type with these properties.
3653   DependentSizedArrayType *canonTy =
3654     DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
3655 
3656   // If we don't have one, build one.
3657   if (!canonTy) {
3658     canonTy = new (*this, TypeAlignment)
3659       DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
3660                               QualType(), numElements, ASM, elementTypeQuals,
3661                               brackets);
3662     DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
3663     Types.push_back(canonTy);
3664   }
3665 
3666   // Apply qualifiers from the element type to the array.
3667   QualType canon = getQualifiedType(QualType(canonTy,0),
3668                                     canonElementType.Quals);
3669 
3670   // If we didn't need extra canonicalization for the element type or the size
3671   // expression, then just use that as our result.
3672   if (QualType(canonElementType.Ty, 0) == elementType &&
3673       canonTy->getSizeExpr() == numElements)
3674     return canon;
3675 
3676   // Otherwise, we need to build a type which follows the spelling
3677   // of the element type.
3678   auto *sugaredType
3679     = new (*this, TypeAlignment)
3680         DependentSizedArrayType(*this, elementType, canon, numElements,
3681                                 ASM, elementTypeQuals, brackets);
3682   Types.push_back(sugaredType);
3683   return QualType(sugaredType, 0);
3684 }
3685 
3686 QualType ASTContext::getIncompleteArrayType(QualType elementType,
3687                                             ArrayType::ArraySizeModifier ASM,
3688                                             unsigned elementTypeQuals) const {
3689   llvm::FoldingSetNodeID ID;
3690   IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
3691 
3692   void *insertPos = nullptr;
3693   if (IncompleteArrayType *iat =
3694        IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
3695     return QualType(iat, 0);
3696 
3697   // If the element type isn't canonical, this won't be a canonical type
3698   // either, so fill in the canonical type field.  We also have to pull
3699   // qualifiers off the element type.
3700   QualType canon;
3701 
3702   if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
3703     SplitQualType canonSplit = getCanonicalType(elementType).split();
3704     canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
3705                                    ASM, elementTypeQuals);
3706     canon = getQualifiedType(canon, canonSplit.Quals);
3707 
3708     // Get the new insert position for the node we care about.
3709     IncompleteArrayType *existing =
3710       IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
3711     assert(!existing && "Shouldn't be in the map!"); (void) existing;
3712   }
3713 
3714   auto *newType = new (*this, TypeAlignment)
3715     IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
3716 
3717   IncompleteArrayTypes.InsertNode(newType, insertPos);
3718   Types.push_back(newType);
3719   return QualType(newType, 0);
3720 }
3721 
3722 ASTContext::BuiltinVectorTypeInfo
3723 ASTContext::getBuiltinVectorTypeInfo(const BuiltinType *Ty) const {
3724 #define SVE_INT_ELTTY(BITS, ELTS, SIGNED, NUMVECTORS)                          \
3725   {getIntTypeForBitwidth(BITS, SIGNED), llvm::ElementCount::getScalable(ELTS), \
3726    NUMVECTORS};
3727 
3728 #define SVE_ELTTY(ELTTY, ELTS, NUMVECTORS)                                     \
3729   {ELTTY, llvm::ElementCount::getScalable(ELTS), NUMVECTORS};
3730 
3731   switch (Ty->getKind()) {
3732   default:
3733     llvm_unreachable("Unsupported builtin vector type");
3734   case BuiltinType::SveInt8:
3735     return SVE_INT_ELTTY(8, 16, true, 1);
3736   case BuiltinType::SveUint8:
3737     return SVE_INT_ELTTY(8, 16, false, 1);
3738   case BuiltinType::SveInt8x2:
3739     return SVE_INT_ELTTY(8, 16, true, 2);
3740   case BuiltinType::SveUint8x2:
3741     return SVE_INT_ELTTY(8, 16, false, 2);
3742   case BuiltinType::SveInt8x3:
3743     return SVE_INT_ELTTY(8, 16, true, 3);
3744   case BuiltinType::SveUint8x3:
3745     return SVE_INT_ELTTY(8, 16, false, 3);
3746   case BuiltinType::SveInt8x4:
3747     return SVE_INT_ELTTY(8, 16, true, 4);
3748   case BuiltinType::SveUint8x4:
3749     return SVE_INT_ELTTY(8, 16, false, 4);
3750   case BuiltinType::SveInt16:
3751     return SVE_INT_ELTTY(16, 8, true, 1);
3752   case BuiltinType::SveUint16:
3753     return SVE_INT_ELTTY(16, 8, false, 1);
3754   case BuiltinType::SveInt16x2:
3755     return SVE_INT_ELTTY(16, 8, true, 2);
3756   case BuiltinType::SveUint16x2:
3757     return SVE_INT_ELTTY(16, 8, false, 2);
3758   case BuiltinType::SveInt16x3:
3759     return SVE_INT_ELTTY(16, 8, true, 3);
3760   case BuiltinType::SveUint16x3:
3761     return SVE_INT_ELTTY(16, 8, false, 3);
3762   case BuiltinType::SveInt16x4:
3763     return SVE_INT_ELTTY(16, 8, true, 4);
3764   case BuiltinType::SveUint16x4:
3765     return SVE_INT_ELTTY(16, 8, false, 4);
3766   case BuiltinType::SveInt32:
3767     return SVE_INT_ELTTY(32, 4, true, 1);
3768   case BuiltinType::SveUint32:
3769     return SVE_INT_ELTTY(32, 4, false, 1);
3770   case BuiltinType::SveInt32x2:
3771     return SVE_INT_ELTTY(32, 4, true, 2);
3772   case BuiltinType::SveUint32x2:
3773     return SVE_INT_ELTTY(32, 4, false, 2);
3774   case BuiltinType::SveInt32x3:
3775     return SVE_INT_ELTTY(32, 4, true, 3);
3776   case BuiltinType::SveUint32x3:
3777     return SVE_INT_ELTTY(32, 4, false, 3);
3778   case BuiltinType::SveInt32x4:
3779     return SVE_INT_ELTTY(32, 4, true, 4);
3780   case BuiltinType::SveUint32x4:
3781     return SVE_INT_ELTTY(32, 4, false, 4);
3782   case BuiltinType::SveInt64:
3783     return SVE_INT_ELTTY(64, 2, true, 1);
3784   case BuiltinType::SveUint64:
3785     return SVE_INT_ELTTY(64, 2, false, 1);
3786   case BuiltinType::SveInt64x2:
3787     return SVE_INT_ELTTY(64, 2, true, 2);
3788   case BuiltinType::SveUint64x2:
3789     return SVE_INT_ELTTY(64, 2, false, 2);
3790   case BuiltinType::SveInt64x3:
3791     return SVE_INT_ELTTY(64, 2, true, 3);
3792   case BuiltinType::SveUint64x3:
3793     return SVE_INT_ELTTY(64, 2, false, 3);
3794   case BuiltinType::SveInt64x4:
3795     return SVE_INT_ELTTY(64, 2, true, 4);
3796   case BuiltinType::SveUint64x4:
3797     return SVE_INT_ELTTY(64, 2, false, 4);
3798   case BuiltinType::SveBool:
3799     return SVE_ELTTY(BoolTy, 16, 1);
3800   case BuiltinType::SveFloat16:
3801     return SVE_ELTTY(HalfTy, 8, 1);
3802   case BuiltinType::SveFloat16x2:
3803     return SVE_ELTTY(HalfTy, 8, 2);
3804   case BuiltinType::SveFloat16x3:
3805     return SVE_ELTTY(HalfTy, 8, 3);
3806   case BuiltinType::SveFloat16x4:
3807     return SVE_ELTTY(HalfTy, 8, 4);
3808   case BuiltinType::SveFloat32:
3809     return SVE_ELTTY(FloatTy, 4, 1);
3810   case BuiltinType::SveFloat32x2:
3811     return SVE_ELTTY(FloatTy, 4, 2);
3812   case BuiltinType::SveFloat32x3:
3813     return SVE_ELTTY(FloatTy, 4, 3);
3814   case BuiltinType::SveFloat32x4:
3815     return SVE_ELTTY(FloatTy, 4, 4);
3816   case BuiltinType::SveFloat64:
3817     return SVE_ELTTY(DoubleTy, 2, 1);
3818   case BuiltinType::SveFloat64x2:
3819     return SVE_ELTTY(DoubleTy, 2, 2);
3820   case BuiltinType::SveFloat64x3:
3821     return SVE_ELTTY(DoubleTy, 2, 3);
3822   case BuiltinType::SveFloat64x4:
3823     return SVE_ELTTY(DoubleTy, 2, 4);
3824   case BuiltinType::SveBFloat16:
3825     return SVE_ELTTY(BFloat16Ty, 8, 1);
3826   case BuiltinType::SveBFloat16x2:
3827     return SVE_ELTTY(BFloat16Ty, 8, 2);
3828   case BuiltinType::SveBFloat16x3:
3829     return SVE_ELTTY(BFloat16Ty, 8, 3);
3830   case BuiltinType::SveBFloat16x4:
3831     return SVE_ELTTY(BFloat16Ty, 8, 4);
3832 #define RVV_VECTOR_TYPE_INT(Name, Id, SingletonId, NumEls, ElBits, NF,         \
3833                             IsSigned)                                          \
3834   case BuiltinType::Id:                                                        \
3835     return {getIntTypeForBitwidth(ElBits, IsSigned),                           \
3836             llvm::ElementCount::getScalable(NumEls), NF};
3837 #define RVV_VECTOR_TYPE_FLOAT(Name, Id, SingletonId, NumEls, ElBits, NF)       \
3838   case BuiltinType::Id:                                                        \
3839     return {ElBits == 16 ? HalfTy : (ElBits == 32 ? FloatTy : DoubleTy),       \
3840             llvm::ElementCount::getScalable(NumEls), NF};
3841 #define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls)                      \
3842   case BuiltinType::Id:                                                        \
3843     return {BoolTy, llvm::ElementCount::getScalable(NumEls), 1};
3844 #include "clang/Basic/RISCVVTypes.def"
3845   }
3846 }
3847 
3848 /// getScalableVectorType - Return the unique reference to a scalable vector
3849 /// type of the specified element type and size. VectorType must be a built-in
3850 /// type.
3851 QualType ASTContext::getScalableVectorType(QualType EltTy,
3852                                            unsigned NumElts) const {
3853   if (Target->hasAArch64SVETypes()) {
3854     uint64_t EltTySize = getTypeSize(EltTy);
3855 #define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId, NumEls, ElBits,    \
3856                         IsSigned, IsFP, IsBF)                                  \
3857   if (!EltTy->isBooleanType() &&                                               \
3858       ((EltTy->hasIntegerRepresentation() &&                                   \
3859         EltTy->hasSignedIntegerRepresentation() == IsSigned) ||                \
3860        (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() &&      \
3861         IsFP && !IsBF) ||                                                      \
3862        (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() &&       \
3863         IsBF && !IsFP)) &&                                                     \
3864       EltTySize == ElBits && NumElts == NumEls) {                              \
3865     return SingletonId;                                                        \
3866   }
3867 #define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId, NumEls)         \
3868   if (EltTy->isBooleanType() && NumElts == NumEls)                             \
3869     return SingletonId;
3870 #include "clang/Basic/AArch64SVEACLETypes.def"
3871   } else if (Target->hasRISCVVTypes()) {
3872     uint64_t EltTySize = getTypeSize(EltTy);
3873 #define RVV_VECTOR_TYPE(Name, Id, SingletonId, NumEls, ElBits, NF, IsSigned,   \
3874                         IsFP)                                                  \
3875     if (!EltTy->isBooleanType() &&                                             \
3876         ((EltTy->hasIntegerRepresentation() &&                                 \
3877           EltTy->hasSignedIntegerRepresentation() == IsSigned) ||              \
3878          (EltTy->hasFloatingRepresentation() && IsFP)) &&                      \
3879         EltTySize == ElBits && NumElts == NumEls)                              \
3880       return SingletonId;
3881 #define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls)                      \
3882     if (EltTy->isBooleanType() && NumElts == NumEls)                           \
3883       return SingletonId;
3884 #include "clang/Basic/RISCVVTypes.def"
3885   }
3886   return QualType();
3887 }
3888 
3889 /// getVectorType - Return the unique reference to a vector type of
3890 /// the specified element type and size. VectorType must be a built-in type.
3891 QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
3892                                    VectorType::VectorKind VecKind) const {
3893   assert(vecType->isBuiltinType());
3894 
3895   // Check if we've already instantiated a vector of this type.
3896   llvm::FoldingSetNodeID ID;
3897   VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
3898 
3899   void *InsertPos = nullptr;
3900   if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3901     return QualType(VTP, 0);
3902 
3903   // If the element type isn't canonical, this won't be a canonical type either,
3904   // so fill in the canonical type field.
3905   QualType Canonical;
3906   if (!vecType.isCanonical()) {
3907     Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
3908 
3909     // Get the new insert position for the node we care about.
3910     VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3911     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3912   }
3913   auto *New = new (*this, TypeAlignment)
3914     VectorType(vecType, NumElts, Canonical, VecKind);
3915   VectorTypes.InsertNode(New, InsertPos);
3916   Types.push_back(New);
3917   return QualType(New, 0);
3918 }
3919 
3920 QualType
3921 ASTContext::getDependentVectorType(QualType VecType, Expr *SizeExpr,
3922                                    SourceLocation AttrLoc,
3923                                    VectorType::VectorKind VecKind) const {
3924   llvm::FoldingSetNodeID ID;
3925   DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr,
3926                                VecKind);
3927   void *InsertPos = nullptr;
3928   DependentVectorType *Canon =
3929       DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3930   DependentVectorType *New;
3931 
3932   if (Canon) {
3933     New = new (*this, TypeAlignment) DependentVectorType(
3934         *this, VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind);
3935   } else {
3936     QualType CanonVecTy = getCanonicalType(VecType);
3937     if (CanonVecTy == VecType) {
3938       New = new (*this, TypeAlignment) DependentVectorType(
3939           *this, VecType, QualType(), SizeExpr, AttrLoc, VecKind);
3940 
3941       DependentVectorType *CanonCheck =
3942           DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3943       assert(!CanonCheck &&
3944              "Dependent-sized vector_size canonical type broken");
3945       (void)CanonCheck;
3946       DependentVectorTypes.InsertNode(New, InsertPos);
3947     } else {
3948       QualType CanonTy = getDependentVectorType(CanonVecTy, SizeExpr,
3949                                                 SourceLocation(), VecKind);
3950       New = new (*this, TypeAlignment) DependentVectorType(
3951           *this, VecType, CanonTy, SizeExpr, AttrLoc, VecKind);
3952     }
3953   }
3954 
3955   Types.push_back(New);
3956   return QualType(New, 0);
3957 }
3958 
3959 /// getExtVectorType - Return the unique reference to an extended vector type of
3960 /// the specified element type and size. VectorType must be a built-in type.
3961 QualType
3962 ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
3963   assert(vecType->isBuiltinType() || vecType->isDependentType());
3964 
3965   // Check if we've already instantiated a vector of this type.
3966   llvm::FoldingSetNodeID ID;
3967   VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
3968                       VectorType::GenericVector);
3969   void *InsertPos = nullptr;
3970   if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3971     return QualType(VTP, 0);
3972 
3973   // If the element type isn't canonical, this won't be a canonical type either,
3974   // so fill in the canonical type field.
3975   QualType Canonical;
3976   if (!vecType.isCanonical()) {
3977     Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
3978 
3979     // Get the new insert position for the node we care about.
3980     VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3981     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3982   }
3983   auto *New = new (*this, TypeAlignment)
3984     ExtVectorType(vecType, NumElts, Canonical);
3985   VectorTypes.InsertNode(New, InsertPos);
3986   Types.push_back(New);
3987   return QualType(New, 0);
3988 }
3989 
3990 QualType
3991 ASTContext::getDependentSizedExtVectorType(QualType vecType,
3992                                            Expr *SizeExpr,
3993                                            SourceLocation AttrLoc) const {
3994   llvm::FoldingSetNodeID ID;
3995   DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
3996                                        SizeExpr);
3997 
3998   void *InsertPos = nullptr;
3999   DependentSizedExtVectorType *Canon
4000     = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4001   DependentSizedExtVectorType *New;
4002   if (Canon) {
4003     // We already have a canonical version of this array type; use it as
4004     // the canonical type for a newly-built type.
4005     New = new (*this, TypeAlignment)
4006       DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
4007                                   SizeExpr, AttrLoc);
4008   } else {
4009     QualType CanonVecTy = getCanonicalType(vecType);
4010     if (CanonVecTy == vecType) {
4011       New = new (*this, TypeAlignment)
4012         DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
4013                                     AttrLoc);
4014 
4015       DependentSizedExtVectorType *CanonCheck
4016         = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4017       assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
4018       (void)CanonCheck;
4019       DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
4020     } else {
4021       QualType CanonExtTy = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
4022                                                            SourceLocation());
4023       New = new (*this, TypeAlignment) DependentSizedExtVectorType(
4024           *this, vecType, CanonExtTy, SizeExpr, AttrLoc);
4025     }
4026   }
4027 
4028   Types.push_back(New);
4029   return QualType(New, 0);
4030 }
4031 
4032 QualType ASTContext::getConstantMatrixType(QualType ElementTy, unsigned NumRows,
4033                                            unsigned NumColumns) const {
4034   llvm::FoldingSetNodeID ID;
4035   ConstantMatrixType::Profile(ID, ElementTy, NumRows, NumColumns,
4036                               Type::ConstantMatrix);
4037 
4038   assert(MatrixType::isValidElementType(ElementTy) &&
4039          "need a valid element type");
4040   assert(ConstantMatrixType::isDimensionValid(NumRows) &&
4041          ConstantMatrixType::isDimensionValid(NumColumns) &&
4042          "need valid matrix dimensions");
4043   void *InsertPos = nullptr;
4044   if (ConstantMatrixType *MTP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos))
4045     return QualType(MTP, 0);
4046 
4047   QualType Canonical;
4048   if (!ElementTy.isCanonical()) {
4049     Canonical =
4050         getConstantMatrixType(getCanonicalType(ElementTy), NumRows, NumColumns);
4051 
4052     ConstantMatrixType *NewIP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4053     assert(!NewIP && "Matrix type shouldn't already exist in the map");
4054     (void)NewIP;
4055   }
4056 
4057   auto *New = new (*this, TypeAlignment)
4058       ConstantMatrixType(ElementTy, NumRows, NumColumns, Canonical);
4059   MatrixTypes.InsertNode(New, InsertPos);
4060   Types.push_back(New);
4061   return QualType(New, 0);
4062 }
4063 
4064 QualType ASTContext::getDependentSizedMatrixType(QualType ElementTy,
4065                                                  Expr *RowExpr,
4066                                                  Expr *ColumnExpr,
4067                                                  SourceLocation AttrLoc) const {
4068   QualType CanonElementTy = getCanonicalType(ElementTy);
4069   llvm::FoldingSetNodeID ID;
4070   DependentSizedMatrixType::Profile(ID, *this, CanonElementTy, RowExpr,
4071                                     ColumnExpr);
4072 
4073   void *InsertPos = nullptr;
4074   DependentSizedMatrixType *Canon =
4075       DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4076 
4077   if (!Canon) {
4078     Canon = new (*this, TypeAlignment) DependentSizedMatrixType(
4079         *this, CanonElementTy, QualType(), RowExpr, ColumnExpr, AttrLoc);
4080 #ifndef NDEBUG
4081     DependentSizedMatrixType *CanonCheck =
4082         DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4083     assert(!CanonCheck && "Dependent-sized matrix canonical type broken");
4084 #endif
4085     DependentSizedMatrixTypes.InsertNode(Canon, InsertPos);
4086     Types.push_back(Canon);
4087   }
4088 
4089   // Already have a canonical version of the matrix type
4090   //
4091   // If it exactly matches the requested type, use it directly.
4092   if (Canon->getElementType() == ElementTy && Canon->getRowExpr() == RowExpr &&
4093       Canon->getRowExpr() == ColumnExpr)
4094     return QualType(Canon, 0);
4095 
4096   // Use Canon as the canonical type for newly-built type.
4097   DependentSizedMatrixType *New = new (*this, TypeAlignment)
4098       DependentSizedMatrixType(*this, ElementTy, QualType(Canon, 0), RowExpr,
4099                                ColumnExpr, AttrLoc);
4100   Types.push_back(New);
4101   return QualType(New, 0);
4102 }
4103 
4104 QualType ASTContext::getDependentAddressSpaceType(QualType PointeeType,
4105                                                   Expr *AddrSpaceExpr,
4106                                                   SourceLocation AttrLoc) const {
4107   assert(AddrSpaceExpr->isInstantiationDependent());
4108 
4109   QualType canonPointeeType = getCanonicalType(PointeeType);
4110 
4111   void *insertPos = nullptr;
4112   llvm::FoldingSetNodeID ID;
4113   DependentAddressSpaceType::Profile(ID, *this, canonPointeeType,
4114                                      AddrSpaceExpr);
4115 
4116   DependentAddressSpaceType *canonTy =
4117     DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos);
4118 
4119   if (!canonTy) {
4120     canonTy = new (*this, TypeAlignment)
4121       DependentAddressSpaceType(*this, canonPointeeType,
4122                                 QualType(), AddrSpaceExpr, AttrLoc);
4123     DependentAddressSpaceTypes.InsertNode(canonTy, insertPos);
4124     Types.push_back(canonTy);
4125   }
4126 
4127   if (canonPointeeType == PointeeType &&
4128       canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
4129     return QualType(canonTy, 0);
4130 
4131   auto *sugaredType
4132     = new (*this, TypeAlignment)
4133         DependentAddressSpaceType(*this, PointeeType, QualType(canonTy, 0),
4134                                   AddrSpaceExpr, AttrLoc);
4135   Types.push_back(sugaredType);
4136   return QualType(sugaredType, 0);
4137 }
4138 
4139 /// Determine whether \p T is canonical as the result type of a function.
4140 static bool isCanonicalResultType(QualType T) {
4141   return T.isCanonical() &&
4142          (T.getObjCLifetime() == Qualifiers::OCL_None ||
4143           T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
4144 }
4145 
4146 /// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
4147 QualType
4148 ASTContext::getFunctionNoProtoType(QualType ResultTy,
4149                                    const FunctionType::ExtInfo &Info) const {
4150   // Unique functions, to guarantee there is only one function of a particular
4151   // structure.
4152   llvm::FoldingSetNodeID ID;
4153   FunctionNoProtoType::Profile(ID, ResultTy, Info);
4154 
4155   void *InsertPos = nullptr;
4156   if (FunctionNoProtoType *FT =
4157         FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
4158     return QualType(FT, 0);
4159 
4160   QualType Canonical;
4161   if (!isCanonicalResultType(ResultTy)) {
4162     Canonical =
4163       getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info);
4164 
4165     // Get the new insert position for the node we care about.
4166     FunctionNoProtoType *NewIP =
4167       FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
4168     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4169   }
4170 
4171   auto *New = new (*this, TypeAlignment)
4172     FunctionNoProtoType(ResultTy, Canonical, Info);
4173   Types.push_back(New);
4174   FunctionNoProtoTypes.InsertNode(New, InsertPos);
4175   return QualType(New, 0);
4176 }
4177 
4178 CanQualType
4179 ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
4180   CanQualType CanResultType = getCanonicalType(ResultType);
4181 
4182   // Canonical result types do not have ARC lifetime qualifiers.
4183   if (CanResultType.getQualifiers().hasObjCLifetime()) {
4184     Qualifiers Qs = CanResultType.getQualifiers();
4185     Qs.removeObjCLifetime();
4186     return CanQualType::CreateUnsafe(
4187              getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
4188   }
4189 
4190   return CanResultType;
4191 }
4192 
4193 static bool isCanonicalExceptionSpecification(
4194     const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
4195   if (ESI.Type == EST_None)
4196     return true;
4197   if (!NoexceptInType)
4198     return false;
4199 
4200   // C++17 onwards: exception specification is part of the type, as a simple
4201   // boolean "can this function type throw".
4202   if (ESI.Type == EST_BasicNoexcept)
4203     return true;
4204 
4205   // A noexcept(expr) specification is (possibly) canonical if expr is
4206   // value-dependent.
4207   if (ESI.Type == EST_DependentNoexcept)
4208     return true;
4209 
4210   // A dynamic exception specification is canonical if it only contains pack
4211   // expansions (so we can't tell whether it's non-throwing) and all its
4212   // contained types are canonical.
4213   if (ESI.Type == EST_Dynamic) {
4214     bool AnyPackExpansions = false;
4215     for (QualType ET : ESI.Exceptions) {
4216       if (!ET.isCanonical())
4217         return false;
4218       if (ET->getAs<PackExpansionType>())
4219         AnyPackExpansions = true;
4220     }
4221     return AnyPackExpansions;
4222   }
4223 
4224   return false;
4225 }
4226 
4227 QualType ASTContext::getFunctionTypeInternal(
4228     QualType ResultTy, ArrayRef<QualType> ArgArray,
4229     const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
4230   size_t NumArgs = ArgArray.size();
4231 
4232   // Unique functions, to guarantee there is only one function of a particular
4233   // structure.
4234   llvm::FoldingSetNodeID ID;
4235   FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
4236                              *this, true);
4237 
4238   QualType Canonical;
4239   bool Unique = false;
4240 
4241   void *InsertPos = nullptr;
4242   if (FunctionProtoType *FPT =
4243         FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
4244     QualType Existing = QualType(FPT, 0);
4245 
4246     // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
4247     // it so long as our exception specification doesn't contain a dependent
4248     // noexcept expression, or we're just looking for a canonical type.
4249     // Otherwise, we're going to need to create a type
4250     // sugar node to hold the concrete expression.
4251     if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) ||
4252         EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
4253       return Existing;
4254 
4255     // We need a new type sugar node for this one, to hold the new noexcept
4256     // expression. We do no canonicalization here, but that's OK since we don't
4257     // expect to see the same noexcept expression much more than once.
4258     Canonical = getCanonicalType(Existing);
4259     Unique = true;
4260   }
4261 
4262   bool NoexceptInType = getLangOpts().CPlusPlus17;
4263   bool IsCanonicalExceptionSpec =
4264       isCanonicalExceptionSpecification(EPI.ExceptionSpec, NoexceptInType);
4265 
4266   // Determine whether the type being created is already canonical or not.
4267   bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
4268                      isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
4269   for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
4270     if (!ArgArray[i].isCanonicalAsParam())
4271       isCanonical = false;
4272 
4273   if (OnlyWantCanonical)
4274     assert(isCanonical &&
4275            "given non-canonical parameters constructing canonical type");
4276 
4277   // If this type isn't canonical, get the canonical version of it if we don't
4278   // already have it. The exception spec is only partially part of the
4279   // canonical type, and only in C++17 onwards.
4280   if (!isCanonical && Canonical.isNull()) {
4281     SmallVector<QualType, 16> CanonicalArgs;
4282     CanonicalArgs.reserve(NumArgs);
4283     for (unsigned i = 0; i != NumArgs; ++i)
4284       CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
4285 
4286     llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
4287     FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
4288     CanonicalEPI.HasTrailingReturn = false;
4289 
4290     if (IsCanonicalExceptionSpec) {
4291       // Exception spec is already OK.
4292     } else if (NoexceptInType) {
4293       switch (EPI.ExceptionSpec.Type) {
4294       case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated:
4295         // We don't know yet. It shouldn't matter what we pick here; no-one
4296         // should ever look at this.
4297         LLVM_FALLTHROUGH;
4298       case EST_None: case EST_MSAny: case EST_NoexceptFalse:
4299         CanonicalEPI.ExceptionSpec.Type = EST_None;
4300         break;
4301 
4302         // A dynamic exception specification is almost always "not noexcept",
4303         // with the exception that a pack expansion might expand to no types.
4304       case EST_Dynamic: {
4305         bool AnyPacks = false;
4306         for (QualType ET : EPI.ExceptionSpec.Exceptions) {
4307           if (ET->getAs<PackExpansionType>())
4308             AnyPacks = true;
4309           ExceptionTypeStorage.push_back(getCanonicalType(ET));
4310         }
4311         if (!AnyPacks)
4312           CanonicalEPI.ExceptionSpec.Type = EST_None;
4313         else {
4314           CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
4315           CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
4316         }
4317         break;
4318       }
4319 
4320       case EST_DynamicNone:
4321       case EST_BasicNoexcept:
4322       case EST_NoexceptTrue:
4323       case EST_NoThrow:
4324         CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
4325         break;
4326 
4327       case EST_DependentNoexcept:
4328         llvm_unreachable("dependent noexcept is already canonical");
4329       }
4330     } else {
4331       CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
4332     }
4333 
4334     // Adjust the canonical function result type.
4335     CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
4336     Canonical =
4337         getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
4338 
4339     // Get the new insert position for the node we care about.
4340     FunctionProtoType *NewIP =
4341       FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
4342     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4343   }
4344 
4345   // Compute the needed size to hold this FunctionProtoType and the
4346   // various trailing objects.
4347   auto ESH = FunctionProtoType::getExceptionSpecSize(
4348       EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size());
4349   size_t Size = FunctionProtoType::totalSizeToAlloc<
4350       QualType, SourceLocation, FunctionType::FunctionTypeExtraBitfields,
4351       FunctionType::ExceptionType, Expr *, FunctionDecl *,
4352       FunctionProtoType::ExtParameterInfo, Qualifiers>(
4353       NumArgs, EPI.Variadic,
4354       FunctionProtoType::hasExtraBitfields(EPI.ExceptionSpec.Type),
4355       ESH.NumExceptionType, ESH.NumExprPtr, ESH.NumFunctionDeclPtr,
4356       EPI.ExtParameterInfos ? NumArgs : 0,
4357       EPI.TypeQuals.hasNonFastQualifiers() ? 1 : 0);
4358 
4359   auto *FTP = (FunctionProtoType *)Allocate(Size, TypeAlignment);
4360   FunctionProtoType::ExtProtoInfo newEPI = EPI;
4361   new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
4362   Types.push_back(FTP);
4363   if (!Unique)
4364     FunctionProtoTypes.InsertNode(FTP, InsertPos);
4365   return QualType(FTP, 0);
4366 }
4367 
4368 QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
4369   llvm::FoldingSetNodeID ID;
4370   PipeType::Profile(ID, T, ReadOnly);
4371 
4372   void *InsertPos = nullptr;
4373   if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
4374     return QualType(PT, 0);
4375 
4376   // If the pipe element type isn't canonical, this won't be a canonical type
4377   // either, so fill in the canonical type field.
4378   QualType Canonical;
4379   if (!T.isCanonical()) {
4380     Canonical = getPipeType(getCanonicalType(T), ReadOnly);
4381 
4382     // Get the new insert position for the node we care about.
4383     PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
4384     assert(!NewIP && "Shouldn't be in the map!");
4385     (void)NewIP;
4386   }
4387   auto *New = new (*this, TypeAlignment) PipeType(T, Canonical, ReadOnly);
4388   Types.push_back(New);
4389   PipeTypes.InsertNode(New, InsertPos);
4390   return QualType(New, 0);
4391 }
4392 
4393 QualType ASTContext::adjustStringLiteralBaseType(QualType Ty) const {
4394   // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
4395   return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant)
4396                          : Ty;
4397 }
4398 
4399 QualType ASTContext::getReadPipeType(QualType T) const {
4400   return getPipeType(T, true);
4401 }
4402 
4403 QualType ASTContext::getWritePipeType(QualType T) const {
4404   return getPipeType(T, false);
4405 }
4406 
4407 QualType ASTContext::getExtIntType(bool IsUnsigned, unsigned NumBits) const {
4408   llvm::FoldingSetNodeID ID;
4409   ExtIntType::Profile(ID, IsUnsigned, NumBits);
4410 
4411   void *InsertPos = nullptr;
4412   if (ExtIntType *EIT = ExtIntTypes.FindNodeOrInsertPos(ID, InsertPos))
4413     return QualType(EIT, 0);
4414 
4415   auto *New = new (*this, TypeAlignment) ExtIntType(IsUnsigned, NumBits);
4416   ExtIntTypes.InsertNode(New, InsertPos);
4417   Types.push_back(New);
4418   return QualType(New, 0);
4419 }
4420 
4421 QualType ASTContext::getDependentExtIntType(bool IsUnsigned,
4422                                             Expr *NumBitsExpr) const {
4423   assert(NumBitsExpr->isInstantiationDependent() && "Only good for dependent");
4424   llvm::FoldingSetNodeID ID;
4425   DependentExtIntType::Profile(ID, *this, IsUnsigned, NumBitsExpr);
4426 
4427   void *InsertPos = nullptr;
4428   if (DependentExtIntType *Existing =
4429           DependentExtIntTypes.FindNodeOrInsertPos(ID, InsertPos))
4430     return QualType(Existing, 0);
4431 
4432   auto *New = new (*this, TypeAlignment)
4433       DependentExtIntType(*this, IsUnsigned, NumBitsExpr);
4434   DependentExtIntTypes.InsertNode(New, InsertPos);
4435 
4436   Types.push_back(New);
4437   return QualType(New, 0);
4438 }
4439 
4440 #ifndef NDEBUG
4441 static bool NeedsInjectedClassNameType(const RecordDecl *D) {
4442   if (!isa<CXXRecordDecl>(D)) return false;
4443   const auto *RD = cast<CXXRecordDecl>(D);
4444   if (isa<ClassTemplatePartialSpecializationDecl>(RD))
4445     return true;
4446   if (RD->getDescribedClassTemplate() &&
4447       !isa<ClassTemplateSpecializationDecl>(RD))
4448     return true;
4449   return false;
4450 }
4451 #endif
4452 
4453 /// getInjectedClassNameType - Return the unique reference to the
4454 /// injected class name type for the specified templated declaration.
4455 QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
4456                                               QualType TST) const {
4457   assert(NeedsInjectedClassNameType(Decl));
4458   if (Decl->TypeForDecl) {
4459     assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
4460   } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
4461     assert(PrevDecl->TypeForDecl && "previous declaration has no type");
4462     Decl->TypeForDecl = PrevDecl->TypeForDecl;
4463     assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
4464   } else {
4465     Type *newType =
4466       new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
4467     Decl->TypeForDecl = newType;
4468     Types.push_back(newType);
4469   }
4470   return QualType(Decl->TypeForDecl, 0);
4471 }
4472 
4473 /// getTypeDeclType - Return the unique reference to the type for the
4474 /// specified type declaration.
4475 QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
4476   assert(Decl && "Passed null for Decl param");
4477   assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
4478 
4479   if (const auto *Typedef = dyn_cast<TypedefNameDecl>(Decl))
4480     return getTypedefType(Typedef);
4481 
4482   assert(!isa<TemplateTypeParmDecl>(Decl) &&
4483          "Template type parameter types are always available.");
4484 
4485   if (const auto *Record = dyn_cast<RecordDecl>(Decl)) {
4486     assert(Record->isFirstDecl() && "struct/union has previous declaration");
4487     assert(!NeedsInjectedClassNameType(Record));
4488     return getRecordType(Record);
4489   } else if (const auto *Enum = dyn_cast<EnumDecl>(Decl)) {
4490     assert(Enum->isFirstDecl() && "enum has previous declaration");
4491     return getEnumType(Enum);
4492   } else if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
4493     Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
4494     Decl->TypeForDecl = newType;
4495     Types.push_back(newType);
4496   } else
4497     llvm_unreachable("TypeDecl without a type?");
4498 
4499   return QualType(Decl->TypeForDecl, 0);
4500 }
4501 
4502 /// getTypedefType - Return the unique reference to the type for the
4503 /// specified typedef name decl.
4504 QualType ASTContext::getTypedefType(const TypedefNameDecl *Decl,
4505                                     QualType Underlying) const {
4506   if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
4507 
4508   if (Underlying.isNull())
4509     Underlying = Decl->getUnderlyingType();
4510   QualType Canonical = getCanonicalType(Underlying);
4511   auto *newType = new (*this, TypeAlignment)
4512       TypedefType(Type::Typedef, Decl, Underlying, Canonical);
4513   Decl->TypeForDecl = newType;
4514   Types.push_back(newType);
4515   return QualType(newType, 0);
4516 }
4517 
4518 QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
4519   if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
4520 
4521   if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
4522     if (PrevDecl->TypeForDecl)
4523       return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
4524 
4525   auto *newType = new (*this, TypeAlignment) RecordType(Decl);
4526   Decl->TypeForDecl = newType;
4527   Types.push_back(newType);
4528   return QualType(newType, 0);
4529 }
4530 
4531 QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
4532   if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
4533 
4534   if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
4535     if (PrevDecl->TypeForDecl)
4536       return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
4537 
4538   auto *newType = new (*this, TypeAlignment) EnumType(Decl);
4539   Decl->TypeForDecl = newType;
4540   Types.push_back(newType);
4541   return QualType(newType, 0);
4542 }
4543 
4544 QualType ASTContext::getAttributedType(attr::Kind attrKind,
4545                                        QualType modifiedType,
4546                                        QualType equivalentType) {
4547   llvm::FoldingSetNodeID id;
4548   AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
4549 
4550   void *insertPos = nullptr;
4551   AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
4552   if (type) return QualType(type, 0);
4553 
4554   QualType canon = getCanonicalType(equivalentType);
4555   type = new (*this, TypeAlignment)
4556       AttributedType(canon, attrKind, modifiedType, equivalentType);
4557 
4558   Types.push_back(type);
4559   AttributedTypes.InsertNode(type, insertPos);
4560 
4561   return QualType(type, 0);
4562 }
4563 
4564 /// Retrieve a substitution-result type.
4565 QualType
4566 ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
4567                                          QualType Replacement) const {
4568   assert(Replacement.isCanonical()
4569          && "replacement types must always be canonical");
4570 
4571   llvm::FoldingSetNodeID ID;
4572   SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
4573   void *InsertPos = nullptr;
4574   SubstTemplateTypeParmType *SubstParm
4575     = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4576 
4577   if (!SubstParm) {
4578     SubstParm = new (*this, TypeAlignment)
4579       SubstTemplateTypeParmType(Parm, Replacement);
4580     Types.push_back(SubstParm);
4581     SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
4582   }
4583 
4584   return QualType(SubstParm, 0);
4585 }
4586 
4587 /// Retrieve a
4588 QualType ASTContext::getSubstTemplateTypeParmPackType(
4589                                           const TemplateTypeParmType *Parm,
4590                                               const TemplateArgument &ArgPack) {
4591 #ifndef NDEBUG
4592   for (const auto &P : ArgPack.pack_elements()) {
4593     assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
4594     assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
4595   }
4596 #endif
4597 
4598   llvm::FoldingSetNodeID ID;
4599   SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
4600   void *InsertPos = nullptr;
4601   if (SubstTemplateTypeParmPackType *SubstParm
4602         = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
4603     return QualType(SubstParm, 0);
4604 
4605   QualType Canon;
4606   if (!Parm->isCanonicalUnqualified()) {
4607     Canon = getCanonicalType(QualType(Parm, 0));
4608     Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
4609                                              ArgPack);
4610     SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
4611   }
4612 
4613   auto *SubstParm
4614     = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
4615                                                                ArgPack);
4616   Types.push_back(SubstParm);
4617   SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos);
4618   return QualType(SubstParm, 0);
4619 }
4620 
4621 /// Retrieve the template type parameter type for a template
4622 /// parameter or parameter pack with the given depth, index, and (optionally)
4623 /// name.
4624 QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
4625                                              bool ParameterPack,
4626                                              TemplateTypeParmDecl *TTPDecl) const {
4627   llvm::FoldingSetNodeID ID;
4628   TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
4629   void *InsertPos = nullptr;
4630   TemplateTypeParmType *TypeParm
4631     = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4632 
4633   if (TypeParm)
4634     return QualType(TypeParm, 0);
4635 
4636   if (TTPDecl) {
4637     QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
4638     TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
4639 
4640     TemplateTypeParmType *TypeCheck
4641       = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4642     assert(!TypeCheck && "Template type parameter canonical type broken");
4643     (void)TypeCheck;
4644   } else
4645     TypeParm = new (*this, TypeAlignment)
4646       TemplateTypeParmType(Depth, Index, ParameterPack);
4647 
4648   Types.push_back(TypeParm);
4649   TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
4650 
4651   return QualType(TypeParm, 0);
4652 }
4653 
4654 TypeSourceInfo *
4655 ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
4656                                               SourceLocation NameLoc,
4657                                         const TemplateArgumentListInfo &Args,
4658                                               QualType Underlying) const {
4659   assert(!Name.getAsDependentTemplateName() &&
4660          "No dependent template names here!");
4661   QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
4662 
4663   TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
4664   TemplateSpecializationTypeLoc TL =
4665       DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
4666   TL.setTemplateKeywordLoc(SourceLocation());
4667   TL.setTemplateNameLoc(NameLoc);
4668   TL.setLAngleLoc(Args.getLAngleLoc());
4669   TL.setRAngleLoc(Args.getRAngleLoc());
4670   for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
4671     TL.setArgLocInfo(i, Args[i].getLocInfo());
4672   return DI;
4673 }
4674 
4675 QualType
4676 ASTContext::getTemplateSpecializationType(TemplateName Template,
4677                                           const TemplateArgumentListInfo &Args,
4678                                           QualType Underlying) const {
4679   assert(!Template.getAsDependentTemplateName() &&
4680          "No dependent template names here!");
4681 
4682   SmallVector<TemplateArgument, 4> ArgVec;
4683   ArgVec.reserve(Args.size());
4684   for (const TemplateArgumentLoc &Arg : Args.arguments())
4685     ArgVec.push_back(Arg.getArgument());
4686 
4687   return getTemplateSpecializationType(Template, ArgVec, Underlying);
4688 }
4689 
4690 #ifndef NDEBUG
4691 static bool hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) {
4692   for (const TemplateArgument &Arg : Args)
4693     if (Arg.isPackExpansion())
4694       return true;
4695 
4696   return true;
4697 }
4698 #endif
4699 
4700 QualType
4701 ASTContext::getTemplateSpecializationType(TemplateName Template,
4702                                           ArrayRef<TemplateArgument> Args,
4703                                           QualType Underlying) const {
4704   assert(!Template.getAsDependentTemplateName() &&
4705          "No dependent template names here!");
4706   // Look through qualified template names.
4707   if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
4708     Template = TemplateName(QTN->getTemplateDecl());
4709 
4710   bool IsTypeAlias =
4711     Template.getAsTemplateDecl() &&
4712     isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
4713   QualType CanonType;
4714   if (!Underlying.isNull())
4715     CanonType = getCanonicalType(Underlying);
4716   else {
4717     // We can get here with an alias template when the specialization contains
4718     // a pack expansion that does not match up with a parameter pack.
4719     assert((!IsTypeAlias || hasAnyPackExpansions(Args)) &&
4720            "Caller must compute aliased type");
4721     IsTypeAlias = false;
4722     CanonType = getCanonicalTemplateSpecializationType(Template, Args);
4723   }
4724 
4725   // Allocate the (non-canonical) template specialization type, but don't
4726   // try to unique it: these types typically have location information that
4727   // we don't unique and don't want to lose.
4728   void *Mem = Allocate(sizeof(TemplateSpecializationType) +
4729                        sizeof(TemplateArgument) * Args.size() +
4730                        (IsTypeAlias? sizeof(QualType) : 0),
4731                        TypeAlignment);
4732   auto *Spec
4733     = new (Mem) TemplateSpecializationType(Template, Args, CanonType,
4734                                          IsTypeAlias ? Underlying : QualType());
4735 
4736   Types.push_back(Spec);
4737   return QualType(Spec, 0);
4738 }
4739 
4740 QualType ASTContext::getCanonicalTemplateSpecializationType(
4741     TemplateName Template, ArrayRef<TemplateArgument> Args) const {
4742   assert(!Template.getAsDependentTemplateName() &&
4743          "No dependent template names here!");
4744 
4745   // Look through qualified template names.
4746   if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
4747     Template = TemplateName(QTN->getTemplateDecl());
4748 
4749   // Build the canonical template specialization type.
4750   TemplateName CanonTemplate = getCanonicalTemplateName(Template);
4751   SmallVector<TemplateArgument, 4> CanonArgs;
4752   unsigned NumArgs = Args.size();
4753   CanonArgs.reserve(NumArgs);
4754   for (const TemplateArgument &Arg : Args)
4755     CanonArgs.push_back(getCanonicalTemplateArgument(Arg));
4756 
4757   // Determine whether this canonical template specialization type already
4758   // exists.
4759   llvm::FoldingSetNodeID ID;
4760   TemplateSpecializationType::Profile(ID, CanonTemplate,
4761                                       CanonArgs, *this);
4762 
4763   void *InsertPos = nullptr;
4764   TemplateSpecializationType *Spec
4765     = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
4766 
4767   if (!Spec) {
4768     // Allocate a new canonical template specialization type.
4769     void *Mem = Allocate((sizeof(TemplateSpecializationType) +
4770                           sizeof(TemplateArgument) * NumArgs),
4771                          TypeAlignment);
4772     Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
4773                                                 CanonArgs,
4774                                                 QualType(), QualType());
4775     Types.push_back(Spec);
4776     TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
4777   }
4778 
4779   assert(Spec->isDependentType() &&
4780          "Non-dependent template-id type must have a canonical type");
4781   return QualType(Spec, 0);
4782 }
4783 
4784 QualType ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
4785                                        NestedNameSpecifier *NNS,
4786                                        QualType NamedType,
4787                                        TagDecl *OwnedTagDecl) const {
4788   llvm::FoldingSetNodeID ID;
4789   ElaboratedType::Profile(ID, Keyword, NNS, NamedType, OwnedTagDecl);
4790 
4791   void *InsertPos = nullptr;
4792   ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
4793   if (T)
4794     return QualType(T, 0);
4795 
4796   QualType Canon = NamedType;
4797   if (!Canon.isCanonical()) {
4798     Canon = getCanonicalType(NamedType);
4799     ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
4800     assert(!CheckT && "Elaborated canonical type broken");
4801     (void)CheckT;
4802   }
4803 
4804   void *Mem = Allocate(ElaboratedType::totalSizeToAlloc<TagDecl *>(!!OwnedTagDecl),
4805                        TypeAlignment);
4806   T = new (Mem) ElaboratedType(Keyword, NNS, NamedType, Canon, OwnedTagDecl);
4807 
4808   Types.push_back(T);
4809   ElaboratedTypes.InsertNode(T, InsertPos);
4810   return QualType(T, 0);
4811 }
4812 
4813 QualType
4814 ASTContext::getParenType(QualType InnerType) const {
4815   llvm::FoldingSetNodeID ID;
4816   ParenType::Profile(ID, InnerType);
4817 
4818   void *InsertPos = nullptr;
4819   ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
4820   if (T)
4821     return QualType(T, 0);
4822 
4823   QualType Canon = InnerType;
4824   if (!Canon.isCanonical()) {
4825     Canon = getCanonicalType(InnerType);
4826     ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
4827     assert(!CheckT && "Paren canonical type broken");
4828     (void)CheckT;
4829   }
4830 
4831   T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
4832   Types.push_back(T);
4833   ParenTypes.InsertNode(T, InsertPos);
4834   return QualType(T, 0);
4835 }
4836 
4837 QualType
4838 ASTContext::getMacroQualifiedType(QualType UnderlyingTy,
4839                                   const IdentifierInfo *MacroII) const {
4840   QualType Canon = UnderlyingTy;
4841   if (!Canon.isCanonical())
4842     Canon = getCanonicalType(UnderlyingTy);
4843 
4844   auto *newType = new (*this, TypeAlignment)
4845       MacroQualifiedType(UnderlyingTy, Canon, MacroII);
4846   Types.push_back(newType);
4847   return QualType(newType, 0);
4848 }
4849 
4850 QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
4851                                           NestedNameSpecifier *NNS,
4852                                           const IdentifierInfo *Name,
4853                                           QualType Canon) const {
4854   if (Canon.isNull()) {
4855     NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4856     if (CanonNNS != NNS)
4857       Canon = getDependentNameType(Keyword, CanonNNS, Name);
4858   }
4859 
4860   llvm::FoldingSetNodeID ID;
4861   DependentNameType::Profile(ID, Keyword, NNS, Name);
4862 
4863   void *InsertPos = nullptr;
4864   DependentNameType *T
4865     = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
4866   if (T)
4867     return QualType(T, 0);
4868 
4869   T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
4870   Types.push_back(T);
4871   DependentNameTypes.InsertNode(T, InsertPos);
4872   return QualType(T, 0);
4873 }
4874 
4875 QualType
4876 ASTContext::getDependentTemplateSpecializationType(
4877                                  ElaboratedTypeKeyword Keyword,
4878                                  NestedNameSpecifier *NNS,
4879                                  const IdentifierInfo *Name,
4880                                  const TemplateArgumentListInfo &Args) const {
4881   // TODO: avoid this copy
4882   SmallVector<TemplateArgument, 16> ArgCopy;
4883   for (unsigned I = 0, E = Args.size(); I != E; ++I)
4884     ArgCopy.push_back(Args[I].getArgument());
4885   return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy);
4886 }
4887 
4888 QualType
4889 ASTContext::getDependentTemplateSpecializationType(
4890                                  ElaboratedTypeKeyword Keyword,
4891                                  NestedNameSpecifier *NNS,
4892                                  const IdentifierInfo *Name,
4893                                  ArrayRef<TemplateArgument> Args) const {
4894   assert((!NNS || NNS->isDependent()) &&
4895          "nested-name-specifier must be dependent");
4896 
4897   llvm::FoldingSetNodeID ID;
4898   DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
4899                                                Name, Args);
4900 
4901   void *InsertPos = nullptr;
4902   DependentTemplateSpecializationType *T
4903     = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
4904   if (T)
4905     return QualType(T, 0);
4906 
4907   NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4908 
4909   ElaboratedTypeKeyword CanonKeyword = Keyword;
4910   if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
4911 
4912   bool AnyNonCanonArgs = false;
4913   unsigned NumArgs = Args.size();
4914   SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
4915   for (unsigned I = 0; I != NumArgs; ++I) {
4916     CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
4917     if (!CanonArgs[I].structurallyEquals(Args[I]))
4918       AnyNonCanonArgs = true;
4919   }
4920 
4921   QualType Canon;
4922   if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
4923     Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
4924                                                    Name,
4925                                                    CanonArgs);
4926 
4927     // Find the insert position again.
4928     DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
4929   }
4930 
4931   void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
4932                         sizeof(TemplateArgument) * NumArgs),
4933                        TypeAlignment);
4934   T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
4935                                                     Name, Args, Canon);
4936   Types.push_back(T);
4937   DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
4938   return QualType(T, 0);
4939 }
4940 
4941 TemplateArgument ASTContext::getInjectedTemplateArg(NamedDecl *Param) {
4942   TemplateArgument Arg;
4943   if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
4944     QualType ArgType = getTypeDeclType(TTP);
4945     if (TTP->isParameterPack())
4946       ArgType = getPackExpansionType(ArgType, None);
4947 
4948     Arg = TemplateArgument(ArgType);
4949   } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4950     QualType T =
4951         NTTP->getType().getNonPackExpansionType().getNonLValueExprType(*this);
4952     // For class NTTPs, ensure we include the 'const' so the type matches that
4953     // of a real template argument.
4954     // FIXME: It would be more faithful to model this as something like an
4955     // lvalue-to-rvalue conversion applied to a const-qualified lvalue.
4956     if (T->isRecordType())
4957       T.addConst();
4958     Expr *E = new (*this) DeclRefExpr(
4959         *this, NTTP, /*enclosing*/ false, T,
4960         Expr::getValueKindForType(NTTP->getType()), NTTP->getLocation());
4961 
4962     if (NTTP->isParameterPack())
4963       E = new (*this) PackExpansionExpr(DependentTy, E, NTTP->getLocation(),
4964                                         None);
4965     Arg = TemplateArgument(E);
4966   } else {
4967     auto *TTP = cast<TemplateTemplateParmDecl>(Param);
4968     if (TTP->isParameterPack())
4969       Arg = TemplateArgument(TemplateName(TTP), Optional<unsigned>());
4970     else
4971       Arg = TemplateArgument(TemplateName(TTP));
4972   }
4973 
4974   if (Param->isTemplateParameterPack())
4975     Arg = TemplateArgument::CreatePackCopy(*this, Arg);
4976 
4977   return Arg;
4978 }
4979 
4980 void
4981 ASTContext::getInjectedTemplateArgs(const TemplateParameterList *Params,
4982                                     SmallVectorImpl<TemplateArgument> &Args) {
4983   Args.reserve(Args.size() + Params->size());
4984 
4985   for (NamedDecl *Param : *Params)
4986     Args.push_back(getInjectedTemplateArg(Param));
4987 }
4988 
4989 QualType ASTContext::getPackExpansionType(QualType Pattern,
4990                                           Optional<unsigned> NumExpansions,
4991                                           bool ExpectPackInType) {
4992   assert((!ExpectPackInType || Pattern->containsUnexpandedParameterPack()) &&
4993          "Pack expansions must expand one or more parameter packs");
4994 
4995   llvm::FoldingSetNodeID ID;
4996   PackExpansionType::Profile(ID, Pattern, NumExpansions);
4997 
4998   void *InsertPos = nullptr;
4999   PackExpansionType *T = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
5000   if (T)
5001     return QualType(T, 0);
5002 
5003   QualType Canon;
5004   if (!Pattern.isCanonical()) {
5005     Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions,
5006                                  /*ExpectPackInType=*/false);
5007 
5008     // Find the insert position again, in case we inserted an element into
5009     // PackExpansionTypes and invalidated our insert position.
5010     PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
5011   }
5012 
5013   T = new (*this, TypeAlignment)
5014       PackExpansionType(Pattern, Canon, NumExpansions);
5015   Types.push_back(T);
5016   PackExpansionTypes.InsertNode(T, InsertPos);
5017   return QualType(T, 0);
5018 }
5019 
5020 /// CmpProtocolNames - Comparison predicate for sorting protocols
5021 /// alphabetically.
5022 static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
5023                             ObjCProtocolDecl *const *RHS) {
5024   return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
5025 }
5026 
5027 static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) {
5028   if (Protocols.empty()) return true;
5029 
5030   if (Protocols[0]->getCanonicalDecl() != Protocols[0])
5031     return false;
5032 
5033   for (unsigned i = 1; i != Protocols.size(); ++i)
5034     if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
5035         Protocols[i]->getCanonicalDecl() != Protocols[i])
5036       return false;
5037   return true;
5038 }
5039 
5040 static void
5041 SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
5042   // Sort protocols, keyed by name.
5043   llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
5044 
5045   // Canonicalize.
5046   for (ObjCProtocolDecl *&P : Protocols)
5047     P = P->getCanonicalDecl();
5048 
5049   // Remove duplicates.
5050   auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
5051   Protocols.erase(ProtocolsEnd, Protocols.end());
5052 }
5053 
5054 QualType ASTContext::getObjCObjectType(QualType BaseType,
5055                                        ObjCProtocolDecl * const *Protocols,
5056                                        unsigned NumProtocols) const {
5057   return getObjCObjectType(BaseType, {},
5058                            llvm::makeArrayRef(Protocols, NumProtocols),
5059                            /*isKindOf=*/false);
5060 }
5061 
5062 QualType ASTContext::getObjCObjectType(
5063            QualType baseType,
5064            ArrayRef<QualType> typeArgs,
5065            ArrayRef<ObjCProtocolDecl *> protocols,
5066            bool isKindOf) const {
5067   // If the base type is an interface and there aren't any protocols or
5068   // type arguments to add, then the interface type will do just fine.
5069   if (typeArgs.empty() && protocols.empty() && !isKindOf &&
5070       isa<ObjCInterfaceType>(baseType))
5071     return baseType;
5072 
5073   // Look in the folding set for an existing type.
5074   llvm::FoldingSetNodeID ID;
5075   ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
5076   void *InsertPos = nullptr;
5077   if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
5078     return QualType(QT, 0);
5079 
5080   // Determine the type arguments to be used for canonicalization,
5081   // which may be explicitly specified here or written on the base
5082   // type.
5083   ArrayRef<QualType> effectiveTypeArgs = typeArgs;
5084   if (effectiveTypeArgs.empty()) {
5085     if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
5086       effectiveTypeArgs = baseObject->getTypeArgs();
5087   }
5088 
5089   // Build the canonical type, which has the canonical base type and a
5090   // sorted-and-uniqued list of protocols and the type arguments
5091   // canonicalized.
5092   QualType canonical;
5093   bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(),
5094                                           effectiveTypeArgs.end(),
5095                                           [&](QualType type) {
5096                                             return type.isCanonical();
5097                                           });
5098   bool protocolsSorted = areSortedAndUniqued(protocols);
5099   if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
5100     // Determine the canonical type arguments.
5101     ArrayRef<QualType> canonTypeArgs;
5102     SmallVector<QualType, 4> canonTypeArgsVec;
5103     if (!typeArgsAreCanonical) {
5104       canonTypeArgsVec.reserve(effectiveTypeArgs.size());
5105       for (auto typeArg : effectiveTypeArgs)
5106         canonTypeArgsVec.push_back(getCanonicalType(typeArg));
5107       canonTypeArgs = canonTypeArgsVec;
5108     } else {
5109       canonTypeArgs = effectiveTypeArgs;
5110     }
5111 
5112     ArrayRef<ObjCProtocolDecl *> canonProtocols;
5113     SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
5114     if (!protocolsSorted) {
5115       canonProtocolsVec.append(protocols.begin(), protocols.end());
5116       SortAndUniqueProtocols(canonProtocolsVec);
5117       canonProtocols = canonProtocolsVec;
5118     } else {
5119       canonProtocols = protocols;
5120     }
5121 
5122     canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
5123                                   canonProtocols, isKindOf);
5124 
5125     // Regenerate InsertPos.
5126     ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
5127   }
5128 
5129   unsigned size = sizeof(ObjCObjectTypeImpl);
5130   size += typeArgs.size() * sizeof(QualType);
5131   size += protocols.size() * sizeof(ObjCProtocolDecl *);
5132   void *mem = Allocate(size, TypeAlignment);
5133   auto *T =
5134     new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
5135                                  isKindOf);
5136 
5137   Types.push_back(T);
5138   ObjCObjectTypes.InsertNode(T, InsertPos);
5139   return QualType(T, 0);
5140 }
5141 
5142 /// Apply Objective-C protocol qualifiers to the given type.
5143 /// If this is for the canonical type of a type parameter, we can apply
5144 /// protocol qualifiers on the ObjCObjectPointerType.
5145 QualType
5146 ASTContext::applyObjCProtocolQualifiers(QualType type,
5147                   ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
5148                   bool allowOnPointerType) const {
5149   hasError = false;
5150 
5151   if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
5152     return getObjCTypeParamType(objT->getDecl(), protocols);
5153   }
5154 
5155   // Apply protocol qualifiers to ObjCObjectPointerType.
5156   if (allowOnPointerType) {
5157     if (const auto *objPtr =
5158             dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
5159       const ObjCObjectType *objT = objPtr->getObjectType();
5160       // Merge protocol lists and construct ObjCObjectType.
5161       SmallVector<ObjCProtocolDecl*, 8> protocolsVec;
5162       protocolsVec.append(objT->qual_begin(),
5163                           objT->qual_end());
5164       protocolsVec.append(protocols.begin(), protocols.end());
5165       ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
5166       type = getObjCObjectType(
5167              objT->getBaseType(),
5168              objT->getTypeArgsAsWritten(),
5169              protocols,
5170              objT->isKindOfTypeAsWritten());
5171       return getObjCObjectPointerType(type);
5172     }
5173   }
5174 
5175   // Apply protocol qualifiers to ObjCObjectType.
5176   if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
5177     // FIXME: Check for protocols to which the class type is already
5178     // known to conform.
5179 
5180     return getObjCObjectType(objT->getBaseType(),
5181                              objT->getTypeArgsAsWritten(),
5182                              protocols,
5183                              objT->isKindOfTypeAsWritten());
5184   }
5185 
5186   // If the canonical type is ObjCObjectType, ...
5187   if (type->isObjCObjectType()) {
5188     // Silently overwrite any existing protocol qualifiers.
5189     // TODO: determine whether that's the right thing to do.
5190 
5191     // FIXME: Check for protocols to which the class type is already
5192     // known to conform.
5193     return getObjCObjectType(type, {}, protocols, false);
5194   }
5195 
5196   // id<protocol-list>
5197   if (type->isObjCIdType()) {
5198     const auto *objPtr = type->castAs<ObjCObjectPointerType>();
5199     type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols,
5200                                  objPtr->isKindOfType());
5201     return getObjCObjectPointerType(type);
5202   }
5203 
5204   // Class<protocol-list>
5205   if (type->isObjCClassType()) {
5206     const auto *objPtr = type->castAs<ObjCObjectPointerType>();
5207     type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols,
5208                                  objPtr->isKindOfType());
5209     return getObjCObjectPointerType(type);
5210   }
5211 
5212   hasError = true;
5213   return type;
5214 }
5215 
5216 QualType
5217 ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
5218                                  ArrayRef<ObjCProtocolDecl *> protocols) const {
5219   // Look in the folding set for an existing type.
5220   llvm::FoldingSetNodeID ID;
5221   ObjCTypeParamType::Profile(ID, Decl, Decl->getUnderlyingType(), protocols);
5222   void *InsertPos = nullptr;
5223   if (ObjCTypeParamType *TypeParam =
5224       ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
5225     return QualType(TypeParam, 0);
5226 
5227   // We canonicalize to the underlying type.
5228   QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
5229   if (!protocols.empty()) {
5230     // Apply the protocol qualifers.
5231     bool hasError;
5232     Canonical = getCanonicalType(applyObjCProtocolQualifiers(
5233         Canonical, protocols, hasError, true /*allowOnPointerType*/));
5234     assert(!hasError && "Error when apply protocol qualifier to bound type");
5235   }
5236 
5237   unsigned size = sizeof(ObjCTypeParamType);
5238   size += protocols.size() * sizeof(ObjCProtocolDecl *);
5239   void *mem = Allocate(size, TypeAlignment);
5240   auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
5241 
5242   Types.push_back(newType);
5243   ObjCTypeParamTypes.InsertNode(newType, InsertPos);
5244   return QualType(newType, 0);
5245 }
5246 
5247 void ASTContext::adjustObjCTypeParamBoundType(const ObjCTypeParamDecl *Orig,
5248                                               ObjCTypeParamDecl *New) const {
5249   New->setTypeSourceInfo(getTrivialTypeSourceInfo(Orig->getUnderlyingType()));
5250   // Update TypeForDecl after updating TypeSourceInfo.
5251   auto NewTypeParamTy = cast<ObjCTypeParamType>(New->getTypeForDecl());
5252   SmallVector<ObjCProtocolDecl *, 8> protocols;
5253   protocols.append(NewTypeParamTy->qual_begin(), NewTypeParamTy->qual_end());
5254   QualType UpdatedTy = getObjCTypeParamType(New, protocols);
5255   New->setTypeForDecl(UpdatedTy.getTypePtr());
5256 }
5257 
5258 /// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
5259 /// protocol list adopt all protocols in QT's qualified-id protocol
5260 /// list.
5261 bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
5262                                                 ObjCInterfaceDecl *IC) {
5263   if (!QT->isObjCQualifiedIdType())
5264     return false;
5265 
5266   if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
5267     // If both the right and left sides have qualifiers.
5268     for (auto *Proto : OPT->quals()) {
5269       if (!IC->ClassImplementsProtocol(Proto, false))
5270         return false;
5271     }
5272     return true;
5273   }
5274   return false;
5275 }
5276 
5277 /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
5278 /// QT's qualified-id protocol list adopt all protocols in IDecl's list
5279 /// of protocols.
5280 bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
5281                                                 ObjCInterfaceDecl *IDecl) {
5282   if (!QT->isObjCQualifiedIdType())
5283     return false;
5284   const auto *OPT = QT->getAs<ObjCObjectPointerType>();
5285   if (!OPT)
5286     return false;
5287   if (!IDecl->hasDefinition())
5288     return false;
5289   llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
5290   CollectInheritedProtocols(IDecl, InheritedProtocols);
5291   if (InheritedProtocols.empty())
5292     return false;
5293   // Check that if every protocol in list of id<plist> conforms to a protocol
5294   // of IDecl's, then bridge casting is ok.
5295   bool Conforms = false;
5296   for (auto *Proto : OPT->quals()) {
5297     Conforms = false;
5298     for (auto *PI : InheritedProtocols) {
5299       if (ProtocolCompatibleWithProtocol(Proto, PI)) {
5300         Conforms = true;
5301         break;
5302       }
5303     }
5304     if (!Conforms)
5305       break;
5306   }
5307   if (Conforms)
5308     return true;
5309 
5310   for (auto *PI : InheritedProtocols) {
5311     // If both the right and left sides have qualifiers.
5312     bool Adopts = false;
5313     for (auto *Proto : OPT->quals()) {
5314       // return 'true' if 'PI' is in the inheritance hierarchy of Proto
5315       if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
5316         break;
5317     }
5318     if (!Adopts)
5319       return false;
5320   }
5321   return true;
5322 }
5323 
5324 /// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
5325 /// the given object type.
5326 QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
5327   llvm::FoldingSetNodeID ID;
5328   ObjCObjectPointerType::Profile(ID, ObjectT);
5329 
5330   void *InsertPos = nullptr;
5331   if (ObjCObjectPointerType *QT =
5332               ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
5333     return QualType(QT, 0);
5334 
5335   // Find the canonical object type.
5336   QualType Canonical;
5337   if (!ObjectT.isCanonical()) {
5338     Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
5339 
5340     // Regenerate InsertPos.
5341     ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
5342   }
5343 
5344   // No match.
5345   void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
5346   auto *QType =
5347     new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
5348 
5349   Types.push_back(QType);
5350   ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
5351   return QualType(QType, 0);
5352 }
5353 
5354 /// getObjCInterfaceType - Return the unique reference to the type for the
5355 /// specified ObjC interface decl. The list of protocols is optional.
5356 QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
5357                                           ObjCInterfaceDecl *PrevDecl) const {
5358   if (Decl->TypeForDecl)
5359     return QualType(Decl->TypeForDecl, 0);
5360 
5361   if (PrevDecl) {
5362     assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
5363     Decl->TypeForDecl = PrevDecl->TypeForDecl;
5364     return QualType(PrevDecl->TypeForDecl, 0);
5365   }
5366 
5367   // Prefer the definition, if there is one.
5368   if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
5369     Decl = Def;
5370 
5371   void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
5372   auto *T = new (Mem) ObjCInterfaceType(Decl);
5373   Decl->TypeForDecl = T;
5374   Types.push_back(T);
5375   return QualType(T, 0);
5376 }
5377 
5378 /// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
5379 /// TypeOfExprType AST's (since expression's are never shared). For example,
5380 /// multiple declarations that refer to "typeof(x)" all contain different
5381 /// DeclRefExpr's. This doesn't effect the type checker, since it operates
5382 /// on canonical type's (which are always unique).
5383 QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
5384   TypeOfExprType *toe;
5385   if (tofExpr->isTypeDependent()) {
5386     llvm::FoldingSetNodeID ID;
5387     DependentTypeOfExprType::Profile(ID, *this, tofExpr);
5388 
5389     void *InsertPos = nullptr;
5390     DependentTypeOfExprType *Canon
5391       = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
5392     if (Canon) {
5393       // We already have a "canonical" version of an identical, dependent
5394       // typeof(expr) type. Use that as our canonical type.
5395       toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
5396                                           QualType((TypeOfExprType*)Canon, 0));
5397     } else {
5398       // Build a new, canonical typeof(expr) type.
5399       Canon
5400         = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
5401       DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
5402       toe = Canon;
5403     }
5404   } else {
5405     QualType Canonical = getCanonicalType(tofExpr->getType());
5406     toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
5407   }
5408   Types.push_back(toe);
5409   return QualType(toe, 0);
5410 }
5411 
5412 /// getTypeOfType -  Unlike many "get<Type>" functions, we don't unique
5413 /// TypeOfType nodes. The only motivation to unique these nodes would be
5414 /// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
5415 /// an issue. This doesn't affect the type checker, since it operates
5416 /// on canonical types (which are always unique).
5417 QualType ASTContext::getTypeOfType(QualType tofType) const {
5418   QualType Canonical = getCanonicalType(tofType);
5419   auto *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
5420   Types.push_back(tot);
5421   return QualType(tot, 0);
5422 }
5423 
5424 /// Unlike many "get<Type>" functions, we don't unique DecltypeType
5425 /// nodes. This would never be helpful, since each such type has its own
5426 /// expression, and would not give a significant memory saving, since there
5427 /// is an Expr tree under each such type.
5428 QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
5429   DecltypeType *dt;
5430 
5431   // C++11 [temp.type]p2:
5432   //   If an expression e involves a template parameter, decltype(e) denotes a
5433   //   unique dependent type. Two such decltype-specifiers refer to the same
5434   //   type only if their expressions are equivalent (14.5.6.1).
5435   if (e->isInstantiationDependent()) {
5436     llvm::FoldingSetNodeID ID;
5437     DependentDecltypeType::Profile(ID, *this, e);
5438 
5439     void *InsertPos = nullptr;
5440     DependentDecltypeType *Canon
5441       = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
5442     if (!Canon) {
5443       // Build a new, canonical decltype(expr) type.
5444       Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
5445       DependentDecltypeTypes.InsertNode(Canon, InsertPos);
5446     }
5447     dt = new (*this, TypeAlignment)
5448         DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
5449   } else {
5450     dt = new (*this, TypeAlignment)
5451         DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
5452   }
5453   Types.push_back(dt);
5454   return QualType(dt, 0);
5455 }
5456 
5457 /// getUnaryTransformationType - We don't unique these, since the memory
5458 /// savings are minimal and these are rare.
5459 QualType ASTContext::getUnaryTransformType(QualType BaseType,
5460                                            QualType UnderlyingType,
5461                                            UnaryTransformType::UTTKind Kind)
5462     const {
5463   UnaryTransformType *ut = nullptr;
5464 
5465   if (BaseType->isDependentType()) {
5466     // Look in the folding set for an existing type.
5467     llvm::FoldingSetNodeID ID;
5468     DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind);
5469 
5470     void *InsertPos = nullptr;
5471     DependentUnaryTransformType *Canon
5472       = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
5473 
5474     if (!Canon) {
5475       // Build a new, canonical __underlying_type(type) type.
5476       Canon = new (*this, TypeAlignment)
5477              DependentUnaryTransformType(*this, getCanonicalType(BaseType),
5478                                          Kind);
5479       DependentUnaryTransformTypes.InsertNode(Canon, InsertPos);
5480     }
5481     ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
5482                                                         QualType(), Kind,
5483                                                         QualType(Canon, 0));
5484   } else {
5485     QualType CanonType = getCanonicalType(UnderlyingType);
5486     ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
5487                                                         UnderlyingType, Kind,
5488                                                         CanonType);
5489   }
5490   Types.push_back(ut);
5491   return QualType(ut, 0);
5492 }
5493 
5494 /// getAutoType - Return the uniqued reference to the 'auto' type which has been
5495 /// deduced to the given type, or to the canonical undeduced 'auto' type, or the
5496 /// canonical deduced-but-dependent 'auto' type.
5497 QualType
5498 ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
5499                         bool IsDependent, bool IsPack,
5500                         ConceptDecl *TypeConstraintConcept,
5501                         ArrayRef<TemplateArgument> TypeConstraintArgs) const {
5502   assert((!IsPack || IsDependent) && "only use IsPack for a dependent pack");
5503   if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto &&
5504       !TypeConstraintConcept && !IsDependent)
5505     return getAutoDeductType();
5506 
5507   // Look in the folding set for an existing type.
5508   void *InsertPos = nullptr;
5509   llvm::FoldingSetNodeID ID;
5510   AutoType::Profile(ID, *this, DeducedType, Keyword, IsDependent,
5511                     TypeConstraintConcept, TypeConstraintArgs);
5512   if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
5513     return QualType(AT, 0);
5514 
5515   void *Mem = Allocate(sizeof(AutoType) +
5516                        sizeof(TemplateArgument) * TypeConstraintArgs.size(),
5517                        TypeAlignment);
5518   auto *AT = new (Mem) AutoType(
5519       DeducedType, Keyword,
5520       (IsDependent ? TypeDependence::DependentInstantiation
5521                    : TypeDependence::None) |
5522           (IsPack ? TypeDependence::UnexpandedPack : TypeDependence::None),
5523       TypeConstraintConcept, TypeConstraintArgs);
5524   Types.push_back(AT);
5525   if (InsertPos)
5526     AutoTypes.InsertNode(AT, InsertPos);
5527   return QualType(AT, 0);
5528 }
5529 
5530 /// Return the uniqued reference to the deduced template specialization type
5531 /// which has been deduced to the given type, or to the canonical undeduced
5532 /// such type, or the canonical deduced-but-dependent such type.
5533 QualType ASTContext::getDeducedTemplateSpecializationType(
5534     TemplateName Template, QualType DeducedType, bool IsDependent) const {
5535   // Look in the folding set for an existing type.
5536   void *InsertPos = nullptr;
5537   llvm::FoldingSetNodeID ID;
5538   DeducedTemplateSpecializationType::Profile(ID, Template, DeducedType,
5539                                              IsDependent);
5540   if (DeducedTemplateSpecializationType *DTST =
5541           DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
5542     return QualType(DTST, 0);
5543 
5544   auto *DTST = new (*this, TypeAlignment)
5545       DeducedTemplateSpecializationType(Template, DeducedType, IsDependent);
5546   Types.push_back(DTST);
5547   if (InsertPos)
5548     DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
5549   return QualType(DTST, 0);
5550 }
5551 
5552 /// getAtomicType - Return the uniqued reference to the atomic type for
5553 /// the given value type.
5554 QualType ASTContext::getAtomicType(QualType T) const {
5555   // Unique pointers, to guarantee there is only one pointer of a particular
5556   // structure.
5557   llvm::FoldingSetNodeID ID;
5558   AtomicType::Profile(ID, T);
5559 
5560   void *InsertPos = nullptr;
5561   if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
5562     return QualType(AT, 0);
5563 
5564   // If the atomic value type isn't canonical, this won't be a canonical type
5565   // either, so fill in the canonical type field.
5566   QualType Canonical;
5567   if (!T.isCanonical()) {
5568     Canonical = getAtomicType(getCanonicalType(T));
5569 
5570     // Get the new insert position for the node we care about.
5571     AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
5572     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
5573   }
5574   auto *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
5575   Types.push_back(New);
5576   AtomicTypes.InsertNode(New, InsertPos);
5577   return QualType(New, 0);
5578 }
5579 
5580 /// getAutoDeductType - Get type pattern for deducing against 'auto'.
5581 QualType ASTContext::getAutoDeductType() const {
5582   if (AutoDeductTy.isNull())
5583     AutoDeductTy = QualType(new (*this, TypeAlignment)
5584                                 AutoType(QualType(), AutoTypeKeyword::Auto,
5585                                          TypeDependence::None,
5586                                          /*concept*/ nullptr, /*args*/ {}),
5587                             0);
5588   return AutoDeductTy;
5589 }
5590 
5591 /// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
5592 QualType ASTContext::getAutoRRefDeductType() const {
5593   if (AutoRRefDeductTy.isNull())
5594     AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
5595   assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
5596   return AutoRRefDeductTy;
5597 }
5598 
5599 /// getTagDeclType - Return the unique reference to the type for the
5600 /// specified TagDecl (struct/union/class/enum) decl.
5601 QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
5602   assert(Decl);
5603   // FIXME: What is the design on getTagDeclType when it requires casting
5604   // away const?  mutable?
5605   return getTypeDeclType(const_cast<TagDecl*>(Decl));
5606 }
5607 
5608 /// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
5609 /// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
5610 /// needs to agree with the definition in <stddef.h>.
5611 CanQualType ASTContext::getSizeType() const {
5612   return getFromTargetType(Target->getSizeType());
5613 }
5614 
5615 /// Return the unique signed counterpart of the integer type
5616 /// corresponding to size_t.
5617 CanQualType ASTContext::getSignedSizeType() const {
5618   return getFromTargetType(Target->getSignedSizeType());
5619 }
5620 
5621 /// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
5622 CanQualType ASTContext::getIntMaxType() const {
5623   return getFromTargetType(Target->getIntMaxType());
5624 }
5625 
5626 /// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
5627 CanQualType ASTContext::getUIntMaxType() const {
5628   return getFromTargetType(Target->getUIntMaxType());
5629 }
5630 
5631 /// getSignedWCharType - Return the type of "signed wchar_t".
5632 /// Used when in C++, as a GCC extension.
5633 QualType ASTContext::getSignedWCharType() const {
5634   // FIXME: derive from "Target" ?
5635   return WCharTy;
5636 }
5637 
5638 /// getUnsignedWCharType - Return the type of "unsigned wchar_t".
5639 /// Used when in C++, as a GCC extension.
5640 QualType ASTContext::getUnsignedWCharType() const {
5641   // FIXME: derive from "Target" ?
5642   return UnsignedIntTy;
5643 }
5644 
5645 QualType ASTContext::getIntPtrType() const {
5646   return getFromTargetType(Target->getIntPtrType());
5647 }
5648 
5649 QualType ASTContext::getUIntPtrType() const {
5650   return getCorrespondingUnsignedType(getIntPtrType());
5651 }
5652 
5653 /// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
5654 /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
5655 QualType ASTContext::getPointerDiffType() const {
5656   return getFromTargetType(Target->getPtrDiffType(0));
5657 }
5658 
5659 /// Return the unique unsigned counterpart of "ptrdiff_t"
5660 /// integer type. The standard (C11 7.21.6.1p7) refers to this type
5661 /// in the definition of %tu format specifier.
5662 QualType ASTContext::getUnsignedPointerDiffType() const {
5663   return getFromTargetType(Target->getUnsignedPtrDiffType(0));
5664 }
5665 
5666 /// Return the unique type for "pid_t" defined in
5667 /// <sys/types.h>. We need this to compute the correct type for vfork().
5668 QualType ASTContext::getProcessIDType() const {
5669   return getFromTargetType(Target->getProcessIDType());
5670 }
5671 
5672 //===----------------------------------------------------------------------===//
5673 //                              Type Operators
5674 //===----------------------------------------------------------------------===//
5675 
5676 CanQualType ASTContext::getCanonicalParamType(QualType T) const {
5677   // Push qualifiers into arrays, and then discard any remaining
5678   // qualifiers.
5679   T = getCanonicalType(T);
5680   T = getVariableArrayDecayedType(T);
5681   const Type *Ty = T.getTypePtr();
5682   QualType Result;
5683   if (isa<ArrayType>(Ty)) {
5684     Result = getArrayDecayedType(QualType(Ty,0));
5685   } else if (isa<FunctionType>(Ty)) {
5686     Result = getPointerType(QualType(Ty, 0));
5687   } else {
5688     Result = QualType(Ty, 0);
5689   }
5690 
5691   return CanQualType::CreateUnsafe(Result);
5692 }
5693 
5694 QualType ASTContext::getUnqualifiedArrayType(QualType type,
5695                                              Qualifiers &quals) {
5696   SplitQualType splitType = type.getSplitUnqualifiedType();
5697 
5698   // FIXME: getSplitUnqualifiedType() actually walks all the way to
5699   // the unqualified desugared type and then drops it on the floor.
5700   // We then have to strip that sugar back off with
5701   // getUnqualifiedDesugaredType(), which is silly.
5702   const auto *AT =
5703       dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
5704 
5705   // If we don't have an array, just use the results in splitType.
5706   if (!AT) {
5707     quals = splitType.Quals;
5708     return QualType(splitType.Ty, 0);
5709   }
5710 
5711   // Otherwise, recurse on the array's element type.
5712   QualType elementType = AT->getElementType();
5713   QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
5714 
5715   // If that didn't change the element type, AT has no qualifiers, so we
5716   // can just use the results in splitType.
5717   if (elementType == unqualElementType) {
5718     assert(quals.empty()); // from the recursive call
5719     quals = splitType.Quals;
5720     return QualType(splitType.Ty, 0);
5721   }
5722 
5723   // Otherwise, add in the qualifiers from the outermost type, then
5724   // build the type back up.
5725   quals.addConsistentQualifiers(splitType.Quals);
5726 
5727   if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
5728     return getConstantArrayType(unqualElementType, CAT->getSize(),
5729                                 CAT->getSizeExpr(), CAT->getSizeModifier(), 0);
5730   }
5731 
5732   if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) {
5733     return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
5734   }
5735 
5736   if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) {
5737     return getVariableArrayType(unqualElementType,
5738                                 VAT->getSizeExpr(),
5739                                 VAT->getSizeModifier(),
5740                                 VAT->getIndexTypeCVRQualifiers(),
5741                                 VAT->getBracketsRange());
5742   }
5743 
5744   const auto *DSAT = cast<DependentSizedArrayType>(AT);
5745   return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
5746                                     DSAT->getSizeModifier(), 0,
5747                                     SourceRange());
5748 }
5749 
5750 /// Attempt to unwrap two types that may both be array types with the same bound
5751 /// (or both be array types of unknown bound) for the purpose of comparing the
5752 /// cv-decomposition of two types per C++ [conv.qual].
5753 bool ASTContext::UnwrapSimilarArrayTypes(QualType &T1, QualType &T2) {
5754   bool UnwrappedAny = false;
5755   while (true) {
5756     auto *AT1 = getAsArrayType(T1);
5757     if (!AT1) return UnwrappedAny;
5758 
5759     auto *AT2 = getAsArrayType(T2);
5760     if (!AT2) return UnwrappedAny;
5761 
5762     // If we don't have two array types with the same constant bound nor two
5763     // incomplete array types, we've unwrapped everything we can.
5764     if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) {
5765       auto *CAT2 = dyn_cast<ConstantArrayType>(AT2);
5766       if (!CAT2 || CAT1->getSize() != CAT2->getSize())
5767         return UnwrappedAny;
5768     } else if (!isa<IncompleteArrayType>(AT1) ||
5769                !isa<IncompleteArrayType>(AT2)) {
5770       return UnwrappedAny;
5771     }
5772 
5773     T1 = AT1->getElementType();
5774     T2 = AT2->getElementType();
5775     UnwrappedAny = true;
5776   }
5777 }
5778 
5779 /// Attempt to unwrap two types that may be similar (C++ [conv.qual]).
5780 ///
5781 /// If T1 and T2 are both pointer types of the same kind, or both array types
5782 /// with the same bound, unwraps layers from T1 and T2 until a pointer type is
5783 /// unwrapped. Top-level qualifiers on T1 and T2 are ignored.
5784 ///
5785 /// This function will typically be called in a loop that successively
5786 /// "unwraps" pointer and pointer-to-member types to compare them at each
5787 /// level.
5788 ///
5789 /// \return \c true if a pointer type was unwrapped, \c false if we reached a
5790 /// pair of types that can't be unwrapped further.
5791 bool ASTContext::UnwrapSimilarTypes(QualType &T1, QualType &T2) {
5792   UnwrapSimilarArrayTypes(T1, T2);
5793 
5794   const auto *T1PtrType = T1->getAs<PointerType>();
5795   const auto *T2PtrType = T2->getAs<PointerType>();
5796   if (T1PtrType && T2PtrType) {
5797     T1 = T1PtrType->getPointeeType();
5798     T2 = T2PtrType->getPointeeType();
5799     return true;
5800   }
5801 
5802   const auto *T1MPType = T1->getAs<MemberPointerType>();
5803   const auto *T2MPType = T2->getAs<MemberPointerType>();
5804   if (T1MPType && T2MPType &&
5805       hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
5806                              QualType(T2MPType->getClass(), 0))) {
5807     T1 = T1MPType->getPointeeType();
5808     T2 = T2MPType->getPointeeType();
5809     return true;
5810   }
5811 
5812   if (getLangOpts().ObjC) {
5813     const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
5814     const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
5815     if (T1OPType && T2OPType) {
5816       T1 = T1OPType->getPointeeType();
5817       T2 = T2OPType->getPointeeType();
5818       return true;
5819     }
5820   }
5821 
5822   // FIXME: Block pointers, too?
5823 
5824   return false;
5825 }
5826 
5827 bool ASTContext::hasSimilarType(QualType T1, QualType T2) {
5828   while (true) {
5829     Qualifiers Quals;
5830     T1 = getUnqualifiedArrayType(T1, Quals);
5831     T2 = getUnqualifiedArrayType(T2, Quals);
5832     if (hasSameType(T1, T2))
5833       return true;
5834     if (!UnwrapSimilarTypes(T1, T2))
5835       return false;
5836   }
5837 }
5838 
5839 bool ASTContext::hasCvrSimilarType(QualType T1, QualType T2) {
5840   while (true) {
5841     Qualifiers Quals1, Quals2;
5842     T1 = getUnqualifiedArrayType(T1, Quals1);
5843     T2 = getUnqualifiedArrayType(T2, Quals2);
5844 
5845     Quals1.removeCVRQualifiers();
5846     Quals2.removeCVRQualifiers();
5847     if (Quals1 != Quals2)
5848       return false;
5849 
5850     if (hasSameType(T1, T2))
5851       return true;
5852 
5853     if (!UnwrapSimilarTypes(T1, T2))
5854       return false;
5855   }
5856 }
5857 
5858 DeclarationNameInfo
5859 ASTContext::getNameForTemplate(TemplateName Name,
5860                                SourceLocation NameLoc) const {
5861   switch (Name.getKind()) {
5862   case TemplateName::QualifiedTemplate:
5863   case TemplateName::Template:
5864     // DNInfo work in progress: CHECKME: what about DNLoc?
5865     return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
5866                                NameLoc);
5867 
5868   case TemplateName::OverloadedTemplate: {
5869     OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
5870     // DNInfo work in progress: CHECKME: what about DNLoc?
5871     return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
5872   }
5873 
5874   case TemplateName::AssumedTemplate: {
5875     AssumedTemplateStorage *Storage = Name.getAsAssumedTemplateName();
5876     return DeclarationNameInfo(Storage->getDeclName(), NameLoc);
5877   }
5878 
5879   case TemplateName::DependentTemplate: {
5880     DependentTemplateName *DTN = Name.getAsDependentTemplateName();
5881     DeclarationName DName;
5882     if (DTN->isIdentifier()) {
5883       DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
5884       return DeclarationNameInfo(DName, NameLoc);
5885     } else {
5886       DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
5887       // DNInfo work in progress: FIXME: source locations?
5888       DeclarationNameLoc DNLoc =
5889           DeclarationNameLoc::makeCXXOperatorNameLoc(SourceRange());
5890       return DeclarationNameInfo(DName, NameLoc, DNLoc);
5891     }
5892   }
5893 
5894   case TemplateName::SubstTemplateTemplateParm: {
5895     SubstTemplateTemplateParmStorage *subst
5896       = Name.getAsSubstTemplateTemplateParm();
5897     return DeclarationNameInfo(subst->getParameter()->getDeclName(),
5898                                NameLoc);
5899   }
5900 
5901   case TemplateName::SubstTemplateTemplateParmPack: {
5902     SubstTemplateTemplateParmPackStorage *subst
5903       = Name.getAsSubstTemplateTemplateParmPack();
5904     return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
5905                                NameLoc);
5906   }
5907   }
5908 
5909   llvm_unreachable("bad template name kind!");
5910 }
5911 
5912 TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
5913   switch (Name.getKind()) {
5914   case TemplateName::QualifiedTemplate:
5915   case TemplateName::Template: {
5916     TemplateDecl *Template = Name.getAsTemplateDecl();
5917     if (auto *TTP  = dyn_cast<TemplateTemplateParmDecl>(Template))
5918       Template = getCanonicalTemplateTemplateParmDecl(TTP);
5919 
5920     // The canonical template name is the canonical template declaration.
5921     return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
5922   }
5923 
5924   case TemplateName::OverloadedTemplate:
5925   case TemplateName::AssumedTemplate:
5926     llvm_unreachable("cannot canonicalize unresolved template");
5927 
5928   case TemplateName::DependentTemplate: {
5929     DependentTemplateName *DTN = Name.getAsDependentTemplateName();
5930     assert(DTN && "Non-dependent template names must refer to template decls.");
5931     return DTN->CanonicalTemplateName;
5932   }
5933 
5934   case TemplateName::SubstTemplateTemplateParm: {
5935     SubstTemplateTemplateParmStorage *subst
5936       = Name.getAsSubstTemplateTemplateParm();
5937     return getCanonicalTemplateName(subst->getReplacement());
5938   }
5939 
5940   case TemplateName::SubstTemplateTemplateParmPack: {
5941     SubstTemplateTemplateParmPackStorage *subst
5942                                   = Name.getAsSubstTemplateTemplateParmPack();
5943     TemplateTemplateParmDecl *canonParameter
5944       = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
5945     TemplateArgument canonArgPack
5946       = getCanonicalTemplateArgument(subst->getArgumentPack());
5947     return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
5948   }
5949   }
5950 
5951   llvm_unreachable("bad template name!");
5952 }
5953 
5954 bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
5955   X = getCanonicalTemplateName(X);
5956   Y = getCanonicalTemplateName(Y);
5957   return X.getAsVoidPointer() == Y.getAsVoidPointer();
5958 }
5959 
5960 TemplateArgument
5961 ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
5962   switch (Arg.getKind()) {
5963     case TemplateArgument::Null:
5964       return Arg;
5965 
5966     case TemplateArgument::Expression:
5967       return Arg;
5968 
5969     case TemplateArgument::Declaration: {
5970       auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
5971       return TemplateArgument(D, Arg.getParamTypeForDecl());
5972     }
5973 
5974     case TemplateArgument::NullPtr:
5975       return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
5976                               /*isNullPtr*/true);
5977 
5978     case TemplateArgument::Template:
5979       return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
5980 
5981     case TemplateArgument::TemplateExpansion:
5982       return TemplateArgument(getCanonicalTemplateName(
5983                                          Arg.getAsTemplateOrTemplatePattern()),
5984                               Arg.getNumTemplateExpansions());
5985 
5986     case TemplateArgument::Integral:
5987       return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
5988 
5989     case TemplateArgument::Type:
5990       return TemplateArgument(getCanonicalType(Arg.getAsType()));
5991 
5992     case TemplateArgument::Pack: {
5993       if (Arg.pack_size() == 0)
5994         return Arg;
5995 
5996       auto *CanonArgs = new (*this) TemplateArgument[Arg.pack_size()];
5997       unsigned Idx = 0;
5998       for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
5999                                         AEnd = Arg.pack_end();
6000            A != AEnd; (void)++A, ++Idx)
6001         CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
6002 
6003       return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
6004     }
6005   }
6006 
6007   // Silence GCC warning
6008   llvm_unreachable("Unhandled template argument kind");
6009 }
6010 
6011 NestedNameSpecifier *
6012 ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
6013   if (!NNS)
6014     return nullptr;
6015 
6016   switch (NNS->getKind()) {
6017   case NestedNameSpecifier::Identifier:
6018     // Canonicalize the prefix but keep the identifier the same.
6019     return NestedNameSpecifier::Create(*this,
6020                          getCanonicalNestedNameSpecifier(NNS->getPrefix()),
6021                                        NNS->getAsIdentifier());
6022 
6023   case NestedNameSpecifier::Namespace:
6024     // A namespace is canonical; build a nested-name-specifier with
6025     // this namespace and no prefix.
6026     return NestedNameSpecifier::Create(*this, nullptr,
6027                                  NNS->getAsNamespace()->getOriginalNamespace());
6028 
6029   case NestedNameSpecifier::NamespaceAlias:
6030     // A namespace is canonical; build a nested-name-specifier with
6031     // this namespace and no prefix.
6032     return NestedNameSpecifier::Create(*this, nullptr,
6033                                     NNS->getAsNamespaceAlias()->getNamespace()
6034                                                       ->getOriginalNamespace());
6035 
6036   case NestedNameSpecifier::TypeSpec:
6037   case NestedNameSpecifier::TypeSpecWithTemplate: {
6038     QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
6039 
6040     // If we have some kind of dependent-named type (e.g., "typename T::type"),
6041     // break it apart into its prefix and identifier, then reconsititute those
6042     // as the canonical nested-name-specifier. This is required to canonicalize
6043     // a dependent nested-name-specifier involving typedefs of dependent-name
6044     // types, e.g.,
6045     //   typedef typename T::type T1;
6046     //   typedef typename T1::type T2;
6047     if (const auto *DNT = T->getAs<DependentNameType>())
6048       return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
6049                            const_cast<IdentifierInfo *>(DNT->getIdentifier()));
6050 
6051     // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
6052     // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
6053     // first place?
6054     return NestedNameSpecifier::Create(*this, nullptr, false,
6055                                        const_cast<Type *>(T.getTypePtr()));
6056   }
6057 
6058   case NestedNameSpecifier::Global:
6059   case NestedNameSpecifier::Super:
6060     // The global specifier and __super specifer are canonical and unique.
6061     return NNS;
6062   }
6063 
6064   llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
6065 }
6066 
6067 const ArrayType *ASTContext::getAsArrayType(QualType T) const {
6068   // Handle the non-qualified case efficiently.
6069   if (!T.hasLocalQualifiers()) {
6070     // Handle the common positive case fast.
6071     if (const auto *AT = dyn_cast<ArrayType>(T))
6072       return AT;
6073   }
6074 
6075   // Handle the common negative case fast.
6076   if (!isa<ArrayType>(T.getCanonicalType()))
6077     return nullptr;
6078 
6079   // Apply any qualifiers from the array type to the element type.  This
6080   // implements C99 6.7.3p8: "If the specification of an array type includes
6081   // any type qualifiers, the element type is so qualified, not the array type."
6082 
6083   // If we get here, we either have type qualifiers on the type, or we have
6084   // sugar such as a typedef in the way.  If we have type qualifiers on the type
6085   // we must propagate them down into the element type.
6086 
6087   SplitQualType split = T.getSplitDesugaredType();
6088   Qualifiers qs = split.Quals;
6089 
6090   // If we have a simple case, just return now.
6091   const auto *ATy = dyn_cast<ArrayType>(split.Ty);
6092   if (!ATy || qs.empty())
6093     return ATy;
6094 
6095   // Otherwise, we have an array and we have qualifiers on it.  Push the
6096   // qualifiers into the array element type and return a new array type.
6097   QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
6098 
6099   if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy))
6100     return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
6101                                                 CAT->getSizeExpr(),
6102                                                 CAT->getSizeModifier(),
6103                                            CAT->getIndexTypeCVRQualifiers()));
6104   if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy))
6105     return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
6106                                                   IAT->getSizeModifier(),
6107                                            IAT->getIndexTypeCVRQualifiers()));
6108 
6109   if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy))
6110     return cast<ArrayType>(
6111                      getDependentSizedArrayType(NewEltTy,
6112                                                 DSAT->getSizeExpr(),
6113                                                 DSAT->getSizeModifier(),
6114                                               DSAT->getIndexTypeCVRQualifiers(),
6115                                                 DSAT->getBracketsRange()));
6116 
6117   const auto *VAT = cast<VariableArrayType>(ATy);
6118   return cast<ArrayType>(getVariableArrayType(NewEltTy,
6119                                               VAT->getSizeExpr(),
6120                                               VAT->getSizeModifier(),
6121                                               VAT->getIndexTypeCVRQualifiers(),
6122                                               VAT->getBracketsRange()));
6123 }
6124 
6125 QualType ASTContext::getAdjustedParameterType(QualType T) const {
6126   if (T->isArrayType() || T->isFunctionType())
6127     return getDecayedType(T);
6128   return T;
6129 }
6130 
6131 QualType ASTContext::getSignatureParameterType(QualType T) const {
6132   T = getVariableArrayDecayedType(T);
6133   T = getAdjustedParameterType(T);
6134   return T.getUnqualifiedType();
6135 }
6136 
6137 QualType ASTContext::getExceptionObjectType(QualType T) const {
6138   // C++ [except.throw]p3:
6139   //   A throw-expression initializes a temporary object, called the exception
6140   //   object, the type of which is determined by removing any top-level
6141   //   cv-qualifiers from the static type of the operand of throw and adjusting
6142   //   the type from "array of T" or "function returning T" to "pointer to T"
6143   //   or "pointer to function returning T", [...]
6144   T = getVariableArrayDecayedType(T);
6145   if (T->isArrayType() || T->isFunctionType())
6146     T = getDecayedType(T);
6147   return T.getUnqualifiedType();
6148 }
6149 
6150 /// getArrayDecayedType - Return the properly qualified result of decaying the
6151 /// specified array type to a pointer.  This operation is non-trivial when
6152 /// handling typedefs etc.  The canonical type of "T" must be an array type,
6153 /// this returns a pointer to a properly qualified element of the array.
6154 ///
6155 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
6156 QualType ASTContext::getArrayDecayedType(QualType Ty) const {
6157   // Get the element type with 'getAsArrayType' so that we don't lose any
6158   // typedefs in the element type of the array.  This also handles propagation
6159   // of type qualifiers from the array type into the element type if present
6160   // (C99 6.7.3p8).
6161   const ArrayType *PrettyArrayType = getAsArrayType(Ty);
6162   assert(PrettyArrayType && "Not an array type!");
6163 
6164   QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
6165 
6166   // int x[restrict 4] ->  int *restrict
6167   QualType Result = getQualifiedType(PtrTy,
6168                                      PrettyArrayType->getIndexTypeQualifiers());
6169 
6170   // int x[_Nullable] -> int * _Nullable
6171   if (auto Nullability = Ty->getNullability(*this)) {
6172     Result = const_cast<ASTContext *>(this)->getAttributedType(
6173         AttributedType::getNullabilityAttrKind(*Nullability), Result, Result);
6174   }
6175   return Result;
6176 }
6177 
6178 QualType ASTContext::getBaseElementType(const ArrayType *array) const {
6179   return getBaseElementType(array->getElementType());
6180 }
6181 
6182 QualType ASTContext::getBaseElementType(QualType type) const {
6183   Qualifiers qs;
6184   while (true) {
6185     SplitQualType split = type.getSplitDesugaredType();
6186     const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
6187     if (!array) break;
6188 
6189     type = array->getElementType();
6190     qs.addConsistentQualifiers(split.Quals);
6191   }
6192 
6193   return getQualifiedType(type, qs);
6194 }
6195 
6196 /// getConstantArrayElementCount - Returns number of constant array elements.
6197 uint64_t
6198 ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA)  const {
6199   uint64_t ElementCount = 1;
6200   do {
6201     ElementCount *= CA->getSize().getZExtValue();
6202     CA = dyn_cast_or_null<ConstantArrayType>(
6203       CA->getElementType()->getAsArrayTypeUnsafe());
6204   } while (CA);
6205   return ElementCount;
6206 }
6207 
6208 /// getFloatingRank - Return a relative rank for floating point types.
6209 /// This routine will assert if passed a built-in type that isn't a float.
6210 static FloatingRank getFloatingRank(QualType T) {
6211   if (const auto *CT = T->getAs<ComplexType>())
6212     return getFloatingRank(CT->getElementType());
6213 
6214   switch (T->castAs<BuiltinType>()->getKind()) {
6215   default: llvm_unreachable("getFloatingRank(): not a floating type");
6216   case BuiltinType::Float16:    return Float16Rank;
6217   case BuiltinType::Half:       return HalfRank;
6218   case BuiltinType::Float:      return FloatRank;
6219   case BuiltinType::Double:     return DoubleRank;
6220   case BuiltinType::LongDouble: return LongDoubleRank;
6221   case BuiltinType::Float128:   return Float128Rank;
6222   case BuiltinType::BFloat16:   return BFloat16Rank;
6223   }
6224 }
6225 
6226 /// getFloatingTypeOfSizeWithinDomain - Returns a real floating
6227 /// point or a complex type (based on typeDomain/typeSize).
6228 /// 'typeDomain' is a real floating point or complex type.
6229 /// 'typeSize' is a real floating point or complex type.
6230 QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
6231                                                        QualType Domain) const {
6232   FloatingRank EltRank = getFloatingRank(Size);
6233   if (Domain->isComplexType()) {
6234     switch (EltRank) {
6235     case BFloat16Rank: llvm_unreachable("Complex bfloat16 is not supported");
6236     case Float16Rank:
6237     case HalfRank: llvm_unreachable("Complex half is not supported");
6238     case FloatRank:      return FloatComplexTy;
6239     case DoubleRank:     return DoubleComplexTy;
6240     case LongDoubleRank: return LongDoubleComplexTy;
6241     case Float128Rank:   return Float128ComplexTy;
6242     }
6243   }
6244 
6245   assert(Domain->isRealFloatingType() && "Unknown domain!");
6246   switch (EltRank) {
6247   case Float16Rank:    return HalfTy;
6248   case BFloat16Rank:   return BFloat16Ty;
6249   case HalfRank:       return HalfTy;
6250   case FloatRank:      return FloatTy;
6251   case DoubleRank:     return DoubleTy;
6252   case LongDoubleRank: return LongDoubleTy;
6253   case Float128Rank:   return Float128Ty;
6254   }
6255   llvm_unreachable("getFloatingRank(): illegal value for rank");
6256 }
6257 
6258 /// getFloatingTypeOrder - Compare the rank of the two specified floating
6259 /// point types, ignoring the domain of the type (i.e. 'double' ==
6260 /// '_Complex double').  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
6261 /// LHS < RHS, return -1.
6262 int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
6263   FloatingRank LHSR = getFloatingRank(LHS);
6264   FloatingRank RHSR = getFloatingRank(RHS);
6265 
6266   if (LHSR == RHSR)
6267     return 0;
6268   if (LHSR > RHSR)
6269     return 1;
6270   return -1;
6271 }
6272 
6273 int ASTContext::getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const {
6274   if (&getFloatTypeSemantics(LHS) == &getFloatTypeSemantics(RHS))
6275     return 0;
6276   return getFloatingTypeOrder(LHS, RHS);
6277 }
6278 
6279 /// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
6280 /// routine will assert if passed a built-in type that isn't an integer or enum,
6281 /// or if it is not canonicalized.
6282 unsigned ASTContext::getIntegerRank(const Type *T) const {
6283   assert(T->isCanonicalUnqualified() && "T should be canonicalized");
6284 
6285   // Results in this 'losing' to any type of the same size, but winning if
6286   // larger.
6287   if (const auto *EIT = dyn_cast<ExtIntType>(T))
6288     return 0 + (EIT->getNumBits() << 3);
6289 
6290   switch (cast<BuiltinType>(T)->getKind()) {
6291   default: llvm_unreachable("getIntegerRank(): not a built-in integer");
6292   case BuiltinType::Bool:
6293     return 1 + (getIntWidth(BoolTy) << 3);
6294   case BuiltinType::Char_S:
6295   case BuiltinType::Char_U:
6296   case BuiltinType::SChar:
6297   case BuiltinType::UChar:
6298     return 2 + (getIntWidth(CharTy) << 3);
6299   case BuiltinType::Short:
6300   case BuiltinType::UShort:
6301     return 3 + (getIntWidth(ShortTy) << 3);
6302   case BuiltinType::Int:
6303   case BuiltinType::UInt:
6304     return 4 + (getIntWidth(IntTy) << 3);
6305   case BuiltinType::Long:
6306   case BuiltinType::ULong:
6307     return 5 + (getIntWidth(LongTy) << 3);
6308   case BuiltinType::LongLong:
6309   case BuiltinType::ULongLong:
6310     return 6 + (getIntWidth(LongLongTy) << 3);
6311   case BuiltinType::Int128:
6312   case BuiltinType::UInt128:
6313     return 7 + (getIntWidth(Int128Ty) << 3);
6314   }
6315 }
6316 
6317 /// Whether this is a promotable bitfield reference according
6318 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
6319 ///
6320 /// \returns the type this bit-field will promote to, or NULL if no
6321 /// promotion occurs.
6322 QualType ASTContext::isPromotableBitField(Expr *E) const {
6323   if (E->isTypeDependent() || E->isValueDependent())
6324     return {};
6325 
6326   // C++ [conv.prom]p5:
6327   //    If the bit-field has an enumerated type, it is treated as any other
6328   //    value of that type for promotion purposes.
6329   if (getLangOpts().CPlusPlus && E->getType()->isEnumeralType())
6330     return {};
6331 
6332   // FIXME: We should not do this unless E->refersToBitField() is true. This
6333   // matters in C where getSourceBitField() will find bit-fields for various
6334   // cases where the source expression is not a bit-field designator.
6335 
6336   FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
6337   if (!Field)
6338     return {};
6339 
6340   QualType FT = Field->getType();
6341 
6342   uint64_t BitWidth = Field->getBitWidthValue(*this);
6343   uint64_t IntSize = getTypeSize(IntTy);
6344   // C++ [conv.prom]p5:
6345   //   A prvalue for an integral bit-field can be converted to a prvalue of type
6346   //   int if int can represent all the values of the bit-field; otherwise, it
6347   //   can be converted to unsigned int if unsigned int can represent all the
6348   //   values of the bit-field. If the bit-field is larger yet, no integral
6349   //   promotion applies to it.
6350   // C11 6.3.1.1/2:
6351   //   [For a bit-field of type _Bool, int, signed int, or unsigned int:]
6352   //   If an int can represent all values of the original type (as restricted by
6353   //   the width, for a bit-field), the value is converted to an int; otherwise,
6354   //   it is converted to an unsigned int.
6355   //
6356   // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
6357   //        We perform that promotion here to match GCC and C++.
6358   // FIXME: C does not permit promotion of an enum bit-field whose rank is
6359   //        greater than that of 'int'. We perform that promotion to match GCC.
6360   if (BitWidth < IntSize)
6361     return IntTy;
6362 
6363   if (BitWidth == IntSize)
6364     return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
6365 
6366   // Bit-fields wider than int are not subject to promotions, and therefore act
6367   // like the base type. GCC has some weird bugs in this area that we
6368   // deliberately do not follow (GCC follows a pre-standard resolution to
6369   // C's DR315 which treats bit-width as being part of the type, and this leaks
6370   // into their semantics in some cases).
6371   return {};
6372 }
6373 
6374 /// getPromotedIntegerType - Returns the type that Promotable will
6375 /// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
6376 /// integer type.
6377 QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
6378   assert(!Promotable.isNull());
6379   assert(Promotable->isPromotableIntegerType());
6380   if (const auto *ET = Promotable->getAs<EnumType>())
6381     return ET->getDecl()->getPromotionType();
6382 
6383   if (const auto *BT = Promotable->getAs<BuiltinType>()) {
6384     // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
6385     // (3.9.1) can be converted to a prvalue of the first of the following
6386     // types that can represent all the values of its underlying type:
6387     // int, unsigned int, long int, unsigned long int, long long int, or
6388     // unsigned long long int [...]
6389     // FIXME: Is there some better way to compute this?
6390     if (BT->getKind() == BuiltinType::WChar_S ||
6391         BT->getKind() == BuiltinType::WChar_U ||
6392         BT->getKind() == BuiltinType::Char8 ||
6393         BT->getKind() == BuiltinType::Char16 ||
6394         BT->getKind() == BuiltinType::Char32) {
6395       bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
6396       uint64_t FromSize = getTypeSize(BT);
6397       QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
6398                                   LongLongTy, UnsignedLongLongTy };
6399       for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
6400         uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
6401         if (FromSize < ToSize ||
6402             (FromSize == ToSize &&
6403              FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
6404           return PromoteTypes[Idx];
6405       }
6406       llvm_unreachable("char type should fit into long long");
6407     }
6408   }
6409 
6410   // At this point, we should have a signed or unsigned integer type.
6411   if (Promotable->isSignedIntegerType())
6412     return IntTy;
6413   uint64_t PromotableSize = getIntWidth(Promotable);
6414   uint64_t IntSize = getIntWidth(IntTy);
6415   assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
6416   return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
6417 }
6418 
6419 /// Recurses in pointer/array types until it finds an objc retainable
6420 /// type and returns its ownership.
6421 Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
6422   while (!T.isNull()) {
6423     if (T.getObjCLifetime() != Qualifiers::OCL_None)
6424       return T.getObjCLifetime();
6425     if (T->isArrayType())
6426       T = getBaseElementType(T);
6427     else if (const auto *PT = T->getAs<PointerType>())
6428       T = PT->getPointeeType();
6429     else if (const auto *RT = T->getAs<ReferenceType>())
6430       T = RT->getPointeeType();
6431     else
6432       break;
6433   }
6434 
6435   return Qualifiers::OCL_None;
6436 }
6437 
6438 static const Type *getIntegerTypeForEnum(const EnumType *ET) {
6439   // Incomplete enum types are not treated as integer types.
6440   // FIXME: In C++, enum types are never integer types.
6441   if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
6442     return ET->getDecl()->getIntegerType().getTypePtr();
6443   return nullptr;
6444 }
6445 
6446 /// getIntegerTypeOrder - Returns the highest ranked integer type:
6447 /// C99 6.3.1.8p1.  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
6448 /// LHS < RHS, return -1.
6449 int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
6450   const Type *LHSC = getCanonicalType(LHS).getTypePtr();
6451   const Type *RHSC = getCanonicalType(RHS).getTypePtr();
6452 
6453   // Unwrap enums to their underlying type.
6454   if (const auto *ET = dyn_cast<EnumType>(LHSC))
6455     LHSC = getIntegerTypeForEnum(ET);
6456   if (const auto *ET = dyn_cast<EnumType>(RHSC))
6457     RHSC = getIntegerTypeForEnum(ET);
6458 
6459   if (LHSC == RHSC) return 0;
6460 
6461   bool LHSUnsigned = LHSC->isUnsignedIntegerType();
6462   bool RHSUnsigned = RHSC->isUnsignedIntegerType();
6463 
6464   unsigned LHSRank = getIntegerRank(LHSC);
6465   unsigned RHSRank = getIntegerRank(RHSC);
6466 
6467   if (LHSUnsigned == RHSUnsigned) {  // Both signed or both unsigned.
6468     if (LHSRank == RHSRank) return 0;
6469     return LHSRank > RHSRank ? 1 : -1;
6470   }
6471 
6472   // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
6473   if (LHSUnsigned) {
6474     // If the unsigned [LHS] type is larger, return it.
6475     if (LHSRank >= RHSRank)
6476       return 1;
6477 
6478     // If the signed type can represent all values of the unsigned type, it
6479     // wins.  Because we are dealing with 2's complement and types that are
6480     // powers of two larger than each other, this is always safe.
6481     return -1;
6482   }
6483 
6484   // If the unsigned [RHS] type is larger, return it.
6485   if (RHSRank >= LHSRank)
6486     return -1;
6487 
6488   // If the signed type can represent all values of the unsigned type, it
6489   // wins.  Because we are dealing with 2's complement and types that are
6490   // powers of two larger than each other, this is always safe.
6491   return 1;
6492 }
6493 
6494 TypedefDecl *ASTContext::getCFConstantStringDecl() const {
6495   if (CFConstantStringTypeDecl)
6496     return CFConstantStringTypeDecl;
6497 
6498   assert(!CFConstantStringTagDecl &&
6499          "tag and typedef should be initialized together");
6500   CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
6501   CFConstantStringTagDecl->startDefinition();
6502 
6503   struct {
6504     QualType Type;
6505     const char *Name;
6506   } Fields[5];
6507   unsigned Count = 0;
6508 
6509   /// Objective-C ABI
6510   ///
6511   ///    typedef struct __NSConstantString_tag {
6512   ///      const int *isa;
6513   ///      int flags;
6514   ///      const char *str;
6515   ///      long length;
6516   ///    } __NSConstantString;
6517   ///
6518   /// Swift ABI (4.1, 4.2)
6519   ///
6520   ///    typedef struct __NSConstantString_tag {
6521   ///      uintptr_t _cfisa;
6522   ///      uintptr_t _swift_rc;
6523   ///      _Atomic(uint64_t) _cfinfoa;
6524   ///      const char *_ptr;
6525   ///      uint32_t _length;
6526   ///    } __NSConstantString;
6527   ///
6528   /// Swift ABI (5.0)
6529   ///
6530   ///    typedef struct __NSConstantString_tag {
6531   ///      uintptr_t _cfisa;
6532   ///      uintptr_t _swift_rc;
6533   ///      _Atomic(uint64_t) _cfinfoa;
6534   ///      const char *_ptr;
6535   ///      uintptr_t _length;
6536   ///    } __NSConstantString;
6537 
6538   const auto CFRuntime = getLangOpts().CFRuntime;
6539   if (static_cast<unsigned>(CFRuntime) <
6540       static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) {
6541     Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" };
6542     Fields[Count++] = { IntTy, "flags" };
6543     Fields[Count++] = { getPointerType(CharTy.withConst()), "str" };
6544     Fields[Count++] = { LongTy, "length" };
6545   } else {
6546     Fields[Count++] = { getUIntPtrType(), "_cfisa" };
6547     Fields[Count++] = { getUIntPtrType(), "_swift_rc" };
6548     Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" };
6549     Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" };
6550     if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
6551         CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
6552       Fields[Count++] = { IntTy, "_ptr" };
6553     else
6554       Fields[Count++] = { getUIntPtrType(), "_ptr" };
6555   }
6556 
6557   // Create fields
6558   for (unsigned i = 0; i < Count; ++i) {
6559     FieldDecl *Field =
6560         FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(),
6561                           SourceLocation(), &Idents.get(Fields[i].Name),
6562                           Fields[i].Type, /*TInfo=*/nullptr,
6563                           /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
6564     Field->setAccess(AS_public);
6565     CFConstantStringTagDecl->addDecl(Field);
6566   }
6567 
6568   CFConstantStringTagDecl->completeDefinition();
6569   // This type is designed to be compatible with NSConstantString, but cannot
6570   // use the same name, since NSConstantString is an interface.
6571   auto tagType = getTagDeclType(CFConstantStringTagDecl);
6572   CFConstantStringTypeDecl =
6573       buildImplicitTypedef(tagType, "__NSConstantString");
6574 
6575   return CFConstantStringTypeDecl;
6576 }
6577 
6578 RecordDecl *ASTContext::getCFConstantStringTagDecl() const {
6579   if (!CFConstantStringTagDecl)
6580     getCFConstantStringDecl(); // Build the tag and the typedef.
6581   return CFConstantStringTagDecl;
6582 }
6583 
6584 // getCFConstantStringType - Return the type used for constant CFStrings.
6585 QualType ASTContext::getCFConstantStringType() const {
6586   return getTypedefType(getCFConstantStringDecl());
6587 }
6588 
6589 QualType ASTContext::getObjCSuperType() const {
6590   if (ObjCSuperType.isNull()) {
6591     RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
6592     TUDecl->addDecl(ObjCSuperTypeDecl);
6593     ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
6594   }
6595   return ObjCSuperType;
6596 }
6597 
6598 void ASTContext::setCFConstantStringType(QualType T) {
6599   const auto *TD = T->castAs<TypedefType>();
6600   CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl());
6601   const auto *TagType =
6602       CFConstantStringTypeDecl->getUnderlyingType()->castAs<RecordType>();
6603   CFConstantStringTagDecl = TagType->getDecl();
6604 }
6605 
6606 QualType ASTContext::getBlockDescriptorType() const {
6607   if (BlockDescriptorType)
6608     return getTagDeclType(BlockDescriptorType);
6609 
6610   RecordDecl *RD;
6611   // FIXME: Needs the FlagAppleBlock bit.
6612   RD = buildImplicitRecord("__block_descriptor");
6613   RD->startDefinition();
6614 
6615   QualType FieldTypes[] = {
6616     UnsignedLongTy,
6617     UnsignedLongTy,
6618   };
6619 
6620   static const char *const FieldNames[] = {
6621     "reserved",
6622     "Size"
6623   };
6624 
6625   for (size_t i = 0; i < 2; ++i) {
6626     FieldDecl *Field = FieldDecl::Create(
6627         *this, RD, SourceLocation(), SourceLocation(),
6628         &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
6629         /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
6630     Field->setAccess(AS_public);
6631     RD->addDecl(Field);
6632   }
6633 
6634   RD->completeDefinition();
6635 
6636   BlockDescriptorType = RD;
6637 
6638   return getTagDeclType(BlockDescriptorType);
6639 }
6640 
6641 QualType ASTContext::getBlockDescriptorExtendedType() const {
6642   if (BlockDescriptorExtendedType)
6643     return getTagDeclType(BlockDescriptorExtendedType);
6644 
6645   RecordDecl *RD;
6646   // FIXME: Needs the FlagAppleBlock bit.
6647   RD = buildImplicitRecord("__block_descriptor_withcopydispose");
6648   RD->startDefinition();
6649 
6650   QualType FieldTypes[] = {
6651     UnsignedLongTy,
6652     UnsignedLongTy,
6653     getPointerType(VoidPtrTy),
6654     getPointerType(VoidPtrTy)
6655   };
6656 
6657   static const char *const FieldNames[] = {
6658     "reserved",
6659     "Size",
6660     "CopyFuncPtr",
6661     "DestroyFuncPtr"
6662   };
6663 
6664   for (size_t i = 0; i < 4; ++i) {
6665     FieldDecl *Field = FieldDecl::Create(
6666         *this, RD, SourceLocation(), SourceLocation(),
6667         &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
6668         /*BitWidth=*/nullptr,
6669         /*Mutable=*/false, ICIS_NoInit);
6670     Field->setAccess(AS_public);
6671     RD->addDecl(Field);
6672   }
6673 
6674   RD->completeDefinition();
6675 
6676   BlockDescriptorExtendedType = RD;
6677   return getTagDeclType(BlockDescriptorExtendedType);
6678 }
6679 
6680 OpenCLTypeKind ASTContext::getOpenCLTypeKind(const Type *T) const {
6681   const auto *BT = dyn_cast<BuiltinType>(T);
6682 
6683   if (!BT) {
6684     if (isa<PipeType>(T))
6685       return OCLTK_Pipe;
6686 
6687     return OCLTK_Default;
6688   }
6689 
6690   switch (BT->getKind()) {
6691 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix)                   \
6692   case BuiltinType::Id:                                                        \
6693     return OCLTK_Image;
6694 #include "clang/Basic/OpenCLImageTypes.def"
6695 
6696   case BuiltinType::OCLClkEvent:
6697     return OCLTK_ClkEvent;
6698 
6699   case BuiltinType::OCLEvent:
6700     return OCLTK_Event;
6701 
6702   case BuiltinType::OCLQueue:
6703     return OCLTK_Queue;
6704 
6705   case BuiltinType::OCLReserveID:
6706     return OCLTK_ReserveID;
6707 
6708   case BuiltinType::OCLSampler:
6709     return OCLTK_Sampler;
6710 
6711   default:
6712     return OCLTK_Default;
6713   }
6714 }
6715 
6716 LangAS ASTContext::getOpenCLTypeAddrSpace(const Type *T) const {
6717   return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
6718 }
6719 
6720 /// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
6721 /// requires copy/dispose. Note that this must match the logic
6722 /// in buildByrefHelpers.
6723 bool ASTContext::BlockRequiresCopying(QualType Ty,
6724                                       const VarDecl *D) {
6725   if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
6726     const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr();
6727     if (!copyExpr && record->hasTrivialDestructor()) return false;
6728 
6729     return true;
6730   }
6731 
6732   // The block needs copy/destroy helpers if Ty is non-trivial to destructively
6733   // move or destroy.
6734   if (Ty.isNonTrivialToPrimitiveDestructiveMove() || Ty.isDestructedType())
6735     return true;
6736 
6737   if (!Ty->isObjCRetainableType()) return false;
6738 
6739   Qualifiers qs = Ty.getQualifiers();
6740 
6741   // If we have lifetime, that dominates.
6742   if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
6743     switch (lifetime) {
6744       case Qualifiers::OCL_None: llvm_unreachable("impossible");
6745 
6746       // These are just bits as far as the runtime is concerned.
6747       case Qualifiers::OCL_ExplicitNone:
6748       case Qualifiers::OCL_Autoreleasing:
6749         return false;
6750 
6751       // These cases should have been taken care of when checking the type's
6752       // non-triviality.
6753       case Qualifiers::OCL_Weak:
6754       case Qualifiers::OCL_Strong:
6755         llvm_unreachable("impossible");
6756     }
6757     llvm_unreachable("fell out of lifetime switch!");
6758   }
6759   return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
6760           Ty->isObjCObjectPointerType());
6761 }
6762 
6763 bool ASTContext::getByrefLifetime(QualType Ty,
6764                               Qualifiers::ObjCLifetime &LifeTime,
6765                               bool &HasByrefExtendedLayout) const {
6766   if (!getLangOpts().ObjC ||
6767       getLangOpts().getGC() != LangOptions::NonGC)
6768     return false;
6769 
6770   HasByrefExtendedLayout = false;
6771   if (Ty->isRecordType()) {
6772     HasByrefExtendedLayout = true;
6773     LifeTime = Qualifiers::OCL_None;
6774   } else if ((LifeTime = Ty.getObjCLifetime())) {
6775     // Honor the ARC qualifiers.
6776   } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
6777     // The MRR rule.
6778     LifeTime = Qualifiers::OCL_ExplicitNone;
6779   } else {
6780     LifeTime = Qualifiers::OCL_None;
6781   }
6782   return true;
6783 }
6784 
6785 CanQualType ASTContext::getNSUIntegerType() const {
6786   assert(Target && "Expected target to be initialized");
6787   const llvm::Triple &T = Target->getTriple();
6788   // Windows is LLP64 rather than LP64
6789   if (T.isOSWindows() && T.isArch64Bit())
6790     return UnsignedLongLongTy;
6791   return UnsignedLongTy;
6792 }
6793 
6794 CanQualType ASTContext::getNSIntegerType() const {
6795   assert(Target && "Expected target to be initialized");
6796   const llvm::Triple &T = Target->getTriple();
6797   // Windows is LLP64 rather than LP64
6798   if (T.isOSWindows() && T.isArch64Bit())
6799     return LongLongTy;
6800   return LongTy;
6801 }
6802 
6803 TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
6804   if (!ObjCInstanceTypeDecl)
6805     ObjCInstanceTypeDecl =
6806         buildImplicitTypedef(getObjCIdType(), "instancetype");
6807   return ObjCInstanceTypeDecl;
6808 }
6809 
6810 // This returns true if a type has been typedefed to BOOL:
6811 // typedef <type> BOOL;
6812 static bool isTypeTypedefedAsBOOL(QualType T) {
6813   if (const auto *TT = dyn_cast<TypedefType>(T))
6814     if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
6815       return II->isStr("BOOL");
6816 
6817   return false;
6818 }
6819 
6820 /// getObjCEncodingTypeSize returns size of type for objective-c encoding
6821 /// purpose.
6822 CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
6823   if (!type->isIncompleteArrayType() && type->isIncompleteType())
6824     return CharUnits::Zero();
6825 
6826   CharUnits sz = getTypeSizeInChars(type);
6827 
6828   // Make all integer and enum types at least as large as an int
6829   if (sz.isPositive() && type->isIntegralOrEnumerationType())
6830     sz = std::max(sz, getTypeSizeInChars(IntTy));
6831   // Treat arrays as pointers, since that's how they're passed in.
6832   else if (type->isArrayType())
6833     sz = getTypeSizeInChars(VoidPtrTy);
6834   return sz;
6835 }
6836 
6837 bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
6838   return getTargetInfo().getCXXABI().isMicrosoft() &&
6839          VD->isStaticDataMember() &&
6840          VD->getType()->isIntegralOrEnumerationType() &&
6841          !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
6842 }
6843 
6844 ASTContext::InlineVariableDefinitionKind
6845 ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const {
6846   if (!VD->isInline())
6847     return InlineVariableDefinitionKind::None;
6848 
6849   // In almost all cases, it's a weak definition.
6850   auto *First = VD->getFirstDecl();
6851   if (First->isInlineSpecified() || !First->isStaticDataMember())
6852     return InlineVariableDefinitionKind::Weak;
6853 
6854   // If there's a file-context declaration in this translation unit, it's a
6855   // non-discardable definition.
6856   for (auto *D : VD->redecls())
6857     if (D->getLexicalDeclContext()->isFileContext() &&
6858         !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
6859       return InlineVariableDefinitionKind::Strong;
6860 
6861   // If we've not seen one yet, we don't know.
6862   return InlineVariableDefinitionKind::WeakUnknown;
6863 }
6864 
6865 static std::string charUnitsToString(const CharUnits &CU) {
6866   return llvm::itostr(CU.getQuantity());
6867 }
6868 
6869 /// getObjCEncodingForBlock - Return the encoded type for this block
6870 /// declaration.
6871 std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
6872   std::string S;
6873 
6874   const BlockDecl *Decl = Expr->getBlockDecl();
6875   QualType BlockTy =
6876       Expr->getType()->castAs<BlockPointerType>()->getPointeeType();
6877   QualType BlockReturnTy = BlockTy->castAs<FunctionType>()->getReturnType();
6878   // Encode result type.
6879   if (getLangOpts().EncodeExtendedBlockSig)
6880     getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, BlockReturnTy, S,
6881                                       true /*Extended*/);
6882   else
6883     getObjCEncodingForType(BlockReturnTy, S);
6884   // Compute size of all parameters.
6885   // Start with computing size of a pointer in number of bytes.
6886   // FIXME: There might(should) be a better way of doing this computation!
6887   CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
6888   CharUnits ParmOffset = PtrSize;
6889   for (auto PI : Decl->parameters()) {
6890     QualType PType = PI->getType();
6891     CharUnits sz = getObjCEncodingTypeSize(PType);
6892     if (sz.isZero())
6893       continue;
6894     assert(sz.isPositive() && "BlockExpr - Incomplete param type");
6895     ParmOffset += sz;
6896   }
6897   // Size of the argument frame
6898   S += charUnitsToString(ParmOffset);
6899   // Block pointer and offset.
6900   S += "@?0";
6901 
6902   // Argument types.
6903   ParmOffset = PtrSize;
6904   for (auto PVDecl : Decl->parameters()) {
6905     QualType PType = PVDecl->getOriginalType();
6906     if (const auto *AT =
6907             dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
6908       // Use array's original type only if it has known number of
6909       // elements.
6910       if (!isa<ConstantArrayType>(AT))
6911         PType = PVDecl->getType();
6912     } else if (PType->isFunctionType())
6913       PType = PVDecl->getType();
6914     if (getLangOpts().EncodeExtendedBlockSig)
6915       getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
6916                                       S, true /*Extended*/);
6917     else
6918       getObjCEncodingForType(PType, S);
6919     S += charUnitsToString(ParmOffset);
6920     ParmOffset += getObjCEncodingTypeSize(PType);
6921   }
6922 
6923   return S;
6924 }
6925 
6926 std::string
6927 ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const {
6928   std::string S;
6929   // Encode result type.
6930   getObjCEncodingForType(Decl->getReturnType(), S);
6931   CharUnits ParmOffset;
6932   // Compute size of all parameters.
6933   for (auto PI : Decl->parameters()) {
6934     QualType PType = PI->getType();
6935     CharUnits sz = getObjCEncodingTypeSize(PType);
6936     if (sz.isZero())
6937       continue;
6938 
6939     assert(sz.isPositive() &&
6940            "getObjCEncodingForFunctionDecl - Incomplete param type");
6941     ParmOffset += sz;
6942   }
6943   S += charUnitsToString(ParmOffset);
6944   ParmOffset = CharUnits::Zero();
6945 
6946   // Argument types.
6947   for (auto PVDecl : Decl->parameters()) {
6948     QualType PType = PVDecl->getOriginalType();
6949     if (const auto *AT =
6950             dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
6951       // Use array's original type only if it has known number of
6952       // elements.
6953       if (!isa<ConstantArrayType>(AT))
6954         PType = PVDecl->getType();
6955     } else if (PType->isFunctionType())
6956       PType = PVDecl->getType();
6957     getObjCEncodingForType(PType, S);
6958     S += charUnitsToString(ParmOffset);
6959     ParmOffset += getObjCEncodingTypeSize(PType);
6960   }
6961 
6962   return S;
6963 }
6964 
6965 /// getObjCEncodingForMethodParameter - Return the encoded type for a single
6966 /// method parameter or return type. If Extended, include class names and
6967 /// block object types.
6968 void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
6969                                                    QualType T, std::string& S,
6970                                                    bool Extended) const {
6971   // Encode type qualifer, 'in', 'inout', etc. for the parameter.
6972   getObjCEncodingForTypeQualifier(QT, S);
6973   // Encode parameter type.
6974   ObjCEncOptions Options = ObjCEncOptions()
6975                                .setExpandPointedToStructures()
6976                                .setExpandStructures()
6977                                .setIsOutermostType();
6978   if (Extended)
6979     Options.setEncodeBlockParameters().setEncodeClassNames();
6980   getObjCEncodingForTypeImpl(T, S, Options, /*Field=*/nullptr);
6981 }
6982 
6983 /// getObjCEncodingForMethodDecl - Return the encoded type for this method
6984 /// declaration.
6985 std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
6986                                                      bool Extended) const {
6987   // FIXME: This is not very efficient.
6988   // Encode return type.
6989   std::string S;
6990   getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
6991                                     Decl->getReturnType(), S, Extended);
6992   // Compute size of all parameters.
6993   // Start with computing size of a pointer in number of bytes.
6994   // FIXME: There might(should) be a better way of doing this computation!
6995   CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
6996   // The first two arguments (self and _cmd) are pointers; account for
6997   // their size.
6998   CharUnits ParmOffset = 2 * PtrSize;
6999   for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
7000        E = Decl->sel_param_end(); PI != E; ++PI) {
7001     QualType PType = (*PI)->getType();
7002     CharUnits sz = getObjCEncodingTypeSize(PType);
7003     if (sz.isZero())
7004       continue;
7005 
7006     assert(sz.isPositive() &&
7007            "getObjCEncodingForMethodDecl - Incomplete param type");
7008     ParmOffset += sz;
7009   }
7010   S += charUnitsToString(ParmOffset);
7011   S += "@0:";
7012   S += charUnitsToString(PtrSize);
7013 
7014   // Argument types.
7015   ParmOffset = 2 * PtrSize;
7016   for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
7017        E = Decl->sel_param_end(); PI != E; ++PI) {
7018     const ParmVarDecl *PVDecl = *PI;
7019     QualType PType = PVDecl->getOriginalType();
7020     if (const auto *AT =
7021             dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
7022       // Use array's original type only if it has known number of
7023       // elements.
7024       if (!isa<ConstantArrayType>(AT))
7025         PType = PVDecl->getType();
7026     } else if (PType->isFunctionType())
7027       PType = PVDecl->getType();
7028     getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
7029                                       PType, S, Extended);
7030     S += charUnitsToString(ParmOffset);
7031     ParmOffset += getObjCEncodingTypeSize(PType);
7032   }
7033 
7034   return S;
7035 }
7036 
7037 ObjCPropertyImplDecl *
7038 ASTContext::getObjCPropertyImplDeclForPropertyDecl(
7039                                       const ObjCPropertyDecl *PD,
7040                                       const Decl *Container) const {
7041   if (!Container)
7042     return nullptr;
7043   if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) {
7044     for (auto *PID : CID->property_impls())
7045       if (PID->getPropertyDecl() == PD)
7046         return PID;
7047   } else {
7048     const auto *OID = cast<ObjCImplementationDecl>(Container);
7049     for (auto *PID : OID->property_impls())
7050       if (PID->getPropertyDecl() == PD)
7051         return PID;
7052   }
7053   return nullptr;
7054 }
7055 
7056 /// getObjCEncodingForPropertyDecl - Return the encoded type for this
7057 /// property declaration. If non-NULL, Container must be either an
7058 /// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
7059 /// NULL when getting encodings for protocol properties.
7060 /// Property attributes are stored as a comma-delimited C string. The simple
7061 /// attributes readonly and bycopy are encoded as single characters. The
7062 /// parametrized attributes, getter=name, setter=name, and ivar=name, are
7063 /// encoded as single characters, followed by an identifier. Property types
7064 /// are also encoded as a parametrized attribute. The characters used to encode
7065 /// these attributes are defined by the following enumeration:
7066 /// @code
7067 /// enum PropertyAttributes {
7068 /// kPropertyReadOnly = 'R',   // property is read-only.
7069 /// kPropertyBycopy = 'C',     // property is a copy of the value last assigned
7070 /// kPropertyByref = '&',  // property is a reference to the value last assigned
7071 /// kPropertyDynamic = 'D',    // property is dynamic
7072 /// kPropertyGetter = 'G',     // followed by getter selector name
7073 /// kPropertySetter = 'S',     // followed by setter selector name
7074 /// kPropertyInstanceVariable = 'V'  // followed by instance variable  name
7075 /// kPropertyType = 'T'              // followed by old-style type encoding.
7076 /// kPropertyWeak = 'W'              // 'weak' property
7077 /// kPropertyStrong = 'P'            // property GC'able
7078 /// kPropertyNonAtomic = 'N'         // property non-atomic
7079 /// };
7080 /// @endcode
7081 std::string
7082 ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
7083                                            const Decl *Container) const {
7084   // Collect information from the property implementation decl(s).
7085   bool Dynamic = false;
7086   ObjCPropertyImplDecl *SynthesizePID = nullptr;
7087 
7088   if (ObjCPropertyImplDecl *PropertyImpDecl =
7089       getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
7090     if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
7091       Dynamic = true;
7092     else
7093       SynthesizePID = PropertyImpDecl;
7094   }
7095 
7096   // FIXME: This is not very efficient.
7097   std::string S = "T";
7098 
7099   // Encode result type.
7100   // GCC has some special rules regarding encoding of properties which
7101   // closely resembles encoding of ivars.
7102   getObjCEncodingForPropertyType(PD->getType(), S);
7103 
7104   if (PD->isReadOnly()) {
7105     S += ",R";
7106     if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_copy)
7107       S += ",C";
7108     if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_retain)
7109       S += ",&";
7110     if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_weak)
7111       S += ",W";
7112   } else {
7113     switch (PD->getSetterKind()) {
7114     case ObjCPropertyDecl::Assign: break;
7115     case ObjCPropertyDecl::Copy:   S += ",C"; break;
7116     case ObjCPropertyDecl::Retain: S += ",&"; break;
7117     case ObjCPropertyDecl::Weak:   S += ",W"; break;
7118     }
7119   }
7120 
7121   // It really isn't clear at all what this means, since properties
7122   // are "dynamic by default".
7123   if (Dynamic)
7124     S += ",D";
7125 
7126   if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_nonatomic)
7127     S += ",N";
7128 
7129   if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_getter) {
7130     S += ",G";
7131     S += PD->getGetterName().getAsString();
7132   }
7133 
7134   if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_setter) {
7135     S += ",S";
7136     S += PD->getSetterName().getAsString();
7137   }
7138 
7139   if (SynthesizePID) {
7140     const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
7141     S += ",V";
7142     S += OID->getNameAsString();
7143   }
7144 
7145   // FIXME: OBJCGC: weak & strong
7146   return S;
7147 }
7148 
7149 /// getLegacyIntegralTypeEncoding -
7150 /// Another legacy compatibility encoding: 32-bit longs are encoded as
7151 /// 'l' or 'L' , but not always.  For typedefs, we need to use
7152 /// 'i' or 'I' instead if encoding a struct field, or a pointer!
7153 void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
7154   if (isa<TypedefType>(PointeeTy.getTypePtr())) {
7155     if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
7156       if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
7157         PointeeTy = UnsignedIntTy;
7158       else
7159         if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
7160           PointeeTy = IntTy;
7161     }
7162   }
7163 }
7164 
7165 void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
7166                                         const FieldDecl *Field,
7167                                         QualType *NotEncodedT) const {
7168   // We follow the behavior of gcc, expanding structures which are
7169   // directly pointed to, and expanding embedded structures. Note that
7170   // these rules are sufficient to prevent recursive encoding of the
7171   // same type.
7172   getObjCEncodingForTypeImpl(T, S,
7173                              ObjCEncOptions()
7174                                  .setExpandPointedToStructures()
7175                                  .setExpandStructures()
7176                                  .setIsOutermostType(),
7177                              Field, NotEncodedT);
7178 }
7179 
7180 void ASTContext::getObjCEncodingForPropertyType(QualType T,
7181                                                 std::string& S) const {
7182   // Encode result type.
7183   // GCC has some special rules regarding encoding of properties which
7184   // closely resembles encoding of ivars.
7185   getObjCEncodingForTypeImpl(T, S,
7186                              ObjCEncOptions()
7187                                  .setExpandPointedToStructures()
7188                                  .setExpandStructures()
7189                                  .setIsOutermostType()
7190                                  .setEncodingProperty(),
7191                              /*Field=*/nullptr);
7192 }
7193 
7194 static char getObjCEncodingForPrimitiveType(const ASTContext *C,
7195                                             const BuiltinType *BT) {
7196     BuiltinType::Kind kind = BT->getKind();
7197     switch (kind) {
7198     case BuiltinType::Void:       return 'v';
7199     case BuiltinType::Bool:       return 'B';
7200     case BuiltinType::Char8:
7201     case BuiltinType::Char_U:
7202     case BuiltinType::UChar:      return 'C';
7203     case BuiltinType::Char16:
7204     case BuiltinType::UShort:     return 'S';
7205     case BuiltinType::Char32:
7206     case BuiltinType::UInt:       return 'I';
7207     case BuiltinType::ULong:
7208         return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
7209     case BuiltinType::UInt128:    return 'T';
7210     case BuiltinType::ULongLong:  return 'Q';
7211     case BuiltinType::Char_S:
7212     case BuiltinType::SChar:      return 'c';
7213     case BuiltinType::Short:      return 's';
7214     case BuiltinType::WChar_S:
7215     case BuiltinType::WChar_U:
7216     case BuiltinType::Int:        return 'i';
7217     case BuiltinType::Long:
7218       return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
7219     case BuiltinType::LongLong:   return 'q';
7220     case BuiltinType::Int128:     return 't';
7221     case BuiltinType::Float:      return 'f';
7222     case BuiltinType::Double:     return 'd';
7223     case BuiltinType::LongDouble: return 'D';
7224     case BuiltinType::NullPtr:    return '*'; // like char*
7225 
7226     case BuiltinType::BFloat16:
7227     case BuiltinType::Float16:
7228     case BuiltinType::Float128:
7229     case BuiltinType::Half:
7230     case BuiltinType::ShortAccum:
7231     case BuiltinType::Accum:
7232     case BuiltinType::LongAccum:
7233     case BuiltinType::UShortAccum:
7234     case BuiltinType::UAccum:
7235     case BuiltinType::ULongAccum:
7236     case BuiltinType::ShortFract:
7237     case BuiltinType::Fract:
7238     case BuiltinType::LongFract:
7239     case BuiltinType::UShortFract:
7240     case BuiltinType::UFract:
7241     case BuiltinType::ULongFract:
7242     case BuiltinType::SatShortAccum:
7243     case BuiltinType::SatAccum:
7244     case BuiltinType::SatLongAccum:
7245     case BuiltinType::SatUShortAccum:
7246     case BuiltinType::SatUAccum:
7247     case BuiltinType::SatULongAccum:
7248     case BuiltinType::SatShortFract:
7249     case BuiltinType::SatFract:
7250     case BuiltinType::SatLongFract:
7251     case BuiltinType::SatUShortFract:
7252     case BuiltinType::SatUFract:
7253     case BuiltinType::SatULongFract:
7254       // FIXME: potentially need @encodes for these!
7255       return ' ';
7256 
7257 #define SVE_TYPE(Name, Id, SingletonId) \
7258     case BuiltinType::Id:
7259 #include "clang/Basic/AArch64SVEACLETypes.def"
7260 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
7261 #include "clang/Basic/RISCVVTypes.def"
7262       {
7263         DiagnosticsEngine &Diags = C->getDiagnostics();
7264         unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
7265                                                 "cannot yet @encode type %0");
7266         Diags.Report(DiagID) << BT->getName(C->getPrintingPolicy());
7267         return ' ';
7268       }
7269 
7270     case BuiltinType::ObjCId:
7271     case BuiltinType::ObjCClass:
7272     case BuiltinType::ObjCSel:
7273       llvm_unreachable("@encoding ObjC primitive type");
7274 
7275     // OpenCL and placeholder types don't need @encodings.
7276 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7277     case BuiltinType::Id:
7278 #include "clang/Basic/OpenCLImageTypes.def"
7279 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
7280     case BuiltinType::Id:
7281 #include "clang/Basic/OpenCLExtensionTypes.def"
7282     case BuiltinType::OCLEvent:
7283     case BuiltinType::OCLClkEvent:
7284     case BuiltinType::OCLQueue:
7285     case BuiltinType::OCLReserveID:
7286     case BuiltinType::OCLSampler:
7287     case BuiltinType::Dependent:
7288 #define PPC_VECTOR_TYPE(Name, Id, Size) \
7289     case BuiltinType::Id:
7290 #include "clang/Basic/PPCTypes.def"
7291 #define BUILTIN_TYPE(KIND, ID)
7292 #define PLACEHOLDER_TYPE(KIND, ID) \
7293     case BuiltinType::KIND:
7294 #include "clang/AST/BuiltinTypes.def"
7295       llvm_unreachable("invalid builtin type for @encode");
7296     }
7297     llvm_unreachable("invalid BuiltinType::Kind value");
7298 }
7299 
7300 static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
7301   EnumDecl *Enum = ET->getDecl();
7302 
7303   // The encoding of an non-fixed enum type is always 'i', regardless of size.
7304   if (!Enum->isFixed())
7305     return 'i';
7306 
7307   // The encoding of a fixed enum type matches its fixed underlying type.
7308   const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
7309   return getObjCEncodingForPrimitiveType(C, BT);
7310 }
7311 
7312 static void EncodeBitField(const ASTContext *Ctx, std::string& S,
7313                            QualType T, const FieldDecl *FD) {
7314   assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
7315   S += 'b';
7316   // The NeXT runtime encodes bit fields as b followed by the number of bits.
7317   // The GNU runtime requires more information; bitfields are encoded as b,
7318   // then the offset (in bits) of the first element, then the type of the
7319   // bitfield, then the size in bits.  For example, in this structure:
7320   //
7321   // struct
7322   // {
7323   //    int integer;
7324   //    int flags:2;
7325   // };
7326   // On a 32-bit system, the encoding for flags would be b2 for the NeXT
7327   // runtime, but b32i2 for the GNU runtime.  The reason for this extra
7328   // information is not especially sensible, but we're stuck with it for
7329   // compatibility with GCC, although providing it breaks anything that
7330   // actually uses runtime introspection and wants to work on both runtimes...
7331   if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
7332     uint64_t Offset;
7333 
7334     if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
7335       Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), nullptr,
7336                                          IVD);
7337     } else {
7338       const RecordDecl *RD = FD->getParent();
7339       const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
7340       Offset = RL.getFieldOffset(FD->getFieldIndex());
7341     }
7342 
7343     S += llvm::utostr(Offset);
7344 
7345     if (const auto *ET = T->getAs<EnumType>())
7346       S += ObjCEncodingForEnumType(Ctx, ET);
7347     else {
7348       const auto *BT = T->castAs<BuiltinType>();
7349       S += getObjCEncodingForPrimitiveType(Ctx, BT);
7350     }
7351   }
7352   S += llvm::utostr(FD->getBitWidthValue(*Ctx));
7353 }
7354 
7355 // FIXME: Use SmallString for accumulating string.
7356 void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
7357                                             const ObjCEncOptions Options,
7358                                             const FieldDecl *FD,
7359                                             QualType *NotEncodedT) const {
7360   CanQualType CT = getCanonicalType(T);
7361   switch (CT->getTypeClass()) {
7362   case Type::Builtin:
7363   case Type::Enum:
7364     if (FD && FD->isBitField())
7365       return EncodeBitField(this, S, T, FD);
7366     if (const auto *BT = dyn_cast<BuiltinType>(CT))
7367       S += getObjCEncodingForPrimitiveType(this, BT);
7368     else
7369       S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
7370     return;
7371 
7372   case Type::Complex:
7373     S += 'j';
7374     getObjCEncodingForTypeImpl(T->castAs<ComplexType>()->getElementType(), S,
7375                                ObjCEncOptions(),
7376                                /*Field=*/nullptr);
7377     return;
7378 
7379   case Type::Atomic:
7380     S += 'A';
7381     getObjCEncodingForTypeImpl(T->castAs<AtomicType>()->getValueType(), S,
7382                                ObjCEncOptions(),
7383                                /*Field=*/nullptr);
7384     return;
7385 
7386   // encoding for pointer or reference types.
7387   case Type::Pointer:
7388   case Type::LValueReference:
7389   case Type::RValueReference: {
7390     QualType PointeeTy;
7391     if (isa<PointerType>(CT)) {
7392       const auto *PT = T->castAs<PointerType>();
7393       if (PT->isObjCSelType()) {
7394         S += ':';
7395         return;
7396       }
7397       PointeeTy = PT->getPointeeType();
7398     } else {
7399       PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
7400     }
7401 
7402     bool isReadOnly = false;
7403     // For historical/compatibility reasons, the read-only qualifier of the
7404     // pointee gets emitted _before_ the '^'.  The read-only qualifier of
7405     // the pointer itself gets ignored, _unless_ we are looking at a typedef!
7406     // Also, do not emit the 'r' for anything but the outermost type!
7407     if (isa<TypedefType>(T.getTypePtr())) {
7408       if (Options.IsOutermostType() && T.isConstQualified()) {
7409         isReadOnly = true;
7410         S += 'r';
7411       }
7412     } else if (Options.IsOutermostType()) {
7413       QualType P = PointeeTy;
7414       while (auto PT = P->getAs<PointerType>())
7415         P = PT->getPointeeType();
7416       if (P.isConstQualified()) {
7417         isReadOnly = true;
7418         S += 'r';
7419       }
7420     }
7421     if (isReadOnly) {
7422       // Another legacy compatibility encoding. Some ObjC qualifier and type
7423       // combinations need to be rearranged.
7424       // Rewrite "in const" from "nr" to "rn"
7425       if (StringRef(S).endswith("nr"))
7426         S.replace(S.end()-2, S.end(), "rn");
7427     }
7428 
7429     if (PointeeTy->isCharType()) {
7430       // char pointer types should be encoded as '*' unless it is a
7431       // type that has been typedef'd to 'BOOL'.
7432       if (!isTypeTypedefedAsBOOL(PointeeTy)) {
7433         S += '*';
7434         return;
7435       }
7436     } else if (const auto *RTy = PointeeTy->getAs<RecordType>()) {
7437       // GCC binary compat: Need to convert "struct objc_class *" to "#".
7438       if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
7439         S += '#';
7440         return;
7441       }
7442       // GCC binary compat: Need to convert "struct objc_object *" to "@".
7443       if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
7444         S += '@';
7445         return;
7446       }
7447       // fall through...
7448     }
7449     S += '^';
7450     getLegacyIntegralTypeEncoding(PointeeTy);
7451 
7452     ObjCEncOptions NewOptions;
7453     if (Options.ExpandPointedToStructures())
7454       NewOptions.setExpandStructures();
7455     getObjCEncodingForTypeImpl(PointeeTy, S, NewOptions,
7456                                /*Field=*/nullptr, NotEncodedT);
7457     return;
7458   }
7459 
7460   case Type::ConstantArray:
7461   case Type::IncompleteArray:
7462   case Type::VariableArray: {
7463     const auto *AT = cast<ArrayType>(CT);
7464 
7465     if (isa<IncompleteArrayType>(AT) && !Options.IsStructField()) {
7466       // Incomplete arrays are encoded as a pointer to the array element.
7467       S += '^';
7468 
7469       getObjCEncodingForTypeImpl(
7470           AT->getElementType(), S,
7471           Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD);
7472     } else {
7473       S += '[';
7474 
7475       if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
7476         S += llvm::utostr(CAT->getSize().getZExtValue());
7477       else {
7478         //Variable length arrays are encoded as a regular array with 0 elements.
7479         assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
7480                "Unknown array type!");
7481         S += '0';
7482       }
7483 
7484       getObjCEncodingForTypeImpl(
7485           AT->getElementType(), S,
7486           Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD,
7487           NotEncodedT);
7488       S += ']';
7489     }
7490     return;
7491   }
7492 
7493   case Type::FunctionNoProto:
7494   case Type::FunctionProto:
7495     S += '?';
7496     return;
7497 
7498   case Type::Record: {
7499     RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
7500     S += RDecl->isUnion() ? '(' : '{';
7501     // Anonymous structures print as '?'
7502     if (const IdentifierInfo *II = RDecl->getIdentifier()) {
7503       S += II->getName();
7504       if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
7505         const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
7506         llvm::raw_string_ostream OS(S);
7507         printTemplateArgumentList(OS, TemplateArgs.asArray(),
7508                                   getPrintingPolicy());
7509       }
7510     } else {
7511       S += '?';
7512     }
7513     if (Options.ExpandStructures()) {
7514       S += '=';
7515       if (!RDecl->isUnion()) {
7516         getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
7517       } else {
7518         for (const auto *Field : RDecl->fields()) {
7519           if (FD) {
7520             S += '"';
7521             S += Field->getNameAsString();
7522             S += '"';
7523           }
7524 
7525           // Special case bit-fields.
7526           if (Field->isBitField()) {
7527             getObjCEncodingForTypeImpl(Field->getType(), S,
7528                                        ObjCEncOptions().setExpandStructures(),
7529                                        Field);
7530           } else {
7531             QualType qt = Field->getType();
7532             getLegacyIntegralTypeEncoding(qt);
7533             getObjCEncodingForTypeImpl(
7534                 qt, S,
7535                 ObjCEncOptions().setExpandStructures().setIsStructField(), FD,
7536                 NotEncodedT);
7537           }
7538         }
7539       }
7540     }
7541     S += RDecl->isUnion() ? ')' : '}';
7542     return;
7543   }
7544 
7545   case Type::BlockPointer: {
7546     const auto *BT = T->castAs<BlockPointerType>();
7547     S += "@?"; // Unlike a pointer-to-function, which is "^?".
7548     if (Options.EncodeBlockParameters()) {
7549       const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
7550 
7551       S += '<';
7552       // Block return type
7553       getObjCEncodingForTypeImpl(FT->getReturnType(), S,
7554                                  Options.forComponentType(), FD, NotEncodedT);
7555       // Block self
7556       S += "@?";
7557       // Block parameters
7558       if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) {
7559         for (const auto &I : FPT->param_types())
7560           getObjCEncodingForTypeImpl(I, S, Options.forComponentType(), FD,
7561                                      NotEncodedT);
7562       }
7563       S += '>';
7564     }
7565     return;
7566   }
7567 
7568   case Type::ObjCObject: {
7569     // hack to match legacy encoding of *id and *Class
7570     QualType Ty = getObjCObjectPointerType(CT);
7571     if (Ty->isObjCIdType()) {
7572       S += "{objc_object=}";
7573       return;
7574     }
7575     else if (Ty->isObjCClassType()) {
7576       S += "{objc_class=}";
7577       return;
7578     }
7579     // TODO: Double check to make sure this intentionally falls through.
7580     LLVM_FALLTHROUGH;
7581   }
7582 
7583   case Type::ObjCInterface: {
7584     // Ignore protocol qualifiers when mangling at this level.
7585     // @encode(class_name)
7586     ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
7587     S += '{';
7588     S += OI->getObjCRuntimeNameAsString();
7589     if (Options.ExpandStructures()) {
7590       S += '=';
7591       SmallVector<const ObjCIvarDecl*, 32> Ivars;
7592       DeepCollectObjCIvars(OI, true, Ivars);
7593       for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
7594         const FieldDecl *Field = Ivars[i];
7595         if (Field->isBitField())
7596           getObjCEncodingForTypeImpl(Field->getType(), S,
7597                                      ObjCEncOptions().setExpandStructures(),
7598                                      Field);
7599         else
7600           getObjCEncodingForTypeImpl(Field->getType(), S,
7601                                      ObjCEncOptions().setExpandStructures(), FD,
7602                                      NotEncodedT);
7603       }
7604     }
7605     S += '}';
7606     return;
7607   }
7608 
7609   case Type::ObjCObjectPointer: {
7610     const auto *OPT = T->castAs<ObjCObjectPointerType>();
7611     if (OPT->isObjCIdType()) {
7612       S += '@';
7613       return;
7614     }
7615 
7616     if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
7617       // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
7618       // Since this is a binary compatibility issue, need to consult with
7619       // runtime folks. Fortunately, this is a *very* obscure construct.
7620       S += '#';
7621       return;
7622     }
7623 
7624     if (OPT->isObjCQualifiedIdType()) {
7625       getObjCEncodingForTypeImpl(
7626           getObjCIdType(), S,
7627           Options.keepingOnly(ObjCEncOptions()
7628                                   .setExpandPointedToStructures()
7629                                   .setExpandStructures()),
7630           FD);
7631       if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) {
7632         // Note that we do extended encoding of protocol qualifer list
7633         // Only when doing ivar or property encoding.
7634         S += '"';
7635         for (const auto *I : OPT->quals()) {
7636           S += '<';
7637           S += I->getObjCRuntimeNameAsString();
7638           S += '>';
7639         }
7640         S += '"';
7641       }
7642       return;
7643     }
7644 
7645     S += '@';
7646     if (OPT->getInterfaceDecl() &&
7647         (FD || Options.EncodingProperty() || Options.EncodeClassNames())) {
7648       S += '"';
7649       S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
7650       for (const auto *I : OPT->quals()) {
7651         S += '<';
7652         S += I->getObjCRuntimeNameAsString();
7653         S += '>';
7654       }
7655       S += '"';
7656     }
7657     return;
7658   }
7659 
7660   // gcc just blithely ignores member pointers.
7661   // FIXME: we should do better than that.  'M' is available.
7662   case Type::MemberPointer:
7663   // This matches gcc's encoding, even though technically it is insufficient.
7664   //FIXME. We should do a better job than gcc.
7665   case Type::Vector:
7666   case Type::ExtVector:
7667   // Until we have a coherent encoding of these three types, issue warning.
7668     if (NotEncodedT)
7669       *NotEncodedT = T;
7670     return;
7671 
7672   case Type::ConstantMatrix:
7673     if (NotEncodedT)
7674       *NotEncodedT = T;
7675     return;
7676 
7677   // We could see an undeduced auto type here during error recovery.
7678   // Just ignore it.
7679   case Type::Auto:
7680   case Type::DeducedTemplateSpecialization:
7681     return;
7682 
7683   case Type::Pipe:
7684   case Type::ExtInt:
7685 #define ABSTRACT_TYPE(KIND, BASE)
7686 #define TYPE(KIND, BASE)
7687 #define DEPENDENT_TYPE(KIND, BASE) \
7688   case Type::KIND:
7689 #define NON_CANONICAL_TYPE(KIND, BASE) \
7690   case Type::KIND:
7691 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
7692   case Type::KIND:
7693 #include "clang/AST/TypeNodes.inc"
7694     llvm_unreachable("@encode for dependent type!");
7695   }
7696   llvm_unreachable("bad type kind!");
7697 }
7698 
7699 void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
7700                                                  std::string &S,
7701                                                  const FieldDecl *FD,
7702                                                  bool includeVBases,
7703                                                  QualType *NotEncodedT) const {
7704   assert(RDecl && "Expected non-null RecordDecl");
7705   assert(!RDecl->isUnion() && "Should not be called for unions");
7706   if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
7707     return;
7708 
7709   const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
7710   std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
7711   const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
7712 
7713   if (CXXRec) {
7714     for (const auto &BI : CXXRec->bases()) {
7715       if (!BI.isVirtual()) {
7716         CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
7717         if (base->isEmpty())
7718           continue;
7719         uint64_t offs = toBits(layout.getBaseClassOffset(base));
7720         FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
7721                                   std::make_pair(offs, base));
7722       }
7723     }
7724   }
7725 
7726   unsigned i = 0;
7727   for (FieldDecl *Field : RDecl->fields()) {
7728     if (!Field->isZeroLengthBitField(*this) && Field->isZeroSize(*this))
7729       continue;
7730     uint64_t offs = layout.getFieldOffset(i);
7731     FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
7732                               std::make_pair(offs, Field));
7733     ++i;
7734   }
7735 
7736   if (CXXRec && includeVBases) {
7737     for (const auto &BI : CXXRec->vbases()) {
7738       CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
7739       if (base->isEmpty())
7740         continue;
7741       uint64_t offs = toBits(layout.getVBaseClassOffset(base));
7742       if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
7743           FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
7744         FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
7745                                   std::make_pair(offs, base));
7746     }
7747   }
7748 
7749   CharUnits size;
7750   if (CXXRec) {
7751     size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
7752   } else {
7753     size = layout.getSize();
7754   }
7755 
7756 #ifndef NDEBUG
7757   uint64_t CurOffs = 0;
7758 #endif
7759   std::multimap<uint64_t, NamedDecl *>::iterator
7760     CurLayObj = FieldOrBaseOffsets.begin();
7761 
7762   if (CXXRec && CXXRec->isDynamicClass() &&
7763       (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
7764     if (FD) {
7765       S += "\"_vptr$";
7766       std::string recname = CXXRec->getNameAsString();
7767       if (recname.empty()) recname = "?";
7768       S += recname;
7769       S += '"';
7770     }
7771     S += "^^?";
7772 #ifndef NDEBUG
7773     CurOffs += getTypeSize(VoidPtrTy);
7774 #endif
7775   }
7776 
7777   if (!RDecl->hasFlexibleArrayMember()) {
7778     // Mark the end of the structure.
7779     uint64_t offs = toBits(size);
7780     FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
7781                               std::make_pair(offs, nullptr));
7782   }
7783 
7784   for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
7785 #ifndef NDEBUG
7786     assert(CurOffs <= CurLayObj->first);
7787     if (CurOffs < CurLayObj->first) {
7788       uint64_t padding = CurLayObj->first - CurOffs;
7789       // FIXME: There doesn't seem to be a way to indicate in the encoding that
7790       // packing/alignment of members is different that normal, in which case
7791       // the encoding will be out-of-sync with the real layout.
7792       // If the runtime switches to just consider the size of types without
7793       // taking into account alignment, we could make padding explicit in the
7794       // encoding (e.g. using arrays of chars). The encoding strings would be
7795       // longer then though.
7796       CurOffs += padding;
7797     }
7798 #endif
7799 
7800     NamedDecl *dcl = CurLayObj->second;
7801     if (!dcl)
7802       break; // reached end of structure.
7803 
7804     if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) {
7805       // We expand the bases without their virtual bases since those are going
7806       // in the initial structure. Note that this differs from gcc which
7807       // expands virtual bases each time one is encountered in the hierarchy,
7808       // making the encoding type bigger than it really is.
7809       getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
7810                                       NotEncodedT);
7811       assert(!base->isEmpty());
7812 #ifndef NDEBUG
7813       CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
7814 #endif
7815     } else {
7816       const auto *field = cast<FieldDecl>(dcl);
7817       if (FD) {
7818         S += '"';
7819         S += field->getNameAsString();
7820         S += '"';
7821       }
7822 
7823       if (field->isBitField()) {
7824         EncodeBitField(this, S, field->getType(), field);
7825 #ifndef NDEBUG
7826         CurOffs += field->getBitWidthValue(*this);
7827 #endif
7828       } else {
7829         QualType qt = field->getType();
7830         getLegacyIntegralTypeEncoding(qt);
7831         getObjCEncodingForTypeImpl(
7832             qt, S, ObjCEncOptions().setExpandStructures().setIsStructField(),
7833             FD, NotEncodedT);
7834 #ifndef NDEBUG
7835         CurOffs += getTypeSize(field->getType());
7836 #endif
7837       }
7838     }
7839   }
7840 }
7841 
7842 void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
7843                                                  std::string& S) const {
7844   if (QT & Decl::OBJC_TQ_In)
7845     S += 'n';
7846   if (QT & Decl::OBJC_TQ_Inout)
7847     S += 'N';
7848   if (QT & Decl::OBJC_TQ_Out)
7849     S += 'o';
7850   if (QT & Decl::OBJC_TQ_Bycopy)
7851     S += 'O';
7852   if (QT & Decl::OBJC_TQ_Byref)
7853     S += 'R';
7854   if (QT & Decl::OBJC_TQ_Oneway)
7855     S += 'V';
7856 }
7857 
7858 TypedefDecl *ASTContext::getObjCIdDecl() const {
7859   if (!ObjCIdDecl) {
7860     QualType T = getObjCObjectType(ObjCBuiltinIdTy, {}, {});
7861     T = getObjCObjectPointerType(T);
7862     ObjCIdDecl = buildImplicitTypedef(T, "id");
7863   }
7864   return ObjCIdDecl;
7865 }
7866 
7867 TypedefDecl *ASTContext::getObjCSelDecl() const {
7868   if (!ObjCSelDecl) {
7869     QualType T = getPointerType(ObjCBuiltinSelTy);
7870     ObjCSelDecl = buildImplicitTypedef(T, "SEL");
7871   }
7872   return ObjCSelDecl;
7873 }
7874 
7875 TypedefDecl *ASTContext::getObjCClassDecl() const {
7876   if (!ObjCClassDecl) {
7877     QualType T = getObjCObjectType(ObjCBuiltinClassTy, {}, {});
7878     T = getObjCObjectPointerType(T);
7879     ObjCClassDecl = buildImplicitTypedef(T, "Class");
7880   }
7881   return ObjCClassDecl;
7882 }
7883 
7884 ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
7885   if (!ObjCProtocolClassDecl) {
7886     ObjCProtocolClassDecl
7887       = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
7888                                   SourceLocation(),
7889                                   &Idents.get("Protocol"),
7890                                   /*typeParamList=*/nullptr,
7891                                   /*PrevDecl=*/nullptr,
7892                                   SourceLocation(), true);
7893   }
7894 
7895   return ObjCProtocolClassDecl;
7896 }
7897 
7898 //===----------------------------------------------------------------------===//
7899 // __builtin_va_list Construction Functions
7900 //===----------------------------------------------------------------------===//
7901 
7902 static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
7903                                                  StringRef Name) {
7904   // typedef char* __builtin[_ms]_va_list;
7905   QualType T = Context->getPointerType(Context->CharTy);
7906   return Context->buildImplicitTypedef(T, Name);
7907 }
7908 
7909 static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
7910   return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
7911 }
7912 
7913 static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
7914   return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
7915 }
7916 
7917 static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
7918   // typedef void* __builtin_va_list;
7919   QualType T = Context->getPointerType(Context->VoidTy);
7920   return Context->buildImplicitTypedef(T, "__builtin_va_list");
7921 }
7922 
7923 static TypedefDecl *
7924 CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
7925   // struct __va_list
7926   RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
7927   if (Context->getLangOpts().CPlusPlus) {
7928     // namespace std { struct __va_list {
7929     NamespaceDecl *NS;
7930     NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
7931                                Context->getTranslationUnitDecl(),
7932                                /*Inline*/ false, SourceLocation(),
7933                                SourceLocation(), &Context->Idents.get("std"),
7934                                /*PrevDecl*/ nullptr);
7935     NS->setImplicit();
7936     VaListTagDecl->setDeclContext(NS);
7937   }
7938 
7939   VaListTagDecl->startDefinition();
7940 
7941   const size_t NumFields = 5;
7942   QualType FieldTypes[NumFields];
7943   const char *FieldNames[NumFields];
7944 
7945   // void *__stack;
7946   FieldTypes[0] = Context->getPointerType(Context->VoidTy);
7947   FieldNames[0] = "__stack";
7948 
7949   // void *__gr_top;
7950   FieldTypes[1] = Context->getPointerType(Context->VoidTy);
7951   FieldNames[1] = "__gr_top";
7952 
7953   // void *__vr_top;
7954   FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7955   FieldNames[2] = "__vr_top";
7956 
7957   // int __gr_offs;
7958   FieldTypes[3] = Context->IntTy;
7959   FieldNames[3] = "__gr_offs";
7960 
7961   // int __vr_offs;
7962   FieldTypes[4] = Context->IntTy;
7963   FieldNames[4] = "__vr_offs";
7964 
7965   // Create fields
7966   for (unsigned i = 0; i < NumFields; ++i) {
7967     FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7968                                          VaListTagDecl,
7969                                          SourceLocation(),
7970                                          SourceLocation(),
7971                                          &Context->Idents.get(FieldNames[i]),
7972                                          FieldTypes[i], /*TInfo=*/nullptr,
7973                                          /*BitWidth=*/nullptr,
7974                                          /*Mutable=*/false,
7975                                          ICIS_NoInit);
7976     Field->setAccess(AS_public);
7977     VaListTagDecl->addDecl(Field);
7978   }
7979   VaListTagDecl->completeDefinition();
7980   Context->VaListTagDecl = VaListTagDecl;
7981   QualType VaListTagType = Context->getRecordType(VaListTagDecl);
7982 
7983   // } __builtin_va_list;
7984   return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
7985 }
7986 
7987 static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
7988   // typedef struct __va_list_tag {
7989   RecordDecl *VaListTagDecl;
7990 
7991   VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
7992   VaListTagDecl->startDefinition();
7993 
7994   const size_t NumFields = 5;
7995   QualType FieldTypes[NumFields];
7996   const char *FieldNames[NumFields];
7997 
7998   //   unsigned char gpr;
7999   FieldTypes[0] = Context->UnsignedCharTy;
8000   FieldNames[0] = "gpr";
8001 
8002   //   unsigned char fpr;
8003   FieldTypes[1] = Context->UnsignedCharTy;
8004   FieldNames[1] = "fpr";
8005 
8006   //   unsigned short reserved;
8007   FieldTypes[2] = Context->UnsignedShortTy;
8008   FieldNames[2] = "reserved";
8009 
8010   //   void* overflow_arg_area;
8011   FieldTypes[3] = Context->getPointerType(Context->VoidTy);
8012   FieldNames[3] = "overflow_arg_area";
8013 
8014   //   void* reg_save_area;
8015   FieldTypes[4] = Context->getPointerType(Context->VoidTy);
8016   FieldNames[4] = "reg_save_area";
8017 
8018   // Create fields
8019   for (unsigned i = 0; i < NumFields; ++i) {
8020     FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
8021                                          SourceLocation(),
8022                                          SourceLocation(),
8023                                          &Context->Idents.get(FieldNames[i]),
8024                                          FieldTypes[i], /*TInfo=*/nullptr,
8025                                          /*BitWidth=*/nullptr,
8026                                          /*Mutable=*/false,
8027                                          ICIS_NoInit);
8028     Field->setAccess(AS_public);
8029     VaListTagDecl->addDecl(Field);
8030   }
8031   VaListTagDecl->completeDefinition();
8032   Context->VaListTagDecl = VaListTagDecl;
8033   QualType VaListTagType = Context->getRecordType(VaListTagDecl);
8034 
8035   // } __va_list_tag;
8036   TypedefDecl *VaListTagTypedefDecl =
8037       Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
8038 
8039   QualType VaListTagTypedefType =
8040     Context->getTypedefType(VaListTagTypedefDecl);
8041 
8042   // typedef __va_list_tag __builtin_va_list[1];
8043   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
8044   QualType VaListTagArrayType
8045     = Context->getConstantArrayType(VaListTagTypedefType,
8046                                     Size, nullptr, ArrayType::Normal, 0);
8047   return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
8048 }
8049 
8050 static TypedefDecl *
8051 CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
8052   // struct __va_list_tag {
8053   RecordDecl *VaListTagDecl;
8054   VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
8055   VaListTagDecl->startDefinition();
8056 
8057   const size_t NumFields = 4;
8058   QualType FieldTypes[NumFields];
8059   const char *FieldNames[NumFields];
8060 
8061   //   unsigned gp_offset;
8062   FieldTypes[0] = Context->UnsignedIntTy;
8063   FieldNames[0] = "gp_offset";
8064 
8065   //   unsigned fp_offset;
8066   FieldTypes[1] = Context->UnsignedIntTy;
8067   FieldNames[1] = "fp_offset";
8068 
8069   //   void* overflow_arg_area;
8070   FieldTypes[2] = Context->getPointerType(Context->VoidTy);
8071   FieldNames[2] = "overflow_arg_area";
8072 
8073   //   void* reg_save_area;
8074   FieldTypes[3] = Context->getPointerType(Context->VoidTy);
8075   FieldNames[3] = "reg_save_area";
8076 
8077   // Create fields
8078   for (unsigned i = 0; i < NumFields; ++i) {
8079     FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
8080                                          VaListTagDecl,
8081                                          SourceLocation(),
8082                                          SourceLocation(),
8083                                          &Context->Idents.get(FieldNames[i]),
8084                                          FieldTypes[i], /*TInfo=*/nullptr,
8085                                          /*BitWidth=*/nullptr,
8086                                          /*Mutable=*/false,
8087                                          ICIS_NoInit);
8088     Field->setAccess(AS_public);
8089     VaListTagDecl->addDecl(Field);
8090   }
8091   VaListTagDecl->completeDefinition();
8092   Context->VaListTagDecl = VaListTagDecl;
8093   QualType VaListTagType = Context->getRecordType(VaListTagDecl);
8094 
8095   // };
8096 
8097   // typedef struct __va_list_tag __builtin_va_list[1];
8098   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
8099   QualType VaListTagArrayType = Context->getConstantArrayType(
8100       VaListTagType, Size, nullptr, ArrayType::Normal, 0);
8101   return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
8102 }
8103 
8104 static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
8105   // typedef int __builtin_va_list[4];
8106   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
8107   QualType IntArrayType = Context->getConstantArrayType(
8108       Context->IntTy, Size, nullptr, ArrayType::Normal, 0);
8109   return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
8110 }
8111 
8112 static TypedefDecl *
8113 CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
8114   // struct __va_list
8115   RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
8116   if (Context->getLangOpts().CPlusPlus) {
8117     // namespace std { struct __va_list {
8118     NamespaceDecl *NS;
8119     NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
8120                                Context->getTranslationUnitDecl(),
8121                                /*Inline*/false, SourceLocation(),
8122                                SourceLocation(), &Context->Idents.get("std"),
8123                                /*PrevDecl*/ nullptr);
8124     NS->setImplicit();
8125     VaListDecl->setDeclContext(NS);
8126   }
8127 
8128   VaListDecl->startDefinition();
8129 
8130   // void * __ap;
8131   FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
8132                                        VaListDecl,
8133                                        SourceLocation(),
8134                                        SourceLocation(),
8135                                        &Context->Idents.get("__ap"),
8136                                        Context->getPointerType(Context->VoidTy),
8137                                        /*TInfo=*/nullptr,
8138                                        /*BitWidth=*/nullptr,
8139                                        /*Mutable=*/false,
8140                                        ICIS_NoInit);
8141   Field->setAccess(AS_public);
8142   VaListDecl->addDecl(Field);
8143 
8144   // };
8145   VaListDecl->completeDefinition();
8146   Context->VaListTagDecl = VaListDecl;
8147 
8148   // typedef struct __va_list __builtin_va_list;
8149   QualType T = Context->getRecordType(VaListDecl);
8150   return Context->buildImplicitTypedef(T, "__builtin_va_list");
8151 }
8152 
8153 static TypedefDecl *
8154 CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
8155   // struct __va_list_tag {
8156   RecordDecl *VaListTagDecl;
8157   VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
8158   VaListTagDecl->startDefinition();
8159 
8160   const size_t NumFields = 4;
8161   QualType FieldTypes[NumFields];
8162   const char *FieldNames[NumFields];
8163 
8164   //   long __gpr;
8165   FieldTypes[0] = Context->LongTy;
8166   FieldNames[0] = "__gpr";
8167 
8168   //   long __fpr;
8169   FieldTypes[1] = Context->LongTy;
8170   FieldNames[1] = "__fpr";
8171 
8172   //   void *__overflow_arg_area;
8173   FieldTypes[2] = Context->getPointerType(Context->VoidTy);
8174   FieldNames[2] = "__overflow_arg_area";
8175 
8176   //   void *__reg_save_area;
8177   FieldTypes[3] = Context->getPointerType(Context->VoidTy);
8178   FieldNames[3] = "__reg_save_area";
8179 
8180   // Create fields
8181   for (unsigned i = 0; i < NumFields; ++i) {
8182     FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
8183                                          VaListTagDecl,
8184                                          SourceLocation(),
8185                                          SourceLocation(),
8186                                          &Context->Idents.get(FieldNames[i]),
8187                                          FieldTypes[i], /*TInfo=*/nullptr,
8188                                          /*BitWidth=*/nullptr,
8189                                          /*Mutable=*/false,
8190                                          ICIS_NoInit);
8191     Field->setAccess(AS_public);
8192     VaListTagDecl->addDecl(Field);
8193   }
8194   VaListTagDecl->completeDefinition();
8195   Context->VaListTagDecl = VaListTagDecl;
8196   QualType VaListTagType = Context->getRecordType(VaListTagDecl);
8197 
8198   // };
8199 
8200   // typedef __va_list_tag __builtin_va_list[1];
8201   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
8202   QualType VaListTagArrayType = Context->getConstantArrayType(
8203       VaListTagType, Size, nullptr, ArrayType::Normal, 0);
8204 
8205   return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
8206 }
8207 
8208 static TypedefDecl *CreateHexagonBuiltinVaListDecl(const ASTContext *Context) {
8209   // typedef struct __va_list_tag {
8210   RecordDecl *VaListTagDecl;
8211   VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
8212   VaListTagDecl->startDefinition();
8213 
8214   const size_t NumFields = 3;
8215   QualType FieldTypes[NumFields];
8216   const char *FieldNames[NumFields];
8217 
8218   //   void *CurrentSavedRegisterArea;
8219   FieldTypes[0] = Context->getPointerType(Context->VoidTy);
8220   FieldNames[0] = "__current_saved_reg_area_pointer";
8221 
8222   //   void *SavedRegAreaEnd;
8223   FieldTypes[1] = Context->getPointerType(Context->VoidTy);
8224   FieldNames[1] = "__saved_reg_area_end_pointer";
8225 
8226   //   void *OverflowArea;
8227   FieldTypes[2] = Context->getPointerType(Context->VoidTy);
8228   FieldNames[2] = "__overflow_area_pointer";
8229 
8230   // Create fields
8231   for (unsigned i = 0; i < NumFields; ++i) {
8232     FieldDecl *Field = FieldDecl::Create(
8233         const_cast<ASTContext &>(*Context), VaListTagDecl, SourceLocation(),
8234         SourceLocation(), &Context->Idents.get(FieldNames[i]), FieldTypes[i],
8235         /*TInfo=*/0,
8236         /*BitWidth=*/0,
8237         /*Mutable=*/false, ICIS_NoInit);
8238     Field->setAccess(AS_public);
8239     VaListTagDecl->addDecl(Field);
8240   }
8241   VaListTagDecl->completeDefinition();
8242   Context->VaListTagDecl = VaListTagDecl;
8243   QualType VaListTagType = Context->getRecordType(VaListTagDecl);
8244 
8245   // } __va_list_tag;
8246   TypedefDecl *VaListTagTypedefDecl =
8247       Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
8248 
8249   QualType VaListTagTypedefType = Context->getTypedefType(VaListTagTypedefDecl);
8250 
8251   // typedef __va_list_tag __builtin_va_list[1];
8252   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
8253   QualType VaListTagArrayType = Context->getConstantArrayType(
8254       VaListTagTypedefType, Size, nullptr, ArrayType::Normal, 0);
8255 
8256   return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
8257 }
8258 
8259 static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
8260                                      TargetInfo::BuiltinVaListKind Kind) {
8261   switch (Kind) {
8262   case TargetInfo::CharPtrBuiltinVaList:
8263     return CreateCharPtrBuiltinVaListDecl(Context);
8264   case TargetInfo::VoidPtrBuiltinVaList:
8265     return CreateVoidPtrBuiltinVaListDecl(Context);
8266   case TargetInfo::AArch64ABIBuiltinVaList:
8267     return CreateAArch64ABIBuiltinVaListDecl(Context);
8268   case TargetInfo::PowerABIBuiltinVaList:
8269     return CreatePowerABIBuiltinVaListDecl(Context);
8270   case TargetInfo::X86_64ABIBuiltinVaList:
8271     return CreateX86_64ABIBuiltinVaListDecl(Context);
8272   case TargetInfo::PNaClABIBuiltinVaList:
8273     return CreatePNaClABIBuiltinVaListDecl(Context);
8274   case TargetInfo::AAPCSABIBuiltinVaList:
8275     return CreateAAPCSABIBuiltinVaListDecl(Context);
8276   case TargetInfo::SystemZBuiltinVaList:
8277     return CreateSystemZBuiltinVaListDecl(Context);
8278   case TargetInfo::HexagonBuiltinVaList:
8279     return CreateHexagonBuiltinVaListDecl(Context);
8280   }
8281 
8282   llvm_unreachable("Unhandled __builtin_va_list type kind");
8283 }
8284 
8285 TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
8286   if (!BuiltinVaListDecl) {
8287     BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
8288     assert(BuiltinVaListDecl->isImplicit());
8289   }
8290 
8291   return BuiltinVaListDecl;
8292 }
8293 
8294 Decl *ASTContext::getVaListTagDecl() const {
8295   // Force the creation of VaListTagDecl by building the __builtin_va_list
8296   // declaration.
8297   if (!VaListTagDecl)
8298     (void)getBuiltinVaListDecl();
8299 
8300   return VaListTagDecl;
8301 }
8302 
8303 TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
8304   if (!BuiltinMSVaListDecl)
8305     BuiltinMSVaListDecl = CreateMSVaListDecl(this);
8306 
8307   return BuiltinMSVaListDecl;
8308 }
8309 
8310 bool ASTContext::canBuiltinBeRedeclared(const FunctionDecl *FD) const {
8311   return BuiltinInfo.canBeRedeclared(FD->getBuiltinID());
8312 }
8313 
8314 void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
8315   assert(ObjCConstantStringType.isNull() &&
8316          "'NSConstantString' type already set!");
8317 
8318   ObjCConstantStringType = getObjCInterfaceType(Decl);
8319 }
8320 
8321 /// Retrieve the template name that corresponds to a non-empty
8322 /// lookup.
8323 TemplateName
8324 ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
8325                                       UnresolvedSetIterator End) const {
8326   unsigned size = End - Begin;
8327   assert(size > 1 && "set is not overloaded!");
8328 
8329   void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
8330                           size * sizeof(FunctionTemplateDecl*));
8331   auto *OT = new (memory) OverloadedTemplateStorage(size);
8332 
8333   NamedDecl **Storage = OT->getStorage();
8334   for (UnresolvedSetIterator I = Begin; I != End; ++I) {
8335     NamedDecl *D = *I;
8336     assert(isa<FunctionTemplateDecl>(D) ||
8337            isa<UnresolvedUsingValueDecl>(D) ||
8338            (isa<UsingShadowDecl>(D) &&
8339             isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
8340     *Storage++ = D;
8341   }
8342 
8343   return TemplateName(OT);
8344 }
8345 
8346 /// Retrieve a template name representing an unqualified-id that has been
8347 /// assumed to name a template for ADL purposes.
8348 TemplateName ASTContext::getAssumedTemplateName(DeclarationName Name) const {
8349   auto *OT = new (*this) AssumedTemplateStorage(Name);
8350   return TemplateName(OT);
8351 }
8352 
8353 /// Retrieve the template name that represents a qualified
8354 /// template name such as \c std::vector.
8355 TemplateName
8356 ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
8357                                      bool TemplateKeyword,
8358                                      TemplateDecl *Template) const {
8359   assert(NNS && "Missing nested-name-specifier in qualified template name");
8360 
8361   // FIXME: Canonicalization?
8362   llvm::FoldingSetNodeID ID;
8363   QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
8364 
8365   void *InsertPos = nullptr;
8366   QualifiedTemplateName *QTN =
8367     QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
8368   if (!QTN) {
8369     QTN = new (*this, alignof(QualifiedTemplateName))
8370         QualifiedTemplateName(NNS, TemplateKeyword, Template);
8371     QualifiedTemplateNames.InsertNode(QTN, InsertPos);
8372   }
8373 
8374   return TemplateName(QTN);
8375 }
8376 
8377 /// Retrieve the template name that represents a dependent
8378 /// template name such as \c MetaFun::template apply.
8379 TemplateName
8380 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
8381                                      const IdentifierInfo *Name) const {
8382   assert((!NNS || NNS->isDependent()) &&
8383          "Nested name specifier must be dependent");
8384 
8385   llvm::FoldingSetNodeID ID;
8386   DependentTemplateName::Profile(ID, NNS, Name);
8387 
8388   void *InsertPos = nullptr;
8389   DependentTemplateName *QTN =
8390     DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
8391 
8392   if (QTN)
8393     return TemplateName(QTN);
8394 
8395   NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
8396   if (CanonNNS == NNS) {
8397     QTN = new (*this, alignof(DependentTemplateName))
8398         DependentTemplateName(NNS, Name);
8399   } else {
8400     TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
8401     QTN = new (*this, alignof(DependentTemplateName))
8402         DependentTemplateName(NNS, Name, Canon);
8403     DependentTemplateName *CheckQTN =
8404       DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
8405     assert(!CheckQTN && "Dependent type name canonicalization broken");
8406     (void)CheckQTN;
8407   }
8408 
8409   DependentTemplateNames.InsertNode(QTN, InsertPos);
8410   return TemplateName(QTN);
8411 }
8412 
8413 /// Retrieve the template name that represents a dependent
8414 /// template name such as \c MetaFun::template operator+.
8415 TemplateName
8416 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
8417                                      OverloadedOperatorKind Operator) const {
8418   assert((!NNS || NNS->isDependent()) &&
8419          "Nested name specifier must be dependent");
8420 
8421   llvm::FoldingSetNodeID ID;
8422   DependentTemplateName::Profile(ID, NNS, Operator);
8423 
8424   void *InsertPos = nullptr;
8425   DependentTemplateName *QTN
8426     = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
8427 
8428   if (QTN)
8429     return TemplateName(QTN);
8430 
8431   NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
8432   if (CanonNNS == NNS) {
8433     QTN = new (*this, alignof(DependentTemplateName))
8434         DependentTemplateName(NNS, Operator);
8435   } else {
8436     TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
8437     QTN = new (*this, alignof(DependentTemplateName))
8438         DependentTemplateName(NNS, Operator, Canon);
8439 
8440     DependentTemplateName *CheckQTN
8441       = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
8442     assert(!CheckQTN && "Dependent template name canonicalization broken");
8443     (void)CheckQTN;
8444   }
8445 
8446   DependentTemplateNames.InsertNode(QTN, InsertPos);
8447   return TemplateName(QTN);
8448 }
8449 
8450 TemplateName
8451 ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
8452                                          TemplateName replacement) const {
8453   llvm::FoldingSetNodeID ID;
8454   SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
8455 
8456   void *insertPos = nullptr;
8457   SubstTemplateTemplateParmStorage *subst
8458     = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
8459 
8460   if (!subst) {
8461     subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
8462     SubstTemplateTemplateParms.InsertNode(subst, insertPos);
8463   }
8464 
8465   return TemplateName(subst);
8466 }
8467 
8468 TemplateName
8469 ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
8470                                        const TemplateArgument &ArgPack) const {
8471   auto &Self = const_cast<ASTContext &>(*this);
8472   llvm::FoldingSetNodeID ID;
8473   SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
8474 
8475   void *InsertPos = nullptr;
8476   SubstTemplateTemplateParmPackStorage *Subst
8477     = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
8478 
8479   if (!Subst) {
8480     Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
8481                                                            ArgPack.pack_size(),
8482                                                          ArgPack.pack_begin());
8483     SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
8484   }
8485 
8486   return TemplateName(Subst);
8487 }
8488 
8489 /// getFromTargetType - Given one of the integer types provided by
8490 /// TargetInfo, produce the corresponding type. The unsigned @p Type
8491 /// is actually a value of type @c TargetInfo::IntType.
8492 CanQualType ASTContext::getFromTargetType(unsigned Type) const {
8493   switch (Type) {
8494   case TargetInfo::NoInt: return {};
8495   case TargetInfo::SignedChar: return SignedCharTy;
8496   case TargetInfo::UnsignedChar: return UnsignedCharTy;
8497   case TargetInfo::SignedShort: return ShortTy;
8498   case TargetInfo::UnsignedShort: return UnsignedShortTy;
8499   case TargetInfo::SignedInt: return IntTy;
8500   case TargetInfo::UnsignedInt: return UnsignedIntTy;
8501   case TargetInfo::SignedLong: return LongTy;
8502   case TargetInfo::UnsignedLong: return UnsignedLongTy;
8503   case TargetInfo::SignedLongLong: return LongLongTy;
8504   case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
8505   }
8506 
8507   llvm_unreachable("Unhandled TargetInfo::IntType value");
8508 }
8509 
8510 //===----------------------------------------------------------------------===//
8511 //                        Type Predicates.
8512 //===----------------------------------------------------------------------===//
8513 
8514 /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
8515 /// garbage collection attribute.
8516 ///
8517 Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
8518   if (getLangOpts().getGC() == LangOptions::NonGC)
8519     return Qualifiers::GCNone;
8520 
8521   assert(getLangOpts().ObjC);
8522   Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
8523 
8524   // Default behaviour under objective-C's gc is for ObjC pointers
8525   // (or pointers to them) be treated as though they were declared
8526   // as __strong.
8527   if (GCAttrs == Qualifiers::GCNone) {
8528     if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
8529       return Qualifiers::Strong;
8530     else if (Ty->isPointerType())
8531       return getObjCGCAttrKind(Ty->castAs<PointerType>()->getPointeeType());
8532   } else {
8533     // It's not valid to set GC attributes on anything that isn't a
8534     // pointer.
8535 #ifndef NDEBUG
8536     QualType CT = Ty->getCanonicalTypeInternal();
8537     while (const auto *AT = dyn_cast<ArrayType>(CT))
8538       CT = AT->getElementType();
8539     assert(CT->isAnyPointerType() || CT->isBlockPointerType());
8540 #endif
8541   }
8542   return GCAttrs;
8543 }
8544 
8545 //===----------------------------------------------------------------------===//
8546 //                        Type Compatibility Testing
8547 //===----------------------------------------------------------------------===//
8548 
8549 /// areCompatVectorTypes - Return true if the two specified vector types are
8550 /// compatible.
8551 static bool areCompatVectorTypes(const VectorType *LHS,
8552                                  const VectorType *RHS) {
8553   assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
8554   return LHS->getElementType() == RHS->getElementType() &&
8555          LHS->getNumElements() == RHS->getNumElements();
8556 }
8557 
8558 /// areCompatMatrixTypes - Return true if the two specified matrix types are
8559 /// compatible.
8560 static bool areCompatMatrixTypes(const ConstantMatrixType *LHS,
8561                                  const ConstantMatrixType *RHS) {
8562   assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
8563   return LHS->getElementType() == RHS->getElementType() &&
8564          LHS->getNumRows() == RHS->getNumRows() &&
8565          LHS->getNumColumns() == RHS->getNumColumns();
8566 }
8567 
8568 bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
8569                                           QualType SecondVec) {
8570   assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
8571   assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
8572 
8573   if (hasSameUnqualifiedType(FirstVec, SecondVec))
8574     return true;
8575 
8576   // Treat Neon vector types and most AltiVec vector types as if they are the
8577   // equivalent GCC vector types.
8578   const auto *First = FirstVec->castAs<VectorType>();
8579   const auto *Second = SecondVec->castAs<VectorType>();
8580   if (First->getNumElements() == Second->getNumElements() &&
8581       hasSameType(First->getElementType(), Second->getElementType()) &&
8582       First->getVectorKind() != VectorType::AltiVecPixel &&
8583       First->getVectorKind() != VectorType::AltiVecBool &&
8584       Second->getVectorKind() != VectorType::AltiVecPixel &&
8585       Second->getVectorKind() != VectorType::AltiVecBool &&
8586       First->getVectorKind() != VectorType::SveFixedLengthDataVector &&
8587       First->getVectorKind() != VectorType::SveFixedLengthPredicateVector &&
8588       Second->getVectorKind() != VectorType::SveFixedLengthDataVector &&
8589       Second->getVectorKind() != VectorType::SveFixedLengthPredicateVector)
8590     return true;
8591 
8592   return false;
8593 }
8594 
8595 bool ASTContext::areCompatibleSveTypes(QualType FirstType,
8596                                        QualType SecondType) {
8597   assert(((FirstType->isSizelessBuiltinType() && SecondType->isVectorType()) ||
8598           (FirstType->isVectorType() && SecondType->isSizelessBuiltinType())) &&
8599          "Expected SVE builtin type and vector type!");
8600 
8601   auto IsValidCast = [this](QualType FirstType, QualType SecondType) {
8602     if (const auto *BT = FirstType->getAs<BuiltinType>()) {
8603       if (const auto *VT = SecondType->getAs<VectorType>()) {
8604         // Predicates have the same representation as uint8 so we also have to
8605         // check the kind to make these types incompatible.
8606         if (VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector)
8607           return BT->getKind() == BuiltinType::SveBool;
8608         else if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector)
8609           return VT->getElementType().getCanonicalType() ==
8610                  FirstType->getSveEltType(*this);
8611         else if (VT->getVectorKind() == VectorType::GenericVector)
8612           return getTypeSize(SecondType) == getLangOpts().ArmSveVectorBits &&
8613                  hasSameType(VT->getElementType(),
8614                              getBuiltinVectorTypeInfo(BT).ElementType);
8615       }
8616     }
8617     return false;
8618   };
8619 
8620   return IsValidCast(FirstType, SecondType) ||
8621          IsValidCast(SecondType, FirstType);
8622 }
8623 
8624 bool ASTContext::areLaxCompatibleSveTypes(QualType FirstType,
8625                                           QualType SecondType) {
8626   assert(((FirstType->isSizelessBuiltinType() && SecondType->isVectorType()) ||
8627           (FirstType->isVectorType() && SecondType->isSizelessBuiltinType())) &&
8628          "Expected SVE builtin type and vector type!");
8629 
8630   auto IsLaxCompatible = [this](QualType FirstType, QualType SecondType) {
8631     if (!FirstType->getAs<BuiltinType>())
8632       return false;
8633 
8634     const auto *VecTy = SecondType->getAs<VectorType>();
8635     if (VecTy &&
8636         (VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector ||
8637          VecTy->getVectorKind() == VectorType::GenericVector)) {
8638       const LangOptions::LaxVectorConversionKind LVCKind =
8639           getLangOpts().getLaxVectorConversions();
8640 
8641       // If __ARM_FEATURE_SVE_BITS != N do not allow GNU vector lax conversion.
8642       // "Whenever __ARM_FEATURE_SVE_BITS==N, GNUT implicitly
8643       // converts to VLAT and VLAT implicitly converts to GNUT."
8644       // ACLE Spec Version 00bet6, 3.7.3.2. Behavior common to vectors and
8645       // predicates.
8646       if (VecTy->getVectorKind() == VectorType::GenericVector &&
8647           getTypeSize(SecondType) != getLangOpts().ArmSveVectorBits)
8648         return false;
8649 
8650       // If -flax-vector-conversions=all is specified, the types are
8651       // certainly compatible.
8652       if (LVCKind == LangOptions::LaxVectorConversionKind::All)
8653         return true;
8654 
8655       // If -flax-vector-conversions=integer is specified, the types are
8656       // compatible if the elements are integer types.
8657       if (LVCKind == LangOptions::LaxVectorConversionKind::Integer)
8658         return VecTy->getElementType().getCanonicalType()->isIntegerType() &&
8659                FirstType->getSveEltType(*this)->isIntegerType();
8660     }
8661 
8662     return false;
8663   };
8664 
8665   return IsLaxCompatible(FirstType, SecondType) ||
8666          IsLaxCompatible(SecondType, FirstType);
8667 }
8668 
8669 bool ASTContext::hasDirectOwnershipQualifier(QualType Ty) const {
8670   while (true) {
8671     // __strong id
8672     if (const AttributedType *Attr = dyn_cast<AttributedType>(Ty)) {
8673       if (Attr->getAttrKind() == attr::ObjCOwnership)
8674         return true;
8675 
8676       Ty = Attr->getModifiedType();
8677 
8678     // X *__strong (...)
8679     } else if (const ParenType *Paren = dyn_cast<ParenType>(Ty)) {
8680       Ty = Paren->getInnerType();
8681 
8682     // We do not want to look through typedefs, typeof(expr),
8683     // typeof(type), or any other way that the type is somehow
8684     // abstracted.
8685     } else {
8686       return false;
8687     }
8688   }
8689 }
8690 
8691 //===----------------------------------------------------------------------===//
8692 // ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
8693 //===----------------------------------------------------------------------===//
8694 
8695 /// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
8696 /// inheritance hierarchy of 'rProto'.
8697 bool
8698 ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
8699                                            ObjCProtocolDecl *rProto) const {
8700   if (declaresSameEntity(lProto, rProto))
8701     return true;
8702   for (auto *PI : rProto->protocols())
8703     if (ProtocolCompatibleWithProtocol(lProto, PI))
8704       return true;
8705   return false;
8706 }
8707 
8708 /// ObjCQualifiedClassTypesAreCompatible - compare  Class<pr,...> and
8709 /// Class<pr1, ...>.
8710 bool ASTContext::ObjCQualifiedClassTypesAreCompatible(
8711     const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs) {
8712   for (auto *lhsProto : lhs->quals()) {
8713     bool match = false;
8714     for (auto *rhsProto : rhs->quals()) {
8715       if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
8716         match = true;
8717         break;
8718       }
8719     }
8720     if (!match)
8721       return false;
8722   }
8723   return true;
8724 }
8725 
8726 /// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
8727 /// ObjCQualifiedIDType.
8728 bool ASTContext::ObjCQualifiedIdTypesAreCompatible(
8729     const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs,
8730     bool compare) {
8731   // Allow id<P..> and an 'id' in all cases.
8732   if (lhs->isObjCIdType() || rhs->isObjCIdType())
8733     return true;
8734 
8735   // Don't allow id<P..> to convert to Class or Class<P..> in either direction.
8736   if (lhs->isObjCClassType() || lhs->isObjCQualifiedClassType() ||
8737       rhs->isObjCClassType() || rhs->isObjCQualifiedClassType())
8738     return false;
8739 
8740   if (lhs->isObjCQualifiedIdType()) {
8741     if (rhs->qual_empty()) {
8742       // If the RHS is a unqualified interface pointer "NSString*",
8743       // make sure we check the class hierarchy.
8744       if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
8745         for (auto *I : lhs->quals()) {
8746           // when comparing an id<P> on lhs with a static type on rhs,
8747           // see if static class implements all of id's protocols, directly or
8748           // through its super class and categories.
8749           if (!rhsID->ClassImplementsProtocol(I, true))
8750             return false;
8751         }
8752       }
8753       // If there are no qualifiers and no interface, we have an 'id'.
8754       return true;
8755     }
8756     // Both the right and left sides have qualifiers.
8757     for (auto *lhsProto : lhs->quals()) {
8758       bool match = false;
8759 
8760       // when comparing an id<P> on lhs with a static type on rhs,
8761       // see if static class implements all of id's protocols, directly or
8762       // through its super class and categories.
8763       for (auto *rhsProto : rhs->quals()) {
8764         if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
8765             (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
8766           match = true;
8767           break;
8768         }
8769       }
8770       // If the RHS is a qualified interface pointer "NSString<P>*",
8771       // make sure we check the class hierarchy.
8772       if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
8773         for (auto *I : lhs->quals()) {
8774           // when comparing an id<P> on lhs with a static type on rhs,
8775           // see if static class implements all of id's protocols, directly or
8776           // through its super class and categories.
8777           if (rhsID->ClassImplementsProtocol(I, true)) {
8778             match = true;
8779             break;
8780           }
8781         }
8782       }
8783       if (!match)
8784         return false;
8785     }
8786 
8787     return true;
8788   }
8789 
8790   assert(rhs->isObjCQualifiedIdType() && "One of the LHS/RHS should be id<x>");
8791 
8792   if (lhs->getInterfaceType()) {
8793     // If both the right and left sides have qualifiers.
8794     for (auto *lhsProto : lhs->quals()) {
8795       bool match = false;
8796 
8797       // when comparing an id<P> on rhs with a static type on lhs,
8798       // see if static class implements all of id's protocols, directly or
8799       // through its super class and categories.
8800       // First, lhs protocols in the qualifier list must be found, direct
8801       // or indirect in rhs's qualifier list or it is a mismatch.
8802       for (auto *rhsProto : rhs->quals()) {
8803         if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
8804             (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
8805           match = true;
8806           break;
8807         }
8808       }
8809       if (!match)
8810         return false;
8811     }
8812 
8813     // Static class's protocols, or its super class or category protocols
8814     // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
8815     if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) {
8816       llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
8817       CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
8818       // This is rather dubious but matches gcc's behavior. If lhs has
8819       // no type qualifier and its class has no static protocol(s)
8820       // assume that it is mismatch.
8821       if (LHSInheritedProtocols.empty() && lhs->qual_empty())
8822         return false;
8823       for (auto *lhsProto : LHSInheritedProtocols) {
8824         bool match = false;
8825         for (auto *rhsProto : rhs->quals()) {
8826           if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
8827               (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
8828             match = true;
8829             break;
8830           }
8831         }
8832         if (!match)
8833           return false;
8834       }
8835     }
8836     return true;
8837   }
8838   return false;
8839 }
8840 
8841 /// canAssignObjCInterfaces - Return true if the two interface types are
8842 /// compatible for assignment from RHS to LHS.  This handles validation of any
8843 /// protocol qualifiers on the LHS or RHS.
8844 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
8845                                          const ObjCObjectPointerType *RHSOPT) {
8846   const ObjCObjectType* LHS = LHSOPT->getObjectType();
8847   const ObjCObjectType* RHS = RHSOPT->getObjectType();
8848 
8849   // If either type represents the built-in 'id' type, return true.
8850   if (LHS->isObjCUnqualifiedId() || RHS->isObjCUnqualifiedId())
8851     return true;
8852 
8853   // Function object that propagates a successful result or handles
8854   // __kindof types.
8855   auto finish = [&](bool succeeded) -> bool {
8856     if (succeeded)
8857       return true;
8858 
8859     if (!RHS->isKindOfType())
8860       return false;
8861 
8862     // Strip off __kindof and protocol qualifiers, then check whether
8863     // we can assign the other way.
8864     return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
8865                                    LHSOPT->stripObjCKindOfTypeAndQuals(*this));
8866   };
8867 
8868   // Casts from or to id<P> are allowed when the other side has compatible
8869   // protocols.
8870   if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
8871     return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false));
8872   }
8873 
8874   // Verify protocol compatibility for casts from Class<P1> to Class<P2>.
8875   if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
8876     return finish(ObjCQualifiedClassTypesAreCompatible(LHSOPT, RHSOPT));
8877   }
8878 
8879   // Casts from Class to Class<Foo>, or vice-versa, are allowed.
8880   if (LHS->isObjCClass() && RHS->isObjCClass()) {
8881     return true;
8882   }
8883 
8884   // If we have 2 user-defined types, fall into that path.
8885   if (LHS->getInterface() && RHS->getInterface()) {
8886     return finish(canAssignObjCInterfaces(LHS, RHS));
8887   }
8888 
8889   return false;
8890 }
8891 
8892 /// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
8893 /// for providing type-safety for objective-c pointers used to pass/return
8894 /// arguments in block literals. When passed as arguments, passing 'A*' where
8895 /// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
8896 /// not OK. For the return type, the opposite is not OK.
8897 bool ASTContext::canAssignObjCInterfacesInBlockPointer(
8898                                          const ObjCObjectPointerType *LHSOPT,
8899                                          const ObjCObjectPointerType *RHSOPT,
8900                                          bool BlockReturnType) {
8901 
8902   // Function object that propagates a successful result or handles
8903   // __kindof types.
8904   auto finish = [&](bool succeeded) -> bool {
8905     if (succeeded)
8906       return true;
8907 
8908     const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
8909     if (!Expected->isKindOfType())
8910       return false;
8911 
8912     // Strip off __kindof and protocol qualifiers, then check whether
8913     // we can assign the other way.
8914     return canAssignObjCInterfacesInBlockPointer(
8915              RHSOPT->stripObjCKindOfTypeAndQuals(*this),
8916              LHSOPT->stripObjCKindOfTypeAndQuals(*this),
8917              BlockReturnType);
8918   };
8919 
8920   if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
8921     return true;
8922 
8923   if (LHSOPT->isObjCBuiltinType()) {
8924     return finish(RHSOPT->isObjCBuiltinType() ||
8925                   RHSOPT->isObjCQualifiedIdType());
8926   }
8927 
8928   if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) {
8929     if (getLangOpts().CompatibilityQualifiedIdBlockParamTypeChecking)
8930       // Use for block parameters previous type checking for compatibility.
8931       return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false) ||
8932                     // Or corrected type checking as in non-compat mode.
8933                     (!BlockReturnType &&
8934                      ObjCQualifiedIdTypesAreCompatible(RHSOPT, LHSOPT, false)));
8935     else
8936       return finish(ObjCQualifiedIdTypesAreCompatible(
8937           (BlockReturnType ? LHSOPT : RHSOPT),
8938           (BlockReturnType ? RHSOPT : LHSOPT), false));
8939   }
8940 
8941   const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
8942   const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
8943   if (LHS && RHS)  { // We have 2 user-defined types.
8944     if (LHS != RHS) {
8945       if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
8946         return finish(BlockReturnType);
8947       if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
8948         return finish(!BlockReturnType);
8949     }
8950     else
8951       return true;
8952   }
8953   return false;
8954 }
8955 
8956 /// Comparison routine for Objective-C protocols to be used with
8957 /// llvm::array_pod_sort.
8958 static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
8959                                       ObjCProtocolDecl * const *rhs) {
8960   return (*lhs)->getName().compare((*rhs)->getName());
8961 }
8962 
8963 /// getIntersectionOfProtocols - This routine finds the intersection of set
8964 /// of protocols inherited from two distinct objective-c pointer objects with
8965 /// the given common base.
8966 /// It is used to build composite qualifier list of the composite type of
8967 /// the conditional expression involving two objective-c pointer objects.
8968 static
8969 void getIntersectionOfProtocols(ASTContext &Context,
8970                                 const ObjCInterfaceDecl *CommonBase,
8971                                 const ObjCObjectPointerType *LHSOPT,
8972                                 const ObjCObjectPointerType *RHSOPT,
8973       SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
8974 
8975   const ObjCObjectType* LHS = LHSOPT->getObjectType();
8976   const ObjCObjectType* RHS = RHSOPT->getObjectType();
8977   assert(LHS->getInterface() && "LHS must have an interface base");
8978   assert(RHS->getInterface() && "RHS must have an interface base");
8979 
8980   // Add all of the protocols for the LHS.
8981   llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
8982 
8983   // Start with the protocol qualifiers.
8984   for (auto proto : LHS->quals()) {
8985     Context.CollectInheritedProtocols(proto, LHSProtocolSet);
8986   }
8987 
8988   // Also add the protocols associated with the LHS interface.
8989   Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
8990 
8991   // Add all of the protocols for the RHS.
8992   llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
8993 
8994   // Start with the protocol qualifiers.
8995   for (auto proto : RHS->quals()) {
8996     Context.CollectInheritedProtocols(proto, RHSProtocolSet);
8997   }
8998 
8999   // Also add the protocols associated with the RHS interface.
9000   Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
9001 
9002   // Compute the intersection of the collected protocol sets.
9003   for (auto proto : LHSProtocolSet) {
9004     if (RHSProtocolSet.count(proto))
9005       IntersectionSet.push_back(proto);
9006   }
9007 
9008   // Compute the set of protocols that is implied by either the common type or
9009   // the protocols within the intersection.
9010   llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
9011   Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
9012 
9013   // Remove any implied protocols from the list of inherited protocols.
9014   if (!ImpliedProtocols.empty()) {
9015     IntersectionSet.erase(
9016       std::remove_if(IntersectionSet.begin(),
9017                      IntersectionSet.end(),
9018                      [&](ObjCProtocolDecl *proto) -> bool {
9019                        return ImpliedProtocols.count(proto) > 0;
9020                      }),
9021       IntersectionSet.end());
9022   }
9023 
9024   // Sort the remaining protocols by name.
9025   llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
9026                        compareObjCProtocolsByName);
9027 }
9028 
9029 /// Determine whether the first type is a subtype of the second.
9030 static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
9031                                      QualType rhs) {
9032   // Common case: two object pointers.
9033   const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
9034   const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
9035   if (lhsOPT && rhsOPT)
9036     return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
9037 
9038   // Two block pointers.
9039   const auto *lhsBlock = lhs->getAs<BlockPointerType>();
9040   const auto *rhsBlock = rhs->getAs<BlockPointerType>();
9041   if (lhsBlock && rhsBlock)
9042     return ctx.typesAreBlockPointerCompatible(lhs, rhs);
9043 
9044   // If either is an unqualified 'id' and the other is a block, it's
9045   // acceptable.
9046   if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
9047       (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
9048     return true;
9049 
9050   return false;
9051 }
9052 
9053 // Check that the given Objective-C type argument lists are equivalent.
9054 static bool sameObjCTypeArgs(ASTContext &ctx,
9055                              const ObjCInterfaceDecl *iface,
9056                              ArrayRef<QualType> lhsArgs,
9057                              ArrayRef<QualType> rhsArgs,
9058                              bool stripKindOf) {
9059   if (lhsArgs.size() != rhsArgs.size())
9060     return false;
9061 
9062   ObjCTypeParamList *typeParams = iface->getTypeParamList();
9063   for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
9064     if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
9065       continue;
9066 
9067     switch (typeParams->begin()[i]->getVariance()) {
9068     case ObjCTypeParamVariance::Invariant:
9069       if (!stripKindOf ||
9070           !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
9071                            rhsArgs[i].stripObjCKindOfType(ctx))) {
9072         return false;
9073       }
9074       break;
9075 
9076     case ObjCTypeParamVariance::Covariant:
9077       if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
9078         return false;
9079       break;
9080 
9081     case ObjCTypeParamVariance::Contravariant:
9082       if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
9083         return false;
9084       break;
9085     }
9086   }
9087 
9088   return true;
9089 }
9090 
9091 QualType ASTContext::areCommonBaseCompatible(
9092            const ObjCObjectPointerType *Lptr,
9093            const ObjCObjectPointerType *Rptr) {
9094   const ObjCObjectType *LHS = Lptr->getObjectType();
9095   const ObjCObjectType *RHS = Rptr->getObjectType();
9096   const ObjCInterfaceDecl* LDecl = LHS->getInterface();
9097   const ObjCInterfaceDecl* RDecl = RHS->getInterface();
9098 
9099   if (!LDecl || !RDecl)
9100     return {};
9101 
9102   // When either LHS or RHS is a kindof type, we should return a kindof type.
9103   // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
9104   // kindof(A).
9105   bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
9106 
9107   // Follow the left-hand side up the class hierarchy until we either hit a
9108   // root or find the RHS. Record the ancestors in case we don't find it.
9109   llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
9110     LHSAncestors;
9111   while (true) {
9112     // Record this ancestor. We'll need this if the common type isn't in the
9113     // path from the LHS to the root.
9114     LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
9115 
9116     if (declaresSameEntity(LHS->getInterface(), RDecl)) {
9117       // Get the type arguments.
9118       ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
9119       bool anyChanges = false;
9120       if (LHS->isSpecialized() && RHS->isSpecialized()) {
9121         // Both have type arguments, compare them.
9122         if (!sameObjCTypeArgs(*this, LHS->getInterface(),
9123                               LHS->getTypeArgs(), RHS->getTypeArgs(),
9124                               /*stripKindOf=*/true))
9125           return {};
9126       } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
9127         // If only one has type arguments, the result will not have type
9128         // arguments.
9129         LHSTypeArgs = {};
9130         anyChanges = true;
9131       }
9132 
9133       // Compute the intersection of protocols.
9134       SmallVector<ObjCProtocolDecl *, 8> Protocols;
9135       getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
9136                                  Protocols);
9137       if (!Protocols.empty())
9138         anyChanges = true;
9139 
9140       // If anything in the LHS will have changed, build a new result type.
9141       // If we need to return a kindof type but LHS is not a kindof type, we
9142       // build a new result type.
9143       if (anyChanges || LHS->isKindOfType() != anyKindOf) {
9144         QualType Result = getObjCInterfaceType(LHS->getInterface());
9145         Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
9146                                    anyKindOf || LHS->isKindOfType());
9147         return getObjCObjectPointerType(Result);
9148       }
9149 
9150       return getObjCObjectPointerType(QualType(LHS, 0));
9151     }
9152 
9153     // Find the superclass.
9154     QualType LHSSuperType = LHS->getSuperClassType();
9155     if (LHSSuperType.isNull())
9156       break;
9157 
9158     LHS = LHSSuperType->castAs<ObjCObjectType>();
9159   }
9160 
9161   // We didn't find anything by following the LHS to its root; now check
9162   // the RHS against the cached set of ancestors.
9163   while (true) {
9164     auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
9165     if (KnownLHS != LHSAncestors.end()) {
9166       LHS = KnownLHS->second;
9167 
9168       // Get the type arguments.
9169       ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
9170       bool anyChanges = false;
9171       if (LHS->isSpecialized() && RHS->isSpecialized()) {
9172         // Both have type arguments, compare them.
9173         if (!sameObjCTypeArgs(*this, LHS->getInterface(),
9174                               LHS->getTypeArgs(), RHS->getTypeArgs(),
9175                               /*stripKindOf=*/true))
9176           return {};
9177       } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
9178         // If only one has type arguments, the result will not have type
9179         // arguments.
9180         RHSTypeArgs = {};
9181         anyChanges = true;
9182       }
9183 
9184       // Compute the intersection of protocols.
9185       SmallVector<ObjCProtocolDecl *, 8> Protocols;
9186       getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
9187                                  Protocols);
9188       if (!Protocols.empty())
9189         anyChanges = true;
9190 
9191       // If we need to return a kindof type but RHS is not a kindof type, we
9192       // build a new result type.
9193       if (anyChanges || RHS->isKindOfType() != anyKindOf) {
9194         QualType Result = getObjCInterfaceType(RHS->getInterface());
9195         Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
9196                                    anyKindOf || RHS->isKindOfType());
9197         return getObjCObjectPointerType(Result);
9198       }
9199 
9200       return getObjCObjectPointerType(QualType(RHS, 0));
9201     }
9202 
9203     // Find the superclass of the RHS.
9204     QualType RHSSuperType = RHS->getSuperClassType();
9205     if (RHSSuperType.isNull())
9206       break;
9207 
9208     RHS = RHSSuperType->castAs<ObjCObjectType>();
9209   }
9210 
9211   return {};
9212 }
9213 
9214 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
9215                                          const ObjCObjectType *RHS) {
9216   assert(LHS->getInterface() && "LHS is not an interface type");
9217   assert(RHS->getInterface() && "RHS is not an interface type");
9218 
9219   // Verify that the base decls are compatible: the RHS must be a subclass of
9220   // the LHS.
9221   ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
9222   bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
9223   if (!IsSuperClass)
9224     return false;
9225 
9226   // If the LHS has protocol qualifiers, determine whether all of them are
9227   // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
9228   // LHS).
9229   if (LHS->getNumProtocols() > 0) {
9230     // OK if conversion of LHS to SuperClass results in narrowing of types
9231     // ; i.e., SuperClass may implement at least one of the protocols
9232     // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
9233     // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
9234     llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
9235     CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
9236     // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
9237     // qualifiers.
9238     for (auto *RHSPI : RHS->quals())
9239       CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
9240     // If there is no protocols associated with RHS, it is not a match.
9241     if (SuperClassInheritedProtocols.empty())
9242       return false;
9243 
9244     for (const auto *LHSProto : LHS->quals()) {
9245       bool SuperImplementsProtocol = false;
9246       for (auto *SuperClassProto : SuperClassInheritedProtocols)
9247         if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
9248           SuperImplementsProtocol = true;
9249           break;
9250         }
9251       if (!SuperImplementsProtocol)
9252         return false;
9253     }
9254   }
9255 
9256   // If the LHS is specialized, we may need to check type arguments.
9257   if (LHS->isSpecialized()) {
9258     // Follow the superclass chain until we've matched the LHS class in the
9259     // hierarchy. This substitutes type arguments through.
9260     const ObjCObjectType *RHSSuper = RHS;
9261     while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
9262       RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
9263 
9264     // If the RHS is specializd, compare type arguments.
9265     if (RHSSuper->isSpecialized() &&
9266         !sameObjCTypeArgs(*this, LHS->getInterface(),
9267                           LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
9268                           /*stripKindOf=*/true)) {
9269       return false;
9270     }
9271   }
9272 
9273   return true;
9274 }
9275 
9276 bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
9277   // get the "pointed to" types
9278   const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
9279   const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
9280 
9281   if (!LHSOPT || !RHSOPT)
9282     return false;
9283 
9284   return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
9285          canAssignObjCInterfaces(RHSOPT, LHSOPT);
9286 }
9287 
9288 bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
9289   return canAssignObjCInterfaces(
9290       getObjCObjectPointerType(To)->castAs<ObjCObjectPointerType>(),
9291       getObjCObjectPointerType(From)->castAs<ObjCObjectPointerType>());
9292 }
9293 
9294 /// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
9295 /// both shall have the identically qualified version of a compatible type.
9296 /// C99 6.2.7p1: Two types have compatible types if their types are the
9297 /// same. See 6.7.[2,3,5] for additional rules.
9298 bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
9299                                     bool CompareUnqualified) {
9300   if (getLangOpts().CPlusPlus)
9301     return hasSameType(LHS, RHS);
9302 
9303   return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
9304 }
9305 
9306 bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
9307   return typesAreCompatible(LHS, RHS);
9308 }
9309 
9310 bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
9311   return !mergeTypes(LHS, RHS, true).isNull();
9312 }
9313 
9314 /// mergeTransparentUnionType - if T is a transparent union type and a member
9315 /// of T is compatible with SubType, return the merged type, else return
9316 /// QualType()
9317 QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
9318                                                bool OfBlockPointer,
9319                                                bool Unqualified) {
9320   if (const RecordType *UT = T->getAsUnionType()) {
9321     RecordDecl *UD = UT->getDecl();
9322     if (UD->hasAttr<TransparentUnionAttr>()) {
9323       for (const auto *I : UD->fields()) {
9324         QualType ET = I->getType().getUnqualifiedType();
9325         QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
9326         if (!MT.isNull())
9327           return MT;
9328       }
9329     }
9330   }
9331 
9332   return {};
9333 }
9334 
9335 /// mergeFunctionParameterTypes - merge two types which appear as function
9336 /// parameter types
9337 QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
9338                                                  bool OfBlockPointer,
9339                                                  bool Unqualified) {
9340   // GNU extension: two types are compatible if they appear as a function
9341   // argument, one of the types is a transparent union type and the other
9342   // type is compatible with a union member
9343   QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
9344                                               Unqualified);
9345   if (!lmerge.isNull())
9346     return lmerge;
9347 
9348   QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
9349                                               Unqualified);
9350   if (!rmerge.isNull())
9351     return rmerge;
9352 
9353   return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
9354 }
9355 
9356 QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
9357                                         bool OfBlockPointer, bool Unqualified,
9358                                         bool AllowCXX) {
9359   const auto *lbase = lhs->castAs<FunctionType>();
9360   const auto *rbase = rhs->castAs<FunctionType>();
9361   const auto *lproto = dyn_cast<FunctionProtoType>(lbase);
9362   const auto *rproto = dyn_cast<FunctionProtoType>(rbase);
9363   bool allLTypes = true;
9364   bool allRTypes = true;
9365 
9366   // Check return type
9367   QualType retType;
9368   if (OfBlockPointer) {
9369     QualType RHS = rbase->getReturnType();
9370     QualType LHS = lbase->getReturnType();
9371     bool UnqualifiedResult = Unqualified;
9372     if (!UnqualifiedResult)
9373       UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
9374     retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
9375   }
9376   else
9377     retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
9378                          Unqualified);
9379   if (retType.isNull())
9380     return {};
9381 
9382   if (Unqualified)
9383     retType = retType.getUnqualifiedType();
9384 
9385   CanQualType LRetType = getCanonicalType(lbase->getReturnType());
9386   CanQualType RRetType = getCanonicalType(rbase->getReturnType());
9387   if (Unqualified) {
9388     LRetType = LRetType.getUnqualifiedType();
9389     RRetType = RRetType.getUnqualifiedType();
9390   }
9391 
9392   if (getCanonicalType(retType) != LRetType)
9393     allLTypes = false;
9394   if (getCanonicalType(retType) != RRetType)
9395     allRTypes = false;
9396 
9397   // FIXME: double check this
9398   // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
9399   //                           rbase->getRegParmAttr() != 0 &&
9400   //                           lbase->getRegParmAttr() != rbase->getRegParmAttr()?
9401   FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
9402   FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
9403 
9404   // Compatible functions must have compatible calling conventions
9405   if (lbaseInfo.getCC() != rbaseInfo.getCC())
9406     return {};
9407 
9408   // Regparm is part of the calling convention.
9409   if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
9410     return {};
9411   if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
9412     return {};
9413 
9414   if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
9415     return {};
9416   if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
9417     return {};
9418   if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
9419     return {};
9420 
9421   // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
9422   bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
9423 
9424   if (lbaseInfo.getNoReturn() != NoReturn)
9425     allLTypes = false;
9426   if (rbaseInfo.getNoReturn() != NoReturn)
9427     allRTypes = false;
9428 
9429   FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
9430 
9431   if (lproto && rproto) { // two C99 style function prototypes
9432     assert((AllowCXX ||
9433             (!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec())) &&
9434            "C++ shouldn't be here");
9435     // Compatible functions must have the same number of parameters
9436     if (lproto->getNumParams() != rproto->getNumParams())
9437       return {};
9438 
9439     // Variadic and non-variadic functions aren't compatible
9440     if (lproto->isVariadic() != rproto->isVariadic())
9441       return {};
9442 
9443     if (lproto->getMethodQuals() != rproto->getMethodQuals())
9444       return {};
9445 
9446     SmallVector<FunctionProtoType::ExtParameterInfo, 4> newParamInfos;
9447     bool canUseLeft, canUseRight;
9448     if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight,
9449                                newParamInfos))
9450       return {};
9451 
9452     if (!canUseLeft)
9453       allLTypes = false;
9454     if (!canUseRight)
9455       allRTypes = false;
9456 
9457     // Check parameter type compatibility
9458     SmallVector<QualType, 10> types;
9459     for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
9460       QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
9461       QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
9462       QualType paramType = mergeFunctionParameterTypes(
9463           lParamType, rParamType, OfBlockPointer, Unqualified);
9464       if (paramType.isNull())
9465         return {};
9466 
9467       if (Unqualified)
9468         paramType = paramType.getUnqualifiedType();
9469 
9470       types.push_back(paramType);
9471       if (Unqualified) {
9472         lParamType = lParamType.getUnqualifiedType();
9473         rParamType = rParamType.getUnqualifiedType();
9474       }
9475 
9476       if (getCanonicalType(paramType) != getCanonicalType(lParamType))
9477         allLTypes = false;
9478       if (getCanonicalType(paramType) != getCanonicalType(rParamType))
9479         allRTypes = false;
9480     }
9481 
9482     if (allLTypes) return lhs;
9483     if (allRTypes) return rhs;
9484 
9485     FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
9486     EPI.ExtInfo = einfo;
9487     EPI.ExtParameterInfos =
9488         newParamInfos.empty() ? nullptr : newParamInfos.data();
9489     return getFunctionType(retType, types, EPI);
9490   }
9491 
9492   if (lproto) allRTypes = false;
9493   if (rproto) allLTypes = false;
9494 
9495   const FunctionProtoType *proto = lproto ? lproto : rproto;
9496   if (proto) {
9497     assert((AllowCXX || !proto->hasExceptionSpec()) && "C++ shouldn't be here");
9498     if (proto->isVariadic())
9499       return {};
9500     // Check that the types are compatible with the types that
9501     // would result from default argument promotions (C99 6.7.5.3p15).
9502     // The only types actually affected are promotable integer
9503     // types and floats, which would be passed as a different
9504     // type depending on whether the prototype is visible.
9505     for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
9506       QualType paramTy = proto->getParamType(i);
9507 
9508       // Look at the converted type of enum types, since that is the type used
9509       // to pass enum values.
9510       if (const auto *Enum = paramTy->getAs<EnumType>()) {
9511         paramTy = Enum->getDecl()->getIntegerType();
9512         if (paramTy.isNull())
9513           return {};
9514       }
9515 
9516       if (paramTy->isPromotableIntegerType() ||
9517           getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
9518         return {};
9519     }
9520 
9521     if (allLTypes) return lhs;
9522     if (allRTypes) return rhs;
9523 
9524     FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
9525     EPI.ExtInfo = einfo;
9526     return getFunctionType(retType, proto->getParamTypes(), EPI);
9527   }
9528 
9529   if (allLTypes) return lhs;
9530   if (allRTypes) return rhs;
9531   return getFunctionNoProtoType(retType, einfo);
9532 }
9533 
9534 /// Given that we have an enum type and a non-enum type, try to merge them.
9535 static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
9536                                      QualType other, bool isBlockReturnType) {
9537   // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
9538   // a signed integer type, or an unsigned integer type.
9539   // Compatibility is based on the underlying type, not the promotion
9540   // type.
9541   QualType underlyingType = ET->getDecl()->getIntegerType();
9542   if (underlyingType.isNull())
9543     return {};
9544   if (Context.hasSameType(underlyingType, other))
9545     return other;
9546 
9547   // In block return types, we're more permissive and accept any
9548   // integral type of the same size.
9549   if (isBlockReturnType && other->isIntegerType() &&
9550       Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
9551     return other;
9552 
9553   return {};
9554 }
9555 
9556 QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
9557                                 bool OfBlockPointer,
9558                                 bool Unqualified, bool BlockReturnType) {
9559   // C++ [expr]: If an expression initially has the type "reference to T", the
9560   // type is adjusted to "T" prior to any further analysis, the expression
9561   // designates the object or function denoted by the reference, and the
9562   // expression is an lvalue unless the reference is an rvalue reference and
9563   // the expression is a function call (possibly inside parentheses).
9564   if (LHS->getAs<ReferenceType>() || RHS->getAs<ReferenceType>())
9565     return {};
9566 
9567   if (Unqualified) {
9568     LHS = LHS.getUnqualifiedType();
9569     RHS = RHS.getUnqualifiedType();
9570   }
9571 
9572   QualType LHSCan = getCanonicalType(LHS),
9573            RHSCan = getCanonicalType(RHS);
9574 
9575   // If two types are identical, they are compatible.
9576   if (LHSCan == RHSCan)
9577     return LHS;
9578 
9579   // If the qualifiers are different, the types aren't compatible... mostly.
9580   Qualifiers LQuals = LHSCan.getLocalQualifiers();
9581   Qualifiers RQuals = RHSCan.getLocalQualifiers();
9582   if (LQuals != RQuals) {
9583     // If any of these qualifiers are different, we have a type
9584     // mismatch.
9585     if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
9586         LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
9587         LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
9588         LQuals.hasUnaligned() != RQuals.hasUnaligned())
9589       return {};
9590 
9591     // Exactly one GC qualifier difference is allowed: __strong is
9592     // okay if the other type has no GC qualifier but is an Objective
9593     // C object pointer (i.e. implicitly strong by default).  We fix
9594     // this by pretending that the unqualified type was actually
9595     // qualified __strong.
9596     Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
9597     Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
9598     assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
9599 
9600     if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
9601       return {};
9602 
9603     if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
9604       return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
9605     }
9606     if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
9607       return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
9608     }
9609     return {};
9610   }
9611 
9612   // Okay, qualifiers are equal.
9613 
9614   Type::TypeClass LHSClass = LHSCan->getTypeClass();
9615   Type::TypeClass RHSClass = RHSCan->getTypeClass();
9616 
9617   // We want to consider the two function types to be the same for these
9618   // comparisons, just force one to the other.
9619   if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
9620   if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
9621 
9622   // Same as above for arrays
9623   if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
9624     LHSClass = Type::ConstantArray;
9625   if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
9626     RHSClass = Type::ConstantArray;
9627 
9628   // ObjCInterfaces are just specialized ObjCObjects.
9629   if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
9630   if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
9631 
9632   // Canonicalize ExtVector -> Vector.
9633   if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
9634   if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
9635 
9636   // If the canonical type classes don't match.
9637   if (LHSClass != RHSClass) {
9638     // Note that we only have special rules for turning block enum
9639     // returns into block int returns, not vice-versa.
9640     if (const auto *ETy = LHS->getAs<EnumType>()) {
9641       return mergeEnumWithInteger(*this, ETy, RHS, false);
9642     }
9643     if (const EnumType* ETy = RHS->getAs<EnumType>()) {
9644       return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
9645     }
9646     // allow block pointer type to match an 'id' type.
9647     if (OfBlockPointer && !BlockReturnType) {
9648        if (LHS->isObjCIdType() && RHS->isBlockPointerType())
9649          return LHS;
9650       if (RHS->isObjCIdType() && LHS->isBlockPointerType())
9651         return RHS;
9652     }
9653 
9654     return {};
9655   }
9656 
9657   // The canonical type classes match.
9658   switch (LHSClass) {
9659 #define TYPE(Class, Base)
9660 #define ABSTRACT_TYPE(Class, Base)
9661 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
9662 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
9663 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
9664 #include "clang/AST/TypeNodes.inc"
9665     llvm_unreachable("Non-canonical and dependent types shouldn't get here");
9666 
9667   case Type::Auto:
9668   case Type::DeducedTemplateSpecialization:
9669   case Type::LValueReference:
9670   case Type::RValueReference:
9671   case Type::MemberPointer:
9672     llvm_unreachable("C++ should never be in mergeTypes");
9673 
9674   case Type::ObjCInterface:
9675   case Type::IncompleteArray:
9676   case Type::VariableArray:
9677   case Type::FunctionProto:
9678   case Type::ExtVector:
9679     llvm_unreachable("Types are eliminated above");
9680 
9681   case Type::Pointer:
9682   {
9683     // Merge two pointer types, while trying to preserve typedef info
9684     QualType LHSPointee = LHS->castAs<PointerType>()->getPointeeType();
9685     QualType RHSPointee = RHS->castAs<PointerType>()->getPointeeType();
9686     if (Unqualified) {
9687       LHSPointee = LHSPointee.getUnqualifiedType();
9688       RHSPointee = RHSPointee.getUnqualifiedType();
9689     }
9690     QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
9691                                      Unqualified);
9692     if (ResultType.isNull())
9693       return {};
9694     if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
9695       return LHS;
9696     if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
9697       return RHS;
9698     return getPointerType(ResultType);
9699   }
9700   case Type::BlockPointer:
9701   {
9702     // Merge two block pointer types, while trying to preserve typedef info
9703     QualType LHSPointee = LHS->castAs<BlockPointerType>()->getPointeeType();
9704     QualType RHSPointee = RHS->castAs<BlockPointerType>()->getPointeeType();
9705     if (Unqualified) {
9706       LHSPointee = LHSPointee.getUnqualifiedType();
9707       RHSPointee = RHSPointee.getUnqualifiedType();
9708     }
9709     if (getLangOpts().OpenCL) {
9710       Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
9711       Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
9712       // Blocks can't be an expression in a ternary operator (OpenCL v2.0
9713       // 6.12.5) thus the following check is asymmetric.
9714       if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual))
9715         return {};
9716       LHSPteeQual.removeAddressSpace();
9717       RHSPteeQual.removeAddressSpace();
9718       LHSPointee =
9719           QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
9720       RHSPointee =
9721           QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
9722     }
9723     QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
9724                                      Unqualified);
9725     if (ResultType.isNull())
9726       return {};
9727     if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
9728       return LHS;
9729     if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
9730       return RHS;
9731     return getBlockPointerType(ResultType);
9732   }
9733   case Type::Atomic:
9734   {
9735     // Merge two pointer types, while trying to preserve typedef info
9736     QualType LHSValue = LHS->castAs<AtomicType>()->getValueType();
9737     QualType RHSValue = RHS->castAs<AtomicType>()->getValueType();
9738     if (Unqualified) {
9739       LHSValue = LHSValue.getUnqualifiedType();
9740       RHSValue = RHSValue.getUnqualifiedType();
9741     }
9742     QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
9743                                      Unqualified);
9744     if (ResultType.isNull())
9745       return {};
9746     if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
9747       return LHS;
9748     if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
9749       return RHS;
9750     return getAtomicType(ResultType);
9751   }
9752   case Type::ConstantArray:
9753   {
9754     const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
9755     const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
9756     if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
9757       return {};
9758 
9759     QualType LHSElem = getAsArrayType(LHS)->getElementType();
9760     QualType RHSElem = getAsArrayType(RHS)->getElementType();
9761     if (Unqualified) {
9762       LHSElem = LHSElem.getUnqualifiedType();
9763       RHSElem = RHSElem.getUnqualifiedType();
9764     }
9765 
9766     QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
9767     if (ResultType.isNull())
9768       return {};
9769 
9770     const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
9771     const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
9772 
9773     // If either side is a variable array, and both are complete, check whether
9774     // the current dimension is definite.
9775     if (LVAT || RVAT) {
9776       auto SizeFetch = [this](const VariableArrayType* VAT,
9777           const ConstantArrayType* CAT)
9778           -> std::pair<bool,llvm::APInt> {
9779         if (VAT) {
9780           Optional<llvm::APSInt> TheInt;
9781           Expr *E = VAT->getSizeExpr();
9782           if (E && (TheInt = E->getIntegerConstantExpr(*this)))
9783             return std::make_pair(true, *TheInt);
9784           return std::make_pair(false, llvm::APSInt());
9785         }
9786         if (CAT)
9787           return std::make_pair(true, CAT->getSize());
9788         return std::make_pair(false, llvm::APInt());
9789       };
9790 
9791       bool HaveLSize, HaveRSize;
9792       llvm::APInt LSize, RSize;
9793       std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT);
9794       std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT);
9795       if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize))
9796         return {}; // Definite, but unequal, array dimension
9797     }
9798 
9799     if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
9800       return LHS;
9801     if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
9802       return RHS;
9803     if (LCAT)
9804       return getConstantArrayType(ResultType, LCAT->getSize(),
9805                                   LCAT->getSizeExpr(),
9806                                   ArrayType::ArraySizeModifier(), 0);
9807     if (RCAT)
9808       return getConstantArrayType(ResultType, RCAT->getSize(),
9809                                   RCAT->getSizeExpr(),
9810                                   ArrayType::ArraySizeModifier(), 0);
9811     if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
9812       return LHS;
9813     if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
9814       return RHS;
9815     if (LVAT) {
9816       // FIXME: This isn't correct! But tricky to implement because
9817       // the array's size has to be the size of LHS, but the type
9818       // has to be different.
9819       return LHS;
9820     }
9821     if (RVAT) {
9822       // FIXME: This isn't correct! But tricky to implement because
9823       // the array's size has to be the size of RHS, but the type
9824       // has to be different.
9825       return RHS;
9826     }
9827     if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
9828     if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
9829     return getIncompleteArrayType(ResultType,
9830                                   ArrayType::ArraySizeModifier(), 0);
9831   }
9832   case Type::FunctionNoProto:
9833     return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
9834   case Type::Record:
9835   case Type::Enum:
9836     return {};
9837   case Type::Builtin:
9838     // Only exactly equal builtin types are compatible, which is tested above.
9839     return {};
9840   case Type::Complex:
9841     // Distinct complex types are incompatible.
9842     return {};
9843   case Type::Vector:
9844     // FIXME: The merged type should be an ExtVector!
9845     if (areCompatVectorTypes(LHSCan->castAs<VectorType>(),
9846                              RHSCan->castAs<VectorType>()))
9847       return LHS;
9848     return {};
9849   case Type::ConstantMatrix:
9850     if (areCompatMatrixTypes(LHSCan->castAs<ConstantMatrixType>(),
9851                              RHSCan->castAs<ConstantMatrixType>()))
9852       return LHS;
9853     return {};
9854   case Type::ObjCObject: {
9855     // Check if the types are assignment compatible.
9856     // FIXME: This should be type compatibility, e.g. whether
9857     // "LHS x; RHS x;" at global scope is legal.
9858     if (canAssignObjCInterfaces(LHS->castAs<ObjCObjectType>(),
9859                                 RHS->castAs<ObjCObjectType>()))
9860       return LHS;
9861     return {};
9862   }
9863   case Type::ObjCObjectPointer:
9864     if (OfBlockPointer) {
9865       if (canAssignObjCInterfacesInBlockPointer(
9866               LHS->castAs<ObjCObjectPointerType>(),
9867               RHS->castAs<ObjCObjectPointerType>(), BlockReturnType))
9868         return LHS;
9869       return {};
9870     }
9871     if (canAssignObjCInterfaces(LHS->castAs<ObjCObjectPointerType>(),
9872                                 RHS->castAs<ObjCObjectPointerType>()))
9873       return LHS;
9874     return {};
9875   case Type::Pipe:
9876     assert(LHS != RHS &&
9877            "Equivalent pipe types should have already been handled!");
9878     return {};
9879   case Type::ExtInt: {
9880     // Merge two ext-int types, while trying to preserve typedef info.
9881     bool LHSUnsigned  = LHS->castAs<ExtIntType>()->isUnsigned();
9882     bool RHSUnsigned = RHS->castAs<ExtIntType>()->isUnsigned();
9883     unsigned LHSBits = LHS->castAs<ExtIntType>()->getNumBits();
9884     unsigned RHSBits = RHS->castAs<ExtIntType>()->getNumBits();
9885 
9886     // Like unsigned/int, shouldn't have a type if they dont match.
9887     if (LHSUnsigned != RHSUnsigned)
9888       return {};
9889 
9890     if (LHSBits != RHSBits)
9891       return {};
9892     return LHS;
9893   }
9894   }
9895 
9896   llvm_unreachable("Invalid Type::Class!");
9897 }
9898 
9899 bool ASTContext::mergeExtParameterInfo(
9900     const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
9901     bool &CanUseFirst, bool &CanUseSecond,
9902     SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos) {
9903   assert(NewParamInfos.empty() && "param info list not empty");
9904   CanUseFirst = CanUseSecond = true;
9905   bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
9906   bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
9907 
9908   // Fast path: if the first type doesn't have ext parameter infos,
9909   // we match if and only if the second type also doesn't have them.
9910   if (!FirstHasInfo && !SecondHasInfo)
9911     return true;
9912 
9913   bool NeedParamInfo = false;
9914   size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
9915                           : SecondFnType->getExtParameterInfos().size();
9916 
9917   for (size_t I = 0; I < E; ++I) {
9918     FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
9919     if (FirstHasInfo)
9920       FirstParam = FirstFnType->getExtParameterInfo(I);
9921     if (SecondHasInfo)
9922       SecondParam = SecondFnType->getExtParameterInfo(I);
9923 
9924     // Cannot merge unless everything except the noescape flag matches.
9925     if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false))
9926       return false;
9927 
9928     bool FirstNoEscape = FirstParam.isNoEscape();
9929     bool SecondNoEscape = SecondParam.isNoEscape();
9930     bool IsNoEscape = FirstNoEscape && SecondNoEscape;
9931     NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape));
9932     if (NewParamInfos.back().getOpaqueValue())
9933       NeedParamInfo = true;
9934     if (FirstNoEscape != IsNoEscape)
9935       CanUseFirst = false;
9936     if (SecondNoEscape != IsNoEscape)
9937       CanUseSecond = false;
9938   }
9939 
9940   if (!NeedParamInfo)
9941     NewParamInfos.clear();
9942 
9943   return true;
9944 }
9945 
9946 void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) {
9947   ObjCLayouts[CD] = nullptr;
9948 }
9949 
9950 /// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
9951 /// 'RHS' attributes and returns the merged version; including for function
9952 /// return types.
9953 QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
9954   QualType LHSCan = getCanonicalType(LHS),
9955   RHSCan = getCanonicalType(RHS);
9956   // If two types are identical, they are compatible.
9957   if (LHSCan == RHSCan)
9958     return LHS;
9959   if (RHSCan->isFunctionType()) {
9960     if (!LHSCan->isFunctionType())
9961       return {};
9962     QualType OldReturnType =
9963         cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
9964     QualType NewReturnType =
9965         cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
9966     QualType ResReturnType =
9967       mergeObjCGCQualifiers(NewReturnType, OldReturnType);
9968     if (ResReturnType.isNull())
9969       return {};
9970     if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
9971       // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
9972       // In either case, use OldReturnType to build the new function type.
9973       const auto *F = LHS->castAs<FunctionType>();
9974       if (const auto *FPT = cast<FunctionProtoType>(F)) {
9975         FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9976         EPI.ExtInfo = getFunctionExtInfo(LHS);
9977         QualType ResultType =
9978             getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
9979         return ResultType;
9980       }
9981     }
9982     return {};
9983   }
9984 
9985   // If the qualifiers are different, the types can still be merged.
9986   Qualifiers LQuals = LHSCan.getLocalQualifiers();
9987   Qualifiers RQuals = RHSCan.getLocalQualifiers();
9988   if (LQuals != RQuals) {
9989     // If any of these qualifiers are different, we have a type mismatch.
9990     if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
9991         LQuals.getAddressSpace() != RQuals.getAddressSpace())
9992       return {};
9993 
9994     // Exactly one GC qualifier difference is allowed: __strong is
9995     // okay if the other type has no GC qualifier but is an Objective
9996     // C object pointer (i.e. implicitly strong by default).  We fix
9997     // this by pretending that the unqualified type was actually
9998     // qualified __strong.
9999     Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
10000     Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
10001     assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
10002 
10003     if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
10004       return {};
10005 
10006     if (GC_L == Qualifiers::Strong)
10007       return LHS;
10008     if (GC_R == Qualifiers::Strong)
10009       return RHS;
10010     return {};
10011   }
10012 
10013   if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
10014     QualType LHSBaseQT = LHS->castAs<ObjCObjectPointerType>()->getPointeeType();
10015     QualType RHSBaseQT = RHS->castAs<ObjCObjectPointerType>()->getPointeeType();
10016     QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
10017     if (ResQT == LHSBaseQT)
10018       return LHS;
10019     if (ResQT == RHSBaseQT)
10020       return RHS;
10021   }
10022   return {};
10023 }
10024 
10025 //===----------------------------------------------------------------------===//
10026 //                         Integer Predicates
10027 //===----------------------------------------------------------------------===//
10028 
10029 unsigned ASTContext::getIntWidth(QualType T) const {
10030   if (const auto *ET = T->getAs<EnumType>())
10031     T = ET->getDecl()->getIntegerType();
10032   if (T->isBooleanType())
10033     return 1;
10034   if(const auto *EIT = T->getAs<ExtIntType>())
10035     return EIT->getNumBits();
10036   // For builtin types, just use the standard type sizing method
10037   return (unsigned)getTypeSize(T);
10038 }
10039 
10040 QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
10041   assert((T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) &&
10042          "Unexpected type");
10043 
10044   // Turn <4 x signed int> -> <4 x unsigned int>
10045   if (const auto *VTy = T->getAs<VectorType>())
10046     return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
10047                          VTy->getNumElements(), VTy->getVectorKind());
10048 
10049   // For enums, we return the unsigned version of the base type.
10050   if (const auto *ETy = T->getAs<EnumType>())
10051     T = ETy->getDecl()->getIntegerType();
10052 
10053   switch (T->castAs<BuiltinType>()->getKind()) {
10054   case BuiltinType::Char_S:
10055   case BuiltinType::SChar:
10056     return UnsignedCharTy;
10057   case BuiltinType::Short:
10058     return UnsignedShortTy;
10059   case BuiltinType::Int:
10060     return UnsignedIntTy;
10061   case BuiltinType::Long:
10062     return UnsignedLongTy;
10063   case BuiltinType::LongLong:
10064     return UnsignedLongLongTy;
10065   case BuiltinType::Int128:
10066     return UnsignedInt128Ty;
10067   // wchar_t is special. It is either signed or not, but when it's signed,
10068   // there's no matching "unsigned wchar_t". Therefore we return the unsigned
10069   // version of it's underlying type instead.
10070   case BuiltinType::WChar_S:
10071     return getUnsignedWCharType();
10072 
10073   case BuiltinType::ShortAccum:
10074     return UnsignedShortAccumTy;
10075   case BuiltinType::Accum:
10076     return UnsignedAccumTy;
10077   case BuiltinType::LongAccum:
10078     return UnsignedLongAccumTy;
10079   case BuiltinType::SatShortAccum:
10080     return SatUnsignedShortAccumTy;
10081   case BuiltinType::SatAccum:
10082     return SatUnsignedAccumTy;
10083   case BuiltinType::SatLongAccum:
10084     return SatUnsignedLongAccumTy;
10085   case BuiltinType::ShortFract:
10086     return UnsignedShortFractTy;
10087   case BuiltinType::Fract:
10088     return UnsignedFractTy;
10089   case BuiltinType::LongFract:
10090     return UnsignedLongFractTy;
10091   case BuiltinType::SatShortFract:
10092     return SatUnsignedShortFractTy;
10093   case BuiltinType::SatFract:
10094     return SatUnsignedFractTy;
10095   case BuiltinType::SatLongFract:
10096     return SatUnsignedLongFractTy;
10097   default:
10098     llvm_unreachable("Unexpected signed integer or fixed point type");
10099   }
10100 }
10101 
10102 ASTMutationListener::~ASTMutationListener() = default;
10103 
10104 void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
10105                                             QualType ReturnType) {}
10106 
10107 //===----------------------------------------------------------------------===//
10108 //                          Builtin Type Computation
10109 //===----------------------------------------------------------------------===//
10110 
10111 /// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
10112 /// pointer over the consumed characters.  This returns the resultant type.  If
10113 /// AllowTypeModifiers is false then modifier like * are not parsed, just basic
10114 /// types.  This allows "v2i*" to be parsed as a pointer to a v2i instead of
10115 /// a vector of "i*".
10116 ///
10117 /// RequiresICE is filled in on return to indicate whether the value is required
10118 /// to be an Integer Constant Expression.
10119 static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
10120                                   ASTContext::GetBuiltinTypeError &Error,
10121                                   bool &RequiresICE,
10122                                   bool AllowTypeModifiers) {
10123   // Modifiers.
10124   int HowLong = 0;
10125   bool Signed = false, Unsigned = false;
10126   RequiresICE = false;
10127 
10128   // Read the prefixed modifiers first.
10129   bool Done = false;
10130   #ifndef NDEBUG
10131   bool IsSpecial = false;
10132   #endif
10133   while (!Done) {
10134     switch (*Str++) {
10135     default: Done = true; --Str; break;
10136     case 'I':
10137       RequiresICE = true;
10138       break;
10139     case 'S':
10140       assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
10141       assert(!Signed && "Can't use 'S' modifier multiple times!");
10142       Signed = true;
10143       break;
10144     case 'U':
10145       assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
10146       assert(!Unsigned && "Can't use 'U' modifier multiple times!");
10147       Unsigned = true;
10148       break;
10149     case 'L':
10150       assert(!IsSpecial && "Can't use 'L' with 'W', 'N', 'Z' or 'O' modifiers");
10151       assert(HowLong <= 2 && "Can't have LLLL modifier");
10152       ++HowLong;
10153       break;
10154     case 'N':
10155       // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
10156       assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
10157       assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
10158       #ifndef NDEBUG
10159       IsSpecial = true;
10160       #endif
10161       if (Context.getTargetInfo().getLongWidth() == 32)
10162         ++HowLong;
10163       break;
10164     case 'W':
10165       // This modifier represents int64 type.
10166       assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
10167       assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
10168       #ifndef NDEBUG
10169       IsSpecial = true;
10170       #endif
10171       switch (Context.getTargetInfo().getInt64Type()) {
10172       default:
10173         llvm_unreachable("Unexpected integer type");
10174       case TargetInfo::SignedLong:
10175         HowLong = 1;
10176         break;
10177       case TargetInfo::SignedLongLong:
10178         HowLong = 2;
10179         break;
10180       }
10181       break;
10182     case 'Z':
10183       // This modifier represents int32 type.
10184       assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
10185       assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!");
10186       #ifndef NDEBUG
10187       IsSpecial = true;
10188       #endif
10189       switch (Context.getTargetInfo().getIntTypeByWidth(32, true)) {
10190       default:
10191         llvm_unreachable("Unexpected integer type");
10192       case TargetInfo::SignedInt:
10193         HowLong = 0;
10194         break;
10195       case TargetInfo::SignedLong:
10196         HowLong = 1;
10197         break;
10198       case TargetInfo::SignedLongLong:
10199         HowLong = 2;
10200         break;
10201       }
10202       break;
10203     case 'O':
10204       assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
10205       assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!");
10206       #ifndef NDEBUG
10207       IsSpecial = true;
10208       #endif
10209       if (Context.getLangOpts().OpenCL)
10210         HowLong = 1;
10211       else
10212         HowLong = 2;
10213       break;
10214     }
10215   }
10216 
10217   QualType Type;
10218 
10219   // Read the base type.
10220   switch (*Str++) {
10221   default: llvm_unreachable("Unknown builtin type letter!");
10222   case 'y':
10223     assert(HowLong == 0 && !Signed && !Unsigned &&
10224            "Bad modifiers used with 'y'!");
10225     Type = Context.BFloat16Ty;
10226     break;
10227   case 'v':
10228     assert(HowLong == 0 && !Signed && !Unsigned &&
10229            "Bad modifiers used with 'v'!");
10230     Type = Context.VoidTy;
10231     break;
10232   case 'h':
10233     assert(HowLong == 0 && !Signed && !Unsigned &&
10234            "Bad modifiers used with 'h'!");
10235     Type = Context.HalfTy;
10236     break;
10237   case 'f':
10238     assert(HowLong == 0 && !Signed && !Unsigned &&
10239            "Bad modifiers used with 'f'!");
10240     Type = Context.FloatTy;
10241     break;
10242   case 'd':
10243     assert(HowLong < 3 && !Signed && !Unsigned &&
10244            "Bad modifiers used with 'd'!");
10245     if (HowLong == 1)
10246       Type = Context.LongDoubleTy;
10247     else if (HowLong == 2)
10248       Type = Context.Float128Ty;
10249     else
10250       Type = Context.DoubleTy;
10251     break;
10252   case 's':
10253     assert(HowLong == 0 && "Bad modifiers used with 's'!");
10254     if (Unsigned)
10255       Type = Context.UnsignedShortTy;
10256     else
10257       Type = Context.ShortTy;
10258     break;
10259   case 'i':
10260     if (HowLong == 3)
10261       Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
10262     else if (HowLong == 2)
10263       Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
10264     else if (HowLong == 1)
10265       Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
10266     else
10267       Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
10268     break;
10269   case 'c':
10270     assert(HowLong == 0 && "Bad modifiers used with 'c'!");
10271     if (Signed)
10272       Type = Context.SignedCharTy;
10273     else if (Unsigned)
10274       Type = Context.UnsignedCharTy;
10275     else
10276       Type = Context.CharTy;
10277     break;
10278   case 'b': // boolean
10279     assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
10280     Type = Context.BoolTy;
10281     break;
10282   case 'z':  // size_t.
10283     assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
10284     Type = Context.getSizeType();
10285     break;
10286   case 'w':  // wchar_t.
10287     assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
10288     Type = Context.getWideCharType();
10289     break;
10290   case 'F':
10291     Type = Context.getCFConstantStringType();
10292     break;
10293   case 'G':
10294     Type = Context.getObjCIdType();
10295     break;
10296   case 'H':
10297     Type = Context.getObjCSelType();
10298     break;
10299   case 'M':
10300     Type = Context.getObjCSuperType();
10301     break;
10302   case 'a':
10303     Type = Context.getBuiltinVaListType();
10304     assert(!Type.isNull() && "builtin va list type not initialized!");
10305     break;
10306   case 'A':
10307     // This is a "reference" to a va_list; however, what exactly
10308     // this means depends on how va_list is defined. There are two
10309     // different kinds of va_list: ones passed by value, and ones
10310     // passed by reference.  An example of a by-value va_list is
10311     // x86, where va_list is a char*. An example of by-ref va_list
10312     // is x86-64, where va_list is a __va_list_tag[1]. For x86,
10313     // we want this argument to be a char*&; for x86-64, we want
10314     // it to be a __va_list_tag*.
10315     Type = Context.getBuiltinVaListType();
10316     assert(!Type.isNull() && "builtin va list type not initialized!");
10317     if (Type->isArrayType())
10318       Type = Context.getArrayDecayedType(Type);
10319     else
10320       Type = Context.getLValueReferenceType(Type);
10321     break;
10322   case 'q': {
10323     char *End;
10324     unsigned NumElements = strtoul(Str, &End, 10);
10325     assert(End != Str && "Missing vector size");
10326     Str = End;
10327 
10328     QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
10329                                              RequiresICE, false);
10330     assert(!RequiresICE && "Can't require vector ICE");
10331 
10332     Type = Context.getScalableVectorType(ElementType, NumElements);
10333     break;
10334   }
10335   case 'V': {
10336     char *End;
10337     unsigned NumElements = strtoul(Str, &End, 10);
10338     assert(End != Str && "Missing vector size");
10339     Str = End;
10340 
10341     QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
10342                                              RequiresICE, false);
10343     assert(!RequiresICE && "Can't require vector ICE");
10344 
10345     // TODO: No way to make AltiVec vectors in builtins yet.
10346     Type = Context.getVectorType(ElementType, NumElements,
10347                                  VectorType::GenericVector);
10348     break;
10349   }
10350   case 'E': {
10351     char *End;
10352 
10353     unsigned NumElements = strtoul(Str, &End, 10);
10354     assert(End != Str && "Missing vector size");
10355 
10356     Str = End;
10357 
10358     QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
10359                                              false);
10360     Type = Context.getExtVectorType(ElementType, NumElements);
10361     break;
10362   }
10363   case 'X': {
10364     QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
10365                                              false);
10366     assert(!RequiresICE && "Can't require complex ICE");
10367     Type = Context.getComplexType(ElementType);
10368     break;
10369   }
10370   case 'Y':
10371     Type = Context.getPointerDiffType();
10372     break;
10373   case 'P':
10374     Type = Context.getFILEType();
10375     if (Type.isNull()) {
10376       Error = ASTContext::GE_Missing_stdio;
10377       return {};
10378     }
10379     break;
10380   case 'J':
10381     if (Signed)
10382       Type = Context.getsigjmp_bufType();
10383     else
10384       Type = Context.getjmp_bufType();
10385 
10386     if (Type.isNull()) {
10387       Error = ASTContext::GE_Missing_setjmp;
10388       return {};
10389     }
10390     break;
10391   case 'K':
10392     assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
10393     Type = Context.getucontext_tType();
10394 
10395     if (Type.isNull()) {
10396       Error = ASTContext::GE_Missing_ucontext;
10397       return {};
10398     }
10399     break;
10400   case 'p':
10401     Type = Context.getProcessIDType();
10402     break;
10403   }
10404 
10405   // If there are modifiers and if we're allowed to parse them, go for it.
10406   Done = !AllowTypeModifiers;
10407   while (!Done) {
10408     switch (char c = *Str++) {
10409     default: Done = true; --Str; break;
10410     case '*':
10411     case '&': {
10412       // Both pointers and references can have their pointee types
10413       // qualified with an address space.
10414       char *End;
10415       unsigned AddrSpace = strtoul(Str, &End, 10);
10416       if (End != Str) {
10417         // Note AddrSpace == 0 is not the same as an unspecified address space.
10418         Type = Context.getAddrSpaceQualType(
10419           Type,
10420           Context.getLangASForBuiltinAddressSpace(AddrSpace));
10421         Str = End;
10422       }
10423       if (c == '*')
10424         Type = Context.getPointerType(Type);
10425       else
10426         Type = Context.getLValueReferenceType(Type);
10427       break;
10428     }
10429     // FIXME: There's no way to have a built-in with an rvalue ref arg.
10430     case 'C':
10431       Type = Type.withConst();
10432       break;
10433     case 'D':
10434       Type = Context.getVolatileType(Type);
10435       break;
10436     case 'R':
10437       Type = Type.withRestrict();
10438       break;
10439     }
10440   }
10441 
10442   assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
10443          "Integer constant 'I' type must be an integer");
10444 
10445   return Type;
10446 }
10447 
10448 // On some targets such as PowerPC, some of the builtins are defined with custom
10449 // type decriptors for target-dependent types. These descriptors are decoded in
10450 // other functions, but it may be useful to be able to fall back to default
10451 // descriptor decoding to define builtins mixing target-dependent and target-
10452 // independent types. This function allows decoding one type descriptor with
10453 // default decoding.
10454 QualType ASTContext::DecodeTypeStr(const char *&Str, const ASTContext &Context,
10455                                    GetBuiltinTypeError &Error, bool &RequireICE,
10456                                    bool AllowTypeModifiers) const {
10457   return DecodeTypeFromStr(Str, Context, Error, RequireICE, AllowTypeModifiers);
10458 }
10459 
10460 /// GetBuiltinType - Return the type for the specified builtin.
10461 QualType ASTContext::GetBuiltinType(unsigned Id,
10462                                     GetBuiltinTypeError &Error,
10463                                     unsigned *IntegerConstantArgs) const {
10464   const char *TypeStr = BuiltinInfo.getTypeString(Id);
10465   if (TypeStr[0] == '\0') {
10466     Error = GE_Missing_type;
10467     return {};
10468   }
10469 
10470   SmallVector<QualType, 8> ArgTypes;
10471 
10472   bool RequiresICE = false;
10473   Error = GE_None;
10474   QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
10475                                        RequiresICE, true);
10476   if (Error != GE_None)
10477     return {};
10478 
10479   assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
10480 
10481   while (TypeStr[0] && TypeStr[0] != '.') {
10482     QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
10483     if (Error != GE_None)
10484       return {};
10485 
10486     // If this argument is required to be an IntegerConstantExpression and the
10487     // caller cares, fill in the bitmask we return.
10488     if (RequiresICE && IntegerConstantArgs)
10489       *IntegerConstantArgs |= 1 << ArgTypes.size();
10490 
10491     // Do array -> pointer decay.  The builtin should use the decayed type.
10492     if (Ty->isArrayType())
10493       Ty = getArrayDecayedType(Ty);
10494 
10495     ArgTypes.push_back(Ty);
10496   }
10497 
10498   if (Id == Builtin::BI__GetExceptionInfo)
10499     return {};
10500 
10501   assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
10502          "'.' should only occur at end of builtin type list!");
10503 
10504   bool Variadic = (TypeStr[0] == '.');
10505 
10506   FunctionType::ExtInfo EI(getDefaultCallingConvention(
10507       Variadic, /*IsCXXMethod=*/false, /*IsBuiltin=*/true));
10508   if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
10509 
10510 
10511   // We really shouldn't be making a no-proto type here.
10512   if (ArgTypes.empty() && Variadic && !getLangOpts().CPlusPlus)
10513     return getFunctionNoProtoType(ResType, EI);
10514 
10515   FunctionProtoType::ExtProtoInfo EPI;
10516   EPI.ExtInfo = EI;
10517   EPI.Variadic = Variadic;
10518   if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id))
10519     EPI.ExceptionSpec.Type =
10520         getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
10521 
10522   return getFunctionType(ResType, ArgTypes, EPI);
10523 }
10524 
10525 static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
10526                                              const FunctionDecl *FD) {
10527   if (!FD->isExternallyVisible())
10528     return GVA_Internal;
10529 
10530   // Non-user-provided functions get emitted as weak definitions with every
10531   // use, no matter whether they've been explicitly instantiated etc.
10532   if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
10533     if (!MD->isUserProvided())
10534       return GVA_DiscardableODR;
10535 
10536   GVALinkage External;
10537   switch (FD->getTemplateSpecializationKind()) {
10538   case TSK_Undeclared:
10539   case TSK_ExplicitSpecialization:
10540     External = GVA_StrongExternal;
10541     break;
10542 
10543   case TSK_ExplicitInstantiationDefinition:
10544     return GVA_StrongODR;
10545 
10546   // C++11 [temp.explicit]p10:
10547   //   [ Note: The intent is that an inline function that is the subject of
10548   //   an explicit instantiation declaration will still be implicitly
10549   //   instantiated when used so that the body can be considered for
10550   //   inlining, but that no out-of-line copy of the inline function would be
10551   //   generated in the translation unit. -- end note ]
10552   case TSK_ExplicitInstantiationDeclaration:
10553     return GVA_AvailableExternally;
10554 
10555   case TSK_ImplicitInstantiation:
10556     External = GVA_DiscardableODR;
10557     break;
10558   }
10559 
10560   if (!FD->isInlined())
10561     return External;
10562 
10563   if ((!Context.getLangOpts().CPlusPlus &&
10564        !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
10565        !FD->hasAttr<DLLExportAttr>()) ||
10566       FD->hasAttr<GNUInlineAttr>()) {
10567     // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
10568 
10569     // GNU or C99 inline semantics. Determine whether this symbol should be
10570     // externally visible.
10571     if (FD->isInlineDefinitionExternallyVisible())
10572       return External;
10573 
10574     // C99 inline semantics, where the symbol is not externally visible.
10575     return GVA_AvailableExternally;
10576   }
10577 
10578   // Functions specified with extern and inline in -fms-compatibility mode
10579   // forcibly get emitted.  While the body of the function cannot be later
10580   // replaced, the function definition cannot be discarded.
10581   if (FD->isMSExternInline())
10582     return GVA_StrongODR;
10583 
10584   return GVA_DiscardableODR;
10585 }
10586 
10587 static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context,
10588                                                 const Decl *D, GVALinkage L) {
10589   // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
10590   // dllexport/dllimport on inline functions.
10591   if (D->hasAttr<DLLImportAttr>()) {
10592     if (L == GVA_DiscardableODR || L == GVA_StrongODR)
10593       return GVA_AvailableExternally;
10594   } else if (D->hasAttr<DLLExportAttr>()) {
10595     if (L == GVA_DiscardableODR)
10596       return GVA_StrongODR;
10597   } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice) {
10598     // Device-side functions with __global__ attribute must always be
10599     // visible externally so they can be launched from host.
10600     if (D->hasAttr<CUDAGlobalAttr>() &&
10601         (L == GVA_DiscardableODR || L == GVA_Internal))
10602       return GVA_StrongODR;
10603     // Single source offloading languages like CUDA/HIP need to be able to
10604     // access static device variables from host code of the same compilation
10605     // unit. This is done by externalizing the static variable.
10606     if (Context.shouldExternalizeStaticVar(D))
10607       return GVA_StrongExternal;
10608   }
10609   return L;
10610 }
10611 
10612 /// Adjust the GVALinkage for a declaration based on what an external AST source
10613 /// knows about whether there can be other definitions of this declaration.
10614 static GVALinkage
10615 adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D,
10616                                           GVALinkage L) {
10617   ExternalASTSource *Source = Ctx.getExternalSource();
10618   if (!Source)
10619     return L;
10620 
10621   switch (Source->hasExternalDefinitions(D)) {
10622   case ExternalASTSource::EK_Never:
10623     // Other translation units rely on us to provide the definition.
10624     if (L == GVA_DiscardableODR)
10625       return GVA_StrongODR;
10626     break;
10627 
10628   case ExternalASTSource::EK_Always:
10629     return GVA_AvailableExternally;
10630 
10631   case ExternalASTSource::EK_ReplyHazy:
10632     break;
10633   }
10634   return L;
10635 }
10636 
10637 GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
10638   return adjustGVALinkageForExternalDefinitionKind(*this, FD,
10639            adjustGVALinkageForAttributes(*this, FD,
10640              basicGVALinkageForFunction(*this, FD)));
10641 }
10642 
10643 static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
10644                                              const VarDecl *VD) {
10645   if (!VD->isExternallyVisible())
10646     return GVA_Internal;
10647 
10648   if (VD->isStaticLocal()) {
10649     const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
10650     while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
10651       LexicalContext = LexicalContext->getLexicalParent();
10652 
10653     // ObjC Blocks can create local variables that don't have a FunctionDecl
10654     // LexicalContext.
10655     if (!LexicalContext)
10656       return GVA_DiscardableODR;
10657 
10658     // Otherwise, let the static local variable inherit its linkage from the
10659     // nearest enclosing function.
10660     auto StaticLocalLinkage =
10661         Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
10662 
10663     // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
10664     // be emitted in any object with references to the symbol for the object it
10665     // contains, whether inline or out-of-line."
10666     // Similar behavior is observed with MSVC. An alternative ABI could use
10667     // StrongODR/AvailableExternally to match the function, but none are
10668     // known/supported currently.
10669     if (StaticLocalLinkage == GVA_StrongODR ||
10670         StaticLocalLinkage == GVA_AvailableExternally)
10671       return GVA_DiscardableODR;
10672     return StaticLocalLinkage;
10673   }
10674 
10675   // MSVC treats in-class initialized static data members as definitions.
10676   // By giving them non-strong linkage, out-of-line definitions won't
10677   // cause link errors.
10678   if (Context.isMSStaticDataMemberInlineDefinition(VD))
10679     return GVA_DiscardableODR;
10680 
10681   // Most non-template variables have strong linkage; inline variables are
10682   // linkonce_odr or (occasionally, for compatibility) weak_odr.
10683   GVALinkage StrongLinkage;
10684   switch (Context.getInlineVariableDefinitionKind(VD)) {
10685   case ASTContext::InlineVariableDefinitionKind::None:
10686     StrongLinkage = GVA_StrongExternal;
10687     break;
10688   case ASTContext::InlineVariableDefinitionKind::Weak:
10689   case ASTContext::InlineVariableDefinitionKind::WeakUnknown:
10690     StrongLinkage = GVA_DiscardableODR;
10691     break;
10692   case ASTContext::InlineVariableDefinitionKind::Strong:
10693     StrongLinkage = GVA_StrongODR;
10694     break;
10695   }
10696 
10697   switch (VD->getTemplateSpecializationKind()) {
10698   case TSK_Undeclared:
10699     return StrongLinkage;
10700 
10701   case TSK_ExplicitSpecialization:
10702     return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
10703                    VD->isStaticDataMember()
10704                ? GVA_StrongODR
10705                : StrongLinkage;
10706 
10707   case TSK_ExplicitInstantiationDefinition:
10708     return GVA_StrongODR;
10709 
10710   case TSK_ExplicitInstantiationDeclaration:
10711     return GVA_AvailableExternally;
10712 
10713   case TSK_ImplicitInstantiation:
10714     return GVA_DiscardableODR;
10715   }
10716 
10717   llvm_unreachable("Invalid Linkage!");
10718 }
10719 
10720 GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
10721   return adjustGVALinkageForExternalDefinitionKind(*this, VD,
10722            adjustGVALinkageForAttributes(*this, VD,
10723              basicGVALinkageForVariable(*this, VD)));
10724 }
10725 
10726 bool ASTContext::DeclMustBeEmitted(const Decl *D) {
10727   if (const auto *VD = dyn_cast<VarDecl>(D)) {
10728     if (!VD->isFileVarDecl())
10729       return false;
10730     // Global named register variables (GNU extension) are never emitted.
10731     if (VD->getStorageClass() == SC_Register)
10732       return false;
10733     if (VD->getDescribedVarTemplate() ||
10734         isa<VarTemplatePartialSpecializationDecl>(VD))
10735       return false;
10736   } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
10737     // We never need to emit an uninstantiated function template.
10738     if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
10739       return false;
10740   } else if (isa<PragmaCommentDecl>(D))
10741     return true;
10742   else if (isa<PragmaDetectMismatchDecl>(D))
10743     return true;
10744   else if (isa<OMPRequiresDecl>(D))
10745     return true;
10746   else if (isa<OMPThreadPrivateDecl>(D))
10747     return !D->getDeclContext()->isDependentContext();
10748   else if (isa<OMPAllocateDecl>(D))
10749     return !D->getDeclContext()->isDependentContext();
10750   else if (isa<OMPDeclareReductionDecl>(D) || isa<OMPDeclareMapperDecl>(D))
10751     return !D->getDeclContext()->isDependentContext();
10752   else if (isa<ImportDecl>(D))
10753     return true;
10754   else
10755     return false;
10756 
10757   // If this is a member of a class template, we do not need to emit it.
10758   if (D->getDeclContext()->isDependentContext())
10759     return false;
10760 
10761   // Weak references don't produce any output by themselves.
10762   if (D->hasAttr<WeakRefAttr>())
10763     return false;
10764 
10765   // Aliases and used decls are required.
10766   if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
10767     return true;
10768 
10769   if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
10770     // Forward declarations aren't required.
10771     if (!FD->doesThisDeclarationHaveABody())
10772       return FD->doesDeclarationForceExternallyVisibleDefinition();
10773 
10774     // Constructors and destructors are required.
10775     if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
10776       return true;
10777 
10778     // The key function for a class is required.  This rule only comes
10779     // into play when inline functions can be key functions, though.
10780     if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
10781       if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
10782         const CXXRecordDecl *RD = MD->getParent();
10783         if (MD->isOutOfLine() && RD->isDynamicClass()) {
10784           const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
10785           if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
10786             return true;
10787         }
10788       }
10789     }
10790 
10791     GVALinkage Linkage = GetGVALinkageForFunction(FD);
10792 
10793     // static, static inline, always_inline, and extern inline functions can
10794     // always be deferred.  Normal inline functions can be deferred in C99/C++.
10795     // Implicit template instantiations can also be deferred in C++.
10796     return !isDiscardableGVALinkage(Linkage);
10797   }
10798 
10799   const auto *VD = cast<VarDecl>(D);
10800   assert(VD->isFileVarDecl() && "Expected file scoped var");
10801 
10802   // If the decl is marked as `declare target to`, it should be emitted for the
10803   // host and for the device.
10804   if (LangOpts.OpenMP &&
10805       OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
10806     return true;
10807 
10808   if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
10809       !isMSStaticDataMemberInlineDefinition(VD))
10810     return false;
10811 
10812   // Variables that can be needed in other TUs are required.
10813   auto Linkage = GetGVALinkageForVariable(VD);
10814   if (!isDiscardableGVALinkage(Linkage))
10815     return true;
10816 
10817   // We never need to emit a variable that is available in another TU.
10818   if (Linkage == GVA_AvailableExternally)
10819     return false;
10820 
10821   // Variables that have destruction with side-effects are required.
10822   if (VD->needsDestruction(*this))
10823     return true;
10824 
10825   // Variables that have initialization with side-effects are required.
10826   if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
10827       // We can get a value-dependent initializer during error recovery.
10828       (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
10829     return true;
10830 
10831   // Likewise, variables with tuple-like bindings are required if their
10832   // bindings have side-effects.
10833   if (const auto *DD = dyn_cast<DecompositionDecl>(VD))
10834     for (const auto *BD : DD->bindings())
10835       if (const auto *BindingVD = BD->getHoldingVar())
10836         if (DeclMustBeEmitted(BindingVD))
10837           return true;
10838 
10839   return false;
10840 }
10841 
10842 void ASTContext::forEachMultiversionedFunctionVersion(
10843     const FunctionDecl *FD,
10844     llvm::function_ref<void(FunctionDecl *)> Pred) const {
10845   assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
10846   llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
10847   FD = FD->getMostRecentDecl();
10848   for (auto *CurDecl :
10849        FD->getDeclContext()->getRedeclContext()->lookup(FD->getDeclName())) {
10850     FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl();
10851     if (CurFD && hasSameType(CurFD->getType(), FD->getType()) &&
10852         std::end(SeenDecls) == llvm::find(SeenDecls, CurFD)) {
10853       SeenDecls.insert(CurFD);
10854       Pred(CurFD);
10855     }
10856   }
10857 }
10858 
10859 CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
10860                                                     bool IsCXXMethod,
10861                                                     bool IsBuiltin) const {
10862   // Pass through to the C++ ABI object
10863   if (IsCXXMethod)
10864     return ABI->getDefaultMethodCallConv(IsVariadic);
10865 
10866   // Builtins ignore user-specified default calling convention and remain the
10867   // Target's default calling convention.
10868   if (!IsBuiltin) {
10869     switch (LangOpts.getDefaultCallingConv()) {
10870     case LangOptions::DCC_None:
10871       break;
10872     case LangOptions::DCC_CDecl:
10873       return CC_C;
10874     case LangOptions::DCC_FastCall:
10875       if (getTargetInfo().hasFeature("sse2") && !IsVariadic)
10876         return CC_X86FastCall;
10877       break;
10878     case LangOptions::DCC_StdCall:
10879       if (!IsVariadic)
10880         return CC_X86StdCall;
10881       break;
10882     case LangOptions::DCC_VectorCall:
10883       // __vectorcall cannot be applied to variadic functions.
10884       if (!IsVariadic)
10885         return CC_X86VectorCall;
10886       break;
10887     case LangOptions::DCC_RegCall:
10888       // __regcall cannot be applied to variadic functions.
10889       if (!IsVariadic)
10890         return CC_X86RegCall;
10891       break;
10892     }
10893   }
10894   return Target->getDefaultCallingConv();
10895 }
10896 
10897 bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
10898   // Pass through to the C++ ABI object
10899   return ABI->isNearlyEmpty(RD);
10900 }
10901 
10902 VTableContextBase *ASTContext::getVTableContext() {
10903   if (!VTContext.get()) {
10904     auto ABI = Target->getCXXABI();
10905     if (ABI.isMicrosoft())
10906       VTContext.reset(new MicrosoftVTableContext(*this));
10907     else {
10908       auto ComponentLayout = getLangOpts().RelativeCXXABIVTables
10909                                  ? ItaniumVTableContext::Relative
10910                                  : ItaniumVTableContext::Pointer;
10911       VTContext.reset(new ItaniumVTableContext(*this, ComponentLayout));
10912     }
10913   }
10914   return VTContext.get();
10915 }
10916 
10917 MangleContext *ASTContext::createMangleContext(const TargetInfo *T) {
10918   if (!T)
10919     T = Target;
10920   switch (T->getCXXABI().getKind()) {
10921   case TargetCXXABI::AppleARM64:
10922   case TargetCXXABI::Fuchsia:
10923   case TargetCXXABI::GenericAArch64:
10924   case TargetCXXABI::GenericItanium:
10925   case TargetCXXABI::GenericARM:
10926   case TargetCXXABI::GenericMIPS:
10927   case TargetCXXABI::iOS:
10928   case TargetCXXABI::WebAssembly:
10929   case TargetCXXABI::WatchOS:
10930   case TargetCXXABI::XL:
10931     return ItaniumMangleContext::create(*this, getDiagnostics());
10932   case TargetCXXABI::Microsoft:
10933     return MicrosoftMangleContext::create(*this, getDiagnostics());
10934   }
10935   llvm_unreachable("Unsupported ABI");
10936 }
10937 
10938 CXXABI::~CXXABI() = default;
10939 
10940 size_t ASTContext::getSideTableAllocatedMemory() const {
10941   return ASTRecordLayouts.getMemorySize() +
10942          llvm::capacity_in_bytes(ObjCLayouts) +
10943          llvm::capacity_in_bytes(KeyFunctions) +
10944          llvm::capacity_in_bytes(ObjCImpls) +
10945          llvm::capacity_in_bytes(BlockVarCopyInits) +
10946          llvm::capacity_in_bytes(DeclAttrs) +
10947          llvm::capacity_in_bytes(TemplateOrInstantiation) +
10948          llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
10949          llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
10950          llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
10951          llvm::capacity_in_bytes(OverriddenMethods) +
10952          llvm::capacity_in_bytes(Types) +
10953          llvm::capacity_in_bytes(VariableArrayTypes);
10954 }
10955 
10956 /// getIntTypeForBitwidth -
10957 /// sets integer QualTy according to specified details:
10958 /// bitwidth, signed/unsigned.
10959 /// Returns empty type if there is no appropriate target types.
10960 QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
10961                                            unsigned Signed) const {
10962   TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
10963   CanQualType QualTy = getFromTargetType(Ty);
10964   if (!QualTy && DestWidth == 128)
10965     return Signed ? Int128Ty : UnsignedInt128Ty;
10966   return QualTy;
10967 }
10968 
10969 /// getRealTypeForBitwidth -
10970 /// sets floating point QualTy according to specified bitwidth.
10971 /// Returns empty type if there is no appropriate target types.
10972 QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth,
10973                                             bool ExplicitIEEE) const {
10974   TargetInfo::RealType Ty =
10975       getTargetInfo().getRealTypeByWidth(DestWidth, ExplicitIEEE);
10976   switch (Ty) {
10977   case TargetInfo::Float:
10978     return FloatTy;
10979   case TargetInfo::Double:
10980     return DoubleTy;
10981   case TargetInfo::LongDouble:
10982     return LongDoubleTy;
10983   case TargetInfo::Float128:
10984     return Float128Ty;
10985   case TargetInfo::NoFloat:
10986     return {};
10987   }
10988 
10989   llvm_unreachable("Unhandled TargetInfo::RealType value");
10990 }
10991 
10992 void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
10993   if (Number > 1)
10994     MangleNumbers[ND] = Number;
10995 }
10996 
10997 unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
10998   auto I = MangleNumbers.find(ND);
10999   return I != MangleNumbers.end() ? I->second : 1;
11000 }
11001 
11002 void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
11003   if (Number > 1)
11004     StaticLocalNumbers[VD] = Number;
11005 }
11006 
11007 unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
11008   auto I = StaticLocalNumbers.find(VD);
11009   return I != StaticLocalNumbers.end() ? I->second : 1;
11010 }
11011 
11012 MangleNumberingContext &
11013 ASTContext::getManglingNumberContext(const DeclContext *DC) {
11014   assert(LangOpts.CPlusPlus);  // We don't need mangling numbers for plain C.
11015   std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
11016   if (!MCtx)
11017     MCtx = createMangleNumberingContext();
11018   return *MCtx;
11019 }
11020 
11021 MangleNumberingContext &
11022 ASTContext::getManglingNumberContext(NeedExtraManglingDecl_t, const Decl *D) {
11023   assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
11024   std::unique_ptr<MangleNumberingContext> &MCtx =
11025       ExtraMangleNumberingContexts[D];
11026   if (!MCtx)
11027     MCtx = createMangleNumberingContext();
11028   return *MCtx;
11029 }
11030 
11031 std::unique_ptr<MangleNumberingContext>
11032 ASTContext::createMangleNumberingContext() const {
11033   return ABI->createMangleNumberingContext();
11034 }
11035 
11036 const CXXConstructorDecl *
11037 ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
11038   return ABI->getCopyConstructorForExceptionObject(
11039       cast<CXXRecordDecl>(RD->getFirstDecl()));
11040 }
11041 
11042 void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
11043                                                       CXXConstructorDecl *CD) {
11044   return ABI->addCopyConstructorForExceptionObject(
11045       cast<CXXRecordDecl>(RD->getFirstDecl()),
11046       cast<CXXConstructorDecl>(CD->getFirstDecl()));
11047 }
11048 
11049 void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
11050                                                  TypedefNameDecl *DD) {
11051   return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
11052 }
11053 
11054 TypedefNameDecl *
11055 ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
11056   return ABI->getTypedefNameForUnnamedTagDecl(TD);
11057 }
11058 
11059 void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
11060                                                 DeclaratorDecl *DD) {
11061   return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
11062 }
11063 
11064 DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
11065   return ABI->getDeclaratorForUnnamedTagDecl(TD);
11066 }
11067 
11068 void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
11069   ParamIndices[D] = index;
11070 }
11071 
11072 unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
11073   ParameterIndexTable::const_iterator I = ParamIndices.find(D);
11074   assert(I != ParamIndices.end() &&
11075          "ParmIndices lacks entry set by ParmVarDecl");
11076   return I->second;
11077 }
11078 
11079 QualType ASTContext::getStringLiteralArrayType(QualType EltTy,
11080                                                unsigned Length) const {
11081   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
11082   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
11083     EltTy = EltTy.withConst();
11084 
11085   EltTy = adjustStringLiteralBaseType(EltTy);
11086 
11087   // Get an array type for the string, according to C99 6.4.5. This includes
11088   // the null terminator character.
11089   return getConstantArrayType(EltTy, llvm::APInt(32, Length + 1), nullptr,
11090                               ArrayType::Normal, /*IndexTypeQuals*/ 0);
11091 }
11092 
11093 StringLiteral *
11094 ASTContext::getPredefinedStringLiteralFromCache(StringRef Key) const {
11095   StringLiteral *&Result = StringLiteralCache[Key];
11096   if (!Result)
11097     Result = StringLiteral::Create(
11098         *this, Key, StringLiteral::Ascii,
11099         /*Pascal*/ false, getStringLiteralArrayType(CharTy, Key.size()),
11100         SourceLocation());
11101   return Result;
11102 }
11103 
11104 MSGuidDecl *
11105 ASTContext::getMSGuidDecl(MSGuidDecl::Parts Parts) const {
11106   assert(MSGuidTagDecl && "building MS GUID without MS extensions?");
11107 
11108   llvm::FoldingSetNodeID ID;
11109   MSGuidDecl::Profile(ID, Parts);
11110 
11111   void *InsertPos;
11112   if (MSGuidDecl *Existing = MSGuidDecls.FindNodeOrInsertPos(ID, InsertPos))
11113     return Existing;
11114 
11115   QualType GUIDType = getMSGuidType().withConst();
11116   MSGuidDecl *New = MSGuidDecl::Create(*this, GUIDType, Parts);
11117   MSGuidDecls.InsertNode(New, InsertPos);
11118   return New;
11119 }
11120 
11121 TemplateParamObjectDecl *
11122 ASTContext::getTemplateParamObjectDecl(QualType T, const APValue &V) const {
11123   assert(T->isRecordType() && "template param object of unexpected type");
11124 
11125   // C++ [temp.param]p8:
11126   //   [...] a static storage duration object of type 'const T' [...]
11127   T.addConst();
11128 
11129   llvm::FoldingSetNodeID ID;
11130   TemplateParamObjectDecl::Profile(ID, T, V);
11131 
11132   void *InsertPos;
11133   if (TemplateParamObjectDecl *Existing =
11134           TemplateParamObjectDecls.FindNodeOrInsertPos(ID, InsertPos))
11135     return Existing;
11136 
11137   TemplateParamObjectDecl *New = TemplateParamObjectDecl::Create(*this, T, V);
11138   TemplateParamObjectDecls.InsertNode(New, InsertPos);
11139   return New;
11140 }
11141 
11142 bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
11143   const llvm::Triple &T = getTargetInfo().getTriple();
11144   if (!T.isOSDarwin())
11145     return false;
11146 
11147   if (!(T.isiOS() && T.isOSVersionLT(7)) &&
11148       !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
11149     return false;
11150 
11151   QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
11152   CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
11153   uint64_t Size = sizeChars.getQuantity();
11154   CharUnits alignChars = getTypeAlignInChars(AtomicTy);
11155   unsigned Align = alignChars.getQuantity();
11156   unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
11157   return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
11158 }
11159 
11160 bool
11161 ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
11162                                 const ObjCMethodDecl *MethodImpl) {
11163   // No point trying to match an unavailable/deprecated mothod.
11164   if (MethodDecl->hasAttr<UnavailableAttr>()
11165       || MethodDecl->hasAttr<DeprecatedAttr>())
11166     return false;
11167   if (MethodDecl->getObjCDeclQualifier() !=
11168       MethodImpl->getObjCDeclQualifier())
11169     return false;
11170   if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
11171     return false;
11172 
11173   if (MethodDecl->param_size() != MethodImpl->param_size())
11174     return false;
11175 
11176   for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
11177        IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
11178        EF = MethodDecl->param_end();
11179        IM != EM && IF != EF; ++IM, ++IF) {
11180     const ParmVarDecl *DeclVar = (*IF);
11181     const ParmVarDecl *ImplVar = (*IM);
11182     if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
11183       return false;
11184     if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
11185       return false;
11186   }
11187 
11188   return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
11189 }
11190 
11191 uint64_t ASTContext::getTargetNullPointerValue(QualType QT) const {
11192   LangAS AS;
11193   if (QT->getUnqualifiedDesugaredType()->isNullPtrType())
11194     AS = LangAS::Default;
11195   else
11196     AS = QT->getPointeeType().getAddressSpace();
11197 
11198   return getTargetInfo().getNullPointerValue(AS);
11199 }
11200 
11201 unsigned ASTContext::getTargetAddressSpace(LangAS AS) const {
11202   if (isTargetAddressSpace(AS))
11203     return toTargetAddressSpace(AS);
11204   else
11205     return (*AddrSpaceMap)[(unsigned)AS];
11206 }
11207 
11208 QualType ASTContext::getCorrespondingSaturatedType(QualType Ty) const {
11209   assert(Ty->isFixedPointType());
11210 
11211   if (Ty->isSaturatedFixedPointType()) return Ty;
11212 
11213   switch (Ty->castAs<BuiltinType>()->getKind()) {
11214     default:
11215       llvm_unreachable("Not a fixed point type!");
11216     case BuiltinType::ShortAccum:
11217       return SatShortAccumTy;
11218     case BuiltinType::Accum:
11219       return SatAccumTy;
11220     case BuiltinType::LongAccum:
11221       return SatLongAccumTy;
11222     case BuiltinType::UShortAccum:
11223       return SatUnsignedShortAccumTy;
11224     case BuiltinType::UAccum:
11225       return SatUnsignedAccumTy;
11226     case BuiltinType::ULongAccum:
11227       return SatUnsignedLongAccumTy;
11228     case BuiltinType::ShortFract:
11229       return SatShortFractTy;
11230     case BuiltinType::Fract:
11231       return SatFractTy;
11232     case BuiltinType::LongFract:
11233       return SatLongFractTy;
11234     case BuiltinType::UShortFract:
11235       return SatUnsignedShortFractTy;
11236     case BuiltinType::UFract:
11237       return SatUnsignedFractTy;
11238     case BuiltinType::ULongFract:
11239       return SatUnsignedLongFractTy;
11240   }
11241 }
11242 
11243 LangAS ASTContext::getLangASForBuiltinAddressSpace(unsigned AS) const {
11244   if (LangOpts.OpenCL)
11245     return getTargetInfo().getOpenCLBuiltinAddressSpace(AS);
11246 
11247   if (LangOpts.CUDA)
11248     return getTargetInfo().getCUDABuiltinAddressSpace(AS);
11249 
11250   return getLangASFromTargetAS(AS);
11251 }
11252 
11253 // Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
11254 // doesn't include ASTContext.h
11255 template
11256 clang::LazyGenerationalUpdatePtr<
11257     const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
11258 clang::LazyGenerationalUpdatePtr<
11259     const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
11260         const clang::ASTContext &Ctx, Decl *Value);
11261 
11262 unsigned char ASTContext::getFixedPointScale(QualType Ty) const {
11263   assert(Ty->isFixedPointType());
11264 
11265   const TargetInfo &Target = getTargetInfo();
11266   switch (Ty->castAs<BuiltinType>()->getKind()) {
11267     default:
11268       llvm_unreachable("Not a fixed point type!");
11269     case BuiltinType::ShortAccum:
11270     case BuiltinType::SatShortAccum:
11271       return Target.getShortAccumScale();
11272     case BuiltinType::Accum:
11273     case BuiltinType::SatAccum:
11274       return Target.getAccumScale();
11275     case BuiltinType::LongAccum:
11276     case BuiltinType::SatLongAccum:
11277       return Target.getLongAccumScale();
11278     case BuiltinType::UShortAccum:
11279     case BuiltinType::SatUShortAccum:
11280       return Target.getUnsignedShortAccumScale();
11281     case BuiltinType::UAccum:
11282     case BuiltinType::SatUAccum:
11283       return Target.getUnsignedAccumScale();
11284     case BuiltinType::ULongAccum:
11285     case BuiltinType::SatULongAccum:
11286       return Target.getUnsignedLongAccumScale();
11287     case BuiltinType::ShortFract:
11288     case BuiltinType::SatShortFract:
11289       return Target.getShortFractScale();
11290     case BuiltinType::Fract:
11291     case BuiltinType::SatFract:
11292       return Target.getFractScale();
11293     case BuiltinType::LongFract:
11294     case BuiltinType::SatLongFract:
11295       return Target.getLongFractScale();
11296     case BuiltinType::UShortFract:
11297     case BuiltinType::SatUShortFract:
11298       return Target.getUnsignedShortFractScale();
11299     case BuiltinType::UFract:
11300     case BuiltinType::SatUFract:
11301       return Target.getUnsignedFractScale();
11302     case BuiltinType::ULongFract:
11303     case BuiltinType::SatULongFract:
11304       return Target.getUnsignedLongFractScale();
11305   }
11306 }
11307 
11308 unsigned char ASTContext::getFixedPointIBits(QualType Ty) const {
11309   assert(Ty->isFixedPointType());
11310 
11311   const TargetInfo &Target = getTargetInfo();
11312   switch (Ty->castAs<BuiltinType>()->getKind()) {
11313     default:
11314       llvm_unreachable("Not a fixed point type!");
11315     case BuiltinType::ShortAccum:
11316     case BuiltinType::SatShortAccum:
11317       return Target.getShortAccumIBits();
11318     case BuiltinType::Accum:
11319     case BuiltinType::SatAccum:
11320       return Target.getAccumIBits();
11321     case BuiltinType::LongAccum:
11322     case BuiltinType::SatLongAccum:
11323       return Target.getLongAccumIBits();
11324     case BuiltinType::UShortAccum:
11325     case BuiltinType::SatUShortAccum:
11326       return Target.getUnsignedShortAccumIBits();
11327     case BuiltinType::UAccum:
11328     case BuiltinType::SatUAccum:
11329       return Target.getUnsignedAccumIBits();
11330     case BuiltinType::ULongAccum:
11331     case BuiltinType::SatULongAccum:
11332       return Target.getUnsignedLongAccumIBits();
11333     case BuiltinType::ShortFract:
11334     case BuiltinType::SatShortFract:
11335     case BuiltinType::Fract:
11336     case BuiltinType::SatFract:
11337     case BuiltinType::LongFract:
11338     case BuiltinType::SatLongFract:
11339     case BuiltinType::UShortFract:
11340     case BuiltinType::SatUShortFract:
11341     case BuiltinType::UFract:
11342     case BuiltinType::SatUFract:
11343     case BuiltinType::ULongFract:
11344     case BuiltinType::SatULongFract:
11345       return 0;
11346   }
11347 }
11348 
11349 llvm::FixedPointSemantics
11350 ASTContext::getFixedPointSemantics(QualType Ty) const {
11351   assert((Ty->isFixedPointType() || Ty->isIntegerType()) &&
11352          "Can only get the fixed point semantics for a "
11353          "fixed point or integer type.");
11354   if (Ty->isIntegerType())
11355     return llvm::FixedPointSemantics::GetIntegerSemantics(
11356         getIntWidth(Ty), Ty->isSignedIntegerType());
11357 
11358   bool isSigned = Ty->isSignedFixedPointType();
11359   return llvm::FixedPointSemantics(
11360       static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned,
11361       Ty->isSaturatedFixedPointType(),
11362       !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding());
11363 }
11364 
11365 llvm::APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const {
11366   assert(Ty->isFixedPointType());
11367   return llvm::APFixedPoint::getMax(getFixedPointSemantics(Ty));
11368 }
11369 
11370 llvm::APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const {
11371   assert(Ty->isFixedPointType());
11372   return llvm::APFixedPoint::getMin(getFixedPointSemantics(Ty));
11373 }
11374 
11375 QualType ASTContext::getCorrespondingSignedFixedPointType(QualType Ty) const {
11376   assert(Ty->isUnsignedFixedPointType() &&
11377          "Expected unsigned fixed point type");
11378 
11379   switch (Ty->castAs<BuiltinType>()->getKind()) {
11380   case BuiltinType::UShortAccum:
11381     return ShortAccumTy;
11382   case BuiltinType::UAccum:
11383     return AccumTy;
11384   case BuiltinType::ULongAccum:
11385     return LongAccumTy;
11386   case BuiltinType::SatUShortAccum:
11387     return SatShortAccumTy;
11388   case BuiltinType::SatUAccum:
11389     return SatAccumTy;
11390   case BuiltinType::SatULongAccum:
11391     return SatLongAccumTy;
11392   case BuiltinType::UShortFract:
11393     return ShortFractTy;
11394   case BuiltinType::UFract:
11395     return FractTy;
11396   case BuiltinType::ULongFract:
11397     return LongFractTy;
11398   case BuiltinType::SatUShortFract:
11399     return SatShortFractTy;
11400   case BuiltinType::SatUFract:
11401     return SatFractTy;
11402   case BuiltinType::SatULongFract:
11403     return SatLongFractTy;
11404   default:
11405     llvm_unreachable("Unexpected unsigned fixed point type");
11406   }
11407 }
11408 
11409 ParsedTargetAttr
11410 ASTContext::filterFunctionTargetAttrs(const TargetAttr *TD) const {
11411   assert(TD != nullptr);
11412   ParsedTargetAttr ParsedAttr = TD->parse();
11413 
11414   ParsedAttr.Features.erase(
11415       llvm::remove_if(ParsedAttr.Features,
11416                       [&](const std::string &Feat) {
11417                         return !Target->isValidFeatureName(
11418                             StringRef{Feat}.substr(1));
11419                       }),
11420       ParsedAttr.Features.end());
11421   return ParsedAttr;
11422 }
11423 
11424 void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
11425                                        const FunctionDecl *FD) const {
11426   if (FD)
11427     getFunctionFeatureMap(FeatureMap, GlobalDecl().getWithDecl(FD));
11428   else
11429     Target->initFeatureMap(FeatureMap, getDiagnostics(),
11430                            Target->getTargetOpts().CPU,
11431                            Target->getTargetOpts().Features);
11432 }
11433 
11434 // Fills in the supplied string map with the set of target features for the
11435 // passed in function.
11436 void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
11437                                        GlobalDecl GD) const {
11438   StringRef TargetCPU = Target->getTargetOpts().CPU;
11439   const FunctionDecl *FD = GD.getDecl()->getAsFunction();
11440   if (const auto *TD = FD->getAttr<TargetAttr>()) {
11441     ParsedTargetAttr ParsedAttr = filterFunctionTargetAttrs(TD);
11442 
11443     // Make a copy of the features as passed on the command line into the
11444     // beginning of the additional features from the function to override.
11445     ParsedAttr.Features.insert(
11446         ParsedAttr.Features.begin(),
11447         Target->getTargetOpts().FeaturesAsWritten.begin(),
11448         Target->getTargetOpts().FeaturesAsWritten.end());
11449 
11450     if (ParsedAttr.Architecture != "" &&
11451         Target->isValidCPUName(ParsedAttr.Architecture))
11452       TargetCPU = ParsedAttr.Architecture;
11453 
11454     // Now populate the feature map, first with the TargetCPU which is either
11455     // the default or a new one from the target attribute string. Then we'll use
11456     // the passed in features (FeaturesAsWritten) along with the new ones from
11457     // the attribute.
11458     Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU,
11459                            ParsedAttr.Features);
11460   } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) {
11461     llvm::SmallVector<StringRef, 32> FeaturesTmp;
11462     Target->getCPUSpecificCPUDispatchFeatures(
11463         SD->getCPUName(GD.getMultiVersionIndex())->getName(), FeaturesTmp);
11464     std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end());
11465     Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
11466   } else {
11467     FeatureMap = Target->getTargetOpts().FeatureMap;
11468   }
11469 }
11470 
11471 OMPTraitInfo &ASTContext::getNewOMPTraitInfo() {
11472   OMPTraitInfoVector.emplace_back(new OMPTraitInfo());
11473   return *OMPTraitInfoVector.back();
11474 }
11475 
11476 const StreamingDiagnostic &clang::
11477 operator<<(const StreamingDiagnostic &DB,
11478            const ASTContext::SectionInfo &Section) {
11479   if (Section.Decl)
11480     return DB << Section.Decl;
11481   return DB << "a prior #pragma section";
11482 }
11483 
11484 bool ASTContext::mayExternalizeStaticVar(const Decl *D) const {
11485   bool IsStaticVar =
11486       isa<VarDecl>(D) && cast<VarDecl>(D)->getStorageClass() == SC_Static;
11487   bool IsExplicitDeviceVar = (D->hasAttr<CUDADeviceAttr>() &&
11488                               !D->getAttr<CUDADeviceAttr>()->isImplicit()) ||
11489                              (D->hasAttr<CUDAConstantAttr>() &&
11490                               !D->getAttr<CUDAConstantAttr>()->isImplicit());
11491   // CUDA/HIP: static managed variables need to be externalized since it is
11492   // a declaration in IR, therefore cannot have internal linkage.
11493   // ToDo: externalize static variables for -fgpu-rdc.
11494   return IsStaticVar &&
11495          (D->hasAttr<HIPManagedAttr>() ||
11496           (!getLangOpts().GPURelocatableDeviceCode && IsExplicitDeviceVar));
11497 }
11498 
11499 bool ASTContext::shouldExternalizeStaticVar(const Decl *D) const {
11500   return mayExternalizeStaticVar(D) &&
11501          (D->hasAttr<HIPManagedAttr>() ||
11502           CUDAStaticDeviceVarReferencedByHost.count(cast<VarDecl>(D)));
11503 }
11504