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/NoSanitizeList.h"
60 #include "clang/Basic/ObjCRuntime.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/MD5.h"
88 #include "llvm/Support/MathExtras.h"
89 #include "llvm/Support/raw_ostream.h"
90 #include <algorithm>
91 #include <cassert>
92 #include <cstddef>
93 #include <cstdint>
94 #include <cstdlib>
95 #include <map>
96 #include <memory>
97 #include <string>
98 #include <tuple>
99 #include <utility>
100 
101 using namespace clang;
102 
103 enum FloatingRank {
104   BFloat16Rank, Float16Rank, HalfRank, FloatRank, DoubleRank, LongDoubleRank, Float128Rank
105 };
106 
107 /// \returns location that is relevant when searching for Doc comments related
108 /// to \p D.
109 static SourceLocation getDeclLocForCommentSearch(const Decl *D,
110                                                  SourceManager &SourceMgr) {
111   assert(D);
112 
113   // User can not attach documentation to implicit declarations.
114   if (D->isImplicit())
115     return {};
116 
117   // User can not attach documentation to implicit instantiations.
118   if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
119     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
120       return {};
121   }
122 
123   if (const auto *VD = dyn_cast<VarDecl>(D)) {
124     if (VD->isStaticDataMember() &&
125         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
126       return {};
127   }
128 
129   if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) {
130     if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
131       return {};
132   }
133 
134   if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
135     TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
136     if (TSK == TSK_ImplicitInstantiation ||
137         TSK == TSK_Undeclared)
138       return {};
139   }
140 
141   if (const auto *ED = dyn_cast<EnumDecl>(D)) {
142     if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
143       return {};
144   }
145   if (const auto *TD = dyn_cast<TagDecl>(D)) {
146     // When tag declaration (but not definition!) is part of the
147     // decl-specifier-seq of some other declaration, it doesn't get comment
148     if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
149       return {};
150   }
151   // TODO: handle comments for function parameters properly.
152   if (isa<ParmVarDecl>(D))
153     return {};
154 
155   // TODO: we could look up template parameter documentation in the template
156   // documentation.
157   if (isa<TemplateTypeParmDecl>(D) ||
158       isa<NonTypeTemplateParmDecl>(D) ||
159       isa<TemplateTemplateParmDecl>(D))
160     return {};
161 
162   // Find declaration location.
163   // For Objective-C declarations we generally don't expect to have multiple
164   // declarators, thus use declaration starting location as the "declaration
165   // location".
166   // For all other declarations multiple declarators are used quite frequently,
167   // so we use the location of the identifier as the "declaration location".
168   if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
169       isa<ObjCPropertyDecl>(D) ||
170       isa<RedeclarableTemplateDecl>(D) ||
171       isa<ClassTemplateSpecializationDecl>(D) ||
172       // Allow association with Y across {} in `typedef struct X {} Y`.
173       isa<TypedefDecl>(D))
174     return D->getBeginLoc();
175   else {
176     const SourceLocation DeclLoc = D->getLocation();
177     if (DeclLoc.isMacroID()) {
178       if (isa<TypedefDecl>(D)) {
179         // If location of the typedef name is in a macro, it is because being
180         // declared via a macro. Try using declaration's starting location as
181         // the "declaration location".
182         return D->getBeginLoc();
183       } else if (const auto *TD = dyn_cast<TagDecl>(D)) {
184         // If location of the tag decl is inside a macro, but the spelling of
185         // the tag name comes from a macro argument, it looks like a special
186         // macro like NS_ENUM is being used to define the tag decl.  In that
187         // case, adjust the source location to the expansion loc so that we can
188         // attach the comment to the tag decl.
189         if (SourceMgr.isMacroArgExpansion(DeclLoc) &&
190             TD->isCompleteDefinition())
191           return SourceMgr.getExpansionLoc(DeclLoc);
192       }
193     }
194     return DeclLoc;
195   }
196 
197   return {};
198 }
199 
200 RawComment *ASTContext::getRawCommentForDeclNoCacheImpl(
201     const Decl *D, const SourceLocation RepresentativeLocForDecl,
202     const std::map<unsigned, RawComment *> &CommentsInTheFile) const {
203   // If the declaration doesn't map directly to a location in a file, we
204   // can't find the comment.
205   if (RepresentativeLocForDecl.isInvalid() ||
206       !RepresentativeLocForDecl.isFileID())
207     return nullptr;
208 
209   // If there are no comments anywhere, we won't find anything.
210   if (CommentsInTheFile.empty())
211     return nullptr;
212 
213   // Decompose the location for the declaration and find the beginning of the
214   // file buffer.
215   const std::pair<FileID, unsigned> DeclLocDecomp =
216       SourceMgr.getDecomposedLoc(RepresentativeLocForDecl);
217 
218   // Slow path.
219   auto OffsetCommentBehindDecl =
220       CommentsInTheFile.lower_bound(DeclLocDecomp.second);
221 
222   // First check whether we have a trailing comment.
223   if (OffsetCommentBehindDecl != CommentsInTheFile.end()) {
224     RawComment *CommentBehindDecl = OffsetCommentBehindDecl->second;
225     if ((CommentBehindDecl->isDocumentation() ||
226          LangOpts.CommentOpts.ParseAllComments) &&
227         CommentBehindDecl->isTrailingComment() &&
228         (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
229          isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
230 
231       // Check that Doxygen trailing comment comes after the declaration, starts
232       // on the same line and in the same file as the declaration.
233       if (SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second) ==
234           Comments.getCommentBeginLine(CommentBehindDecl, DeclLocDecomp.first,
235                                        OffsetCommentBehindDecl->first)) {
236         return CommentBehindDecl;
237       }
238     }
239   }
240 
241   // The comment just after the declaration was not a trailing comment.
242   // Let's look at the previous comment.
243   if (OffsetCommentBehindDecl == CommentsInTheFile.begin())
244     return nullptr;
245 
246   auto OffsetCommentBeforeDecl = --OffsetCommentBehindDecl;
247   RawComment *CommentBeforeDecl = OffsetCommentBeforeDecl->second;
248 
249   // Check that we actually have a non-member Doxygen comment.
250   if (!(CommentBeforeDecl->isDocumentation() ||
251         LangOpts.CommentOpts.ParseAllComments) ||
252       CommentBeforeDecl->isTrailingComment())
253     return nullptr;
254 
255   // Decompose the end of the comment.
256   const unsigned CommentEndOffset =
257       Comments.getCommentEndOffset(CommentBeforeDecl);
258 
259   // Get the corresponding buffer.
260   bool Invalid = false;
261   const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
262                                                &Invalid).data();
263   if (Invalid)
264     return nullptr;
265 
266   // Extract text between the comment and declaration.
267   StringRef Text(Buffer + CommentEndOffset,
268                  DeclLocDecomp.second - CommentEndOffset);
269 
270   // There should be no other declarations or preprocessor directives between
271   // comment and declaration.
272   if (Text.find_first_of(";{}#@") != StringRef::npos)
273     return nullptr;
274 
275   return CommentBeforeDecl;
276 }
277 
278 RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
279   const SourceLocation DeclLoc = getDeclLocForCommentSearch(D, SourceMgr);
280 
281   // If the declaration doesn't map directly to a location in a file, we
282   // can't find the comment.
283   if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
284     return nullptr;
285 
286   if (ExternalSource && !CommentsLoaded) {
287     ExternalSource->ReadComments();
288     CommentsLoaded = true;
289   }
290 
291   if (Comments.empty())
292     return nullptr;
293 
294   const FileID File = SourceMgr.getDecomposedLoc(DeclLoc).first;
295   const auto CommentsInThisFile = Comments.getCommentsInFile(File);
296   if (!CommentsInThisFile || CommentsInThisFile->empty())
297     return nullptr;
298 
299   return getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile);
300 }
301 
302 void ASTContext::addComment(const RawComment &RC) {
303   assert(LangOpts.RetainCommentsFromSystemHeaders ||
304          !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin()));
305   Comments.addComment(RC, LangOpts.CommentOpts, BumpAlloc);
306 }
307 
308 /// If we have a 'templated' declaration for a template, adjust 'D' to
309 /// refer to the actual template.
310 /// If we have an implicit instantiation, adjust 'D' to refer to template.
311 static const Decl &adjustDeclToTemplate(const Decl &D) {
312   if (const auto *FD = dyn_cast<FunctionDecl>(&D)) {
313     // Is this function declaration part of a function template?
314     if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
315       return *FTD;
316 
317     // Nothing to do if function is not an implicit instantiation.
318     if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
319       return D;
320 
321     // Function is an implicit instantiation of a function template?
322     if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
323       return *FTD;
324 
325     // Function is instantiated from a member definition of a class template?
326     if (const FunctionDecl *MemberDecl =
327             FD->getInstantiatedFromMemberFunction())
328       return *MemberDecl;
329 
330     return D;
331   }
332   if (const auto *VD = dyn_cast<VarDecl>(&D)) {
333     // Static data member is instantiated from a member definition of a class
334     // template?
335     if (VD->isStaticDataMember())
336       if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
337         return *MemberDecl;
338 
339     return D;
340   }
341   if (const auto *CRD = dyn_cast<CXXRecordDecl>(&D)) {
342     // Is this class declaration part of a class template?
343     if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
344       return *CTD;
345 
346     // Class is an implicit instantiation of a class template or partial
347     // specialization?
348     if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
349       if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
350         return D;
351       llvm::PointerUnion<ClassTemplateDecl *,
352                          ClassTemplatePartialSpecializationDecl *>
353           PU = CTSD->getSpecializedTemplateOrPartial();
354       return PU.is<ClassTemplateDecl *>()
355                  ? *static_cast<const Decl *>(PU.get<ClassTemplateDecl *>())
356                  : *static_cast<const Decl *>(
357                        PU.get<ClassTemplatePartialSpecializationDecl *>());
358     }
359 
360     // Class is instantiated from a member definition of a class template?
361     if (const MemberSpecializationInfo *Info =
362             CRD->getMemberSpecializationInfo())
363       return *Info->getInstantiatedFrom();
364 
365     return D;
366   }
367   if (const auto *ED = dyn_cast<EnumDecl>(&D)) {
368     // Enum is instantiated from a member definition of a class template?
369     if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
370       return *MemberDecl;
371 
372     return D;
373   }
374   // FIXME: Adjust alias templates?
375   return D;
376 }
377 
378 const RawComment *ASTContext::getRawCommentForAnyRedecl(
379                                                 const Decl *D,
380                                                 const Decl **OriginalDecl) const {
381   if (!D) {
382     if (OriginalDecl)
383       OriginalDecl = nullptr;
384     return nullptr;
385   }
386 
387   D = &adjustDeclToTemplate(*D);
388 
389   // Any comment directly attached to D?
390   {
391     auto DeclComment = DeclRawComments.find(D);
392     if (DeclComment != DeclRawComments.end()) {
393       if (OriginalDecl)
394         *OriginalDecl = D;
395       return DeclComment->second;
396     }
397   }
398 
399   // Any comment attached to any redeclaration of D?
400   const Decl *CanonicalD = D->getCanonicalDecl();
401   if (!CanonicalD)
402     return nullptr;
403 
404   {
405     auto RedeclComment = RedeclChainComments.find(CanonicalD);
406     if (RedeclComment != RedeclChainComments.end()) {
407       if (OriginalDecl)
408         *OriginalDecl = RedeclComment->second;
409       auto CommentAtRedecl = DeclRawComments.find(RedeclComment->second);
410       assert(CommentAtRedecl != DeclRawComments.end() &&
411              "This decl is supposed to have comment attached.");
412       return CommentAtRedecl->second;
413     }
414   }
415 
416   // Any redeclarations of D that we haven't checked for comments yet?
417   // We can't use DenseMap::iterator directly since it'd get invalid.
418   auto LastCheckedRedecl = [this, CanonicalD]() -> const Decl * {
419     auto LookupRes = CommentlessRedeclChains.find(CanonicalD);
420     if (LookupRes != CommentlessRedeclChains.end())
421       return LookupRes->second;
422     return nullptr;
423   }();
424 
425   for (const auto Redecl : D->redecls()) {
426     assert(Redecl);
427     // Skip all redeclarations that have been checked previously.
428     if (LastCheckedRedecl) {
429       if (LastCheckedRedecl == Redecl) {
430         LastCheckedRedecl = nullptr;
431       }
432       continue;
433     }
434     const RawComment *RedeclComment = getRawCommentForDeclNoCache(Redecl);
435     if (RedeclComment) {
436       cacheRawCommentForDecl(*Redecl, *RedeclComment);
437       if (OriginalDecl)
438         *OriginalDecl = Redecl;
439       return RedeclComment;
440     }
441     CommentlessRedeclChains[CanonicalD] = Redecl;
442   }
443 
444   if (OriginalDecl)
445     *OriginalDecl = nullptr;
446   return nullptr;
447 }
448 
449 void ASTContext::cacheRawCommentForDecl(const Decl &OriginalD,
450                                         const RawComment &Comment) const {
451   assert(Comment.isDocumentation() || LangOpts.CommentOpts.ParseAllComments);
452   DeclRawComments.try_emplace(&OriginalD, &Comment);
453   const Decl *const CanonicalDecl = OriginalD.getCanonicalDecl();
454   RedeclChainComments.try_emplace(CanonicalDecl, &OriginalD);
455   CommentlessRedeclChains.erase(CanonicalDecl);
456 }
457 
458 static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
459                    SmallVectorImpl<const NamedDecl *> &Redeclared) {
460   const DeclContext *DC = ObjCMethod->getDeclContext();
461   if (const auto *IMD = dyn_cast<ObjCImplDecl>(DC)) {
462     const ObjCInterfaceDecl *ID = IMD->getClassInterface();
463     if (!ID)
464       return;
465     // Add redeclared method here.
466     for (const auto *Ext : ID->known_extensions()) {
467       if (ObjCMethodDecl *RedeclaredMethod =
468             Ext->getMethod(ObjCMethod->getSelector(),
469                                   ObjCMethod->isInstanceMethod()))
470         Redeclared.push_back(RedeclaredMethod);
471     }
472   }
473 }
474 
475 void ASTContext::attachCommentsToJustParsedDecls(ArrayRef<Decl *> Decls,
476                                                  const Preprocessor *PP) {
477   if (Comments.empty() || Decls.empty())
478     return;
479 
480   FileID File;
481   for (Decl *D : Decls) {
482     SourceLocation Loc = D->getLocation();
483     if (Loc.isValid()) {
484       // See if there are any new comments that are not attached to a decl.
485       // The location doesn't have to be precise - we care only about the file.
486       File = SourceMgr.getDecomposedLoc(Loc).first;
487       break;
488     }
489   }
490 
491   if (File.isInvalid())
492     return;
493 
494   auto CommentsInThisFile = Comments.getCommentsInFile(File);
495   if (!CommentsInThisFile || CommentsInThisFile->empty() ||
496       CommentsInThisFile->rbegin()->second->isAttached())
497     return;
498 
499   // There is at least one comment not attached to a decl.
500   // Maybe it should be attached to one of Decls?
501   //
502   // Note that this way we pick up not only comments that precede the
503   // declaration, but also comments that *follow* the declaration -- thanks to
504   // the lookahead in the lexer: we've consumed the semicolon and looked
505   // ahead through comments.
506 
507   for (const Decl *D : Decls) {
508     assert(D);
509     if (D->isInvalidDecl())
510       continue;
511 
512     D = &adjustDeclToTemplate(*D);
513 
514     const SourceLocation DeclLoc = getDeclLocForCommentSearch(D, SourceMgr);
515 
516     if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
517       continue;
518 
519     if (DeclRawComments.count(D) > 0)
520       continue;
521 
522     if (RawComment *const DocComment =
523             getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile)) {
524       cacheRawCommentForDecl(*D, *DocComment);
525       comments::FullComment *FC = DocComment->parse(*this, PP, D);
526       ParsedComments[D->getCanonicalDecl()] = FC;
527     }
528   }
529 }
530 
531 comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
532                                                     const Decl *D) const {
533   auto *ThisDeclInfo = new (*this) comments::DeclInfo;
534   ThisDeclInfo->CommentDecl = D;
535   ThisDeclInfo->IsFilled = false;
536   ThisDeclInfo->fill();
537   ThisDeclInfo->CommentDecl = FC->getDecl();
538   if (!ThisDeclInfo->TemplateParameters)
539     ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
540   comments::FullComment *CFC =
541     new (*this) comments::FullComment(FC->getBlocks(),
542                                       ThisDeclInfo);
543   return CFC;
544 }
545 
546 comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
547   const RawComment *RC = getRawCommentForDeclNoCache(D);
548   return RC ? RC->parse(*this, nullptr, D) : nullptr;
549 }
550 
551 comments::FullComment *ASTContext::getCommentForDecl(
552                                               const Decl *D,
553                                               const Preprocessor *PP) const {
554   if (!D || D->isInvalidDecl())
555     return nullptr;
556   D = &adjustDeclToTemplate(*D);
557 
558   const Decl *Canonical = D->getCanonicalDecl();
559   llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
560       ParsedComments.find(Canonical);
561 
562   if (Pos != ParsedComments.end()) {
563     if (Canonical != D) {
564       comments::FullComment *FC = Pos->second;
565       comments::FullComment *CFC = cloneFullComment(FC, D);
566       return CFC;
567     }
568     return Pos->second;
569   }
570 
571   const Decl *OriginalDecl = nullptr;
572 
573   const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
574   if (!RC) {
575     if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
576       SmallVector<const NamedDecl*, 8> Overridden;
577       const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
578       if (OMD && OMD->isPropertyAccessor())
579         if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
580           if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
581             return cloneFullComment(FC, D);
582       if (OMD)
583         addRedeclaredMethods(OMD, Overridden);
584       getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
585       for (unsigned i = 0, e = Overridden.size(); i < e; i++)
586         if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
587           return cloneFullComment(FC, D);
588     }
589     else if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
590       // Attach any tag type's documentation to its typedef if latter
591       // does not have one of its own.
592       QualType QT = TD->getUnderlyingType();
593       if (const auto *TT = QT->getAs<TagType>())
594         if (const Decl *TD = TT->getDecl())
595           if (comments::FullComment *FC = getCommentForDecl(TD, PP))
596             return cloneFullComment(FC, D);
597     }
598     else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
599       while (IC->getSuperClass()) {
600         IC = IC->getSuperClass();
601         if (comments::FullComment *FC = getCommentForDecl(IC, PP))
602           return cloneFullComment(FC, D);
603       }
604     }
605     else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(D)) {
606       if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
607         if (comments::FullComment *FC = getCommentForDecl(IC, PP))
608           return cloneFullComment(FC, D);
609     }
610     else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
611       if (!(RD = RD->getDefinition()))
612         return nullptr;
613       // Check non-virtual bases.
614       for (const auto &I : RD->bases()) {
615         if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
616           continue;
617         QualType Ty = I.getType();
618         if (Ty.isNull())
619           continue;
620         if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
621           if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
622             continue;
623 
624           if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
625             return cloneFullComment(FC, D);
626         }
627       }
628       // Check virtual bases.
629       for (const auto &I : RD->vbases()) {
630         if (I.getAccessSpecifier() != AS_public)
631           continue;
632         QualType Ty = I.getType();
633         if (Ty.isNull())
634           continue;
635         if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
636           if (!(VirtualBase= VirtualBase->getDefinition()))
637             continue;
638           if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
639             return cloneFullComment(FC, D);
640         }
641       }
642     }
643     return nullptr;
644   }
645 
646   // If the RawComment was attached to other redeclaration of this Decl, we
647   // should parse the comment in context of that other Decl.  This is important
648   // because comments can contain references to parameter names which can be
649   // different across redeclarations.
650   if (D != OriginalDecl && OriginalDecl)
651     return getCommentForDecl(OriginalDecl, PP);
652 
653   comments::FullComment *FC = RC->parse(*this, PP, D);
654   ParsedComments[Canonical] = FC;
655   return FC;
656 }
657 
658 void
659 ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
660                                                    const ASTContext &C,
661                                                TemplateTemplateParmDecl *Parm) {
662   ID.AddInteger(Parm->getDepth());
663   ID.AddInteger(Parm->getPosition());
664   ID.AddBoolean(Parm->isParameterPack());
665 
666   TemplateParameterList *Params = Parm->getTemplateParameters();
667   ID.AddInteger(Params->size());
668   for (TemplateParameterList::const_iterator P = Params->begin(),
669                                           PEnd = Params->end();
670        P != PEnd; ++P) {
671     if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
672       ID.AddInteger(0);
673       ID.AddBoolean(TTP->isParameterPack());
674       const TypeConstraint *TC = TTP->getTypeConstraint();
675       ID.AddBoolean(TC != nullptr);
676       if (TC)
677         TC->getImmediatelyDeclaredConstraint()->Profile(ID, C,
678                                                         /*Canonical=*/true);
679       if (TTP->isExpandedParameterPack()) {
680         ID.AddBoolean(true);
681         ID.AddInteger(TTP->getNumExpansionParameters());
682       } else
683         ID.AddBoolean(false);
684       continue;
685     }
686 
687     if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
688       ID.AddInteger(1);
689       ID.AddBoolean(NTTP->isParameterPack());
690       ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
691       if (NTTP->isExpandedParameterPack()) {
692         ID.AddBoolean(true);
693         ID.AddInteger(NTTP->getNumExpansionTypes());
694         for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
695           QualType T = NTTP->getExpansionType(I);
696           ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
697         }
698       } else
699         ID.AddBoolean(false);
700       continue;
701     }
702 
703     auto *TTP = cast<TemplateTemplateParmDecl>(*P);
704     ID.AddInteger(2);
705     Profile(ID, C, TTP);
706   }
707   Expr *RequiresClause = Parm->getTemplateParameters()->getRequiresClause();
708   ID.AddBoolean(RequiresClause != nullptr);
709   if (RequiresClause)
710     RequiresClause->Profile(ID, C, /*Canonical=*/true);
711 }
712 
713 static Expr *
714 canonicalizeImmediatelyDeclaredConstraint(const ASTContext &C, Expr *IDC,
715                                           QualType ConstrainedType) {
716   // This is a bit ugly - we need to form a new immediately-declared
717   // constraint that references the new parameter; this would ideally
718   // require semantic analysis (e.g. template<C T> struct S {}; - the
719   // converted arguments of C<T> could be an argument pack if C is
720   // declared as template<typename... T> concept C = ...).
721   // We don't have semantic analysis here so we dig deep into the
722   // ready-made constraint expr and change the thing manually.
723   ConceptSpecializationExpr *CSE;
724   if (const auto *Fold = dyn_cast<CXXFoldExpr>(IDC))
725     CSE = cast<ConceptSpecializationExpr>(Fold->getLHS());
726   else
727     CSE = cast<ConceptSpecializationExpr>(IDC);
728   ArrayRef<TemplateArgument> OldConverted = CSE->getTemplateArguments();
729   SmallVector<TemplateArgument, 3> NewConverted;
730   NewConverted.reserve(OldConverted.size());
731   if (OldConverted.front().getKind() == TemplateArgument::Pack) {
732     // The case:
733     // template<typename... T> concept C = true;
734     // template<C<int> T> struct S; -> constraint is C<{T, int}>
735     NewConverted.push_back(ConstrainedType);
736     for (auto &Arg : OldConverted.front().pack_elements().drop_front(1))
737       NewConverted.push_back(Arg);
738     TemplateArgument NewPack(NewConverted);
739 
740     NewConverted.clear();
741     NewConverted.push_back(NewPack);
742     assert(OldConverted.size() == 1 &&
743            "Template parameter pack should be the last parameter");
744   } else {
745     assert(OldConverted.front().getKind() == TemplateArgument::Type &&
746            "Unexpected first argument kind for immediately-declared "
747            "constraint");
748     NewConverted.push_back(ConstrainedType);
749     for (auto &Arg : OldConverted.drop_front(1))
750       NewConverted.push_back(Arg);
751   }
752   Expr *NewIDC = ConceptSpecializationExpr::Create(
753       C, CSE->getNamedConcept(), NewConverted, nullptr,
754       CSE->isInstantiationDependent(), CSE->containsUnexpandedParameterPack());
755 
756   if (auto *OrigFold = dyn_cast<CXXFoldExpr>(IDC))
757     NewIDC = new (C) CXXFoldExpr(
758         OrigFold->getType(), /*Callee*/nullptr, SourceLocation(), NewIDC,
759         BinaryOperatorKind::BO_LAnd, SourceLocation(), /*RHS=*/nullptr,
760         SourceLocation(), /*NumExpansions=*/None);
761   return NewIDC;
762 }
763 
764 TemplateTemplateParmDecl *
765 ASTContext::getCanonicalTemplateTemplateParmDecl(
766                                           TemplateTemplateParmDecl *TTP) const {
767   // Check if we already have a canonical template template parameter.
768   llvm::FoldingSetNodeID ID;
769   CanonicalTemplateTemplateParm::Profile(ID, *this, TTP);
770   void *InsertPos = nullptr;
771   CanonicalTemplateTemplateParm *Canonical
772     = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
773   if (Canonical)
774     return Canonical->getParam();
775 
776   // Build a canonical template parameter list.
777   TemplateParameterList *Params = TTP->getTemplateParameters();
778   SmallVector<NamedDecl *, 4> CanonParams;
779   CanonParams.reserve(Params->size());
780   for (TemplateParameterList::const_iterator P = Params->begin(),
781                                           PEnd = Params->end();
782        P != PEnd; ++P) {
783     if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
784       TemplateTypeParmDecl *NewTTP = TemplateTypeParmDecl::Create(*this,
785           getTranslationUnitDecl(), SourceLocation(), SourceLocation(),
786           TTP->getDepth(), TTP->getIndex(), nullptr, false,
787           TTP->isParameterPack(), TTP->hasTypeConstraint(),
788           TTP->isExpandedParameterPack() ?
789           llvm::Optional<unsigned>(TTP->getNumExpansionParameters()) : None);
790       if (const auto *TC = TTP->getTypeConstraint()) {
791         QualType ParamAsArgument(NewTTP->getTypeForDecl(), 0);
792         Expr *NewIDC = canonicalizeImmediatelyDeclaredConstraint(
793                 *this, TC->getImmediatelyDeclaredConstraint(),
794                 ParamAsArgument);
795         TemplateArgumentListInfo CanonArgsAsWritten;
796         if (auto *Args = TC->getTemplateArgsAsWritten())
797           for (const auto &ArgLoc : Args->arguments())
798             CanonArgsAsWritten.addArgument(
799                 TemplateArgumentLoc(ArgLoc.getArgument(),
800                                     TemplateArgumentLocInfo()));
801         NewTTP->setTypeConstraint(
802             NestedNameSpecifierLoc(),
803             DeclarationNameInfo(TC->getNamedConcept()->getDeclName(),
804                                 SourceLocation()), /*FoundDecl=*/nullptr,
805             // Actually canonicalizing a TemplateArgumentLoc is difficult so we
806             // simply omit the ArgsAsWritten
807             TC->getNamedConcept(), /*ArgsAsWritten=*/nullptr, NewIDC);
808       }
809       CanonParams.push_back(NewTTP);
810     } else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
811       QualType T = getCanonicalType(NTTP->getType());
812       TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
813       NonTypeTemplateParmDecl *Param;
814       if (NTTP->isExpandedParameterPack()) {
815         SmallVector<QualType, 2> ExpandedTypes;
816         SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
817         for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
818           ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
819           ExpandedTInfos.push_back(
820                                 getTrivialTypeSourceInfo(ExpandedTypes.back()));
821         }
822 
823         Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
824                                                 SourceLocation(),
825                                                 SourceLocation(),
826                                                 NTTP->getDepth(),
827                                                 NTTP->getPosition(), nullptr,
828                                                 T,
829                                                 TInfo,
830                                                 ExpandedTypes,
831                                                 ExpandedTInfos);
832       } else {
833         Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
834                                                 SourceLocation(),
835                                                 SourceLocation(),
836                                                 NTTP->getDepth(),
837                                                 NTTP->getPosition(), nullptr,
838                                                 T,
839                                                 NTTP->isParameterPack(),
840                                                 TInfo);
841       }
842       if (AutoType *AT = T->getContainedAutoType()) {
843         if (AT->isConstrained()) {
844           Param->setPlaceholderTypeConstraint(
845               canonicalizeImmediatelyDeclaredConstraint(
846                   *this, NTTP->getPlaceholderTypeConstraint(), T));
847         }
848       }
849       CanonParams.push_back(Param);
850 
851     } else
852       CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
853                                            cast<TemplateTemplateParmDecl>(*P)));
854   }
855 
856   Expr *CanonRequiresClause = nullptr;
857   if (Expr *RequiresClause = TTP->getTemplateParameters()->getRequiresClause())
858     CanonRequiresClause = RequiresClause;
859 
860   TemplateTemplateParmDecl *CanonTTP
861     = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
862                                        SourceLocation(), TTP->getDepth(),
863                                        TTP->getPosition(),
864                                        TTP->isParameterPack(),
865                                        nullptr,
866                          TemplateParameterList::Create(*this, SourceLocation(),
867                                                        SourceLocation(),
868                                                        CanonParams,
869                                                        SourceLocation(),
870                                                        CanonRequiresClause));
871 
872   // Get the new insert position for the node we care about.
873   Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
874   assert(!Canonical && "Shouldn't be in the map!");
875   (void)Canonical;
876 
877   // Create the canonical template template parameter entry.
878   Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
879   CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
880   return CanonTTP;
881 }
882 
883 CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
884   if (!LangOpts.CPlusPlus) return nullptr;
885 
886   switch (T.getCXXABI().getKind()) {
887   case TargetCXXABI::AppleARM64:
888   case TargetCXXABI::Fuchsia:
889   case TargetCXXABI::GenericARM: // Same as Itanium at this level
890   case TargetCXXABI::iOS:
891   case TargetCXXABI::WatchOS:
892   case TargetCXXABI::GenericAArch64:
893   case TargetCXXABI::GenericMIPS:
894   case TargetCXXABI::GenericItanium:
895   case TargetCXXABI::WebAssembly:
896   case TargetCXXABI::XL:
897     return CreateItaniumCXXABI(*this);
898   case TargetCXXABI::Microsoft:
899     return CreateMicrosoftCXXABI(*this);
900   }
901   llvm_unreachable("Invalid CXXABI type!");
902 }
903 
904 interp::Context &ASTContext::getInterpContext() {
905   if (!InterpContext) {
906     InterpContext.reset(new interp::Context(*this));
907   }
908   return *InterpContext.get();
909 }
910 
911 ParentMapContext &ASTContext::getParentMapContext() {
912   if (!ParentMapCtx)
913     ParentMapCtx.reset(new ParentMapContext(*this));
914   return *ParentMapCtx.get();
915 }
916 
917 static const LangASMap *getAddressSpaceMap(const TargetInfo &T,
918                                            const LangOptions &LOpts) {
919   if (LOpts.FakeAddressSpaceMap) {
920     // The fake address space map must have a distinct entry for each
921     // language-specific address space.
922     static const unsigned FakeAddrSpaceMap[] = {
923         0,  // Default
924         1,  // opencl_global
925         3,  // opencl_local
926         2,  // opencl_constant
927         0,  // opencl_private
928         4,  // opencl_generic
929         5,  // opencl_global_device
930         6,  // opencl_global_host
931         7,  // cuda_device
932         8,  // cuda_constant
933         9,  // cuda_shared
934         1,  // sycl_global
935         3,  // sycl_local
936         0,  // sycl_private
937         10, // ptr32_sptr
938         11, // ptr32_uptr
939         12  // ptr64
940     };
941     return &FakeAddrSpaceMap;
942   } else {
943     return &T.getAddressSpaceMap();
944   }
945 }
946 
947 static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
948                                           const LangOptions &LangOpts) {
949   switch (LangOpts.getAddressSpaceMapMangling()) {
950   case LangOptions::ASMM_Target:
951     return TI.useAddressSpaceMapMangling();
952   case LangOptions::ASMM_On:
953     return true;
954   case LangOptions::ASMM_Off:
955     return false;
956   }
957   llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
958 }
959 
960 ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
961                        IdentifierTable &idents, SelectorTable &sels,
962                        Builtin::Context &builtins)
963     : ConstantArrayTypes(this_()), FunctionProtoTypes(this_()),
964       TemplateSpecializationTypes(this_()),
965       DependentTemplateSpecializationTypes(this_()), AutoTypes(this_()),
966       SubstTemplateTemplateParmPacks(this_()),
967       CanonTemplateTemplateParms(this_()), SourceMgr(SM), LangOpts(LOpts),
968       NoSanitizeL(new NoSanitizeList(LangOpts.NoSanitizeFiles, SM)),
969       XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
970                                         LangOpts.XRayNeverInstrumentFiles,
971                                         LangOpts.XRayAttrListFiles, SM)),
972       ProfList(new ProfileList(LangOpts.ProfileListFiles, SM)),
973       PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
974       BuiltinInfo(builtins), DeclarationNames(*this), Comments(SM),
975       CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
976       CompCategories(this_()), LastSDM(nullptr, 0) {
977   TUDecl = TranslationUnitDecl::Create(*this);
978   TraversalScope = {TUDecl};
979 }
980 
981 ASTContext::~ASTContext() {
982   // Release the DenseMaps associated with DeclContext objects.
983   // FIXME: Is this the ideal solution?
984   ReleaseDeclContextMaps();
985 
986   // Call all of the deallocation functions on all of their targets.
987   for (auto &Pair : Deallocations)
988     (Pair.first)(Pair.second);
989 
990   // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
991   // because they can contain DenseMaps.
992   for (llvm::DenseMap<const ObjCContainerDecl*,
993        const ASTRecordLayout*>::iterator
994        I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
995     // Increment in loop to prevent using deallocated memory.
996     if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
997       R->Destroy(*this);
998 
999   for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
1000        I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
1001     // Increment in loop to prevent using deallocated memory.
1002     if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
1003       R->Destroy(*this);
1004   }
1005 
1006   for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
1007                                                     AEnd = DeclAttrs.end();
1008        A != AEnd; ++A)
1009     A->second->~AttrVec();
1010 
1011   for (const auto &Value : ModuleInitializers)
1012     Value.second->~PerModuleInitializers();
1013 }
1014 
1015 void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) {
1016   TraversalScope = TopLevelDecls;
1017   getParentMapContext().clear();
1018 }
1019 
1020 void ASTContext::AddDeallocation(void (*Callback)(void *), void *Data) const {
1021   Deallocations.push_back({Callback, Data});
1022 }
1023 
1024 void
1025 ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
1026   ExternalSource = std::move(Source);
1027 }
1028 
1029 void ASTContext::PrintStats() const {
1030   llvm::errs() << "\n*** AST Context Stats:\n";
1031   llvm::errs() << "  " << Types.size() << " types total.\n";
1032 
1033   unsigned counts[] = {
1034 #define TYPE(Name, Parent) 0,
1035 #define ABSTRACT_TYPE(Name, Parent)
1036 #include "clang/AST/TypeNodes.inc"
1037     0 // Extra
1038   };
1039 
1040   for (unsigned i = 0, e = Types.size(); i != e; ++i) {
1041     Type *T = Types[i];
1042     counts[(unsigned)T->getTypeClass()]++;
1043   }
1044 
1045   unsigned Idx = 0;
1046   unsigned TotalBytes = 0;
1047 #define TYPE(Name, Parent)                                              \
1048   if (counts[Idx])                                                      \
1049     llvm::errs() << "    " << counts[Idx] << " " << #Name               \
1050                  << " types, " << sizeof(Name##Type) << " each "        \
1051                  << "(" << counts[Idx] * sizeof(Name##Type)             \
1052                  << " bytes)\n";                                        \
1053   TotalBytes += counts[Idx] * sizeof(Name##Type);                       \
1054   ++Idx;
1055 #define ABSTRACT_TYPE(Name, Parent)
1056 #include "clang/AST/TypeNodes.inc"
1057 
1058   llvm::errs() << "Total bytes = " << TotalBytes << "\n";
1059 
1060   // Implicit special member functions.
1061   llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
1062                << NumImplicitDefaultConstructors
1063                << " implicit default constructors created\n";
1064   llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
1065                << NumImplicitCopyConstructors
1066                << " implicit copy constructors created\n";
1067   if (getLangOpts().CPlusPlus)
1068     llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
1069                  << NumImplicitMoveConstructors
1070                  << " implicit move constructors created\n";
1071   llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
1072                << NumImplicitCopyAssignmentOperators
1073                << " implicit copy assignment operators created\n";
1074   if (getLangOpts().CPlusPlus)
1075     llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
1076                  << NumImplicitMoveAssignmentOperators
1077                  << " implicit move assignment operators created\n";
1078   llvm::errs() << NumImplicitDestructorsDeclared << "/"
1079                << NumImplicitDestructors
1080                << " implicit destructors created\n";
1081 
1082   if (ExternalSource) {
1083     llvm::errs() << "\n";
1084     ExternalSource->PrintStats();
1085   }
1086 
1087   BumpAlloc.PrintStats();
1088 }
1089 
1090 void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
1091                                            bool NotifyListeners) {
1092   if (NotifyListeners)
1093     if (auto *Listener = getASTMutationListener())
1094       Listener->RedefinedHiddenDefinition(ND, M);
1095 
1096   MergedDefModules[cast<NamedDecl>(ND->getCanonicalDecl())].push_back(M);
1097 }
1098 
1099 void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
1100   auto It = MergedDefModules.find(cast<NamedDecl>(ND->getCanonicalDecl()));
1101   if (It == MergedDefModules.end())
1102     return;
1103 
1104   auto &Merged = It->second;
1105   llvm::DenseSet<Module*> Found;
1106   for (Module *&M : Merged)
1107     if (!Found.insert(M).second)
1108       M = nullptr;
1109   Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end());
1110 }
1111 
1112 ArrayRef<Module *>
1113 ASTContext::getModulesWithMergedDefinition(const NamedDecl *Def) {
1114   auto MergedIt =
1115       MergedDefModules.find(cast<NamedDecl>(Def->getCanonicalDecl()));
1116   if (MergedIt == MergedDefModules.end())
1117     return None;
1118   return MergedIt->second;
1119 }
1120 
1121 void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
1122   if (LazyInitializers.empty())
1123     return;
1124 
1125   auto *Source = Ctx.getExternalSource();
1126   assert(Source && "lazy initializers but no external source");
1127 
1128   auto LazyInits = std::move(LazyInitializers);
1129   LazyInitializers.clear();
1130 
1131   for (auto ID : LazyInits)
1132     Initializers.push_back(Source->GetExternalDecl(ID));
1133 
1134   assert(LazyInitializers.empty() &&
1135          "GetExternalDecl for lazy module initializer added more inits");
1136 }
1137 
1138 void ASTContext::addModuleInitializer(Module *M, Decl *D) {
1139   // One special case: if we add a module initializer that imports another
1140   // module, and that module's only initializer is an ImportDecl, simplify.
1141   if (const auto *ID = dyn_cast<ImportDecl>(D)) {
1142     auto It = ModuleInitializers.find(ID->getImportedModule());
1143 
1144     // Maybe the ImportDecl does nothing at all. (Common case.)
1145     if (It == ModuleInitializers.end())
1146       return;
1147 
1148     // Maybe the ImportDecl only imports another ImportDecl.
1149     auto &Imported = *It->second;
1150     if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
1151       Imported.resolve(*this);
1152       auto *OnlyDecl = Imported.Initializers.front();
1153       if (isa<ImportDecl>(OnlyDecl))
1154         D = OnlyDecl;
1155     }
1156   }
1157 
1158   auto *&Inits = ModuleInitializers[M];
1159   if (!Inits)
1160     Inits = new (*this) PerModuleInitializers;
1161   Inits->Initializers.push_back(D);
1162 }
1163 
1164 void ASTContext::addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs) {
1165   auto *&Inits = ModuleInitializers[M];
1166   if (!Inits)
1167     Inits = new (*this) PerModuleInitializers;
1168   Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
1169                                  IDs.begin(), IDs.end());
1170 }
1171 
1172 ArrayRef<Decl *> ASTContext::getModuleInitializers(Module *M) {
1173   auto It = ModuleInitializers.find(M);
1174   if (It == ModuleInitializers.end())
1175     return None;
1176 
1177   auto *Inits = It->second;
1178   Inits->resolve(*this);
1179   return Inits->Initializers;
1180 }
1181 
1182 ExternCContextDecl *ASTContext::getExternCContextDecl() const {
1183   if (!ExternCContext)
1184     ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
1185 
1186   return ExternCContext;
1187 }
1188 
1189 BuiltinTemplateDecl *
1190 ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
1191                                      const IdentifierInfo *II) const {
1192   auto *BuiltinTemplate = BuiltinTemplateDecl::Create(*this, TUDecl, II, BTK);
1193   BuiltinTemplate->setImplicit();
1194   TUDecl->addDecl(BuiltinTemplate);
1195 
1196   return BuiltinTemplate;
1197 }
1198 
1199 BuiltinTemplateDecl *
1200 ASTContext::getMakeIntegerSeqDecl() const {
1201   if (!MakeIntegerSeqDecl)
1202     MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq,
1203                                                   getMakeIntegerSeqName());
1204   return MakeIntegerSeqDecl;
1205 }
1206 
1207 BuiltinTemplateDecl *
1208 ASTContext::getTypePackElementDecl() const {
1209   if (!TypePackElementDecl)
1210     TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element,
1211                                                    getTypePackElementName());
1212   return TypePackElementDecl;
1213 }
1214 
1215 RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
1216                                             RecordDecl::TagKind TK) const {
1217   SourceLocation Loc;
1218   RecordDecl *NewDecl;
1219   if (getLangOpts().CPlusPlus)
1220     NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1221                                     Loc, &Idents.get(Name));
1222   else
1223     NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1224                                  &Idents.get(Name));
1225   NewDecl->setImplicit();
1226   NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1227       const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
1228   return NewDecl;
1229 }
1230 
1231 TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
1232                                               StringRef Name) const {
1233   TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
1234   TypedefDecl *NewDecl = TypedefDecl::Create(
1235       const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1236       SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1237   NewDecl->setImplicit();
1238   return NewDecl;
1239 }
1240 
1241 TypedefDecl *ASTContext::getInt128Decl() const {
1242   if (!Int128Decl)
1243     Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
1244   return Int128Decl;
1245 }
1246 
1247 TypedefDecl *ASTContext::getUInt128Decl() const {
1248   if (!UInt128Decl)
1249     UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
1250   return UInt128Decl;
1251 }
1252 
1253 void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
1254   auto *Ty = new (*this, TypeAlignment) BuiltinType(K);
1255   R = CanQualType::CreateUnsafe(QualType(Ty, 0));
1256   Types.push_back(Ty);
1257 }
1258 
1259 void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
1260                                   const TargetInfo *AuxTarget) {
1261   assert((!this->Target || this->Target == &Target) &&
1262          "Incorrect target reinitialization");
1263   assert(VoidTy.isNull() && "Context reinitialized?");
1264 
1265   this->Target = &Target;
1266   this->AuxTarget = AuxTarget;
1267 
1268   ABI.reset(createCXXABI(Target));
1269   AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
1270   AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
1271 
1272   // C99 6.2.5p19.
1273   InitBuiltinType(VoidTy,              BuiltinType::Void);
1274 
1275   // C99 6.2.5p2.
1276   InitBuiltinType(BoolTy,              BuiltinType::Bool);
1277   // C99 6.2.5p3.
1278   if (LangOpts.CharIsSigned)
1279     InitBuiltinType(CharTy,            BuiltinType::Char_S);
1280   else
1281     InitBuiltinType(CharTy,            BuiltinType::Char_U);
1282   // C99 6.2.5p4.
1283   InitBuiltinType(SignedCharTy,        BuiltinType::SChar);
1284   InitBuiltinType(ShortTy,             BuiltinType::Short);
1285   InitBuiltinType(IntTy,               BuiltinType::Int);
1286   InitBuiltinType(LongTy,              BuiltinType::Long);
1287   InitBuiltinType(LongLongTy,          BuiltinType::LongLong);
1288 
1289   // C99 6.2.5p6.
1290   InitBuiltinType(UnsignedCharTy,      BuiltinType::UChar);
1291   InitBuiltinType(UnsignedShortTy,     BuiltinType::UShort);
1292   InitBuiltinType(UnsignedIntTy,       BuiltinType::UInt);
1293   InitBuiltinType(UnsignedLongTy,      BuiltinType::ULong);
1294   InitBuiltinType(UnsignedLongLongTy,  BuiltinType::ULongLong);
1295 
1296   // C99 6.2.5p10.
1297   InitBuiltinType(FloatTy,             BuiltinType::Float);
1298   InitBuiltinType(DoubleTy,            BuiltinType::Double);
1299   InitBuiltinType(LongDoubleTy,        BuiltinType::LongDouble);
1300 
1301   // GNU extension, __float128 for IEEE quadruple precision
1302   InitBuiltinType(Float128Ty,          BuiltinType::Float128);
1303 
1304   // C11 extension ISO/IEC TS 18661-3
1305   InitBuiltinType(Float16Ty,           BuiltinType::Float16);
1306 
1307   // ISO/IEC JTC1 SC22 WG14 N1169 Extension
1308   InitBuiltinType(ShortAccumTy,            BuiltinType::ShortAccum);
1309   InitBuiltinType(AccumTy,                 BuiltinType::Accum);
1310   InitBuiltinType(LongAccumTy,             BuiltinType::LongAccum);
1311   InitBuiltinType(UnsignedShortAccumTy,    BuiltinType::UShortAccum);
1312   InitBuiltinType(UnsignedAccumTy,         BuiltinType::UAccum);
1313   InitBuiltinType(UnsignedLongAccumTy,     BuiltinType::ULongAccum);
1314   InitBuiltinType(ShortFractTy,            BuiltinType::ShortFract);
1315   InitBuiltinType(FractTy,                 BuiltinType::Fract);
1316   InitBuiltinType(LongFractTy,             BuiltinType::LongFract);
1317   InitBuiltinType(UnsignedShortFractTy,    BuiltinType::UShortFract);
1318   InitBuiltinType(UnsignedFractTy,         BuiltinType::UFract);
1319   InitBuiltinType(UnsignedLongFractTy,     BuiltinType::ULongFract);
1320   InitBuiltinType(SatShortAccumTy,         BuiltinType::SatShortAccum);
1321   InitBuiltinType(SatAccumTy,              BuiltinType::SatAccum);
1322   InitBuiltinType(SatLongAccumTy,          BuiltinType::SatLongAccum);
1323   InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum);
1324   InitBuiltinType(SatUnsignedAccumTy,      BuiltinType::SatUAccum);
1325   InitBuiltinType(SatUnsignedLongAccumTy,  BuiltinType::SatULongAccum);
1326   InitBuiltinType(SatShortFractTy,         BuiltinType::SatShortFract);
1327   InitBuiltinType(SatFractTy,              BuiltinType::SatFract);
1328   InitBuiltinType(SatLongFractTy,          BuiltinType::SatLongFract);
1329   InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract);
1330   InitBuiltinType(SatUnsignedFractTy,      BuiltinType::SatUFract);
1331   InitBuiltinType(SatUnsignedLongFractTy,  BuiltinType::SatULongFract);
1332 
1333   // GNU extension, 128-bit integers.
1334   InitBuiltinType(Int128Ty,            BuiltinType::Int128);
1335   InitBuiltinType(UnsignedInt128Ty,    BuiltinType::UInt128);
1336 
1337   // C++ 3.9.1p5
1338   if (TargetInfo::isTypeSigned(Target.getWCharType()))
1339     InitBuiltinType(WCharTy,           BuiltinType::WChar_S);
1340   else  // -fshort-wchar makes wchar_t be unsigned.
1341     InitBuiltinType(WCharTy,           BuiltinType::WChar_U);
1342   if (LangOpts.CPlusPlus && LangOpts.WChar)
1343     WideCharTy = WCharTy;
1344   else {
1345     // C99 (or C++ using -fno-wchar).
1346     WideCharTy = getFromTargetType(Target.getWCharType());
1347   }
1348 
1349   WIntTy = getFromTargetType(Target.getWIntType());
1350 
1351   // C++20 (proposed)
1352   InitBuiltinType(Char8Ty,              BuiltinType::Char8);
1353 
1354   if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1355     InitBuiltinType(Char16Ty,           BuiltinType::Char16);
1356   else // C99
1357     Char16Ty = getFromTargetType(Target.getChar16Type());
1358 
1359   if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1360     InitBuiltinType(Char32Ty,           BuiltinType::Char32);
1361   else // C99
1362     Char32Ty = getFromTargetType(Target.getChar32Type());
1363 
1364   // Placeholder type for type-dependent expressions whose type is
1365   // completely unknown. No code should ever check a type against
1366   // DependentTy and users should never see it; however, it is here to
1367   // help diagnose failures to properly check for type-dependent
1368   // expressions.
1369   InitBuiltinType(DependentTy,         BuiltinType::Dependent);
1370 
1371   // Placeholder type for functions.
1372   InitBuiltinType(OverloadTy,          BuiltinType::Overload);
1373 
1374   // Placeholder type for bound members.
1375   InitBuiltinType(BoundMemberTy,       BuiltinType::BoundMember);
1376 
1377   // Placeholder type for pseudo-objects.
1378   InitBuiltinType(PseudoObjectTy,      BuiltinType::PseudoObject);
1379 
1380   // "any" type; useful for debugger-like clients.
1381   InitBuiltinType(UnknownAnyTy,        BuiltinType::UnknownAny);
1382 
1383   // Placeholder type for unbridged ARC casts.
1384   InitBuiltinType(ARCUnbridgedCastTy,  BuiltinType::ARCUnbridgedCast);
1385 
1386   // Placeholder type for builtin functions.
1387   InitBuiltinType(BuiltinFnTy,  BuiltinType::BuiltinFn);
1388 
1389   // Placeholder type for OMP array sections.
1390   if (LangOpts.OpenMP) {
1391     InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
1392     InitBuiltinType(OMPArrayShapingTy, BuiltinType::OMPArrayShaping);
1393     InitBuiltinType(OMPIteratorTy, BuiltinType::OMPIterator);
1394   }
1395   if (LangOpts.MatrixTypes)
1396     InitBuiltinType(IncompleteMatrixIdxTy, BuiltinType::IncompleteMatrixIdx);
1397 
1398   // C99 6.2.5p11.
1399   FloatComplexTy      = getComplexType(FloatTy);
1400   DoubleComplexTy     = getComplexType(DoubleTy);
1401   LongDoubleComplexTy = getComplexType(LongDoubleTy);
1402   Float128ComplexTy   = getComplexType(Float128Ty);
1403 
1404   // Builtin types for 'id', 'Class', and 'SEL'.
1405   InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1406   InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
1407   InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
1408 
1409   if (LangOpts.OpenCL) {
1410 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1411     InitBuiltinType(SingletonId, BuiltinType::Id);
1412 #include "clang/Basic/OpenCLImageTypes.def"
1413 
1414     InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
1415     InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
1416     InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1417     InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
1418     InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
1419 
1420 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1421     InitBuiltinType(Id##Ty, BuiltinType::Id);
1422 #include "clang/Basic/OpenCLExtensionTypes.def"
1423   }
1424 
1425   if (Target.hasAArch64SVETypes()) {
1426 #define SVE_TYPE(Name, Id, SingletonId) \
1427     InitBuiltinType(SingletonId, BuiltinType::Id);
1428 #include "clang/Basic/AArch64SVEACLETypes.def"
1429   }
1430 
1431   if (Target.getTriple().isPPC64() &&
1432       Target.hasFeature("paired-vector-memops")) {
1433     if (Target.hasFeature("mma")) {
1434 #define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \
1435       InitBuiltinType(Id##Ty, BuiltinType::Id);
1436 #include "clang/Basic/PPCTypes.def"
1437     }
1438 #define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \
1439     InitBuiltinType(Id##Ty, BuiltinType::Id);
1440 #include "clang/Basic/PPCTypes.def"
1441   }
1442 
1443   if (Target.hasRISCVVTypes()) {
1444 #define RVV_TYPE(Name, Id, SingletonId)                                        \
1445   InitBuiltinType(SingletonId, BuiltinType::Id);
1446 #include "clang/Basic/RISCVVTypes.def"
1447   }
1448 
1449   // Builtin type for __objc_yes and __objc_no
1450   ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1451                        SignedCharTy : BoolTy);
1452 
1453   ObjCConstantStringType = QualType();
1454 
1455   ObjCSuperType = QualType();
1456 
1457   // void * type
1458   if (LangOpts.OpenCLGenericAddressSpace) {
1459     auto Q = VoidTy.getQualifiers();
1460     Q.setAddressSpace(LangAS::opencl_generic);
1461     VoidPtrTy = getPointerType(getCanonicalType(
1462         getQualifiedType(VoidTy.getUnqualifiedType(), Q)));
1463   } else {
1464     VoidPtrTy = getPointerType(VoidTy);
1465   }
1466 
1467   // nullptr type (C++0x 2.14.7)
1468   InitBuiltinType(NullPtrTy,           BuiltinType::NullPtr);
1469 
1470   // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1471   InitBuiltinType(HalfTy, BuiltinType::Half);
1472 
1473   InitBuiltinType(BFloat16Ty, BuiltinType::BFloat16);
1474 
1475   // Builtin type used to help define __builtin_va_list.
1476   VaListTagDecl = nullptr;
1477 
1478   // MSVC predeclares struct _GUID, and we need it to create MSGuidDecls.
1479   if (LangOpts.MicrosoftExt || LangOpts.Borland) {
1480     MSGuidTagDecl = buildImplicitRecord("_GUID");
1481     TUDecl->addDecl(MSGuidTagDecl);
1482   }
1483 }
1484 
1485 DiagnosticsEngine &ASTContext::getDiagnostics() const {
1486   return SourceMgr.getDiagnostics();
1487 }
1488 
1489 AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1490   AttrVec *&Result = DeclAttrs[D];
1491   if (!Result) {
1492     void *Mem = Allocate(sizeof(AttrVec));
1493     Result = new (Mem) AttrVec;
1494   }
1495 
1496   return *Result;
1497 }
1498 
1499 /// Erase the attributes corresponding to the given declaration.
1500 void ASTContext::eraseDeclAttrs(const Decl *D) {
1501   llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1502   if (Pos != DeclAttrs.end()) {
1503     Pos->second->~AttrVec();
1504     DeclAttrs.erase(Pos);
1505   }
1506 }
1507 
1508 // FIXME: Remove ?
1509 MemberSpecializationInfo *
1510 ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
1511   assert(Var->isStaticDataMember() && "Not a static data member");
1512   return getTemplateOrSpecializationInfo(Var)
1513       .dyn_cast<MemberSpecializationInfo *>();
1514 }
1515 
1516 ASTContext::TemplateOrSpecializationInfo
1517 ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1518   llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1519       TemplateOrInstantiation.find(Var);
1520   if (Pos == TemplateOrInstantiation.end())
1521     return {};
1522 
1523   return Pos->second;
1524 }
1525 
1526 void
1527 ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
1528                                                 TemplateSpecializationKind TSK,
1529                                           SourceLocation PointOfInstantiation) {
1530   assert(Inst->isStaticDataMember() && "Not a static data member");
1531   assert(Tmpl->isStaticDataMember() && "Not a static data member");
1532   setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1533                                             Tmpl, TSK, PointOfInstantiation));
1534 }
1535 
1536 void
1537 ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1538                                             TemplateOrSpecializationInfo TSI) {
1539   assert(!TemplateOrInstantiation[Inst] &&
1540          "Already noted what the variable was instantiated from");
1541   TemplateOrInstantiation[Inst] = TSI;
1542 }
1543 
1544 NamedDecl *
1545 ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) {
1546   auto Pos = InstantiatedFromUsingDecl.find(UUD);
1547   if (Pos == InstantiatedFromUsingDecl.end())
1548     return nullptr;
1549 
1550   return Pos->second;
1551 }
1552 
1553 void
1554 ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) {
1555   assert((isa<UsingDecl>(Pattern) ||
1556           isa<UnresolvedUsingValueDecl>(Pattern) ||
1557           isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1558          "pattern decl is not a using decl");
1559   assert((isa<UsingDecl>(Inst) ||
1560           isa<UnresolvedUsingValueDecl>(Inst) ||
1561           isa<UnresolvedUsingTypenameDecl>(Inst)) &&
1562          "instantiation did not produce a using decl");
1563   assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1564   InstantiatedFromUsingDecl[Inst] = Pattern;
1565 }
1566 
1567 UsingShadowDecl *
1568 ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1569   llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1570     = InstantiatedFromUsingShadowDecl.find(Inst);
1571   if (Pos == InstantiatedFromUsingShadowDecl.end())
1572     return nullptr;
1573 
1574   return Pos->second;
1575 }
1576 
1577 void
1578 ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1579                                                UsingShadowDecl *Pattern) {
1580   assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1581   InstantiatedFromUsingShadowDecl[Inst] = Pattern;
1582 }
1583 
1584 FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1585   llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1586     = InstantiatedFromUnnamedFieldDecl.find(Field);
1587   if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1588     return nullptr;
1589 
1590   return Pos->second;
1591 }
1592 
1593 void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1594                                                      FieldDecl *Tmpl) {
1595   assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1596   assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1597   assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1598          "Already noted what unnamed field was instantiated from");
1599 
1600   InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1601 }
1602 
1603 ASTContext::overridden_cxx_method_iterator
1604 ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1605   return overridden_methods(Method).begin();
1606 }
1607 
1608 ASTContext::overridden_cxx_method_iterator
1609 ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1610   return overridden_methods(Method).end();
1611 }
1612 
1613 unsigned
1614 ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1615   auto Range = overridden_methods(Method);
1616   return Range.end() - Range.begin();
1617 }
1618 
1619 ASTContext::overridden_method_range
1620 ASTContext::overridden_methods(const CXXMethodDecl *Method) const {
1621   llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1622       OverriddenMethods.find(Method->getCanonicalDecl());
1623   if (Pos == OverriddenMethods.end())
1624     return overridden_method_range(nullptr, nullptr);
1625   return overridden_method_range(Pos->second.begin(), Pos->second.end());
1626 }
1627 
1628 void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1629                                      const CXXMethodDecl *Overridden) {
1630   assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
1631   OverriddenMethods[Method].push_back(Overridden);
1632 }
1633 
1634 void ASTContext::getOverriddenMethods(
1635                       const NamedDecl *D,
1636                       SmallVectorImpl<const NamedDecl *> &Overridden) const {
1637   assert(D);
1638 
1639   if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
1640     Overridden.append(overridden_methods_begin(CXXMethod),
1641                       overridden_methods_end(CXXMethod));
1642     return;
1643   }
1644 
1645   const auto *Method = dyn_cast<ObjCMethodDecl>(D);
1646   if (!Method)
1647     return;
1648 
1649   SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1650   Method->getOverriddenMethods(OverDecls);
1651   Overridden.append(OverDecls.begin(), OverDecls.end());
1652 }
1653 
1654 void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1655   assert(!Import->getNextLocalImport() &&
1656          "Import declaration already in the chain");
1657   assert(!Import->isFromASTFile() && "Non-local import declaration");
1658   if (!FirstLocalImport) {
1659     FirstLocalImport = Import;
1660     LastLocalImport = Import;
1661     return;
1662   }
1663 
1664   LastLocalImport->setNextLocalImport(Import);
1665   LastLocalImport = Import;
1666 }
1667 
1668 //===----------------------------------------------------------------------===//
1669 //                         Type Sizing and Analysis
1670 //===----------------------------------------------------------------------===//
1671 
1672 /// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1673 /// scalar floating point type.
1674 const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
1675   switch (T->castAs<BuiltinType>()->getKind()) {
1676   default:
1677     llvm_unreachable("Not a floating point type!");
1678   case BuiltinType::BFloat16:
1679     return Target->getBFloat16Format();
1680   case BuiltinType::Float16:
1681   case BuiltinType::Half:
1682     return Target->getHalfFormat();
1683   case BuiltinType::Float:      return Target->getFloatFormat();
1684   case BuiltinType::Double:     return Target->getDoubleFormat();
1685   case BuiltinType::LongDouble:
1686     if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice)
1687       return AuxTarget->getLongDoubleFormat();
1688     return Target->getLongDoubleFormat();
1689   case BuiltinType::Float128:
1690     if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice)
1691       return AuxTarget->getFloat128Format();
1692     return Target->getFloat128Format();
1693   }
1694 }
1695 
1696 CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
1697   unsigned Align = Target->getCharWidth();
1698 
1699   bool UseAlignAttrOnly = false;
1700   if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1701     Align = AlignFromAttr;
1702 
1703     // __attribute__((aligned)) can increase or decrease alignment
1704     // *except* on a struct or struct member, where it only increases
1705     // alignment unless 'packed' is also specified.
1706     //
1707     // It is an error for alignas to decrease alignment, so we can
1708     // ignore that possibility;  Sema should diagnose it.
1709     if (isa<FieldDecl>(D)) {
1710       UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1711         cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1712     } else {
1713       UseAlignAttrOnly = true;
1714     }
1715   }
1716   else if (isa<FieldDecl>(D))
1717       UseAlignAttrOnly =
1718         D->hasAttr<PackedAttr>() ||
1719         cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1720 
1721   // If we're using the align attribute only, just ignore everything
1722   // else about the declaration and its type.
1723   if (UseAlignAttrOnly) {
1724     // do nothing
1725   } else if (const auto *VD = dyn_cast<ValueDecl>(D)) {
1726     QualType T = VD->getType();
1727     if (const auto *RT = T->getAs<ReferenceType>()) {
1728       if (ForAlignof)
1729         T = RT->getPointeeType();
1730       else
1731         T = getPointerType(RT->getPointeeType());
1732     }
1733     QualType BaseT = getBaseElementType(T);
1734     if (T->isFunctionType())
1735       Align = getTypeInfoImpl(T.getTypePtr()).Align;
1736     else if (!BaseT->isIncompleteType()) {
1737       // Adjust alignments of declarations with array type by the
1738       // large-array alignment on the target.
1739       if (const ArrayType *arrayType = getAsArrayType(T)) {
1740         unsigned MinWidth = Target->getLargeArrayMinWidth();
1741         if (!ForAlignof && MinWidth) {
1742           if (isa<VariableArrayType>(arrayType))
1743             Align = std::max(Align, Target->getLargeArrayAlign());
1744           else if (isa<ConstantArrayType>(arrayType) &&
1745                    MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1746             Align = std::max(Align, Target->getLargeArrayAlign());
1747         }
1748       }
1749       Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
1750       if (BaseT.getQualifiers().hasUnaligned())
1751         Align = Target->getCharWidth();
1752       if (const auto *VD = dyn_cast<VarDecl>(D)) {
1753         if (VD->hasGlobalStorage() && !ForAlignof) {
1754           uint64_t TypeSize = getTypeSize(T.getTypePtr());
1755           Align = std::max(Align, getTargetInfo().getMinGlobalAlign(TypeSize));
1756         }
1757       }
1758     }
1759 
1760     // Fields can be subject to extra alignment constraints, like if
1761     // the field is packed, the struct is packed, or the struct has a
1762     // a max-field-alignment constraint (#pragma pack).  So calculate
1763     // the actual alignment of the field within the struct, and then
1764     // (as we're expected to) constrain that by the alignment of the type.
1765     if (const auto *Field = dyn_cast<FieldDecl>(VD)) {
1766       const RecordDecl *Parent = Field->getParent();
1767       // We can only produce a sensible answer if the record is valid.
1768       if (!Parent->isInvalidDecl()) {
1769         const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
1770 
1771         // Start with the record's overall alignment.
1772         unsigned FieldAlign = toBits(Layout.getAlignment());
1773 
1774         // Use the GCD of that and the offset within the record.
1775         uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1776         if (Offset > 0) {
1777           // Alignment is always a power of 2, so the GCD will be a power of 2,
1778           // which means we get to do this crazy thing instead of Euclid's.
1779           uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1780           if (LowBitOfOffset < FieldAlign)
1781             FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1782         }
1783 
1784         Align = std::min(Align, FieldAlign);
1785       }
1786     }
1787   }
1788 
1789   // Some targets have hard limitation on the maximum requestable alignment in
1790   // aligned attribute for static variables.
1791   const unsigned MaxAlignedAttr = getTargetInfo().getMaxAlignedAttribute();
1792   const auto *VD = dyn_cast<VarDecl>(D);
1793   if (MaxAlignedAttr && VD && VD->getStorageClass() == SC_Static)
1794     Align = std::min(Align, MaxAlignedAttr);
1795 
1796   return toCharUnitsFromBits(Align);
1797 }
1798 
1799 CharUnits ASTContext::getExnObjectAlignment() const {
1800   return toCharUnitsFromBits(Target->getExnObjectAlignment());
1801 }
1802 
1803 // getTypeInfoDataSizeInChars - Return the size of a type, in
1804 // chars. If the type is a record, its data size is returned.  This is
1805 // the size of the memcpy that's performed when assigning this type
1806 // using a trivial copy/move assignment operator.
1807 TypeInfoChars ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1808   TypeInfoChars Info = getTypeInfoInChars(T);
1809 
1810   // In C++, objects can sometimes be allocated into the tail padding
1811   // of a base-class subobject.  We decide whether that's possible
1812   // during class layout, so here we can just trust the layout results.
1813   if (getLangOpts().CPlusPlus) {
1814     if (const auto *RT = T->getAs<RecordType>()) {
1815       const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1816       Info.Width = layout.getDataSize();
1817     }
1818   }
1819 
1820   return Info;
1821 }
1822 
1823 /// getConstantArrayInfoInChars - Performing the computation in CharUnits
1824 /// instead of in bits prevents overflowing the uint64_t for some large arrays.
1825 TypeInfoChars
1826 static getConstantArrayInfoInChars(const ASTContext &Context,
1827                                    const ConstantArrayType *CAT) {
1828   TypeInfoChars EltInfo = Context.getTypeInfoInChars(CAT->getElementType());
1829   uint64_t Size = CAT->getSize().getZExtValue();
1830   assert((Size == 0 || static_cast<uint64_t>(EltInfo.Width.getQuantity()) <=
1831               (uint64_t)(-1)/Size) &&
1832          "Overflow in array type char size evaluation");
1833   uint64_t Width = EltInfo.Width.getQuantity() * Size;
1834   unsigned Align = EltInfo.Align.getQuantity();
1835   if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1836       Context.getTargetInfo().getPointerWidth(0) == 64)
1837     Width = llvm::alignTo(Width, Align);
1838   return TypeInfoChars(CharUnits::fromQuantity(Width),
1839                        CharUnits::fromQuantity(Align),
1840                        EltInfo.AlignIsRequired);
1841 }
1842 
1843 TypeInfoChars ASTContext::getTypeInfoInChars(const Type *T) const {
1844   if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
1845     return getConstantArrayInfoInChars(*this, CAT);
1846   TypeInfo Info = getTypeInfo(T);
1847   return TypeInfoChars(toCharUnitsFromBits(Info.Width),
1848                        toCharUnitsFromBits(Info.Align),
1849                        Info.AlignIsRequired);
1850 }
1851 
1852 TypeInfoChars ASTContext::getTypeInfoInChars(QualType T) const {
1853   return getTypeInfoInChars(T.getTypePtr());
1854 }
1855 
1856 bool ASTContext::isAlignmentRequired(const Type *T) const {
1857   return getTypeInfo(T).AlignIsRequired;
1858 }
1859 
1860 bool ASTContext::isAlignmentRequired(QualType T) const {
1861   return isAlignmentRequired(T.getTypePtr());
1862 }
1863 
1864 unsigned ASTContext::getTypeAlignIfKnown(QualType T,
1865                                          bool NeedsPreferredAlignment) const {
1866   // An alignment on a typedef overrides anything else.
1867   if (const auto *TT = T->getAs<TypedefType>())
1868     if (unsigned Align = TT->getDecl()->getMaxAlignment())
1869       return Align;
1870 
1871   // If we have an (array of) complete type, we're done.
1872   T = getBaseElementType(T);
1873   if (!T->isIncompleteType())
1874     return NeedsPreferredAlignment ? getPreferredTypeAlign(T) : getTypeAlign(T);
1875 
1876   // If we had an array type, its element type might be a typedef
1877   // type with an alignment attribute.
1878   if (const auto *TT = T->getAs<TypedefType>())
1879     if (unsigned Align = TT->getDecl()->getMaxAlignment())
1880       return Align;
1881 
1882   // Otherwise, see if the declaration of the type had an attribute.
1883   if (const auto *TT = T->getAs<TagType>())
1884     return TT->getDecl()->getMaxAlignment();
1885 
1886   return 0;
1887 }
1888 
1889 TypeInfo ASTContext::getTypeInfo(const Type *T) const {
1890   TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1891   if (I != MemoizedTypeInfo.end())
1892     return I->second;
1893 
1894   // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1895   TypeInfo TI = getTypeInfoImpl(T);
1896   MemoizedTypeInfo[T] = TI;
1897   return TI;
1898 }
1899 
1900 /// getTypeInfoImpl - Return the size of the specified type, in bits.  This
1901 /// method does not work on incomplete types.
1902 ///
1903 /// FIXME: Pointers into different addr spaces could have different sizes and
1904 /// alignment requirements: getPointerInfo should take an AddrSpace, this
1905 /// should take a QualType, &c.
1906 TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1907   uint64_t Width = 0;
1908   unsigned Align = 8;
1909   bool AlignIsRequired = false;
1910   unsigned AS = 0;
1911   switch (T->getTypeClass()) {
1912 #define TYPE(Class, Base)
1913 #define ABSTRACT_TYPE(Class, Base)
1914 #define NON_CANONICAL_TYPE(Class, Base)
1915 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1916 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)                       \
1917   case Type::Class:                                                            \
1918   assert(!T->isDependentType() && "should not see dependent types here");      \
1919   return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
1920 #include "clang/AST/TypeNodes.inc"
1921     llvm_unreachable("Should not see dependent types");
1922 
1923   case Type::FunctionNoProto:
1924   case Type::FunctionProto:
1925     // GCC extension: alignof(function) = 32 bits
1926     Width = 0;
1927     Align = 32;
1928     break;
1929 
1930   case Type::IncompleteArray:
1931   case Type::VariableArray:
1932   case Type::ConstantArray: {
1933     // Model non-constant sized arrays as size zero, but track the alignment.
1934     uint64_t Size = 0;
1935     if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
1936       Size = CAT->getSize().getZExtValue();
1937 
1938     TypeInfo EltInfo = getTypeInfo(cast<ArrayType>(T)->getElementType());
1939     assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
1940            "Overflow in array type bit size evaluation");
1941     Width = EltInfo.Width * Size;
1942     Align = EltInfo.Align;
1943     AlignIsRequired = EltInfo.AlignIsRequired;
1944     if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1945         getTargetInfo().getPointerWidth(0) == 64)
1946       Width = llvm::alignTo(Width, Align);
1947     break;
1948   }
1949 
1950   case Type::ExtVector:
1951   case Type::Vector: {
1952     const auto *VT = cast<VectorType>(T);
1953     TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1954     Width = EltInfo.Width * VT->getNumElements();
1955     Align = Width;
1956     // If the alignment is not a power of 2, round up to the next power of 2.
1957     // This happens for non-power-of-2 length vectors.
1958     if (Align & (Align-1)) {
1959       Align = llvm::NextPowerOf2(Align);
1960       Width = llvm::alignTo(Width, Align);
1961     }
1962     // Adjust the alignment based on the target max.
1963     uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1964     if (TargetVectorAlign && TargetVectorAlign < Align)
1965       Align = TargetVectorAlign;
1966     if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector)
1967       // Adjust the alignment for fixed-length SVE vectors. This is important
1968       // for non-power-of-2 vector lengths.
1969       Align = 128;
1970     else if (VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector)
1971       // Adjust the alignment for fixed-length SVE predicates.
1972       Align = 16;
1973     break;
1974   }
1975 
1976   case Type::ConstantMatrix: {
1977     const auto *MT = cast<ConstantMatrixType>(T);
1978     TypeInfo ElementInfo = getTypeInfo(MT->getElementType());
1979     // The internal layout of a matrix value is implementation defined.
1980     // Initially be ABI compatible with arrays with respect to alignment and
1981     // size.
1982     Width = ElementInfo.Width * MT->getNumRows() * MT->getNumColumns();
1983     Align = ElementInfo.Align;
1984     break;
1985   }
1986 
1987   case Type::Builtin:
1988     switch (cast<BuiltinType>(T)->getKind()) {
1989     default: llvm_unreachable("Unknown builtin type!");
1990     case BuiltinType::Void:
1991       // GCC extension: alignof(void) = 8 bits.
1992       Width = 0;
1993       Align = 8;
1994       break;
1995     case BuiltinType::Bool:
1996       Width = Target->getBoolWidth();
1997       Align = Target->getBoolAlign();
1998       break;
1999     case BuiltinType::Char_S:
2000     case BuiltinType::Char_U:
2001     case BuiltinType::UChar:
2002     case BuiltinType::SChar:
2003     case BuiltinType::Char8:
2004       Width = Target->getCharWidth();
2005       Align = Target->getCharAlign();
2006       break;
2007     case BuiltinType::WChar_S:
2008     case BuiltinType::WChar_U:
2009       Width = Target->getWCharWidth();
2010       Align = Target->getWCharAlign();
2011       break;
2012     case BuiltinType::Char16:
2013       Width = Target->getChar16Width();
2014       Align = Target->getChar16Align();
2015       break;
2016     case BuiltinType::Char32:
2017       Width = Target->getChar32Width();
2018       Align = Target->getChar32Align();
2019       break;
2020     case BuiltinType::UShort:
2021     case BuiltinType::Short:
2022       Width = Target->getShortWidth();
2023       Align = Target->getShortAlign();
2024       break;
2025     case BuiltinType::UInt:
2026     case BuiltinType::Int:
2027       Width = Target->getIntWidth();
2028       Align = Target->getIntAlign();
2029       break;
2030     case BuiltinType::ULong:
2031     case BuiltinType::Long:
2032       Width = Target->getLongWidth();
2033       Align = Target->getLongAlign();
2034       break;
2035     case BuiltinType::ULongLong:
2036     case BuiltinType::LongLong:
2037       Width = Target->getLongLongWidth();
2038       Align = Target->getLongLongAlign();
2039       break;
2040     case BuiltinType::Int128:
2041     case BuiltinType::UInt128:
2042       Width = 128;
2043       Align = 128; // int128_t is 128-bit aligned on all targets.
2044       break;
2045     case BuiltinType::ShortAccum:
2046     case BuiltinType::UShortAccum:
2047     case BuiltinType::SatShortAccum:
2048     case BuiltinType::SatUShortAccum:
2049       Width = Target->getShortAccumWidth();
2050       Align = Target->getShortAccumAlign();
2051       break;
2052     case BuiltinType::Accum:
2053     case BuiltinType::UAccum:
2054     case BuiltinType::SatAccum:
2055     case BuiltinType::SatUAccum:
2056       Width = Target->getAccumWidth();
2057       Align = Target->getAccumAlign();
2058       break;
2059     case BuiltinType::LongAccum:
2060     case BuiltinType::ULongAccum:
2061     case BuiltinType::SatLongAccum:
2062     case BuiltinType::SatULongAccum:
2063       Width = Target->getLongAccumWidth();
2064       Align = Target->getLongAccumAlign();
2065       break;
2066     case BuiltinType::ShortFract:
2067     case BuiltinType::UShortFract:
2068     case BuiltinType::SatShortFract:
2069     case BuiltinType::SatUShortFract:
2070       Width = Target->getShortFractWidth();
2071       Align = Target->getShortFractAlign();
2072       break;
2073     case BuiltinType::Fract:
2074     case BuiltinType::UFract:
2075     case BuiltinType::SatFract:
2076     case BuiltinType::SatUFract:
2077       Width = Target->getFractWidth();
2078       Align = Target->getFractAlign();
2079       break;
2080     case BuiltinType::LongFract:
2081     case BuiltinType::ULongFract:
2082     case BuiltinType::SatLongFract:
2083     case BuiltinType::SatULongFract:
2084       Width = Target->getLongFractWidth();
2085       Align = Target->getLongFractAlign();
2086       break;
2087     case BuiltinType::BFloat16:
2088       Width = Target->getBFloat16Width();
2089       Align = Target->getBFloat16Align();
2090       break;
2091     case BuiltinType::Float16:
2092     case BuiltinType::Half:
2093       if (Target->hasFloat16Type() || !getLangOpts().OpenMP ||
2094           !getLangOpts().OpenMPIsDevice) {
2095         Width = Target->getHalfWidth();
2096         Align = Target->getHalfAlign();
2097       } else {
2098         assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
2099                "Expected OpenMP device compilation.");
2100         Width = AuxTarget->getHalfWidth();
2101         Align = AuxTarget->getHalfAlign();
2102       }
2103       break;
2104     case BuiltinType::Float:
2105       Width = Target->getFloatWidth();
2106       Align = Target->getFloatAlign();
2107       break;
2108     case BuiltinType::Double:
2109       Width = Target->getDoubleWidth();
2110       Align = Target->getDoubleAlign();
2111       break;
2112     case BuiltinType::LongDouble:
2113       if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
2114           (Target->getLongDoubleWidth() != AuxTarget->getLongDoubleWidth() ||
2115            Target->getLongDoubleAlign() != AuxTarget->getLongDoubleAlign())) {
2116         Width = AuxTarget->getLongDoubleWidth();
2117         Align = AuxTarget->getLongDoubleAlign();
2118       } else {
2119         Width = Target->getLongDoubleWidth();
2120         Align = Target->getLongDoubleAlign();
2121       }
2122       break;
2123     case BuiltinType::Float128:
2124       if (Target->hasFloat128Type() || !getLangOpts().OpenMP ||
2125           !getLangOpts().OpenMPIsDevice) {
2126         Width = Target->getFloat128Width();
2127         Align = Target->getFloat128Align();
2128       } else {
2129         assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
2130                "Expected OpenMP device compilation.");
2131         Width = AuxTarget->getFloat128Width();
2132         Align = AuxTarget->getFloat128Align();
2133       }
2134       break;
2135     case BuiltinType::NullPtr:
2136       Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
2137       Align = Target->getPointerAlign(0); //   == sizeof(void*)
2138       break;
2139     case BuiltinType::ObjCId:
2140     case BuiltinType::ObjCClass:
2141     case BuiltinType::ObjCSel:
2142       Width = Target->getPointerWidth(0);
2143       Align = Target->getPointerAlign(0);
2144       break;
2145     case BuiltinType::OCLSampler:
2146     case BuiltinType::OCLEvent:
2147     case BuiltinType::OCLClkEvent:
2148     case BuiltinType::OCLQueue:
2149     case BuiltinType::OCLReserveID:
2150 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2151     case BuiltinType::Id:
2152 #include "clang/Basic/OpenCLImageTypes.def"
2153 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2154   case BuiltinType::Id:
2155 #include "clang/Basic/OpenCLExtensionTypes.def"
2156       AS = getTargetAddressSpace(
2157           Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T)));
2158       Width = Target->getPointerWidth(AS);
2159       Align = Target->getPointerAlign(AS);
2160       break;
2161     // The SVE types are effectively target-specific.  The length of an
2162     // SVE_VECTOR_TYPE is only known at runtime, but it is always a multiple
2163     // of 128 bits.  There is one predicate bit for each vector byte, so the
2164     // length of an SVE_PREDICATE_TYPE is always a multiple of 16 bits.
2165     //
2166     // Because the length is only known at runtime, we use a dummy value
2167     // of 0 for the static length.  The alignment values are those defined
2168     // by the Procedure Call Standard for the Arm Architecture.
2169 #define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId, NumEls, ElBits,    \
2170                         IsSigned, IsFP, IsBF)                                  \
2171   case BuiltinType::Id:                                                        \
2172     Width = 0;                                                                 \
2173     Align = 128;                                                               \
2174     break;
2175 #define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId, NumEls)         \
2176   case BuiltinType::Id:                                                        \
2177     Width = 0;                                                                 \
2178     Align = 16;                                                                \
2179     break;
2180 #include "clang/Basic/AArch64SVEACLETypes.def"
2181 #define PPC_VECTOR_TYPE(Name, Id, Size)                                        \
2182   case BuiltinType::Id:                                                        \
2183     Width = Size;                                                              \
2184     Align = Size;                                                              \
2185     break;
2186 #include "clang/Basic/PPCTypes.def"
2187 #define RVV_VECTOR_TYPE(Name, Id, SingletonId, ElKind, ElBits, NF, IsSigned,   \
2188                         IsFP)                                                  \
2189   case BuiltinType::Id:                                                        \
2190     Width = 0;                                                                 \
2191     Align = ElBits;                                                            \
2192     break;
2193 #define RVV_PREDICATE_TYPE(Name, Id, SingletonId, ElKind)                      \
2194   case BuiltinType::Id:                                                        \
2195     Width = 0;                                                                 \
2196     Align = 8;                                                                 \
2197     break;
2198 #include "clang/Basic/RISCVVTypes.def"
2199     }
2200     break;
2201   case Type::ObjCObjectPointer:
2202     Width = Target->getPointerWidth(0);
2203     Align = Target->getPointerAlign(0);
2204     break;
2205   case Type::BlockPointer:
2206     AS = getTargetAddressSpace(cast<BlockPointerType>(T)->getPointeeType());
2207     Width = Target->getPointerWidth(AS);
2208     Align = Target->getPointerAlign(AS);
2209     break;
2210   case Type::LValueReference:
2211   case Type::RValueReference:
2212     // alignof and sizeof should never enter this code path here, so we go
2213     // the pointer route.
2214     AS = getTargetAddressSpace(cast<ReferenceType>(T)->getPointeeType());
2215     Width = Target->getPointerWidth(AS);
2216     Align = Target->getPointerAlign(AS);
2217     break;
2218   case Type::Pointer:
2219     AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
2220     Width = Target->getPointerWidth(AS);
2221     Align = Target->getPointerAlign(AS);
2222     break;
2223   case Type::MemberPointer: {
2224     const auto *MPT = cast<MemberPointerType>(T);
2225     CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT);
2226     Width = MPI.Width;
2227     Align = MPI.Align;
2228     break;
2229   }
2230   case Type::Complex: {
2231     // Complex types have the same alignment as their elements, but twice the
2232     // size.
2233     TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
2234     Width = EltInfo.Width * 2;
2235     Align = EltInfo.Align;
2236     break;
2237   }
2238   case Type::ObjCObject:
2239     return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
2240   case Type::Adjusted:
2241   case Type::Decayed:
2242     return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
2243   case Type::ObjCInterface: {
2244     const auto *ObjCI = cast<ObjCInterfaceType>(T);
2245     if (ObjCI->getDecl()->isInvalidDecl()) {
2246       Width = 8;
2247       Align = 8;
2248       break;
2249     }
2250     const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2251     Width = toBits(Layout.getSize());
2252     Align = toBits(Layout.getAlignment());
2253     break;
2254   }
2255   case Type::ExtInt: {
2256     const auto *EIT = cast<ExtIntType>(T);
2257     Align =
2258         std::min(static_cast<unsigned>(std::max(
2259                      getCharWidth(), llvm::PowerOf2Ceil(EIT->getNumBits()))),
2260                  Target->getLongLongAlign());
2261     Width = llvm::alignTo(EIT->getNumBits(), Align);
2262     break;
2263   }
2264   case Type::Record:
2265   case Type::Enum: {
2266     const auto *TT = cast<TagType>(T);
2267 
2268     if (TT->getDecl()->isInvalidDecl()) {
2269       Width = 8;
2270       Align = 8;
2271       break;
2272     }
2273 
2274     if (const auto *ET = dyn_cast<EnumType>(TT)) {
2275       const EnumDecl *ED = ET->getDecl();
2276       TypeInfo Info =
2277           getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
2278       if (unsigned AttrAlign = ED->getMaxAlignment()) {
2279         Info.Align = AttrAlign;
2280         Info.AlignIsRequired = true;
2281       }
2282       return Info;
2283     }
2284 
2285     const auto *RT = cast<RecordType>(TT);
2286     const RecordDecl *RD = RT->getDecl();
2287     const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2288     Width = toBits(Layout.getSize());
2289     Align = toBits(Layout.getAlignment());
2290     AlignIsRequired = RD->hasAttr<AlignedAttr>();
2291     break;
2292   }
2293 
2294   case Type::SubstTemplateTypeParm:
2295     return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
2296                        getReplacementType().getTypePtr());
2297 
2298   case Type::Auto:
2299   case Type::DeducedTemplateSpecialization: {
2300     const auto *A = cast<DeducedType>(T);
2301     assert(!A->getDeducedType().isNull() &&
2302            "cannot request the size of an undeduced or dependent auto type");
2303     return getTypeInfo(A->getDeducedType().getTypePtr());
2304   }
2305 
2306   case Type::Paren:
2307     return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
2308 
2309   case Type::MacroQualified:
2310     return getTypeInfo(
2311         cast<MacroQualifiedType>(T)->getUnderlyingType().getTypePtr());
2312 
2313   case Type::ObjCTypeParam:
2314     return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
2315 
2316   case Type::Typedef: {
2317     const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
2318     TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
2319     // If the typedef has an aligned attribute on it, it overrides any computed
2320     // alignment we have.  This violates the GCC documentation (which says that
2321     // attribute(aligned) can only round up) but matches its implementation.
2322     if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
2323       Align = AttrAlign;
2324       AlignIsRequired = true;
2325     } else {
2326       Align = Info.Align;
2327       AlignIsRequired = Info.AlignIsRequired;
2328     }
2329     Width = Info.Width;
2330     break;
2331   }
2332 
2333   case Type::Elaborated:
2334     return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
2335 
2336   case Type::Attributed:
2337     return getTypeInfo(
2338                   cast<AttributedType>(T)->getEquivalentType().getTypePtr());
2339 
2340   case Type::Atomic: {
2341     // Start with the base type information.
2342     TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
2343     Width = Info.Width;
2344     Align = Info.Align;
2345 
2346     if (!Width) {
2347       // An otherwise zero-sized type should still generate an
2348       // atomic operation.
2349       Width = Target->getCharWidth();
2350       assert(Align);
2351     } else if (Width <= Target->getMaxAtomicPromoteWidth()) {
2352       // If the size of the type doesn't exceed the platform's max
2353       // atomic promotion width, make the size and alignment more
2354       // favorable to atomic operations:
2355 
2356       // Round the size up to a power of 2.
2357       if (!llvm::isPowerOf2_64(Width))
2358         Width = llvm::NextPowerOf2(Width);
2359 
2360       // Set the alignment equal to the size.
2361       Align = static_cast<unsigned>(Width);
2362     }
2363   }
2364   break;
2365 
2366   case Type::Pipe:
2367     Width = Target->getPointerWidth(getTargetAddressSpace(LangAS::opencl_global));
2368     Align = Target->getPointerAlign(getTargetAddressSpace(LangAS::opencl_global));
2369     break;
2370   }
2371 
2372   assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
2373   return TypeInfo(Width, Align, AlignIsRequired);
2374 }
2375 
2376 unsigned ASTContext::getTypeUnadjustedAlign(const Type *T) const {
2377   UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T);
2378   if (I != MemoizedUnadjustedAlign.end())
2379     return I->second;
2380 
2381   unsigned UnadjustedAlign;
2382   if (const auto *RT = T->getAs<RecordType>()) {
2383     const RecordDecl *RD = RT->getDecl();
2384     const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2385     UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2386   } else if (const auto *ObjCI = T->getAs<ObjCInterfaceType>()) {
2387     const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2388     UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2389   } else {
2390     UnadjustedAlign = getTypeAlign(T->getUnqualifiedDesugaredType());
2391   }
2392 
2393   MemoizedUnadjustedAlign[T] = UnadjustedAlign;
2394   return UnadjustedAlign;
2395 }
2396 
2397 unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
2398   unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
2399   return SimdAlign;
2400 }
2401 
2402 /// toCharUnitsFromBits - Convert a size in bits to a size in characters.
2403 CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
2404   return CharUnits::fromQuantity(BitSize / getCharWidth());
2405 }
2406 
2407 /// toBits - Convert a size in characters to a size in characters.
2408 int64_t ASTContext::toBits(CharUnits CharSize) const {
2409   return CharSize.getQuantity() * getCharWidth();
2410 }
2411 
2412 /// getTypeSizeInChars - Return the size of the specified type, in characters.
2413 /// This method does not work on incomplete types.
2414 CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
2415   return getTypeInfoInChars(T).Width;
2416 }
2417 CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
2418   return getTypeInfoInChars(T).Width;
2419 }
2420 
2421 /// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
2422 /// characters. This method does not work on incomplete types.
2423 CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
2424   return toCharUnitsFromBits(getTypeAlign(T));
2425 }
2426 CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
2427   return toCharUnitsFromBits(getTypeAlign(T));
2428 }
2429 
2430 /// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a
2431 /// type, in characters, before alignment adustments. This method does
2432 /// not work on incomplete types.
2433 CharUnits ASTContext::getTypeUnadjustedAlignInChars(QualType T) const {
2434   return toCharUnitsFromBits(getTypeUnadjustedAlign(T));
2435 }
2436 CharUnits ASTContext::getTypeUnadjustedAlignInChars(const Type *T) const {
2437   return toCharUnitsFromBits(getTypeUnadjustedAlign(T));
2438 }
2439 
2440 /// getPreferredTypeAlign - Return the "preferred" alignment of the specified
2441 /// type for the current target in bits.  This can be different than the ABI
2442 /// alignment in cases where it is beneficial for performance or backwards
2443 /// compatibility preserving to overalign a data type. (Note: despite the name,
2444 /// the preferred alignment is ABI-impacting, and not an optimization.)
2445 unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
2446   TypeInfo TI = getTypeInfo(T);
2447   unsigned ABIAlign = TI.Align;
2448 
2449   T = T->getBaseElementTypeUnsafe();
2450 
2451   // The preferred alignment of member pointers is that of a pointer.
2452   if (T->isMemberPointerType())
2453     return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
2454 
2455   if (!Target->allowsLargerPreferedTypeAlignment())
2456     return ABIAlign;
2457 
2458   if (const auto *RT = T->getAs<RecordType>()) {
2459     if (TI.AlignIsRequired || RT->getDecl()->isInvalidDecl())
2460       return ABIAlign;
2461 
2462     unsigned PreferredAlign = static_cast<unsigned>(
2463         toBits(getASTRecordLayout(RT->getDecl()).PreferredAlignment));
2464     assert(PreferredAlign >= ABIAlign &&
2465            "PreferredAlign should be at least as large as ABIAlign.");
2466     return PreferredAlign;
2467   }
2468 
2469   // Double (and, for targets supporting AIX `power` alignment, long double) and
2470   // long long should be naturally aligned (despite requiring less alignment) if
2471   // possible.
2472   if (const auto *CT = T->getAs<ComplexType>())
2473     T = CT->getElementType().getTypePtr();
2474   if (const auto *ET = T->getAs<EnumType>())
2475     T = ET->getDecl()->getIntegerType().getTypePtr();
2476   if (T->isSpecificBuiltinType(BuiltinType::Double) ||
2477       T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2478       T->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2479       (T->isSpecificBuiltinType(BuiltinType::LongDouble) &&
2480        Target->defaultsToAIXPowerAlignment()))
2481     // Don't increase the alignment if an alignment attribute was specified on a
2482     // typedef declaration.
2483     if (!TI.AlignIsRequired)
2484       return std::max(ABIAlign, (unsigned)getTypeSize(T));
2485 
2486   return ABIAlign;
2487 }
2488 
2489 /// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2490 /// for __attribute__((aligned)) on this target, to be used if no alignment
2491 /// value is specified.
2492 unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const {
2493   return getTargetInfo().getDefaultAlignForAttributeAligned();
2494 }
2495 
2496 /// getAlignOfGlobalVar - Return the alignment in bits that should be given
2497 /// to a global variable of the specified type.
2498 unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
2499   uint64_t TypeSize = getTypeSize(T.getTypePtr());
2500   return std::max(getPreferredTypeAlign(T),
2501                   getTargetInfo().getMinGlobalAlign(TypeSize));
2502 }
2503 
2504 /// getAlignOfGlobalVarInChars - Return the alignment in characters that
2505 /// should be given to a global variable of the specified type.
2506 CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
2507   return toCharUnitsFromBits(getAlignOfGlobalVar(T));
2508 }
2509 
2510 CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
2511   CharUnits Offset = CharUnits::Zero();
2512   const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2513   while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2514     Offset += Layout->getBaseClassOffset(Base);
2515     Layout = &getASTRecordLayout(Base);
2516   }
2517   return Offset;
2518 }
2519 
2520 CharUnits ASTContext::getMemberPointerPathAdjustment(const APValue &MP) const {
2521   const ValueDecl *MPD = MP.getMemberPointerDecl();
2522   CharUnits ThisAdjustment = CharUnits::Zero();
2523   ArrayRef<const CXXRecordDecl*> Path = MP.getMemberPointerPath();
2524   bool DerivedMember = MP.isMemberPointerToDerivedMember();
2525   const CXXRecordDecl *RD = cast<CXXRecordDecl>(MPD->getDeclContext());
2526   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
2527     const CXXRecordDecl *Base = RD;
2528     const CXXRecordDecl *Derived = Path[I];
2529     if (DerivedMember)
2530       std::swap(Base, Derived);
2531     ThisAdjustment += getASTRecordLayout(Derived).getBaseClassOffset(Base);
2532     RD = Path[I];
2533   }
2534   if (DerivedMember)
2535     ThisAdjustment = -ThisAdjustment;
2536   return ThisAdjustment;
2537 }
2538 
2539 /// DeepCollectObjCIvars -
2540 /// This routine first collects all declared, but not synthesized, ivars in
2541 /// super class and then collects all ivars, including those synthesized for
2542 /// current class. This routine is used for implementation of current class
2543 /// when all ivars, declared and synthesized are known.
2544 void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
2545                                       bool leafClass,
2546                             SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
2547   if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2548     DeepCollectObjCIvars(SuperClass, false, Ivars);
2549   if (!leafClass) {
2550     for (const auto *I : OI->ivars())
2551       Ivars.push_back(I);
2552   } else {
2553     auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
2554     for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
2555          Iv= Iv->getNextIvar())
2556       Ivars.push_back(Iv);
2557   }
2558 }
2559 
2560 /// CollectInheritedProtocols - Collect all protocols in current class and
2561 /// those inherited by it.
2562 void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
2563                           llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
2564   if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
2565     // We can use protocol_iterator here instead of
2566     // all_referenced_protocol_iterator since we are walking all categories.
2567     for (auto *Proto : OI->all_referenced_protocols()) {
2568       CollectInheritedProtocols(Proto, Protocols);
2569     }
2570 
2571     // Categories of this Interface.
2572     for (const auto *Cat : OI->visible_categories())
2573       CollectInheritedProtocols(Cat, Protocols);
2574 
2575     if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2576       while (SD) {
2577         CollectInheritedProtocols(SD, Protocols);
2578         SD = SD->getSuperClass();
2579       }
2580   } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
2581     for (auto *Proto : OC->protocols()) {
2582       CollectInheritedProtocols(Proto, Protocols);
2583     }
2584   } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
2585     // Insert the protocol.
2586     if (!Protocols.insert(
2587           const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2588       return;
2589 
2590     for (auto *Proto : OP->protocols())
2591       CollectInheritedProtocols(Proto, Protocols);
2592   }
2593 }
2594 
2595 static bool unionHasUniqueObjectRepresentations(const ASTContext &Context,
2596                                                 const RecordDecl *RD) {
2597   assert(RD->isUnion() && "Must be union type");
2598   CharUnits UnionSize = Context.getTypeSizeInChars(RD->getTypeForDecl());
2599 
2600   for (const auto *Field : RD->fields()) {
2601     if (!Context.hasUniqueObjectRepresentations(Field->getType()))
2602       return false;
2603     CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType());
2604     if (FieldSize != UnionSize)
2605       return false;
2606   }
2607   return !RD->field_empty();
2608 }
2609 
2610 static bool isStructEmpty(QualType Ty) {
2611   const RecordDecl *RD = Ty->castAs<RecordType>()->getDecl();
2612 
2613   if (!RD->field_empty())
2614     return false;
2615 
2616   if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD))
2617     return ClassDecl->isEmpty();
2618 
2619   return true;
2620 }
2621 
2622 static llvm::Optional<int64_t>
2623 structHasUniqueObjectRepresentations(const ASTContext &Context,
2624                                      const RecordDecl *RD) {
2625   assert(!RD->isUnion() && "Must be struct/class type");
2626   const auto &Layout = Context.getASTRecordLayout(RD);
2627 
2628   int64_t CurOffsetInBits = 0;
2629   if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) {
2630     if (ClassDecl->isDynamicClass())
2631       return llvm::None;
2632 
2633     SmallVector<std::pair<QualType, int64_t>, 4> Bases;
2634     for (const auto &Base : ClassDecl->bases()) {
2635       // Empty types can be inherited from, and non-empty types can potentially
2636       // have tail padding, so just make sure there isn't an error.
2637       if (!isStructEmpty(Base.getType())) {
2638         llvm::Optional<int64_t> Size = structHasUniqueObjectRepresentations(
2639             Context, Base.getType()->castAs<RecordType>()->getDecl());
2640         if (!Size)
2641           return llvm::None;
2642         Bases.emplace_back(Base.getType(), Size.getValue());
2643       }
2644     }
2645 
2646     llvm::sort(Bases, [&](const std::pair<QualType, int64_t> &L,
2647                           const std::pair<QualType, int64_t> &R) {
2648       return Layout.getBaseClassOffset(L.first->getAsCXXRecordDecl()) <
2649              Layout.getBaseClassOffset(R.first->getAsCXXRecordDecl());
2650     });
2651 
2652     for (const auto &Base : Bases) {
2653       int64_t BaseOffset = Context.toBits(
2654           Layout.getBaseClassOffset(Base.first->getAsCXXRecordDecl()));
2655       int64_t BaseSize = Base.second;
2656       if (BaseOffset != CurOffsetInBits)
2657         return llvm::None;
2658       CurOffsetInBits = BaseOffset + BaseSize;
2659     }
2660   }
2661 
2662   for (const auto *Field : RD->fields()) {
2663     if (!Field->getType()->isReferenceType() &&
2664         !Context.hasUniqueObjectRepresentations(Field->getType()))
2665       return llvm::None;
2666 
2667     int64_t FieldSizeInBits =
2668         Context.toBits(Context.getTypeSizeInChars(Field->getType()));
2669     if (Field->isBitField()) {
2670       int64_t BitfieldSize = Field->getBitWidthValue(Context);
2671 
2672       if (BitfieldSize > FieldSizeInBits)
2673         return llvm::None;
2674       FieldSizeInBits = BitfieldSize;
2675     }
2676 
2677     int64_t FieldOffsetInBits = Context.getFieldOffset(Field);
2678 
2679     if (FieldOffsetInBits != CurOffsetInBits)
2680       return llvm::None;
2681 
2682     CurOffsetInBits = FieldSizeInBits + FieldOffsetInBits;
2683   }
2684 
2685   return CurOffsetInBits;
2686 }
2687 
2688 bool ASTContext::hasUniqueObjectRepresentations(QualType Ty) const {
2689   // C++17 [meta.unary.prop]:
2690   //   The predicate condition for a template specialization
2691   //   has_unique_object_representations<T> shall be
2692   //   satisfied if and only if:
2693   //     (9.1) - T is trivially copyable, and
2694   //     (9.2) - any two objects of type T with the same value have the same
2695   //     object representation, where two objects
2696   //   of array or non-union class type are considered to have the same value
2697   //   if their respective sequences of
2698   //   direct subobjects have the same values, and two objects of union type
2699   //   are considered to have the same
2700   //   value if they have the same active member and the corresponding members
2701   //   have the same value.
2702   //   The set of scalar types for which this condition holds is
2703   //   implementation-defined. [ Note: If a type has padding
2704   //   bits, the condition does not hold; otherwise, the condition holds true
2705   //   for unsigned integral types. -- end note ]
2706   assert(!Ty.isNull() && "Null QualType sent to unique object rep check");
2707 
2708   // Arrays are unique only if their element type is unique.
2709   if (Ty->isArrayType())
2710     return hasUniqueObjectRepresentations(getBaseElementType(Ty));
2711 
2712   // (9.1) - T is trivially copyable...
2713   if (!Ty.isTriviallyCopyableType(*this))
2714     return false;
2715 
2716   // All integrals and enums are unique.
2717   if (Ty->isIntegralOrEnumerationType())
2718     return true;
2719 
2720   // All other pointers are unique.
2721   if (Ty->isPointerType())
2722     return true;
2723 
2724   if (Ty->isMemberPointerType()) {
2725     const auto *MPT = Ty->getAs<MemberPointerType>();
2726     return !ABI->getMemberPointerInfo(MPT).HasPadding;
2727   }
2728 
2729   if (Ty->isRecordType()) {
2730     const RecordDecl *Record = Ty->castAs<RecordType>()->getDecl();
2731 
2732     if (Record->isInvalidDecl())
2733       return false;
2734 
2735     if (Record->isUnion())
2736       return unionHasUniqueObjectRepresentations(*this, Record);
2737 
2738     Optional<int64_t> StructSize =
2739         structHasUniqueObjectRepresentations(*this, Record);
2740 
2741     return StructSize &&
2742            StructSize.getValue() == static_cast<int64_t>(getTypeSize(Ty));
2743   }
2744 
2745   // FIXME: More cases to handle here (list by rsmith):
2746   // vectors (careful about, eg, vector of 3 foo)
2747   // _Complex int and friends
2748   // _Atomic T
2749   // Obj-C block pointers
2750   // Obj-C object pointers
2751   // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t,
2752   // clk_event_t, queue_t, reserve_id_t)
2753   // There're also Obj-C class types and the Obj-C selector type, but I think it
2754   // makes sense for those to return false here.
2755 
2756   return false;
2757 }
2758 
2759 unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
2760   unsigned count = 0;
2761   // Count ivars declared in class extension.
2762   for (const auto *Ext : OI->known_extensions())
2763     count += Ext->ivar_size();
2764 
2765   // Count ivar defined in this class's implementation.  This
2766   // includes synthesized ivars.
2767   if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
2768     count += ImplDecl->ivar_size();
2769 
2770   return count;
2771 }
2772 
2773 bool ASTContext::isSentinelNullExpr(const Expr *E) {
2774   if (!E)
2775     return false;
2776 
2777   // nullptr_t is always treated as null.
2778   if (E->getType()->isNullPtrType()) return true;
2779 
2780   if (E->getType()->isAnyPointerType() &&
2781       E->IgnoreParenCasts()->isNullPointerConstant(*this,
2782                                                 Expr::NPC_ValueDependentIsNull))
2783     return true;
2784 
2785   // Unfortunately, __null has type 'int'.
2786   if (isa<GNUNullExpr>(E)) return true;
2787 
2788   return false;
2789 }
2790 
2791 /// Get the implementation of ObjCInterfaceDecl, or nullptr if none
2792 /// exists.
2793 ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
2794   llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2795     I = ObjCImpls.find(D);
2796   if (I != ObjCImpls.end())
2797     return cast<ObjCImplementationDecl>(I->second);
2798   return nullptr;
2799 }
2800 
2801 /// Get the implementation of ObjCCategoryDecl, or nullptr if none
2802 /// exists.
2803 ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
2804   llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2805     I = ObjCImpls.find(D);
2806   if (I != ObjCImpls.end())
2807     return cast<ObjCCategoryImplDecl>(I->second);
2808   return nullptr;
2809 }
2810 
2811 /// Set the implementation of ObjCInterfaceDecl.
2812 void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2813                            ObjCImplementationDecl *ImplD) {
2814   assert(IFaceD && ImplD && "Passed null params");
2815   ObjCImpls[IFaceD] = ImplD;
2816 }
2817 
2818 /// Set the implementation of ObjCCategoryDecl.
2819 void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
2820                            ObjCCategoryImplDecl *ImplD) {
2821   assert(CatD && ImplD && "Passed null params");
2822   ObjCImpls[CatD] = ImplD;
2823 }
2824 
2825 const ObjCMethodDecl *
2826 ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const {
2827   return ObjCMethodRedecls.lookup(MD);
2828 }
2829 
2830 void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2831                                             const ObjCMethodDecl *Redecl) {
2832   assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
2833   ObjCMethodRedecls[MD] = Redecl;
2834 }
2835 
2836 const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
2837                                               const NamedDecl *ND) const {
2838   if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
2839     return ID;
2840   if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
2841     return CD->getClassInterface();
2842   if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
2843     return IMD->getClassInterface();
2844 
2845   return nullptr;
2846 }
2847 
2848 /// Get the copy initialization expression of VarDecl, or nullptr if
2849 /// none exists.
2850 BlockVarCopyInit ASTContext::getBlockVarCopyInit(const VarDecl *VD) const {
2851   assert(VD && "Passed null params");
2852   assert(VD->hasAttr<BlocksAttr>() &&
2853          "getBlockVarCopyInits - not __block var");
2854   auto I = BlockVarCopyInits.find(VD);
2855   if (I != BlockVarCopyInits.end())
2856     return I->second;
2857   return {nullptr, false};
2858 }
2859 
2860 /// Set the copy initialization expression of a block var decl.
2861 void ASTContext::setBlockVarCopyInit(const VarDecl*VD, Expr *CopyExpr,
2862                                      bool CanThrow) {
2863   assert(VD && CopyExpr && "Passed null params");
2864   assert(VD->hasAttr<BlocksAttr>() &&
2865          "setBlockVarCopyInits - not __block var");
2866   BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow);
2867 }
2868 
2869 TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
2870                                                  unsigned DataSize) const {
2871   if (!DataSize)
2872     DataSize = TypeLoc::getFullDataSizeForType(T);
2873   else
2874     assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
2875            "incorrect data size provided to CreateTypeSourceInfo!");
2876 
2877   auto *TInfo =
2878     (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2879   new (TInfo) TypeSourceInfo(T);
2880   return TInfo;
2881 }
2882 
2883 TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
2884                                                      SourceLocation L) const {
2885   TypeSourceInfo *DI = CreateTypeSourceInfo(T);
2886   DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
2887   return DI;
2888 }
2889 
2890 const ASTRecordLayout &
2891 ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
2892   return getObjCLayout(D, nullptr);
2893 }
2894 
2895 const ASTRecordLayout &
2896 ASTContext::getASTObjCImplementationLayout(
2897                                         const ObjCImplementationDecl *D) const {
2898   return getObjCLayout(D->getClassInterface(), D);
2899 }
2900 
2901 //===----------------------------------------------------------------------===//
2902 //                   Type creation/memoization methods
2903 //===----------------------------------------------------------------------===//
2904 
2905 QualType
2906 ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2907   unsigned fastQuals = quals.getFastQualifiers();
2908   quals.removeFastQualifiers();
2909 
2910   // Check if we've already instantiated this type.
2911   llvm::FoldingSetNodeID ID;
2912   ExtQuals::Profile(ID, baseType, quals);
2913   void *insertPos = nullptr;
2914   if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2915     assert(eq->getQualifiers() == quals);
2916     return QualType(eq, fastQuals);
2917   }
2918 
2919   // If the base type is not canonical, make the appropriate canonical type.
2920   QualType canon;
2921   if (!baseType->isCanonicalUnqualified()) {
2922     SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
2923     canonSplit.Quals.addConsistentQualifiers(quals);
2924     canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
2925 
2926     // Re-find the insert position.
2927     (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2928   }
2929 
2930   auto *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2931   ExtQualNodes.InsertNode(eq, insertPos);
2932   return QualType(eq, fastQuals);
2933 }
2934 
2935 QualType ASTContext::getAddrSpaceQualType(QualType T,
2936                                           LangAS AddressSpace) const {
2937   QualType CanT = getCanonicalType(T);
2938   if (CanT.getAddressSpace() == AddressSpace)
2939     return T;
2940 
2941   // If we are composing extended qualifiers together, merge together
2942   // into one ExtQuals node.
2943   QualifierCollector Quals;
2944   const Type *TypeNode = Quals.strip(T);
2945 
2946   // If this type already has an address space specified, it cannot get
2947   // another one.
2948   assert(!Quals.hasAddressSpace() &&
2949          "Type cannot be in multiple addr spaces!");
2950   Quals.addAddressSpace(AddressSpace);
2951 
2952   return getExtQualType(TypeNode, Quals);
2953 }
2954 
2955 QualType ASTContext::removeAddrSpaceQualType(QualType T) const {
2956   // If the type is not qualified with an address space, just return it
2957   // immediately.
2958   if (!T.hasAddressSpace())
2959     return T;
2960 
2961   // If we are composing extended qualifiers together, merge together
2962   // into one ExtQuals node.
2963   QualifierCollector Quals;
2964   const Type *TypeNode;
2965 
2966   while (T.hasAddressSpace()) {
2967     TypeNode = Quals.strip(T);
2968 
2969     // If the type no longer has an address space after stripping qualifiers,
2970     // jump out.
2971     if (!QualType(TypeNode, 0).hasAddressSpace())
2972       break;
2973 
2974     // There might be sugar in the way. Strip it and try again.
2975     T = T.getSingleStepDesugaredType(*this);
2976   }
2977 
2978   Quals.removeAddressSpace();
2979 
2980   // Removal of the address space can mean there are no longer any
2981   // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
2982   // or required.
2983   if (Quals.hasNonFastQualifiers())
2984     return getExtQualType(TypeNode, Quals);
2985   else
2986     return QualType(TypeNode, Quals.getFastQualifiers());
2987 }
2988 
2989 QualType ASTContext::getObjCGCQualType(QualType T,
2990                                        Qualifiers::GC GCAttr) const {
2991   QualType CanT = getCanonicalType(T);
2992   if (CanT.getObjCGCAttr() == GCAttr)
2993     return T;
2994 
2995   if (const auto *ptr = T->getAs<PointerType>()) {
2996     QualType Pointee = ptr->getPointeeType();
2997     if (Pointee->isAnyPointerType()) {
2998       QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2999       return getPointerType(ResultType);
3000     }
3001   }
3002 
3003   // If we are composing extended qualifiers together, merge together
3004   // into one ExtQuals node.
3005   QualifierCollector Quals;
3006   const Type *TypeNode = Quals.strip(T);
3007 
3008   // If this type already has an ObjCGC specified, it cannot get
3009   // another one.
3010   assert(!Quals.hasObjCGCAttr() &&
3011          "Type cannot have multiple ObjCGCs!");
3012   Quals.addObjCGCAttr(GCAttr);
3013 
3014   return getExtQualType(TypeNode, Quals);
3015 }
3016 
3017 QualType ASTContext::removePtrSizeAddrSpace(QualType T) const {
3018   if (const PointerType *Ptr = T->getAs<PointerType>()) {
3019     QualType Pointee = Ptr->getPointeeType();
3020     if (isPtrSizeAddressSpace(Pointee.getAddressSpace())) {
3021       return getPointerType(removeAddrSpaceQualType(Pointee));
3022     }
3023   }
3024   return T;
3025 }
3026 
3027 const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
3028                                                    FunctionType::ExtInfo Info) {
3029   if (T->getExtInfo() == Info)
3030     return T;
3031 
3032   QualType Result;
3033   if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
3034     Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
3035   } else {
3036     const auto *FPT = cast<FunctionProtoType>(T);
3037     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
3038     EPI.ExtInfo = Info;
3039     Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
3040   }
3041 
3042   return cast<FunctionType>(Result.getTypePtr());
3043 }
3044 
3045 void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
3046                                                  QualType ResultType) {
3047   FD = FD->getMostRecentDecl();
3048   while (true) {
3049     const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
3050     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
3051     FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
3052     if (FunctionDecl *Next = FD->getPreviousDecl())
3053       FD = Next;
3054     else
3055       break;
3056   }
3057   if (ASTMutationListener *L = getASTMutationListener())
3058     L->DeducedReturnType(FD, ResultType);
3059 }
3060 
3061 /// Get a function type and produce the equivalent function type with the
3062 /// specified exception specification. Type sugar that can be present on a
3063 /// declaration of a function with an exception specification is permitted
3064 /// and preserved. Other type sugar (for instance, typedefs) is not.
3065 QualType ASTContext::getFunctionTypeWithExceptionSpec(
3066     QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) {
3067   // Might have some parens.
3068   if (const auto *PT = dyn_cast<ParenType>(Orig))
3069     return getParenType(
3070         getFunctionTypeWithExceptionSpec(PT->getInnerType(), ESI));
3071 
3072   // Might be wrapped in a macro qualified type.
3073   if (const auto *MQT = dyn_cast<MacroQualifiedType>(Orig))
3074     return getMacroQualifiedType(
3075         getFunctionTypeWithExceptionSpec(MQT->getUnderlyingType(), ESI),
3076         MQT->getMacroIdentifier());
3077 
3078   // Might have a calling-convention attribute.
3079   if (const auto *AT = dyn_cast<AttributedType>(Orig))
3080     return getAttributedType(
3081         AT->getAttrKind(),
3082         getFunctionTypeWithExceptionSpec(AT->getModifiedType(), ESI),
3083         getFunctionTypeWithExceptionSpec(AT->getEquivalentType(), ESI));
3084 
3085   // Anything else must be a function type. Rebuild it with the new exception
3086   // specification.
3087   const auto *Proto = Orig->castAs<FunctionProtoType>();
3088   return getFunctionType(
3089       Proto->getReturnType(), Proto->getParamTypes(),
3090       Proto->getExtProtoInfo().withExceptionSpec(ESI));
3091 }
3092 
3093 bool ASTContext::hasSameFunctionTypeIgnoringExceptionSpec(QualType T,
3094                                                           QualType U) {
3095   return hasSameType(T, U) ||
3096          (getLangOpts().CPlusPlus17 &&
3097           hasSameType(getFunctionTypeWithExceptionSpec(T, EST_None),
3098                       getFunctionTypeWithExceptionSpec(U, EST_None)));
3099 }
3100 
3101 QualType ASTContext::getFunctionTypeWithoutPtrSizes(QualType T) {
3102   if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3103     QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3104     SmallVector<QualType, 16> Args(Proto->param_types());
3105     for (unsigned i = 0, n = Args.size(); i != n; ++i)
3106       Args[i] = removePtrSizeAddrSpace(Args[i]);
3107     return getFunctionType(RetTy, Args, Proto->getExtProtoInfo());
3108   }
3109 
3110   if (const FunctionNoProtoType *Proto = T->getAs<FunctionNoProtoType>()) {
3111     QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3112     return getFunctionNoProtoType(RetTy, Proto->getExtInfo());
3113   }
3114 
3115   return T;
3116 }
3117 
3118 bool ASTContext::hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U) {
3119   return hasSameType(T, U) ||
3120          hasSameType(getFunctionTypeWithoutPtrSizes(T),
3121                      getFunctionTypeWithoutPtrSizes(U));
3122 }
3123 
3124 void ASTContext::adjustExceptionSpec(
3125     FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
3126     bool AsWritten) {
3127   // Update the type.
3128   QualType Updated =
3129       getFunctionTypeWithExceptionSpec(FD->getType(), ESI);
3130   FD->setType(Updated);
3131 
3132   if (!AsWritten)
3133     return;
3134 
3135   // Update the type in the type source information too.
3136   if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
3137     // If the type and the type-as-written differ, we may need to update
3138     // the type-as-written too.
3139     if (TSInfo->getType() != FD->getType())
3140       Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI);
3141 
3142     // FIXME: When we get proper type location information for exceptions,
3143     // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
3144     // up the TypeSourceInfo;
3145     assert(TypeLoc::getFullDataSizeForType(Updated) ==
3146                TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
3147            "TypeLoc size mismatch from updating exception specification");
3148     TSInfo->overrideType(Updated);
3149   }
3150 }
3151 
3152 /// getComplexType - Return the uniqued reference to the type for a complex
3153 /// number with the specified element type.
3154 QualType ASTContext::getComplexType(QualType T) const {
3155   // Unique pointers, to guarantee there is only one pointer of a particular
3156   // structure.
3157   llvm::FoldingSetNodeID ID;
3158   ComplexType::Profile(ID, T);
3159 
3160   void *InsertPos = nullptr;
3161   if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
3162     return QualType(CT, 0);
3163 
3164   // If the pointee type isn't canonical, this won't be a canonical type either,
3165   // so fill in the canonical type field.
3166   QualType Canonical;
3167   if (!T.isCanonical()) {
3168     Canonical = getComplexType(getCanonicalType(T));
3169 
3170     // Get the new insert position for the node we care about.
3171     ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
3172     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3173   }
3174   auto *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
3175   Types.push_back(New);
3176   ComplexTypes.InsertNode(New, InsertPos);
3177   return QualType(New, 0);
3178 }
3179 
3180 /// getPointerType - Return the uniqued reference to the type for a pointer to
3181 /// the specified type.
3182 QualType ASTContext::getPointerType(QualType T) const {
3183   // Unique pointers, to guarantee there is only one pointer of a particular
3184   // structure.
3185   llvm::FoldingSetNodeID ID;
3186   PointerType::Profile(ID, T);
3187 
3188   void *InsertPos = nullptr;
3189   if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3190     return QualType(PT, 0);
3191 
3192   // If the pointee type isn't canonical, this won't be a canonical type either,
3193   // so fill in the canonical type field.
3194   QualType Canonical;
3195   if (!T.isCanonical()) {
3196     Canonical = getPointerType(getCanonicalType(T));
3197 
3198     // Get the new insert position for the node we care about.
3199     PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3200     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3201   }
3202   auto *New = new (*this, TypeAlignment) PointerType(T, Canonical);
3203   Types.push_back(New);
3204   PointerTypes.InsertNode(New, InsertPos);
3205   return QualType(New, 0);
3206 }
3207 
3208 QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
3209   llvm::FoldingSetNodeID ID;
3210   AdjustedType::Profile(ID, Orig, New);
3211   void *InsertPos = nullptr;
3212   AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3213   if (AT)
3214     return QualType(AT, 0);
3215 
3216   QualType Canonical = getCanonicalType(New);
3217 
3218   // Get the new insert position for the node we care about.
3219   AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3220   assert(!AT && "Shouldn't be in the map!");
3221 
3222   AT = new (*this, TypeAlignment)
3223       AdjustedType(Type::Adjusted, Orig, New, Canonical);
3224   Types.push_back(AT);
3225   AdjustedTypes.InsertNode(AT, InsertPos);
3226   return QualType(AT, 0);
3227 }
3228 
3229 QualType ASTContext::getDecayedType(QualType T) const {
3230   assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
3231 
3232   QualType Decayed;
3233 
3234   // C99 6.7.5.3p7:
3235   //   A declaration of a parameter as "array of type" shall be
3236   //   adjusted to "qualified pointer to type", where the type
3237   //   qualifiers (if any) are those specified within the [ and ] of
3238   //   the array type derivation.
3239   if (T->isArrayType())
3240     Decayed = getArrayDecayedType(T);
3241 
3242   // C99 6.7.5.3p8:
3243   //   A declaration of a parameter as "function returning type"
3244   //   shall be adjusted to "pointer to function returning type", as
3245   //   in 6.3.2.1.
3246   if (T->isFunctionType())
3247     Decayed = getPointerType(T);
3248 
3249   llvm::FoldingSetNodeID ID;
3250   AdjustedType::Profile(ID, T, Decayed);
3251   void *InsertPos = nullptr;
3252   AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3253   if (AT)
3254     return QualType(AT, 0);
3255 
3256   QualType Canonical = getCanonicalType(Decayed);
3257 
3258   // Get the new insert position for the node we care about.
3259   AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3260   assert(!AT && "Shouldn't be in the map!");
3261 
3262   AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
3263   Types.push_back(AT);
3264   AdjustedTypes.InsertNode(AT, InsertPos);
3265   return QualType(AT, 0);
3266 }
3267 
3268 /// getBlockPointerType - Return the uniqued reference to the type for
3269 /// a pointer to the specified block.
3270 QualType ASTContext::getBlockPointerType(QualType T) const {
3271   assert(T->isFunctionType() && "block of function types only");
3272   // Unique pointers, to guarantee there is only one block of a particular
3273   // structure.
3274   llvm::FoldingSetNodeID ID;
3275   BlockPointerType::Profile(ID, T);
3276 
3277   void *InsertPos = nullptr;
3278   if (BlockPointerType *PT =
3279         BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3280     return QualType(PT, 0);
3281 
3282   // If the block pointee type isn't canonical, this won't be a canonical
3283   // type either so fill in the canonical type field.
3284   QualType Canonical;
3285   if (!T.isCanonical()) {
3286     Canonical = getBlockPointerType(getCanonicalType(T));
3287 
3288     // Get the new insert position for the node we care about.
3289     BlockPointerType *NewIP =
3290       BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3291     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3292   }
3293   auto *New = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
3294   Types.push_back(New);
3295   BlockPointerTypes.InsertNode(New, InsertPos);
3296   return QualType(New, 0);
3297 }
3298 
3299 /// getLValueReferenceType - Return the uniqued reference to the type for an
3300 /// lvalue reference to the specified type.
3301 QualType
3302 ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
3303   assert(getCanonicalType(T) != OverloadTy &&
3304          "Unresolved overloaded function type");
3305 
3306   // Unique pointers, to guarantee there is only one pointer of a particular
3307   // structure.
3308   llvm::FoldingSetNodeID ID;
3309   ReferenceType::Profile(ID, T, SpelledAsLValue);
3310 
3311   void *InsertPos = nullptr;
3312   if (LValueReferenceType *RT =
3313         LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
3314     return QualType(RT, 0);
3315 
3316   const auto *InnerRef = T->getAs<ReferenceType>();
3317 
3318   // If the referencee type isn't canonical, this won't be a canonical type
3319   // either, so fill in the canonical type field.
3320   QualType Canonical;
3321   if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
3322     QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
3323     Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
3324 
3325     // Get the new insert position for the node we care about.
3326     LValueReferenceType *NewIP =
3327       LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
3328     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3329   }
3330 
3331   auto *New = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
3332                                                              SpelledAsLValue);
3333   Types.push_back(New);
3334   LValueReferenceTypes.InsertNode(New, InsertPos);
3335 
3336   return QualType(New, 0);
3337 }
3338 
3339 /// getRValueReferenceType - Return the uniqued reference to the type for an
3340 /// rvalue reference to the specified type.
3341 QualType ASTContext::getRValueReferenceType(QualType T) const {
3342   // Unique pointers, to guarantee there is only one pointer of a particular
3343   // structure.
3344   llvm::FoldingSetNodeID ID;
3345   ReferenceType::Profile(ID, T, false);
3346 
3347   void *InsertPos = nullptr;
3348   if (RValueReferenceType *RT =
3349         RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
3350     return QualType(RT, 0);
3351 
3352   const auto *InnerRef = T->getAs<ReferenceType>();
3353 
3354   // If the referencee type isn't canonical, this won't be a canonical type
3355   // either, so fill in the canonical type field.
3356   QualType Canonical;
3357   if (InnerRef || !T.isCanonical()) {
3358     QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
3359     Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
3360 
3361     // Get the new insert position for the node we care about.
3362     RValueReferenceType *NewIP =
3363       RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
3364     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3365   }
3366 
3367   auto *New = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
3368   Types.push_back(New);
3369   RValueReferenceTypes.InsertNode(New, InsertPos);
3370   return QualType(New, 0);
3371 }
3372 
3373 /// getMemberPointerType - Return the uniqued reference to the type for a
3374 /// member pointer to the specified type, in the specified class.
3375 QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
3376   // Unique pointers, to guarantee there is only one pointer of a particular
3377   // structure.
3378   llvm::FoldingSetNodeID ID;
3379   MemberPointerType::Profile(ID, T, Cls);
3380 
3381   void *InsertPos = nullptr;
3382   if (MemberPointerType *PT =
3383       MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3384     return QualType(PT, 0);
3385 
3386   // If the pointee or class type isn't canonical, this won't be a canonical
3387   // type either, so fill in the canonical type field.
3388   QualType Canonical;
3389   if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
3390     Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
3391 
3392     // Get the new insert position for the node we care about.
3393     MemberPointerType *NewIP =
3394       MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3395     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3396   }
3397   auto *New = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
3398   Types.push_back(New);
3399   MemberPointerTypes.InsertNode(New, InsertPos);
3400   return QualType(New, 0);
3401 }
3402 
3403 /// getConstantArrayType - Return the unique reference to the type for an
3404 /// array of the specified element type.
3405 QualType ASTContext::getConstantArrayType(QualType EltTy,
3406                                           const llvm::APInt &ArySizeIn,
3407                                           const Expr *SizeExpr,
3408                                           ArrayType::ArraySizeModifier ASM,
3409                                           unsigned IndexTypeQuals) const {
3410   assert((EltTy->isDependentType() ||
3411           EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
3412          "Constant array of VLAs is illegal!");
3413 
3414   // We only need the size as part of the type if it's instantiation-dependent.
3415   if (SizeExpr && !SizeExpr->isInstantiationDependent())
3416     SizeExpr = nullptr;
3417 
3418   // Convert the array size into a canonical width matching the pointer size for
3419   // the target.
3420   llvm::APInt ArySize(ArySizeIn);
3421   ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
3422 
3423   llvm::FoldingSetNodeID ID;
3424   ConstantArrayType::Profile(ID, *this, EltTy, ArySize, SizeExpr, ASM,
3425                              IndexTypeQuals);
3426 
3427   void *InsertPos = nullptr;
3428   if (ConstantArrayType *ATP =
3429       ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
3430     return QualType(ATP, 0);
3431 
3432   // If the element type isn't canonical or has qualifiers, or the array bound
3433   // is instantiation-dependent, this won't be a canonical type either, so fill
3434   // in the canonical type field.
3435   QualType Canon;
3436   if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers() || SizeExpr) {
3437     SplitQualType canonSplit = getCanonicalType(EltTy).split();
3438     Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize, nullptr,
3439                                  ASM, IndexTypeQuals);
3440     Canon = getQualifiedType(Canon, canonSplit.Quals);
3441 
3442     // Get the new insert position for the node we care about.
3443     ConstantArrayType *NewIP =
3444       ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
3445     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3446   }
3447 
3448   void *Mem = Allocate(
3449       ConstantArrayType::totalSizeToAlloc<const Expr *>(SizeExpr ? 1 : 0),
3450       TypeAlignment);
3451   auto *New = new (Mem)
3452     ConstantArrayType(EltTy, Canon, ArySize, SizeExpr, ASM, IndexTypeQuals);
3453   ConstantArrayTypes.InsertNode(New, InsertPos);
3454   Types.push_back(New);
3455   return QualType(New, 0);
3456 }
3457 
3458 /// getVariableArrayDecayedType - Turns the given type, which may be
3459 /// variably-modified, into the corresponding type with all the known
3460 /// sizes replaced with [*].
3461 QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
3462   // Vastly most common case.
3463   if (!type->isVariablyModifiedType()) return type;
3464 
3465   QualType result;
3466 
3467   SplitQualType split = type.getSplitDesugaredType();
3468   const Type *ty = split.Ty;
3469   switch (ty->getTypeClass()) {
3470 #define TYPE(Class, Base)
3471 #define ABSTRACT_TYPE(Class, Base)
3472 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3473 #include "clang/AST/TypeNodes.inc"
3474     llvm_unreachable("didn't desugar past all non-canonical types?");
3475 
3476   // These types should never be variably-modified.
3477   case Type::Builtin:
3478   case Type::Complex:
3479   case Type::Vector:
3480   case Type::DependentVector:
3481   case Type::ExtVector:
3482   case Type::DependentSizedExtVector:
3483   case Type::ConstantMatrix:
3484   case Type::DependentSizedMatrix:
3485   case Type::DependentAddressSpace:
3486   case Type::ObjCObject:
3487   case Type::ObjCInterface:
3488   case Type::ObjCObjectPointer:
3489   case Type::Record:
3490   case Type::Enum:
3491   case Type::UnresolvedUsing:
3492   case Type::TypeOfExpr:
3493   case Type::TypeOf:
3494   case Type::Decltype:
3495   case Type::UnaryTransform:
3496   case Type::DependentName:
3497   case Type::InjectedClassName:
3498   case Type::TemplateSpecialization:
3499   case Type::DependentTemplateSpecialization:
3500   case Type::TemplateTypeParm:
3501   case Type::SubstTemplateTypeParmPack:
3502   case Type::Auto:
3503   case Type::DeducedTemplateSpecialization:
3504   case Type::PackExpansion:
3505   case Type::ExtInt:
3506   case Type::DependentExtInt:
3507     llvm_unreachable("type should never be variably-modified");
3508 
3509   // These types can be variably-modified but should never need to
3510   // further decay.
3511   case Type::FunctionNoProto:
3512   case Type::FunctionProto:
3513   case Type::BlockPointer:
3514   case Type::MemberPointer:
3515   case Type::Pipe:
3516     return type;
3517 
3518   // These types can be variably-modified.  All these modifications
3519   // preserve structure except as noted by comments.
3520   // TODO: if we ever care about optimizing VLAs, there are no-op
3521   // optimizations available here.
3522   case Type::Pointer:
3523     result = getPointerType(getVariableArrayDecayedType(
3524                               cast<PointerType>(ty)->getPointeeType()));
3525     break;
3526 
3527   case Type::LValueReference: {
3528     const auto *lv = cast<LValueReferenceType>(ty);
3529     result = getLValueReferenceType(
3530                  getVariableArrayDecayedType(lv->getPointeeType()),
3531                                     lv->isSpelledAsLValue());
3532     break;
3533   }
3534 
3535   case Type::RValueReference: {
3536     const auto *lv = cast<RValueReferenceType>(ty);
3537     result = getRValueReferenceType(
3538                  getVariableArrayDecayedType(lv->getPointeeType()));
3539     break;
3540   }
3541 
3542   case Type::Atomic: {
3543     const auto *at = cast<AtomicType>(ty);
3544     result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
3545     break;
3546   }
3547 
3548   case Type::ConstantArray: {
3549     const auto *cat = cast<ConstantArrayType>(ty);
3550     result = getConstantArrayType(
3551                  getVariableArrayDecayedType(cat->getElementType()),
3552                                   cat->getSize(),
3553                                   cat->getSizeExpr(),
3554                                   cat->getSizeModifier(),
3555                                   cat->getIndexTypeCVRQualifiers());
3556     break;
3557   }
3558 
3559   case Type::DependentSizedArray: {
3560     const auto *dat = cast<DependentSizedArrayType>(ty);
3561     result = getDependentSizedArrayType(
3562                  getVariableArrayDecayedType(dat->getElementType()),
3563                                         dat->getSizeExpr(),
3564                                         dat->getSizeModifier(),
3565                                         dat->getIndexTypeCVRQualifiers(),
3566                                         dat->getBracketsRange());
3567     break;
3568   }
3569 
3570   // Turn incomplete types into [*] types.
3571   case Type::IncompleteArray: {
3572     const auto *iat = cast<IncompleteArrayType>(ty);
3573     result = getVariableArrayType(
3574                  getVariableArrayDecayedType(iat->getElementType()),
3575                                   /*size*/ nullptr,
3576                                   ArrayType::Normal,
3577                                   iat->getIndexTypeCVRQualifiers(),
3578                                   SourceRange());
3579     break;
3580   }
3581 
3582   // Turn VLA types into [*] types.
3583   case Type::VariableArray: {
3584     const auto *vat = cast<VariableArrayType>(ty);
3585     result = getVariableArrayType(
3586                  getVariableArrayDecayedType(vat->getElementType()),
3587                                   /*size*/ nullptr,
3588                                   ArrayType::Star,
3589                                   vat->getIndexTypeCVRQualifiers(),
3590                                   vat->getBracketsRange());
3591     break;
3592   }
3593   }
3594 
3595   // Apply the top-level qualifiers from the original.
3596   return getQualifiedType(result, split.Quals);
3597 }
3598 
3599 /// getVariableArrayType - Returns a non-unique reference to the type for a
3600 /// variable array of the specified element type.
3601 QualType ASTContext::getVariableArrayType(QualType EltTy,
3602                                           Expr *NumElts,
3603                                           ArrayType::ArraySizeModifier ASM,
3604                                           unsigned IndexTypeQuals,
3605                                           SourceRange Brackets) const {
3606   // Since we don't unique expressions, it isn't possible to unique VLA's
3607   // that have an expression provided for their size.
3608   QualType Canon;
3609 
3610   // Be sure to pull qualifiers off the element type.
3611   if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
3612     SplitQualType canonSplit = getCanonicalType(EltTy).split();
3613     Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
3614                                  IndexTypeQuals, Brackets);
3615     Canon = getQualifiedType(Canon, canonSplit.Quals);
3616   }
3617 
3618   auto *New = new (*this, TypeAlignment)
3619     VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
3620 
3621   VariableArrayTypes.push_back(New);
3622   Types.push_back(New);
3623   return QualType(New, 0);
3624 }
3625 
3626 /// getDependentSizedArrayType - Returns a non-unique reference to
3627 /// the type for a dependently-sized array of the specified element
3628 /// type.
3629 QualType ASTContext::getDependentSizedArrayType(QualType elementType,
3630                                                 Expr *numElements,
3631                                                 ArrayType::ArraySizeModifier ASM,
3632                                                 unsigned elementTypeQuals,
3633                                                 SourceRange brackets) const {
3634   assert((!numElements || numElements->isTypeDependent() ||
3635           numElements->isValueDependent()) &&
3636          "Size must be type- or value-dependent!");
3637 
3638   // Dependently-sized array types that do not have a specified number
3639   // of elements will have their sizes deduced from a dependent
3640   // initializer.  We do no canonicalization here at all, which is okay
3641   // because they can't be used in most locations.
3642   if (!numElements) {
3643     auto *newType
3644       = new (*this, TypeAlignment)
3645           DependentSizedArrayType(*this, elementType, QualType(),
3646                                   numElements, ASM, elementTypeQuals,
3647                                   brackets);
3648     Types.push_back(newType);
3649     return QualType(newType, 0);
3650   }
3651 
3652   // Otherwise, we actually build a new type every time, but we
3653   // also build a canonical type.
3654 
3655   SplitQualType canonElementType = getCanonicalType(elementType).split();
3656 
3657   void *insertPos = nullptr;
3658   llvm::FoldingSetNodeID ID;
3659   DependentSizedArrayType::Profile(ID, *this,
3660                                    QualType(canonElementType.Ty, 0),
3661                                    ASM, elementTypeQuals, numElements);
3662 
3663   // Look for an existing type with these properties.
3664   DependentSizedArrayType *canonTy =
3665     DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
3666 
3667   // If we don't have one, build one.
3668   if (!canonTy) {
3669     canonTy = new (*this, TypeAlignment)
3670       DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
3671                               QualType(), numElements, ASM, elementTypeQuals,
3672                               brackets);
3673     DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
3674     Types.push_back(canonTy);
3675   }
3676 
3677   // Apply qualifiers from the element type to the array.
3678   QualType canon = getQualifiedType(QualType(canonTy,0),
3679                                     canonElementType.Quals);
3680 
3681   // If we didn't need extra canonicalization for the element type or the size
3682   // expression, then just use that as our result.
3683   if (QualType(canonElementType.Ty, 0) == elementType &&
3684       canonTy->getSizeExpr() == numElements)
3685     return canon;
3686 
3687   // Otherwise, we need to build a type which follows the spelling
3688   // of the element type.
3689   auto *sugaredType
3690     = new (*this, TypeAlignment)
3691         DependentSizedArrayType(*this, elementType, canon, numElements,
3692                                 ASM, elementTypeQuals, brackets);
3693   Types.push_back(sugaredType);
3694   return QualType(sugaredType, 0);
3695 }
3696 
3697 QualType ASTContext::getIncompleteArrayType(QualType elementType,
3698                                             ArrayType::ArraySizeModifier ASM,
3699                                             unsigned elementTypeQuals) const {
3700   llvm::FoldingSetNodeID ID;
3701   IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
3702 
3703   void *insertPos = nullptr;
3704   if (IncompleteArrayType *iat =
3705        IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
3706     return QualType(iat, 0);
3707 
3708   // If the element type isn't canonical, this won't be a canonical type
3709   // either, so fill in the canonical type field.  We also have to pull
3710   // qualifiers off the element type.
3711   QualType canon;
3712 
3713   if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
3714     SplitQualType canonSplit = getCanonicalType(elementType).split();
3715     canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
3716                                    ASM, elementTypeQuals);
3717     canon = getQualifiedType(canon, canonSplit.Quals);
3718 
3719     // Get the new insert position for the node we care about.
3720     IncompleteArrayType *existing =
3721       IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
3722     assert(!existing && "Shouldn't be in the map!"); (void) existing;
3723   }
3724 
3725   auto *newType = new (*this, TypeAlignment)
3726     IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
3727 
3728   IncompleteArrayTypes.InsertNode(newType, insertPos);
3729   Types.push_back(newType);
3730   return QualType(newType, 0);
3731 }
3732 
3733 ASTContext::BuiltinVectorTypeInfo
3734 ASTContext::getBuiltinVectorTypeInfo(const BuiltinType *Ty) const {
3735 #define SVE_INT_ELTTY(BITS, ELTS, SIGNED, NUMVECTORS)                          \
3736   {getIntTypeForBitwidth(BITS, SIGNED), llvm::ElementCount::getScalable(ELTS), \
3737    NUMVECTORS};
3738 
3739 #define SVE_ELTTY(ELTTY, ELTS, NUMVECTORS)                                     \
3740   {ELTTY, llvm::ElementCount::getScalable(ELTS), NUMVECTORS};
3741 
3742   switch (Ty->getKind()) {
3743   default:
3744     llvm_unreachable("Unsupported builtin vector type");
3745   case BuiltinType::SveInt8:
3746     return SVE_INT_ELTTY(8, 16, true, 1);
3747   case BuiltinType::SveUint8:
3748     return SVE_INT_ELTTY(8, 16, false, 1);
3749   case BuiltinType::SveInt8x2:
3750     return SVE_INT_ELTTY(8, 16, true, 2);
3751   case BuiltinType::SveUint8x2:
3752     return SVE_INT_ELTTY(8, 16, false, 2);
3753   case BuiltinType::SveInt8x3:
3754     return SVE_INT_ELTTY(8, 16, true, 3);
3755   case BuiltinType::SveUint8x3:
3756     return SVE_INT_ELTTY(8, 16, false, 3);
3757   case BuiltinType::SveInt8x4:
3758     return SVE_INT_ELTTY(8, 16, true, 4);
3759   case BuiltinType::SveUint8x4:
3760     return SVE_INT_ELTTY(8, 16, false, 4);
3761   case BuiltinType::SveInt16:
3762     return SVE_INT_ELTTY(16, 8, true, 1);
3763   case BuiltinType::SveUint16:
3764     return SVE_INT_ELTTY(16, 8, false, 1);
3765   case BuiltinType::SveInt16x2:
3766     return SVE_INT_ELTTY(16, 8, true, 2);
3767   case BuiltinType::SveUint16x2:
3768     return SVE_INT_ELTTY(16, 8, false, 2);
3769   case BuiltinType::SveInt16x3:
3770     return SVE_INT_ELTTY(16, 8, true, 3);
3771   case BuiltinType::SveUint16x3:
3772     return SVE_INT_ELTTY(16, 8, false, 3);
3773   case BuiltinType::SveInt16x4:
3774     return SVE_INT_ELTTY(16, 8, true, 4);
3775   case BuiltinType::SveUint16x4:
3776     return SVE_INT_ELTTY(16, 8, false, 4);
3777   case BuiltinType::SveInt32:
3778     return SVE_INT_ELTTY(32, 4, true, 1);
3779   case BuiltinType::SveUint32:
3780     return SVE_INT_ELTTY(32, 4, false, 1);
3781   case BuiltinType::SveInt32x2:
3782     return SVE_INT_ELTTY(32, 4, true, 2);
3783   case BuiltinType::SveUint32x2:
3784     return SVE_INT_ELTTY(32, 4, false, 2);
3785   case BuiltinType::SveInt32x3:
3786     return SVE_INT_ELTTY(32, 4, true, 3);
3787   case BuiltinType::SveUint32x3:
3788     return SVE_INT_ELTTY(32, 4, false, 3);
3789   case BuiltinType::SveInt32x4:
3790     return SVE_INT_ELTTY(32, 4, true, 4);
3791   case BuiltinType::SveUint32x4:
3792     return SVE_INT_ELTTY(32, 4, false, 4);
3793   case BuiltinType::SveInt64:
3794     return SVE_INT_ELTTY(64, 2, true, 1);
3795   case BuiltinType::SveUint64:
3796     return SVE_INT_ELTTY(64, 2, false, 1);
3797   case BuiltinType::SveInt64x2:
3798     return SVE_INT_ELTTY(64, 2, true, 2);
3799   case BuiltinType::SveUint64x2:
3800     return SVE_INT_ELTTY(64, 2, false, 2);
3801   case BuiltinType::SveInt64x3:
3802     return SVE_INT_ELTTY(64, 2, true, 3);
3803   case BuiltinType::SveUint64x3:
3804     return SVE_INT_ELTTY(64, 2, false, 3);
3805   case BuiltinType::SveInt64x4:
3806     return SVE_INT_ELTTY(64, 2, true, 4);
3807   case BuiltinType::SveUint64x4:
3808     return SVE_INT_ELTTY(64, 2, false, 4);
3809   case BuiltinType::SveBool:
3810     return SVE_ELTTY(BoolTy, 16, 1);
3811   case BuiltinType::SveFloat16:
3812     return SVE_ELTTY(HalfTy, 8, 1);
3813   case BuiltinType::SveFloat16x2:
3814     return SVE_ELTTY(HalfTy, 8, 2);
3815   case BuiltinType::SveFloat16x3:
3816     return SVE_ELTTY(HalfTy, 8, 3);
3817   case BuiltinType::SveFloat16x4:
3818     return SVE_ELTTY(HalfTy, 8, 4);
3819   case BuiltinType::SveFloat32:
3820     return SVE_ELTTY(FloatTy, 4, 1);
3821   case BuiltinType::SveFloat32x2:
3822     return SVE_ELTTY(FloatTy, 4, 2);
3823   case BuiltinType::SveFloat32x3:
3824     return SVE_ELTTY(FloatTy, 4, 3);
3825   case BuiltinType::SveFloat32x4:
3826     return SVE_ELTTY(FloatTy, 4, 4);
3827   case BuiltinType::SveFloat64:
3828     return SVE_ELTTY(DoubleTy, 2, 1);
3829   case BuiltinType::SveFloat64x2:
3830     return SVE_ELTTY(DoubleTy, 2, 2);
3831   case BuiltinType::SveFloat64x3:
3832     return SVE_ELTTY(DoubleTy, 2, 3);
3833   case BuiltinType::SveFloat64x4:
3834     return SVE_ELTTY(DoubleTy, 2, 4);
3835   case BuiltinType::SveBFloat16:
3836     return SVE_ELTTY(BFloat16Ty, 8, 1);
3837   case BuiltinType::SveBFloat16x2:
3838     return SVE_ELTTY(BFloat16Ty, 8, 2);
3839   case BuiltinType::SveBFloat16x3:
3840     return SVE_ELTTY(BFloat16Ty, 8, 3);
3841   case BuiltinType::SveBFloat16x4:
3842     return SVE_ELTTY(BFloat16Ty, 8, 4);
3843 #define RVV_VECTOR_TYPE_INT(Name, Id, SingletonId, NumEls, ElBits, NF,         \
3844                             IsSigned)                                          \
3845   case BuiltinType::Id:                                                        \
3846     return {getIntTypeForBitwidth(ElBits, IsSigned),                           \
3847             llvm::ElementCount::getScalable(NumEls), NF};
3848 #define RVV_VECTOR_TYPE_FLOAT(Name, Id, SingletonId, NumEls, ElBits, NF)       \
3849   case BuiltinType::Id:                                                        \
3850     return {ElBits == 16 ? HalfTy : (ElBits == 32 ? FloatTy : DoubleTy),       \
3851             llvm::ElementCount::getScalable(NumEls), NF};
3852 #define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls)                      \
3853   case BuiltinType::Id:                                                        \
3854     return {BoolTy, llvm::ElementCount::getScalable(NumEls), 1};
3855 #include "clang/Basic/RISCVVTypes.def"
3856   }
3857 }
3858 
3859 /// getScalableVectorType - Return the unique reference to a scalable vector
3860 /// type of the specified element type and size. VectorType must be a built-in
3861 /// type.
3862 QualType ASTContext::getScalableVectorType(QualType EltTy,
3863                                            unsigned NumElts) const {
3864   if (Target->hasAArch64SVETypes()) {
3865     uint64_t EltTySize = getTypeSize(EltTy);
3866 #define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId, NumEls, ElBits,    \
3867                         IsSigned, IsFP, IsBF)                                  \
3868   if (!EltTy->isBooleanType() &&                                               \
3869       ((EltTy->hasIntegerRepresentation() &&                                   \
3870         EltTy->hasSignedIntegerRepresentation() == IsSigned) ||                \
3871        (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() &&      \
3872         IsFP && !IsBF) ||                                                      \
3873        (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() &&       \
3874         IsBF && !IsFP)) &&                                                     \
3875       EltTySize == ElBits && NumElts == NumEls) {                              \
3876     return SingletonId;                                                        \
3877   }
3878 #define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId, NumEls)         \
3879   if (EltTy->isBooleanType() && NumElts == NumEls)                             \
3880     return SingletonId;
3881 #include "clang/Basic/AArch64SVEACLETypes.def"
3882   } else if (Target->hasRISCVVTypes()) {
3883     uint64_t EltTySize = getTypeSize(EltTy);
3884 #define RVV_VECTOR_TYPE(Name, Id, SingletonId, NumEls, ElBits, NF, IsSigned,   \
3885                         IsFP)                                                  \
3886     if (!EltTy->isBooleanType() &&                                             \
3887         ((EltTy->hasIntegerRepresentation() &&                                 \
3888           EltTy->hasSignedIntegerRepresentation() == IsSigned) ||              \
3889          (EltTy->hasFloatingRepresentation() && IsFP)) &&                      \
3890         EltTySize == ElBits && NumElts == NumEls)                              \
3891       return SingletonId;
3892 #define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls)                      \
3893     if (EltTy->isBooleanType() && NumElts == NumEls)                           \
3894       return SingletonId;
3895 #include "clang/Basic/RISCVVTypes.def"
3896   }
3897   return QualType();
3898 }
3899 
3900 /// getVectorType - Return the unique reference to a vector type of
3901 /// the specified element type and size. VectorType must be a built-in type.
3902 QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
3903                                    VectorType::VectorKind VecKind) const {
3904   assert(vecType->isBuiltinType());
3905 
3906   // Check if we've already instantiated a vector of this type.
3907   llvm::FoldingSetNodeID ID;
3908   VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
3909 
3910   void *InsertPos = nullptr;
3911   if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3912     return QualType(VTP, 0);
3913 
3914   // If the element type isn't canonical, this won't be a canonical type either,
3915   // so fill in the canonical type field.
3916   QualType Canonical;
3917   if (!vecType.isCanonical()) {
3918     Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
3919 
3920     // Get the new insert position for the node we care about.
3921     VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3922     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3923   }
3924   auto *New = new (*this, TypeAlignment)
3925     VectorType(vecType, NumElts, Canonical, VecKind);
3926   VectorTypes.InsertNode(New, InsertPos);
3927   Types.push_back(New);
3928   return QualType(New, 0);
3929 }
3930 
3931 QualType
3932 ASTContext::getDependentVectorType(QualType VecType, Expr *SizeExpr,
3933                                    SourceLocation AttrLoc,
3934                                    VectorType::VectorKind VecKind) const {
3935   llvm::FoldingSetNodeID ID;
3936   DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr,
3937                                VecKind);
3938   void *InsertPos = nullptr;
3939   DependentVectorType *Canon =
3940       DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3941   DependentVectorType *New;
3942 
3943   if (Canon) {
3944     New = new (*this, TypeAlignment) DependentVectorType(
3945         *this, VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind);
3946   } else {
3947     QualType CanonVecTy = getCanonicalType(VecType);
3948     if (CanonVecTy == VecType) {
3949       New = new (*this, TypeAlignment) DependentVectorType(
3950           *this, VecType, QualType(), SizeExpr, AttrLoc, VecKind);
3951 
3952       DependentVectorType *CanonCheck =
3953           DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3954       assert(!CanonCheck &&
3955              "Dependent-sized vector_size canonical type broken");
3956       (void)CanonCheck;
3957       DependentVectorTypes.InsertNode(New, InsertPos);
3958     } else {
3959       QualType CanonTy = getDependentVectorType(CanonVecTy, SizeExpr,
3960                                                 SourceLocation(), VecKind);
3961       New = new (*this, TypeAlignment) DependentVectorType(
3962           *this, VecType, CanonTy, SizeExpr, AttrLoc, VecKind);
3963     }
3964   }
3965 
3966   Types.push_back(New);
3967   return QualType(New, 0);
3968 }
3969 
3970 /// getExtVectorType - Return the unique reference to an extended vector type of
3971 /// the specified element type and size. VectorType must be a built-in type.
3972 QualType
3973 ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
3974   assert(vecType->isBuiltinType() || vecType->isDependentType());
3975 
3976   // Check if we've already instantiated a vector of this type.
3977   llvm::FoldingSetNodeID ID;
3978   VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
3979                       VectorType::GenericVector);
3980   void *InsertPos = nullptr;
3981   if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3982     return QualType(VTP, 0);
3983 
3984   // If the element type isn't canonical, this won't be a canonical type either,
3985   // so fill in the canonical type field.
3986   QualType Canonical;
3987   if (!vecType.isCanonical()) {
3988     Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
3989 
3990     // Get the new insert position for the node we care about.
3991     VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3992     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3993   }
3994   auto *New = new (*this, TypeAlignment)
3995     ExtVectorType(vecType, NumElts, Canonical);
3996   VectorTypes.InsertNode(New, InsertPos);
3997   Types.push_back(New);
3998   return QualType(New, 0);
3999 }
4000 
4001 QualType
4002 ASTContext::getDependentSizedExtVectorType(QualType vecType,
4003                                            Expr *SizeExpr,
4004                                            SourceLocation AttrLoc) const {
4005   llvm::FoldingSetNodeID ID;
4006   DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
4007                                        SizeExpr);
4008 
4009   void *InsertPos = nullptr;
4010   DependentSizedExtVectorType *Canon
4011     = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4012   DependentSizedExtVectorType *New;
4013   if (Canon) {
4014     // We already have a canonical version of this array type; use it as
4015     // the canonical type for a newly-built type.
4016     New = new (*this, TypeAlignment)
4017       DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
4018                                   SizeExpr, AttrLoc);
4019   } else {
4020     QualType CanonVecTy = getCanonicalType(vecType);
4021     if (CanonVecTy == vecType) {
4022       New = new (*this, TypeAlignment)
4023         DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
4024                                     AttrLoc);
4025 
4026       DependentSizedExtVectorType *CanonCheck
4027         = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4028       assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
4029       (void)CanonCheck;
4030       DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
4031     } else {
4032       QualType CanonExtTy = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
4033                                                            SourceLocation());
4034       New = new (*this, TypeAlignment) DependentSizedExtVectorType(
4035           *this, vecType, CanonExtTy, SizeExpr, AttrLoc);
4036     }
4037   }
4038 
4039   Types.push_back(New);
4040   return QualType(New, 0);
4041 }
4042 
4043 QualType ASTContext::getConstantMatrixType(QualType ElementTy, unsigned NumRows,
4044                                            unsigned NumColumns) const {
4045   llvm::FoldingSetNodeID ID;
4046   ConstantMatrixType::Profile(ID, ElementTy, NumRows, NumColumns,
4047                               Type::ConstantMatrix);
4048 
4049   assert(MatrixType::isValidElementType(ElementTy) &&
4050          "need a valid element type");
4051   assert(ConstantMatrixType::isDimensionValid(NumRows) &&
4052          ConstantMatrixType::isDimensionValid(NumColumns) &&
4053          "need valid matrix dimensions");
4054   void *InsertPos = nullptr;
4055   if (ConstantMatrixType *MTP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos))
4056     return QualType(MTP, 0);
4057 
4058   QualType Canonical;
4059   if (!ElementTy.isCanonical()) {
4060     Canonical =
4061         getConstantMatrixType(getCanonicalType(ElementTy), NumRows, NumColumns);
4062 
4063     ConstantMatrixType *NewIP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4064     assert(!NewIP && "Matrix type shouldn't already exist in the map");
4065     (void)NewIP;
4066   }
4067 
4068   auto *New = new (*this, TypeAlignment)
4069       ConstantMatrixType(ElementTy, NumRows, NumColumns, Canonical);
4070   MatrixTypes.InsertNode(New, InsertPos);
4071   Types.push_back(New);
4072   return QualType(New, 0);
4073 }
4074 
4075 QualType ASTContext::getDependentSizedMatrixType(QualType ElementTy,
4076                                                  Expr *RowExpr,
4077                                                  Expr *ColumnExpr,
4078                                                  SourceLocation AttrLoc) const {
4079   QualType CanonElementTy = getCanonicalType(ElementTy);
4080   llvm::FoldingSetNodeID ID;
4081   DependentSizedMatrixType::Profile(ID, *this, CanonElementTy, RowExpr,
4082                                     ColumnExpr);
4083 
4084   void *InsertPos = nullptr;
4085   DependentSizedMatrixType *Canon =
4086       DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4087 
4088   if (!Canon) {
4089     Canon = new (*this, TypeAlignment) DependentSizedMatrixType(
4090         *this, CanonElementTy, QualType(), RowExpr, ColumnExpr, AttrLoc);
4091 #ifndef NDEBUG
4092     DependentSizedMatrixType *CanonCheck =
4093         DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4094     assert(!CanonCheck && "Dependent-sized matrix canonical type broken");
4095 #endif
4096     DependentSizedMatrixTypes.InsertNode(Canon, InsertPos);
4097     Types.push_back(Canon);
4098   }
4099 
4100   // Already have a canonical version of the matrix type
4101   //
4102   // If it exactly matches the requested type, use it directly.
4103   if (Canon->getElementType() == ElementTy && Canon->getRowExpr() == RowExpr &&
4104       Canon->getRowExpr() == ColumnExpr)
4105     return QualType(Canon, 0);
4106 
4107   // Use Canon as the canonical type for newly-built type.
4108   DependentSizedMatrixType *New = new (*this, TypeAlignment)
4109       DependentSizedMatrixType(*this, ElementTy, QualType(Canon, 0), RowExpr,
4110                                ColumnExpr, AttrLoc);
4111   Types.push_back(New);
4112   return QualType(New, 0);
4113 }
4114 
4115 QualType ASTContext::getDependentAddressSpaceType(QualType PointeeType,
4116                                                   Expr *AddrSpaceExpr,
4117                                                   SourceLocation AttrLoc) const {
4118   assert(AddrSpaceExpr->isInstantiationDependent());
4119 
4120   QualType canonPointeeType = getCanonicalType(PointeeType);
4121 
4122   void *insertPos = nullptr;
4123   llvm::FoldingSetNodeID ID;
4124   DependentAddressSpaceType::Profile(ID, *this, canonPointeeType,
4125                                      AddrSpaceExpr);
4126 
4127   DependentAddressSpaceType *canonTy =
4128     DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos);
4129 
4130   if (!canonTy) {
4131     canonTy = new (*this, TypeAlignment)
4132       DependentAddressSpaceType(*this, canonPointeeType,
4133                                 QualType(), AddrSpaceExpr, AttrLoc);
4134     DependentAddressSpaceTypes.InsertNode(canonTy, insertPos);
4135     Types.push_back(canonTy);
4136   }
4137 
4138   if (canonPointeeType == PointeeType &&
4139       canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
4140     return QualType(canonTy, 0);
4141 
4142   auto *sugaredType
4143     = new (*this, TypeAlignment)
4144         DependentAddressSpaceType(*this, PointeeType, QualType(canonTy, 0),
4145                                   AddrSpaceExpr, AttrLoc);
4146   Types.push_back(sugaredType);
4147   return QualType(sugaredType, 0);
4148 }
4149 
4150 /// Determine whether \p T is canonical as the result type of a function.
4151 static bool isCanonicalResultType(QualType T) {
4152   return T.isCanonical() &&
4153          (T.getObjCLifetime() == Qualifiers::OCL_None ||
4154           T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
4155 }
4156 
4157 /// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
4158 QualType
4159 ASTContext::getFunctionNoProtoType(QualType ResultTy,
4160                                    const FunctionType::ExtInfo &Info) const {
4161   // Unique functions, to guarantee there is only one function of a particular
4162   // structure.
4163   llvm::FoldingSetNodeID ID;
4164   FunctionNoProtoType::Profile(ID, ResultTy, Info);
4165 
4166   void *InsertPos = nullptr;
4167   if (FunctionNoProtoType *FT =
4168         FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
4169     return QualType(FT, 0);
4170 
4171   QualType Canonical;
4172   if (!isCanonicalResultType(ResultTy)) {
4173     Canonical =
4174       getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info);
4175 
4176     // Get the new insert position for the node we care about.
4177     FunctionNoProtoType *NewIP =
4178       FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
4179     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4180   }
4181 
4182   auto *New = new (*this, TypeAlignment)
4183     FunctionNoProtoType(ResultTy, Canonical, Info);
4184   Types.push_back(New);
4185   FunctionNoProtoTypes.InsertNode(New, InsertPos);
4186   return QualType(New, 0);
4187 }
4188 
4189 CanQualType
4190 ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
4191   CanQualType CanResultType = getCanonicalType(ResultType);
4192 
4193   // Canonical result types do not have ARC lifetime qualifiers.
4194   if (CanResultType.getQualifiers().hasObjCLifetime()) {
4195     Qualifiers Qs = CanResultType.getQualifiers();
4196     Qs.removeObjCLifetime();
4197     return CanQualType::CreateUnsafe(
4198              getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
4199   }
4200 
4201   return CanResultType;
4202 }
4203 
4204 static bool isCanonicalExceptionSpecification(
4205     const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
4206   if (ESI.Type == EST_None)
4207     return true;
4208   if (!NoexceptInType)
4209     return false;
4210 
4211   // C++17 onwards: exception specification is part of the type, as a simple
4212   // boolean "can this function type throw".
4213   if (ESI.Type == EST_BasicNoexcept)
4214     return true;
4215 
4216   // A noexcept(expr) specification is (possibly) canonical if expr is
4217   // value-dependent.
4218   if (ESI.Type == EST_DependentNoexcept)
4219     return true;
4220 
4221   // A dynamic exception specification is canonical if it only contains pack
4222   // expansions (so we can't tell whether it's non-throwing) and all its
4223   // contained types are canonical.
4224   if (ESI.Type == EST_Dynamic) {
4225     bool AnyPackExpansions = false;
4226     for (QualType ET : ESI.Exceptions) {
4227       if (!ET.isCanonical())
4228         return false;
4229       if (ET->getAs<PackExpansionType>())
4230         AnyPackExpansions = true;
4231     }
4232     return AnyPackExpansions;
4233   }
4234 
4235   return false;
4236 }
4237 
4238 QualType ASTContext::getFunctionTypeInternal(
4239     QualType ResultTy, ArrayRef<QualType> ArgArray,
4240     const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
4241   size_t NumArgs = ArgArray.size();
4242 
4243   // Unique functions, to guarantee there is only one function of a particular
4244   // structure.
4245   llvm::FoldingSetNodeID ID;
4246   FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
4247                              *this, true);
4248 
4249   QualType Canonical;
4250   bool Unique = false;
4251 
4252   void *InsertPos = nullptr;
4253   if (FunctionProtoType *FPT =
4254         FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
4255     QualType Existing = QualType(FPT, 0);
4256 
4257     // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
4258     // it so long as our exception specification doesn't contain a dependent
4259     // noexcept expression, or we're just looking for a canonical type.
4260     // Otherwise, we're going to need to create a type
4261     // sugar node to hold the concrete expression.
4262     if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) ||
4263         EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
4264       return Existing;
4265 
4266     // We need a new type sugar node for this one, to hold the new noexcept
4267     // expression. We do no canonicalization here, but that's OK since we don't
4268     // expect to see the same noexcept expression much more than once.
4269     Canonical = getCanonicalType(Existing);
4270     Unique = true;
4271   }
4272 
4273   bool NoexceptInType = getLangOpts().CPlusPlus17;
4274   bool IsCanonicalExceptionSpec =
4275       isCanonicalExceptionSpecification(EPI.ExceptionSpec, NoexceptInType);
4276 
4277   // Determine whether the type being created is already canonical or not.
4278   bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
4279                      isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
4280   for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
4281     if (!ArgArray[i].isCanonicalAsParam())
4282       isCanonical = false;
4283 
4284   if (OnlyWantCanonical)
4285     assert(isCanonical &&
4286            "given non-canonical parameters constructing canonical type");
4287 
4288   // If this type isn't canonical, get the canonical version of it if we don't
4289   // already have it. The exception spec is only partially part of the
4290   // canonical type, and only in C++17 onwards.
4291   if (!isCanonical && Canonical.isNull()) {
4292     SmallVector<QualType, 16> CanonicalArgs;
4293     CanonicalArgs.reserve(NumArgs);
4294     for (unsigned i = 0; i != NumArgs; ++i)
4295       CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
4296 
4297     llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
4298     FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
4299     CanonicalEPI.HasTrailingReturn = false;
4300 
4301     if (IsCanonicalExceptionSpec) {
4302       // Exception spec is already OK.
4303     } else if (NoexceptInType) {
4304       switch (EPI.ExceptionSpec.Type) {
4305       case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated:
4306         // We don't know yet. It shouldn't matter what we pick here; no-one
4307         // should ever look at this.
4308         LLVM_FALLTHROUGH;
4309       case EST_None: case EST_MSAny: case EST_NoexceptFalse:
4310         CanonicalEPI.ExceptionSpec.Type = EST_None;
4311         break;
4312 
4313         // A dynamic exception specification is almost always "not noexcept",
4314         // with the exception that a pack expansion might expand to no types.
4315       case EST_Dynamic: {
4316         bool AnyPacks = false;
4317         for (QualType ET : EPI.ExceptionSpec.Exceptions) {
4318           if (ET->getAs<PackExpansionType>())
4319             AnyPacks = true;
4320           ExceptionTypeStorage.push_back(getCanonicalType(ET));
4321         }
4322         if (!AnyPacks)
4323           CanonicalEPI.ExceptionSpec.Type = EST_None;
4324         else {
4325           CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
4326           CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
4327         }
4328         break;
4329       }
4330 
4331       case EST_DynamicNone:
4332       case EST_BasicNoexcept:
4333       case EST_NoexceptTrue:
4334       case EST_NoThrow:
4335         CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
4336         break;
4337 
4338       case EST_DependentNoexcept:
4339         llvm_unreachable("dependent noexcept is already canonical");
4340       }
4341     } else {
4342       CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
4343     }
4344 
4345     // Adjust the canonical function result type.
4346     CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
4347     Canonical =
4348         getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
4349 
4350     // Get the new insert position for the node we care about.
4351     FunctionProtoType *NewIP =
4352       FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
4353     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4354   }
4355 
4356   // Compute the needed size to hold this FunctionProtoType and the
4357   // various trailing objects.
4358   auto ESH = FunctionProtoType::getExceptionSpecSize(
4359       EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size());
4360   size_t Size = FunctionProtoType::totalSizeToAlloc<
4361       QualType, SourceLocation, FunctionType::FunctionTypeExtraBitfields,
4362       FunctionType::ExceptionType, Expr *, FunctionDecl *,
4363       FunctionProtoType::ExtParameterInfo, Qualifiers>(
4364       NumArgs, EPI.Variadic,
4365       FunctionProtoType::hasExtraBitfields(EPI.ExceptionSpec.Type),
4366       ESH.NumExceptionType, ESH.NumExprPtr, ESH.NumFunctionDeclPtr,
4367       EPI.ExtParameterInfos ? NumArgs : 0,
4368       EPI.TypeQuals.hasNonFastQualifiers() ? 1 : 0);
4369 
4370   auto *FTP = (FunctionProtoType *)Allocate(Size, TypeAlignment);
4371   FunctionProtoType::ExtProtoInfo newEPI = EPI;
4372   new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
4373   Types.push_back(FTP);
4374   if (!Unique)
4375     FunctionProtoTypes.InsertNode(FTP, InsertPos);
4376   return QualType(FTP, 0);
4377 }
4378 
4379 QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
4380   llvm::FoldingSetNodeID ID;
4381   PipeType::Profile(ID, T, ReadOnly);
4382 
4383   void *InsertPos = nullptr;
4384   if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
4385     return QualType(PT, 0);
4386 
4387   // If the pipe element type isn't canonical, this won't be a canonical type
4388   // either, so fill in the canonical type field.
4389   QualType Canonical;
4390   if (!T.isCanonical()) {
4391     Canonical = getPipeType(getCanonicalType(T), ReadOnly);
4392 
4393     // Get the new insert position for the node we care about.
4394     PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
4395     assert(!NewIP && "Shouldn't be in the map!");
4396     (void)NewIP;
4397   }
4398   auto *New = new (*this, TypeAlignment) PipeType(T, Canonical, ReadOnly);
4399   Types.push_back(New);
4400   PipeTypes.InsertNode(New, InsertPos);
4401   return QualType(New, 0);
4402 }
4403 
4404 QualType ASTContext::adjustStringLiteralBaseType(QualType Ty) const {
4405   // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
4406   return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant)
4407                          : Ty;
4408 }
4409 
4410 QualType ASTContext::getReadPipeType(QualType T) const {
4411   return getPipeType(T, true);
4412 }
4413 
4414 QualType ASTContext::getWritePipeType(QualType T) const {
4415   return getPipeType(T, false);
4416 }
4417 
4418 QualType ASTContext::getExtIntType(bool IsUnsigned, unsigned NumBits) const {
4419   llvm::FoldingSetNodeID ID;
4420   ExtIntType::Profile(ID, IsUnsigned, NumBits);
4421 
4422   void *InsertPos = nullptr;
4423   if (ExtIntType *EIT = ExtIntTypes.FindNodeOrInsertPos(ID, InsertPos))
4424     return QualType(EIT, 0);
4425 
4426   auto *New = new (*this, TypeAlignment) ExtIntType(IsUnsigned, NumBits);
4427   ExtIntTypes.InsertNode(New, InsertPos);
4428   Types.push_back(New);
4429   return QualType(New, 0);
4430 }
4431 
4432 QualType ASTContext::getDependentExtIntType(bool IsUnsigned,
4433                                             Expr *NumBitsExpr) const {
4434   assert(NumBitsExpr->isInstantiationDependent() && "Only good for dependent");
4435   llvm::FoldingSetNodeID ID;
4436   DependentExtIntType::Profile(ID, *this, IsUnsigned, NumBitsExpr);
4437 
4438   void *InsertPos = nullptr;
4439   if (DependentExtIntType *Existing =
4440           DependentExtIntTypes.FindNodeOrInsertPos(ID, InsertPos))
4441     return QualType(Existing, 0);
4442 
4443   auto *New = new (*this, TypeAlignment)
4444       DependentExtIntType(*this, IsUnsigned, NumBitsExpr);
4445   DependentExtIntTypes.InsertNode(New, InsertPos);
4446 
4447   Types.push_back(New);
4448   return QualType(New, 0);
4449 }
4450 
4451 #ifndef NDEBUG
4452 static bool NeedsInjectedClassNameType(const RecordDecl *D) {
4453   if (!isa<CXXRecordDecl>(D)) return false;
4454   const auto *RD = cast<CXXRecordDecl>(D);
4455   if (isa<ClassTemplatePartialSpecializationDecl>(RD))
4456     return true;
4457   if (RD->getDescribedClassTemplate() &&
4458       !isa<ClassTemplateSpecializationDecl>(RD))
4459     return true;
4460   return false;
4461 }
4462 #endif
4463 
4464 /// getInjectedClassNameType - Return the unique reference to the
4465 /// injected class name type for the specified templated declaration.
4466 QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
4467                                               QualType TST) const {
4468   assert(NeedsInjectedClassNameType(Decl));
4469   if (Decl->TypeForDecl) {
4470     assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
4471   } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
4472     assert(PrevDecl->TypeForDecl && "previous declaration has no type");
4473     Decl->TypeForDecl = PrevDecl->TypeForDecl;
4474     assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
4475   } else {
4476     Type *newType =
4477       new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
4478     Decl->TypeForDecl = newType;
4479     Types.push_back(newType);
4480   }
4481   return QualType(Decl->TypeForDecl, 0);
4482 }
4483 
4484 /// getTypeDeclType - Return the unique reference to the type for the
4485 /// specified type declaration.
4486 QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
4487   assert(Decl && "Passed null for Decl param");
4488   assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
4489 
4490   if (const auto *Typedef = dyn_cast<TypedefNameDecl>(Decl))
4491     return getTypedefType(Typedef);
4492 
4493   assert(!isa<TemplateTypeParmDecl>(Decl) &&
4494          "Template type parameter types are always available.");
4495 
4496   if (const auto *Record = dyn_cast<RecordDecl>(Decl)) {
4497     assert(Record->isFirstDecl() && "struct/union has previous declaration");
4498     assert(!NeedsInjectedClassNameType(Record));
4499     return getRecordType(Record);
4500   } else if (const auto *Enum = dyn_cast<EnumDecl>(Decl)) {
4501     assert(Enum->isFirstDecl() && "enum has previous declaration");
4502     return getEnumType(Enum);
4503   } else if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
4504     Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
4505     Decl->TypeForDecl = newType;
4506     Types.push_back(newType);
4507   } else
4508     llvm_unreachable("TypeDecl without a type?");
4509 
4510   return QualType(Decl->TypeForDecl, 0);
4511 }
4512 
4513 /// getTypedefType - Return the unique reference to the type for the
4514 /// specified typedef name decl.
4515 QualType ASTContext::getTypedefType(const TypedefNameDecl *Decl,
4516                                     QualType Underlying) const {
4517   if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
4518 
4519   if (Underlying.isNull())
4520     Underlying = Decl->getUnderlyingType();
4521   QualType Canonical = getCanonicalType(Underlying);
4522   auto *newType = new (*this, TypeAlignment)
4523       TypedefType(Type::Typedef, Decl, Underlying, Canonical);
4524   Decl->TypeForDecl = newType;
4525   Types.push_back(newType);
4526   return QualType(newType, 0);
4527 }
4528 
4529 QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
4530   if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
4531 
4532   if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
4533     if (PrevDecl->TypeForDecl)
4534       return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
4535 
4536   auto *newType = new (*this, TypeAlignment) RecordType(Decl);
4537   Decl->TypeForDecl = newType;
4538   Types.push_back(newType);
4539   return QualType(newType, 0);
4540 }
4541 
4542 QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
4543   if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
4544 
4545   if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
4546     if (PrevDecl->TypeForDecl)
4547       return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
4548 
4549   auto *newType = new (*this, TypeAlignment) EnumType(Decl);
4550   Decl->TypeForDecl = newType;
4551   Types.push_back(newType);
4552   return QualType(newType, 0);
4553 }
4554 
4555 QualType ASTContext::getAttributedType(attr::Kind attrKind,
4556                                        QualType modifiedType,
4557                                        QualType equivalentType) {
4558   llvm::FoldingSetNodeID id;
4559   AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
4560 
4561   void *insertPos = nullptr;
4562   AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
4563   if (type) return QualType(type, 0);
4564 
4565   QualType canon = getCanonicalType(equivalentType);
4566   type = new (*this, TypeAlignment)
4567       AttributedType(canon, attrKind, modifiedType, equivalentType);
4568 
4569   Types.push_back(type);
4570   AttributedTypes.InsertNode(type, insertPos);
4571 
4572   return QualType(type, 0);
4573 }
4574 
4575 /// Retrieve a substitution-result type.
4576 QualType
4577 ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
4578                                          QualType Replacement) const {
4579   assert(Replacement.isCanonical()
4580          && "replacement types must always be canonical");
4581 
4582   llvm::FoldingSetNodeID ID;
4583   SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
4584   void *InsertPos = nullptr;
4585   SubstTemplateTypeParmType *SubstParm
4586     = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4587 
4588   if (!SubstParm) {
4589     SubstParm = new (*this, TypeAlignment)
4590       SubstTemplateTypeParmType(Parm, Replacement);
4591     Types.push_back(SubstParm);
4592     SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
4593   }
4594 
4595   return QualType(SubstParm, 0);
4596 }
4597 
4598 /// Retrieve a
4599 QualType ASTContext::getSubstTemplateTypeParmPackType(
4600                                           const TemplateTypeParmType *Parm,
4601                                               const TemplateArgument &ArgPack) {
4602 #ifndef NDEBUG
4603   for (const auto &P : ArgPack.pack_elements()) {
4604     assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
4605     assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
4606   }
4607 #endif
4608 
4609   llvm::FoldingSetNodeID ID;
4610   SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
4611   void *InsertPos = nullptr;
4612   if (SubstTemplateTypeParmPackType *SubstParm
4613         = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
4614     return QualType(SubstParm, 0);
4615 
4616   QualType Canon;
4617   if (!Parm->isCanonicalUnqualified()) {
4618     Canon = getCanonicalType(QualType(Parm, 0));
4619     Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
4620                                              ArgPack);
4621     SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
4622   }
4623 
4624   auto *SubstParm
4625     = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
4626                                                                ArgPack);
4627   Types.push_back(SubstParm);
4628   SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos);
4629   return QualType(SubstParm, 0);
4630 }
4631 
4632 /// Retrieve the template type parameter type for a template
4633 /// parameter or parameter pack with the given depth, index, and (optionally)
4634 /// name.
4635 QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
4636                                              bool ParameterPack,
4637                                              TemplateTypeParmDecl *TTPDecl) const {
4638   llvm::FoldingSetNodeID ID;
4639   TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
4640   void *InsertPos = nullptr;
4641   TemplateTypeParmType *TypeParm
4642     = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4643 
4644   if (TypeParm)
4645     return QualType(TypeParm, 0);
4646 
4647   if (TTPDecl) {
4648     QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
4649     TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
4650 
4651     TemplateTypeParmType *TypeCheck
4652       = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4653     assert(!TypeCheck && "Template type parameter canonical type broken");
4654     (void)TypeCheck;
4655   } else
4656     TypeParm = new (*this, TypeAlignment)
4657       TemplateTypeParmType(Depth, Index, ParameterPack);
4658 
4659   Types.push_back(TypeParm);
4660   TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
4661 
4662   return QualType(TypeParm, 0);
4663 }
4664 
4665 TypeSourceInfo *
4666 ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
4667                                               SourceLocation NameLoc,
4668                                         const TemplateArgumentListInfo &Args,
4669                                               QualType Underlying) const {
4670   assert(!Name.getAsDependentTemplateName() &&
4671          "No dependent template names here!");
4672   QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
4673 
4674   TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
4675   TemplateSpecializationTypeLoc TL =
4676       DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
4677   TL.setTemplateKeywordLoc(SourceLocation());
4678   TL.setTemplateNameLoc(NameLoc);
4679   TL.setLAngleLoc(Args.getLAngleLoc());
4680   TL.setRAngleLoc(Args.getRAngleLoc());
4681   for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
4682     TL.setArgLocInfo(i, Args[i].getLocInfo());
4683   return DI;
4684 }
4685 
4686 QualType
4687 ASTContext::getTemplateSpecializationType(TemplateName Template,
4688                                           const TemplateArgumentListInfo &Args,
4689                                           QualType Underlying) const {
4690   assert(!Template.getAsDependentTemplateName() &&
4691          "No dependent template names here!");
4692 
4693   SmallVector<TemplateArgument, 4> ArgVec;
4694   ArgVec.reserve(Args.size());
4695   for (const TemplateArgumentLoc &Arg : Args.arguments())
4696     ArgVec.push_back(Arg.getArgument());
4697 
4698   return getTemplateSpecializationType(Template, ArgVec, Underlying);
4699 }
4700 
4701 #ifndef NDEBUG
4702 static bool hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) {
4703   for (const TemplateArgument &Arg : Args)
4704     if (Arg.isPackExpansion())
4705       return true;
4706 
4707   return true;
4708 }
4709 #endif
4710 
4711 QualType
4712 ASTContext::getTemplateSpecializationType(TemplateName Template,
4713                                           ArrayRef<TemplateArgument> Args,
4714                                           QualType Underlying) const {
4715   assert(!Template.getAsDependentTemplateName() &&
4716          "No dependent template names here!");
4717   // Look through qualified template names.
4718   if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
4719     Template = TemplateName(QTN->getTemplateDecl());
4720 
4721   bool IsTypeAlias =
4722     Template.getAsTemplateDecl() &&
4723     isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
4724   QualType CanonType;
4725   if (!Underlying.isNull())
4726     CanonType = getCanonicalType(Underlying);
4727   else {
4728     // We can get here with an alias template when the specialization contains
4729     // a pack expansion that does not match up with a parameter pack.
4730     assert((!IsTypeAlias || hasAnyPackExpansions(Args)) &&
4731            "Caller must compute aliased type");
4732     IsTypeAlias = false;
4733     CanonType = getCanonicalTemplateSpecializationType(Template, Args);
4734   }
4735 
4736   // Allocate the (non-canonical) template specialization type, but don't
4737   // try to unique it: these types typically have location information that
4738   // we don't unique and don't want to lose.
4739   void *Mem = Allocate(sizeof(TemplateSpecializationType) +
4740                        sizeof(TemplateArgument) * Args.size() +
4741                        (IsTypeAlias? sizeof(QualType) : 0),
4742                        TypeAlignment);
4743   auto *Spec
4744     = new (Mem) TemplateSpecializationType(Template, Args, CanonType,
4745                                          IsTypeAlias ? Underlying : QualType());
4746 
4747   Types.push_back(Spec);
4748   return QualType(Spec, 0);
4749 }
4750 
4751 QualType ASTContext::getCanonicalTemplateSpecializationType(
4752     TemplateName Template, ArrayRef<TemplateArgument> Args) const {
4753   assert(!Template.getAsDependentTemplateName() &&
4754          "No dependent template names here!");
4755 
4756   // Look through qualified template names.
4757   if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
4758     Template = TemplateName(QTN->getTemplateDecl());
4759 
4760   // Build the canonical template specialization type.
4761   TemplateName CanonTemplate = getCanonicalTemplateName(Template);
4762   SmallVector<TemplateArgument, 4> CanonArgs;
4763   unsigned NumArgs = Args.size();
4764   CanonArgs.reserve(NumArgs);
4765   for (const TemplateArgument &Arg : Args)
4766     CanonArgs.push_back(getCanonicalTemplateArgument(Arg));
4767 
4768   // Determine whether this canonical template specialization type already
4769   // exists.
4770   llvm::FoldingSetNodeID ID;
4771   TemplateSpecializationType::Profile(ID, CanonTemplate,
4772                                       CanonArgs, *this);
4773 
4774   void *InsertPos = nullptr;
4775   TemplateSpecializationType *Spec
4776     = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
4777 
4778   if (!Spec) {
4779     // Allocate a new canonical template specialization type.
4780     void *Mem = Allocate((sizeof(TemplateSpecializationType) +
4781                           sizeof(TemplateArgument) * NumArgs),
4782                          TypeAlignment);
4783     Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
4784                                                 CanonArgs,
4785                                                 QualType(), QualType());
4786     Types.push_back(Spec);
4787     TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
4788   }
4789 
4790   assert(Spec->isDependentType() &&
4791          "Non-dependent template-id type must have a canonical type");
4792   return QualType(Spec, 0);
4793 }
4794 
4795 QualType ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
4796                                        NestedNameSpecifier *NNS,
4797                                        QualType NamedType,
4798                                        TagDecl *OwnedTagDecl) const {
4799   llvm::FoldingSetNodeID ID;
4800   ElaboratedType::Profile(ID, Keyword, NNS, NamedType, OwnedTagDecl);
4801 
4802   void *InsertPos = nullptr;
4803   ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
4804   if (T)
4805     return QualType(T, 0);
4806 
4807   QualType Canon = NamedType;
4808   if (!Canon.isCanonical()) {
4809     Canon = getCanonicalType(NamedType);
4810     ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
4811     assert(!CheckT && "Elaborated canonical type broken");
4812     (void)CheckT;
4813   }
4814 
4815   void *Mem = Allocate(ElaboratedType::totalSizeToAlloc<TagDecl *>(!!OwnedTagDecl),
4816                        TypeAlignment);
4817   T = new (Mem) ElaboratedType(Keyword, NNS, NamedType, Canon, OwnedTagDecl);
4818 
4819   Types.push_back(T);
4820   ElaboratedTypes.InsertNode(T, InsertPos);
4821   return QualType(T, 0);
4822 }
4823 
4824 QualType
4825 ASTContext::getParenType(QualType InnerType) const {
4826   llvm::FoldingSetNodeID ID;
4827   ParenType::Profile(ID, InnerType);
4828 
4829   void *InsertPos = nullptr;
4830   ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
4831   if (T)
4832     return QualType(T, 0);
4833 
4834   QualType Canon = InnerType;
4835   if (!Canon.isCanonical()) {
4836     Canon = getCanonicalType(InnerType);
4837     ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
4838     assert(!CheckT && "Paren canonical type broken");
4839     (void)CheckT;
4840   }
4841 
4842   T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
4843   Types.push_back(T);
4844   ParenTypes.InsertNode(T, InsertPos);
4845   return QualType(T, 0);
4846 }
4847 
4848 QualType
4849 ASTContext::getMacroQualifiedType(QualType UnderlyingTy,
4850                                   const IdentifierInfo *MacroII) const {
4851   QualType Canon = UnderlyingTy;
4852   if (!Canon.isCanonical())
4853     Canon = getCanonicalType(UnderlyingTy);
4854 
4855   auto *newType = new (*this, TypeAlignment)
4856       MacroQualifiedType(UnderlyingTy, Canon, MacroII);
4857   Types.push_back(newType);
4858   return QualType(newType, 0);
4859 }
4860 
4861 QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
4862                                           NestedNameSpecifier *NNS,
4863                                           const IdentifierInfo *Name,
4864                                           QualType Canon) const {
4865   if (Canon.isNull()) {
4866     NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4867     if (CanonNNS != NNS)
4868       Canon = getDependentNameType(Keyword, CanonNNS, Name);
4869   }
4870 
4871   llvm::FoldingSetNodeID ID;
4872   DependentNameType::Profile(ID, Keyword, NNS, Name);
4873 
4874   void *InsertPos = nullptr;
4875   DependentNameType *T
4876     = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
4877   if (T)
4878     return QualType(T, 0);
4879 
4880   T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
4881   Types.push_back(T);
4882   DependentNameTypes.InsertNode(T, InsertPos);
4883   return QualType(T, 0);
4884 }
4885 
4886 QualType
4887 ASTContext::getDependentTemplateSpecializationType(
4888                                  ElaboratedTypeKeyword Keyword,
4889                                  NestedNameSpecifier *NNS,
4890                                  const IdentifierInfo *Name,
4891                                  const TemplateArgumentListInfo &Args) const {
4892   // TODO: avoid this copy
4893   SmallVector<TemplateArgument, 16> ArgCopy;
4894   for (unsigned I = 0, E = Args.size(); I != E; ++I)
4895     ArgCopy.push_back(Args[I].getArgument());
4896   return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy);
4897 }
4898 
4899 QualType
4900 ASTContext::getDependentTemplateSpecializationType(
4901                                  ElaboratedTypeKeyword Keyword,
4902                                  NestedNameSpecifier *NNS,
4903                                  const IdentifierInfo *Name,
4904                                  ArrayRef<TemplateArgument> Args) const {
4905   assert((!NNS || NNS->isDependent()) &&
4906          "nested-name-specifier must be dependent");
4907 
4908   llvm::FoldingSetNodeID ID;
4909   DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
4910                                                Name, Args);
4911 
4912   void *InsertPos = nullptr;
4913   DependentTemplateSpecializationType *T
4914     = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
4915   if (T)
4916     return QualType(T, 0);
4917 
4918   NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4919 
4920   ElaboratedTypeKeyword CanonKeyword = Keyword;
4921   if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
4922 
4923   bool AnyNonCanonArgs = false;
4924   unsigned NumArgs = Args.size();
4925   SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
4926   for (unsigned I = 0; I != NumArgs; ++I) {
4927     CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
4928     if (!CanonArgs[I].structurallyEquals(Args[I]))
4929       AnyNonCanonArgs = true;
4930   }
4931 
4932   QualType Canon;
4933   if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
4934     Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
4935                                                    Name,
4936                                                    CanonArgs);
4937 
4938     // Find the insert position again.
4939     DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
4940   }
4941 
4942   void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
4943                         sizeof(TemplateArgument) * NumArgs),
4944                        TypeAlignment);
4945   T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
4946                                                     Name, Args, Canon);
4947   Types.push_back(T);
4948   DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
4949   return QualType(T, 0);
4950 }
4951 
4952 TemplateArgument ASTContext::getInjectedTemplateArg(NamedDecl *Param) {
4953   TemplateArgument Arg;
4954   if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
4955     QualType ArgType = getTypeDeclType(TTP);
4956     if (TTP->isParameterPack())
4957       ArgType = getPackExpansionType(ArgType, None);
4958 
4959     Arg = TemplateArgument(ArgType);
4960   } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4961     QualType T =
4962         NTTP->getType().getNonPackExpansionType().getNonLValueExprType(*this);
4963     // For class NTTPs, ensure we include the 'const' so the type matches that
4964     // of a real template argument.
4965     // FIXME: It would be more faithful to model this as something like an
4966     // lvalue-to-rvalue conversion applied to a const-qualified lvalue.
4967     if (T->isRecordType())
4968       T.addConst();
4969     Expr *E = new (*this) DeclRefExpr(
4970         *this, NTTP, /*enclosing*/ false, T,
4971         Expr::getValueKindForType(NTTP->getType()), NTTP->getLocation());
4972 
4973     if (NTTP->isParameterPack())
4974       E = new (*this) PackExpansionExpr(DependentTy, E, NTTP->getLocation(),
4975                                         None);
4976     Arg = TemplateArgument(E);
4977   } else {
4978     auto *TTP = cast<TemplateTemplateParmDecl>(Param);
4979     if (TTP->isParameterPack())
4980       Arg = TemplateArgument(TemplateName(TTP), Optional<unsigned>());
4981     else
4982       Arg = TemplateArgument(TemplateName(TTP));
4983   }
4984 
4985   if (Param->isTemplateParameterPack())
4986     Arg = TemplateArgument::CreatePackCopy(*this, Arg);
4987 
4988   return Arg;
4989 }
4990 
4991 void
4992 ASTContext::getInjectedTemplateArgs(const TemplateParameterList *Params,
4993                                     SmallVectorImpl<TemplateArgument> &Args) {
4994   Args.reserve(Args.size() + Params->size());
4995 
4996   for (NamedDecl *Param : *Params)
4997     Args.push_back(getInjectedTemplateArg(Param));
4998 }
4999 
5000 QualType ASTContext::getPackExpansionType(QualType Pattern,
5001                                           Optional<unsigned> NumExpansions,
5002                                           bool ExpectPackInType) {
5003   assert((!ExpectPackInType || Pattern->containsUnexpandedParameterPack()) &&
5004          "Pack expansions must expand one or more parameter packs");
5005 
5006   llvm::FoldingSetNodeID ID;
5007   PackExpansionType::Profile(ID, Pattern, NumExpansions);
5008 
5009   void *InsertPos = nullptr;
5010   PackExpansionType *T = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
5011   if (T)
5012     return QualType(T, 0);
5013 
5014   QualType Canon;
5015   if (!Pattern.isCanonical()) {
5016     Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions,
5017                                  /*ExpectPackInType=*/false);
5018 
5019     // Find the insert position again, in case we inserted an element into
5020     // PackExpansionTypes and invalidated our insert position.
5021     PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
5022   }
5023 
5024   T = new (*this, TypeAlignment)
5025       PackExpansionType(Pattern, Canon, NumExpansions);
5026   Types.push_back(T);
5027   PackExpansionTypes.InsertNode(T, InsertPos);
5028   return QualType(T, 0);
5029 }
5030 
5031 /// CmpProtocolNames - Comparison predicate for sorting protocols
5032 /// alphabetically.
5033 static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
5034                             ObjCProtocolDecl *const *RHS) {
5035   return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
5036 }
5037 
5038 static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) {
5039   if (Protocols.empty()) return true;
5040 
5041   if (Protocols[0]->getCanonicalDecl() != Protocols[0])
5042     return false;
5043 
5044   for (unsigned i = 1; i != Protocols.size(); ++i)
5045     if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
5046         Protocols[i]->getCanonicalDecl() != Protocols[i])
5047       return false;
5048   return true;
5049 }
5050 
5051 static void
5052 SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
5053   // Sort protocols, keyed by name.
5054   llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
5055 
5056   // Canonicalize.
5057   for (ObjCProtocolDecl *&P : Protocols)
5058     P = P->getCanonicalDecl();
5059 
5060   // Remove duplicates.
5061   auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
5062   Protocols.erase(ProtocolsEnd, Protocols.end());
5063 }
5064 
5065 QualType ASTContext::getObjCObjectType(QualType BaseType,
5066                                        ObjCProtocolDecl * const *Protocols,
5067                                        unsigned NumProtocols) const {
5068   return getObjCObjectType(BaseType, {},
5069                            llvm::makeArrayRef(Protocols, NumProtocols),
5070                            /*isKindOf=*/false);
5071 }
5072 
5073 QualType ASTContext::getObjCObjectType(
5074            QualType baseType,
5075            ArrayRef<QualType> typeArgs,
5076            ArrayRef<ObjCProtocolDecl *> protocols,
5077            bool isKindOf) const {
5078   // If the base type is an interface and there aren't any protocols or
5079   // type arguments to add, then the interface type will do just fine.
5080   if (typeArgs.empty() && protocols.empty() && !isKindOf &&
5081       isa<ObjCInterfaceType>(baseType))
5082     return baseType;
5083 
5084   // Look in the folding set for an existing type.
5085   llvm::FoldingSetNodeID ID;
5086   ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
5087   void *InsertPos = nullptr;
5088   if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
5089     return QualType(QT, 0);
5090 
5091   // Determine the type arguments to be used for canonicalization,
5092   // which may be explicitly specified here or written on the base
5093   // type.
5094   ArrayRef<QualType> effectiveTypeArgs = typeArgs;
5095   if (effectiveTypeArgs.empty()) {
5096     if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
5097       effectiveTypeArgs = baseObject->getTypeArgs();
5098   }
5099 
5100   // Build the canonical type, which has the canonical base type and a
5101   // sorted-and-uniqued list of protocols and the type arguments
5102   // canonicalized.
5103   QualType canonical;
5104   bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(),
5105                                           effectiveTypeArgs.end(),
5106                                           [&](QualType type) {
5107                                             return type.isCanonical();
5108                                           });
5109   bool protocolsSorted = areSortedAndUniqued(protocols);
5110   if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
5111     // Determine the canonical type arguments.
5112     ArrayRef<QualType> canonTypeArgs;
5113     SmallVector<QualType, 4> canonTypeArgsVec;
5114     if (!typeArgsAreCanonical) {
5115       canonTypeArgsVec.reserve(effectiveTypeArgs.size());
5116       for (auto typeArg : effectiveTypeArgs)
5117         canonTypeArgsVec.push_back(getCanonicalType(typeArg));
5118       canonTypeArgs = canonTypeArgsVec;
5119     } else {
5120       canonTypeArgs = effectiveTypeArgs;
5121     }
5122 
5123     ArrayRef<ObjCProtocolDecl *> canonProtocols;
5124     SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
5125     if (!protocolsSorted) {
5126       canonProtocolsVec.append(protocols.begin(), protocols.end());
5127       SortAndUniqueProtocols(canonProtocolsVec);
5128       canonProtocols = canonProtocolsVec;
5129     } else {
5130       canonProtocols = protocols;
5131     }
5132 
5133     canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
5134                                   canonProtocols, isKindOf);
5135 
5136     // Regenerate InsertPos.
5137     ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
5138   }
5139 
5140   unsigned size = sizeof(ObjCObjectTypeImpl);
5141   size += typeArgs.size() * sizeof(QualType);
5142   size += protocols.size() * sizeof(ObjCProtocolDecl *);
5143   void *mem = Allocate(size, TypeAlignment);
5144   auto *T =
5145     new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
5146                                  isKindOf);
5147 
5148   Types.push_back(T);
5149   ObjCObjectTypes.InsertNode(T, InsertPos);
5150   return QualType(T, 0);
5151 }
5152 
5153 /// Apply Objective-C protocol qualifiers to the given type.
5154 /// If this is for the canonical type of a type parameter, we can apply
5155 /// protocol qualifiers on the ObjCObjectPointerType.
5156 QualType
5157 ASTContext::applyObjCProtocolQualifiers(QualType type,
5158                   ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
5159                   bool allowOnPointerType) const {
5160   hasError = false;
5161 
5162   if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
5163     return getObjCTypeParamType(objT->getDecl(), protocols);
5164   }
5165 
5166   // Apply protocol qualifiers to ObjCObjectPointerType.
5167   if (allowOnPointerType) {
5168     if (const auto *objPtr =
5169             dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
5170       const ObjCObjectType *objT = objPtr->getObjectType();
5171       // Merge protocol lists and construct ObjCObjectType.
5172       SmallVector<ObjCProtocolDecl*, 8> protocolsVec;
5173       protocolsVec.append(objT->qual_begin(),
5174                           objT->qual_end());
5175       protocolsVec.append(protocols.begin(), protocols.end());
5176       ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
5177       type = getObjCObjectType(
5178              objT->getBaseType(),
5179              objT->getTypeArgsAsWritten(),
5180              protocols,
5181              objT->isKindOfTypeAsWritten());
5182       return getObjCObjectPointerType(type);
5183     }
5184   }
5185 
5186   // Apply protocol qualifiers to ObjCObjectType.
5187   if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
5188     // FIXME: Check for protocols to which the class type is already
5189     // known to conform.
5190 
5191     return getObjCObjectType(objT->getBaseType(),
5192                              objT->getTypeArgsAsWritten(),
5193                              protocols,
5194                              objT->isKindOfTypeAsWritten());
5195   }
5196 
5197   // If the canonical type is ObjCObjectType, ...
5198   if (type->isObjCObjectType()) {
5199     // Silently overwrite any existing protocol qualifiers.
5200     // TODO: determine whether that's the right thing to do.
5201 
5202     // FIXME: Check for protocols to which the class type is already
5203     // known to conform.
5204     return getObjCObjectType(type, {}, protocols, false);
5205   }
5206 
5207   // id<protocol-list>
5208   if (type->isObjCIdType()) {
5209     const auto *objPtr = type->castAs<ObjCObjectPointerType>();
5210     type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols,
5211                                  objPtr->isKindOfType());
5212     return getObjCObjectPointerType(type);
5213   }
5214 
5215   // Class<protocol-list>
5216   if (type->isObjCClassType()) {
5217     const auto *objPtr = type->castAs<ObjCObjectPointerType>();
5218     type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols,
5219                                  objPtr->isKindOfType());
5220     return getObjCObjectPointerType(type);
5221   }
5222 
5223   hasError = true;
5224   return type;
5225 }
5226 
5227 QualType
5228 ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
5229                                  ArrayRef<ObjCProtocolDecl *> protocols) const {
5230   // Look in the folding set for an existing type.
5231   llvm::FoldingSetNodeID ID;
5232   ObjCTypeParamType::Profile(ID, Decl, Decl->getUnderlyingType(), protocols);
5233   void *InsertPos = nullptr;
5234   if (ObjCTypeParamType *TypeParam =
5235       ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
5236     return QualType(TypeParam, 0);
5237 
5238   // We canonicalize to the underlying type.
5239   QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
5240   if (!protocols.empty()) {
5241     // Apply the protocol qualifers.
5242     bool hasError;
5243     Canonical = getCanonicalType(applyObjCProtocolQualifiers(
5244         Canonical, protocols, hasError, true /*allowOnPointerType*/));
5245     assert(!hasError && "Error when apply protocol qualifier to bound type");
5246   }
5247 
5248   unsigned size = sizeof(ObjCTypeParamType);
5249   size += protocols.size() * sizeof(ObjCProtocolDecl *);
5250   void *mem = Allocate(size, TypeAlignment);
5251   auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
5252 
5253   Types.push_back(newType);
5254   ObjCTypeParamTypes.InsertNode(newType, InsertPos);
5255   return QualType(newType, 0);
5256 }
5257 
5258 void ASTContext::adjustObjCTypeParamBoundType(const ObjCTypeParamDecl *Orig,
5259                                               ObjCTypeParamDecl *New) const {
5260   New->setTypeSourceInfo(getTrivialTypeSourceInfo(Orig->getUnderlyingType()));
5261   // Update TypeForDecl after updating TypeSourceInfo.
5262   auto NewTypeParamTy = cast<ObjCTypeParamType>(New->getTypeForDecl());
5263   SmallVector<ObjCProtocolDecl *, 8> protocols;
5264   protocols.append(NewTypeParamTy->qual_begin(), NewTypeParamTy->qual_end());
5265   QualType UpdatedTy = getObjCTypeParamType(New, protocols);
5266   New->setTypeForDecl(UpdatedTy.getTypePtr());
5267 }
5268 
5269 /// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
5270 /// protocol list adopt all protocols in QT's qualified-id protocol
5271 /// list.
5272 bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
5273                                                 ObjCInterfaceDecl *IC) {
5274   if (!QT->isObjCQualifiedIdType())
5275     return false;
5276 
5277   if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
5278     // If both the right and left sides have qualifiers.
5279     for (auto *Proto : OPT->quals()) {
5280       if (!IC->ClassImplementsProtocol(Proto, false))
5281         return false;
5282     }
5283     return true;
5284   }
5285   return false;
5286 }
5287 
5288 /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
5289 /// QT's qualified-id protocol list adopt all protocols in IDecl's list
5290 /// of protocols.
5291 bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
5292                                                 ObjCInterfaceDecl *IDecl) {
5293   if (!QT->isObjCQualifiedIdType())
5294     return false;
5295   const auto *OPT = QT->getAs<ObjCObjectPointerType>();
5296   if (!OPT)
5297     return false;
5298   if (!IDecl->hasDefinition())
5299     return false;
5300   llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
5301   CollectInheritedProtocols(IDecl, InheritedProtocols);
5302   if (InheritedProtocols.empty())
5303     return false;
5304   // Check that if every protocol in list of id<plist> conforms to a protocol
5305   // of IDecl's, then bridge casting is ok.
5306   bool Conforms = false;
5307   for (auto *Proto : OPT->quals()) {
5308     Conforms = false;
5309     for (auto *PI : InheritedProtocols) {
5310       if (ProtocolCompatibleWithProtocol(Proto, PI)) {
5311         Conforms = true;
5312         break;
5313       }
5314     }
5315     if (!Conforms)
5316       break;
5317   }
5318   if (Conforms)
5319     return true;
5320 
5321   for (auto *PI : InheritedProtocols) {
5322     // If both the right and left sides have qualifiers.
5323     bool Adopts = false;
5324     for (auto *Proto : OPT->quals()) {
5325       // return 'true' if 'PI' is in the inheritance hierarchy of Proto
5326       if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
5327         break;
5328     }
5329     if (!Adopts)
5330       return false;
5331   }
5332   return true;
5333 }
5334 
5335 /// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
5336 /// the given object type.
5337 QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
5338   llvm::FoldingSetNodeID ID;
5339   ObjCObjectPointerType::Profile(ID, ObjectT);
5340 
5341   void *InsertPos = nullptr;
5342   if (ObjCObjectPointerType *QT =
5343               ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
5344     return QualType(QT, 0);
5345 
5346   // Find the canonical object type.
5347   QualType Canonical;
5348   if (!ObjectT.isCanonical()) {
5349     Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
5350 
5351     // Regenerate InsertPos.
5352     ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
5353   }
5354 
5355   // No match.
5356   void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
5357   auto *QType =
5358     new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
5359 
5360   Types.push_back(QType);
5361   ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
5362   return QualType(QType, 0);
5363 }
5364 
5365 /// getObjCInterfaceType - Return the unique reference to the type for the
5366 /// specified ObjC interface decl. The list of protocols is optional.
5367 QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
5368                                           ObjCInterfaceDecl *PrevDecl) const {
5369   if (Decl->TypeForDecl)
5370     return QualType(Decl->TypeForDecl, 0);
5371 
5372   if (PrevDecl) {
5373     assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
5374     Decl->TypeForDecl = PrevDecl->TypeForDecl;
5375     return QualType(PrevDecl->TypeForDecl, 0);
5376   }
5377 
5378   // Prefer the definition, if there is one.
5379   if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
5380     Decl = Def;
5381 
5382   void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
5383   auto *T = new (Mem) ObjCInterfaceType(Decl);
5384   Decl->TypeForDecl = T;
5385   Types.push_back(T);
5386   return QualType(T, 0);
5387 }
5388 
5389 /// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
5390 /// TypeOfExprType AST's (since expression's are never shared). For example,
5391 /// multiple declarations that refer to "typeof(x)" all contain different
5392 /// DeclRefExpr's. This doesn't effect the type checker, since it operates
5393 /// on canonical type's (which are always unique).
5394 QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
5395   TypeOfExprType *toe;
5396   if (tofExpr->isTypeDependent()) {
5397     llvm::FoldingSetNodeID ID;
5398     DependentTypeOfExprType::Profile(ID, *this, tofExpr);
5399 
5400     void *InsertPos = nullptr;
5401     DependentTypeOfExprType *Canon
5402       = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
5403     if (Canon) {
5404       // We already have a "canonical" version of an identical, dependent
5405       // typeof(expr) type. Use that as our canonical type.
5406       toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
5407                                           QualType((TypeOfExprType*)Canon, 0));
5408     } else {
5409       // Build a new, canonical typeof(expr) type.
5410       Canon
5411         = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
5412       DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
5413       toe = Canon;
5414     }
5415   } else {
5416     QualType Canonical = getCanonicalType(tofExpr->getType());
5417     toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
5418   }
5419   Types.push_back(toe);
5420   return QualType(toe, 0);
5421 }
5422 
5423 /// getTypeOfType -  Unlike many "get<Type>" functions, we don't unique
5424 /// TypeOfType nodes. The only motivation to unique these nodes would be
5425 /// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
5426 /// an issue. This doesn't affect the type checker, since it operates
5427 /// on canonical types (which are always unique).
5428 QualType ASTContext::getTypeOfType(QualType tofType) const {
5429   QualType Canonical = getCanonicalType(tofType);
5430   auto *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
5431   Types.push_back(tot);
5432   return QualType(tot, 0);
5433 }
5434 
5435 /// Unlike many "get<Type>" functions, we don't unique DecltypeType
5436 /// nodes. This would never be helpful, since each such type has its own
5437 /// expression, and would not give a significant memory saving, since there
5438 /// is an Expr tree under each such type.
5439 QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
5440   DecltypeType *dt;
5441 
5442   // C++11 [temp.type]p2:
5443   //   If an expression e involves a template parameter, decltype(e) denotes a
5444   //   unique dependent type. Two such decltype-specifiers refer to the same
5445   //   type only if their expressions are equivalent (14.5.6.1).
5446   if (e->isInstantiationDependent()) {
5447     llvm::FoldingSetNodeID ID;
5448     DependentDecltypeType::Profile(ID, *this, e);
5449 
5450     void *InsertPos = nullptr;
5451     DependentDecltypeType *Canon
5452       = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
5453     if (!Canon) {
5454       // Build a new, canonical decltype(expr) type.
5455       Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
5456       DependentDecltypeTypes.InsertNode(Canon, InsertPos);
5457     }
5458     dt = new (*this, TypeAlignment)
5459         DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
5460   } else {
5461     dt = new (*this, TypeAlignment)
5462         DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
5463   }
5464   Types.push_back(dt);
5465   return QualType(dt, 0);
5466 }
5467 
5468 /// getUnaryTransformationType - We don't unique these, since the memory
5469 /// savings are minimal and these are rare.
5470 QualType ASTContext::getUnaryTransformType(QualType BaseType,
5471                                            QualType UnderlyingType,
5472                                            UnaryTransformType::UTTKind Kind)
5473     const {
5474   UnaryTransformType *ut = nullptr;
5475 
5476   if (BaseType->isDependentType()) {
5477     // Look in the folding set for an existing type.
5478     llvm::FoldingSetNodeID ID;
5479     DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind);
5480 
5481     void *InsertPos = nullptr;
5482     DependentUnaryTransformType *Canon
5483       = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
5484 
5485     if (!Canon) {
5486       // Build a new, canonical __underlying_type(type) type.
5487       Canon = new (*this, TypeAlignment)
5488              DependentUnaryTransformType(*this, getCanonicalType(BaseType),
5489                                          Kind);
5490       DependentUnaryTransformTypes.InsertNode(Canon, InsertPos);
5491     }
5492     ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
5493                                                         QualType(), Kind,
5494                                                         QualType(Canon, 0));
5495   } else {
5496     QualType CanonType = getCanonicalType(UnderlyingType);
5497     ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
5498                                                         UnderlyingType, Kind,
5499                                                         CanonType);
5500   }
5501   Types.push_back(ut);
5502   return QualType(ut, 0);
5503 }
5504 
5505 /// getAutoType - Return the uniqued reference to the 'auto' type which has been
5506 /// deduced to the given type, or to the canonical undeduced 'auto' type, or the
5507 /// canonical deduced-but-dependent 'auto' type.
5508 QualType
5509 ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
5510                         bool IsDependent, bool IsPack,
5511                         ConceptDecl *TypeConstraintConcept,
5512                         ArrayRef<TemplateArgument> TypeConstraintArgs) const {
5513   assert((!IsPack || IsDependent) && "only use IsPack for a dependent pack");
5514   if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto &&
5515       !TypeConstraintConcept && !IsDependent)
5516     return getAutoDeductType();
5517 
5518   // Look in the folding set for an existing type.
5519   void *InsertPos = nullptr;
5520   llvm::FoldingSetNodeID ID;
5521   AutoType::Profile(ID, *this, DeducedType, Keyword, IsDependent,
5522                     TypeConstraintConcept, TypeConstraintArgs);
5523   if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
5524     return QualType(AT, 0);
5525 
5526   void *Mem = Allocate(sizeof(AutoType) +
5527                        sizeof(TemplateArgument) * TypeConstraintArgs.size(),
5528                        TypeAlignment);
5529   auto *AT = new (Mem) AutoType(
5530       DeducedType, Keyword,
5531       (IsDependent ? TypeDependence::DependentInstantiation
5532                    : TypeDependence::None) |
5533           (IsPack ? TypeDependence::UnexpandedPack : TypeDependence::None),
5534       TypeConstraintConcept, TypeConstraintArgs);
5535   Types.push_back(AT);
5536   if (InsertPos)
5537     AutoTypes.InsertNode(AT, InsertPos);
5538   return QualType(AT, 0);
5539 }
5540 
5541 /// Return the uniqued reference to the deduced template specialization type
5542 /// which has been deduced to the given type, or to the canonical undeduced
5543 /// such type, or the canonical deduced-but-dependent such type.
5544 QualType ASTContext::getDeducedTemplateSpecializationType(
5545     TemplateName Template, QualType DeducedType, bool IsDependent) const {
5546   // Look in the folding set for an existing type.
5547   void *InsertPos = nullptr;
5548   llvm::FoldingSetNodeID ID;
5549   DeducedTemplateSpecializationType::Profile(ID, Template, DeducedType,
5550                                              IsDependent);
5551   if (DeducedTemplateSpecializationType *DTST =
5552           DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
5553     return QualType(DTST, 0);
5554 
5555   auto *DTST = new (*this, TypeAlignment)
5556       DeducedTemplateSpecializationType(Template, DeducedType, IsDependent);
5557   Types.push_back(DTST);
5558   if (InsertPos)
5559     DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
5560   return QualType(DTST, 0);
5561 }
5562 
5563 /// getAtomicType - Return the uniqued reference to the atomic type for
5564 /// the given value type.
5565 QualType ASTContext::getAtomicType(QualType T) const {
5566   // Unique pointers, to guarantee there is only one pointer of a particular
5567   // structure.
5568   llvm::FoldingSetNodeID ID;
5569   AtomicType::Profile(ID, T);
5570 
5571   void *InsertPos = nullptr;
5572   if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
5573     return QualType(AT, 0);
5574 
5575   // If the atomic value type isn't canonical, this won't be a canonical type
5576   // either, so fill in the canonical type field.
5577   QualType Canonical;
5578   if (!T.isCanonical()) {
5579     Canonical = getAtomicType(getCanonicalType(T));
5580 
5581     // Get the new insert position for the node we care about.
5582     AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
5583     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
5584   }
5585   auto *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
5586   Types.push_back(New);
5587   AtomicTypes.InsertNode(New, InsertPos);
5588   return QualType(New, 0);
5589 }
5590 
5591 /// getAutoDeductType - Get type pattern for deducing against 'auto'.
5592 QualType ASTContext::getAutoDeductType() const {
5593   if (AutoDeductTy.isNull())
5594     AutoDeductTy = QualType(new (*this, TypeAlignment)
5595                                 AutoType(QualType(), AutoTypeKeyword::Auto,
5596                                          TypeDependence::None,
5597                                          /*concept*/ nullptr, /*args*/ {}),
5598                             0);
5599   return AutoDeductTy;
5600 }
5601 
5602 /// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
5603 QualType ASTContext::getAutoRRefDeductType() const {
5604   if (AutoRRefDeductTy.isNull())
5605     AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
5606   assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
5607   return AutoRRefDeductTy;
5608 }
5609 
5610 /// getTagDeclType - Return the unique reference to the type for the
5611 /// specified TagDecl (struct/union/class/enum) decl.
5612 QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
5613   assert(Decl);
5614   // FIXME: What is the design on getTagDeclType when it requires casting
5615   // away const?  mutable?
5616   return getTypeDeclType(const_cast<TagDecl*>(Decl));
5617 }
5618 
5619 /// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
5620 /// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
5621 /// needs to agree with the definition in <stddef.h>.
5622 CanQualType ASTContext::getSizeType() const {
5623   return getFromTargetType(Target->getSizeType());
5624 }
5625 
5626 /// Return the unique signed counterpart of the integer type
5627 /// corresponding to size_t.
5628 CanQualType ASTContext::getSignedSizeType() const {
5629   return getFromTargetType(Target->getSignedSizeType());
5630 }
5631 
5632 /// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
5633 CanQualType ASTContext::getIntMaxType() const {
5634   return getFromTargetType(Target->getIntMaxType());
5635 }
5636 
5637 /// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
5638 CanQualType ASTContext::getUIntMaxType() const {
5639   return getFromTargetType(Target->getUIntMaxType());
5640 }
5641 
5642 /// getSignedWCharType - Return the type of "signed wchar_t".
5643 /// Used when in C++, as a GCC extension.
5644 QualType ASTContext::getSignedWCharType() const {
5645   // FIXME: derive from "Target" ?
5646   return WCharTy;
5647 }
5648 
5649 /// getUnsignedWCharType - Return the type of "unsigned wchar_t".
5650 /// Used when in C++, as a GCC extension.
5651 QualType ASTContext::getUnsignedWCharType() const {
5652   // FIXME: derive from "Target" ?
5653   return UnsignedIntTy;
5654 }
5655 
5656 QualType ASTContext::getIntPtrType() const {
5657   return getFromTargetType(Target->getIntPtrType());
5658 }
5659 
5660 QualType ASTContext::getUIntPtrType() const {
5661   return getCorrespondingUnsignedType(getIntPtrType());
5662 }
5663 
5664 /// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
5665 /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
5666 QualType ASTContext::getPointerDiffType() const {
5667   return getFromTargetType(Target->getPtrDiffType(0));
5668 }
5669 
5670 /// Return the unique unsigned counterpart of "ptrdiff_t"
5671 /// integer type. The standard (C11 7.21.6.1p7) refers to this type
5672 /// in the definition of %tu format specifier.
5673 QualType ASTContext::getUnsignedPointerDiffType() const {
5674   return getFromTargetType(Target->getUnsignedPtrDiffType(0));
5675 }
5676 
5677 /// Return the unique type for "pid_t" defined in
5678 /// <sys/types.h>. We need this to compute the correct type for vfork().
5679 QualType ASTContext::getProcessIDType() const {
5680   return getFromTargetType(Target->getProcessIDType());
5681 }
5682 
5683 //===----------------------------------------------------------------------===//
5684 //                              Type Operators
5685 //===----------------------------------------------------------------------===//
5686 
5687 CanQualType ASTContext::getCanonicalParamType(QualType T) const {
5688   // Push qualifiers into arrays, and then discard any remaining
5689   // qualifiers.
5690   T = getCanonicalType(T);
5691   T = getVariableArrayDecayedType(T);
5692   const Type *Ty = T.getTypePtr();
5693   QualType Result;
5694   if (isa<ArrayType>(Ty)) {
5695     Result = getArrayDecayedType(QualType(Ty,0));
5696   } else if (isa<FunctionType>(Ty)) {
5697     Result = getPointerType(QualType(Ty, 0));
5698   } else {
5699     Result = QualType(Ty, 0);
5700   }
5701 
5702   return CanQualType::CreateUnsafe(Result);
5703 }
5704 
5705 QualType ASTContext::getUnqualifiedArrayType(QualType type,
5706                                              Qualifiers &quals) {
5707   SplitQualType splitType = type.getSplitUnqualifiedType();
5708 
5709   // FIXME: getSplitUnqualifiedType() actually walks all the way to
5710   // the unqualified desugared type and then drops it on the floor.
5711   // We then have to strip that sugar back off with
5712   // getUnqualifiedDesugaredType(), which is silly.
5713   const auto *AT =
5714       dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
5715 
5716   // If we don't have an array, just use the results in splitType.
5717   if (!AT) {
5718     quals = splitType.Quals;
5719     return QualType(splitType.Ty, 0);
5720   }
5721 
5722   // Otherwise, recurse on the array's element type.
5723   QualType elementType = AT->getElementType();
5724   QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
5725 
5726   // If that didn't change the element type, AT has no qualifiers, so we
5727   // can just use the results in splitType.
5728   if (elementType == unqualElementType) {
5729     assert(quals.empty()); // from the recursive call
5730     quals = splitType.Quals;
5731     return QualType(splitType.Ty, 0);
5732   }
5733 
5734   // Otherwise, add in the qualifiers from the outermost type, then
5735   // build the type back up.
5736   quals.addConsistentQualifiers(splitType.Quals);
5737 
5738   if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
5739     return getConstantArrayType(unqualElementType, CAT->getSize(),
5740                                 CAT->getSizeExpr(), CAT->getSizeModifier(), 0);
5741   }
5742 
5743   if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) {
5744     return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
5745   }
5746 
5747   if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) {
5748     return getVariableArrayType(unqualElementType,
5749                                 VAT->getSizeExpr(),
5750                                 VAT->getSizeModifier(),
5751                                 VAT->getIndexTypeCVRQualifiers(),
5752                                 VAT->getBracketsRange());
5753   }
5754 
5755   const auto *DSAT = cast<DependentSizedArrayType>(AT);
5756   return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
5757                                     DSAT->getSizeModifier(), 0,
5758                                     SourceRange());
5759 }
5760 
5761 /// Attempt to unwrap two types that may both be array types with the same bound
5762 /// (or both be array types of unknown bound) for the purpose of comparing the
5763 /// cv-decomposition of two types per C++ [conv.qual].
5764 bool ASTContext::UnwrapSimilarArrayTypes(QualType &T1, QualType &T2) {
5765   bool UnwrappedAny = false;
5766   while (true) {
5767     auto *AT1 = getAsArrayType(T1);
5768     if (!AT1) return UnwrappedAny;
5769 
5770     auto *AT2 = getAsArrayType(T2);
5771     if (!AT2) return UnwrappedAny;
5772 
5773     // If we don't have two array types with the same constant bound nor two
5774     // incomplete array types, we've unwrapped everything we can.
5775     if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) {
5776       auto *CAT2 = dyn_cast<ConstantArrayType>(AT2);
5777       if (!CAT2 || CAT1->getSize() != CAT2->getSize())
5778         return UnwrappedAny;
5779     } else if (!isa<IncompleteArrayType>(AT1) ||
5780                !isa<IncompleteArrayType>(AT2)) {
5781       return UnwrappedAny;
5782     }
5783 
5784     T1 = AT1->getElementType();
5785     T2 = AT2->getElementType();
5786     UnwrappedAny = true;
5787   }
5788 }
5789 
5790 /// Attempt to unwrap two types that may be similar (C++ [conv.qual]).
5791 ///
5792 /// If T1 and T2 are both pointer types of the same kind, or both array types
5793 /// with the same bound, unwraps layers from T1 and T2 until a pointer type is
5794 /// unwrapped. Top-level qualifiers on T1 and T2 are ignored.
5795 ///
5796 /// This function will typically be called in a loop that successively
5797 /// "unwraps" pointer and pointer-to-member types to compare them at each
5798 /// level.
5799 ///
5800 /// \return \c true if a pointer type was unwrapped, \c false if we reached a
5801 /// pair of types that can't be unwrapped further.
5802 bool ASTContext::UnwrapSimilarTypes(QualType &T1, QualType &T2) {
5803   UnwrapSimilarArrayTypes(T1, T2);
5804 
5805   const auto *T1PtrType = T1->getAs<PointerType>();
5806   const auto *T2PtrType = T2->getAs<PointerType>();
5807   if (T1PtrType && T2PtrType) {
5808     T1 = T1PtrType->getPointeeType();
5809     T2 = T2PtrType->getPointeeType();
5810     return true;
5811   }
5812 
5813   const auto *T1MPType = T1->getAs<MemberPointerType>();
5814   const auto *T2MPType = T2->getAs<MemberPointerType>();
5815   if (T1MPType && T2MPType &&
5816       hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
5817                              QualType(T2MPType->getClass(), 0))) {
5818     T1 = T1MPType->getPointeeType();
5819     T2 = T2MPType->getPointeeType();
5820     return true;
5821   }
5822 
5823   if (getLangOpts().ObjC) {
5824     const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
5825     const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
5826     if (T1OPType && T2OPType) {
5827       T1 = T1OPType->getPointeeType();
5828       T2 = T2OPType->getPointeeType();
5829       return true;
5830     }
5831   }
5832 
5833   // FIXME: Block pointers, too?
5834 
5835   return false;
5836 }
5837 
5838 bool ASTContext::hasSimilarType(QualType T1, QualType T2) {
5839   while (true) {
5840     Qualifiers Quals;
5841     T1 = getUnqualifiedArrayType(T1, Quals);
5842     T2 = getUnqualifiedArrayType(T2, Quals);
5843     if (hasSameType(T1, T2))
5844       return true;
5845     if (!UnwrapSimilarTypes(T1, T2))
5846       return false;
5847   }
5848 }
5849 
5850 bool ASTContext::hasCvrSimilarType(QualType T1, QualType T2) {
5851   while (true) {
5852     Qualifiers Quals1, Quals2;
5853     T1 = getUnqualifiedArrayType(T1, Quals1);
5854     T2 = getUnqualifiedArrayType(T2, Quals2);
5855 
5856     Quals1.removeCVRQualifiers();
5857     Quals2.removeCVRQualifiers();
5858     if (Quals1 != Quals2)
5859       return false;
5860 
5861     if (hasSameType(T1, T2))
5862       return true;
5863 
5864     if (!UnwrapSimilarTypes(T1, T2))
5865       return false;
5866   }
5867 }
5868 
5869 DeclarationNameInfo
5870 ASTContext::getNameForTemplate(TemplateName Name,
5871                                SourceLocation NameLoc) const {
5872   switch (Name.getKind()) {
5873   case TemplateName::QualifiedTemplate:
5874   case TemplateName::Template:
5875     // DNInfo work in progress: CHECKME: what about DNLoc?
5876     return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
5877                                NameLoc);
5878 
5879   case TemplateName::OverloadedTemplate: {
5880     OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
5881     // DNInfo work in progress: CHECKME: what about DNLoc?
5882     return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
5883   }
5884 
5885   case TemplateName::AssumedTemplate: {
5886     AssumedTemplateStorage *Storage = Name.getAsAssumedTemplateName();
5887     return DeclarationNameInfo(Storage->getDeclName(), NameLoc);
5888   }
5889 
5890   case TemplateName::DependentTemplate: {
5891     DependentTemplateName *DTN = Name.getAsDependentTemplateName();
5892     DeclarationName DName;
5893     if (DTN->isIdentifier()) {
5894       DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
5895       return DeclarationNameInfo(DName, NameLoc);
5896     } else {
5897       DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
5898       // DNInfo work in progress: FIXME: source locations?
5899       DeclarationNameLoc DNLoc =
5900           DeclarationNameLoc::makeCXXOperatorNameLoc(SourceRange());
5901       return DeclarationNameInfo(DName, NameLoc, DNLoc);
5902     }
5903   }
5904 
5905   case TemplateName::SubstTemplateTemplateParm: {
5906     SubstTemplateTemplateParmStorage *subst
5907       = Name.getAsSubstTemplateTemplateParm();
5908     return DeclarationNameInfo(subst->getParameter()->getDeclName(),
5909                                NameLoc);
5910   }
5911 
5912   case TemplateName::SubstTemplateTemplateParmPack: {
5913     SubstTemplateTemplateParmPackStorage *subst
5914       = Name.getAsSubstTemplateTemplateParmPack();
5915     return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
5916                                NameLoc);
5917   }
5918   }
5919 
5920   llvm_unreachable("bad template name kind!");
5921 }
5922 
5923 TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
5924   switch (Name.getKind()) {
5925   case TemplateName::QualifiedTemplate:
5926   case TemplateName::Template: {
5927     TemplateDecl *Template = Name.getAsTemplateDecl();
5928     if (auto *TTP  = dyn_cast<TemplateTemplateParmDecl>(Template))
5929       Template = getCanonicalTemplateTemplateParmDecl(TTP);
5930 
5931     // The canonical template name is the canonical template declaration.
5932     return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
5933   }
5934 
5935   case TemplateName::OverloadedTemplate:
5936   case TemplateName::AssumedTemplate:
5937     llvm_unreachable("cannot canonicalize unresolved template");
5938 
5939   case TemplateName::DependentTemplate: {
5940     DependentTemplateName *DTN = Name.getAsDependentTemplateName();
5941     assert(DTN && "Non-dependent template names must refer to template decls.");
5942     return DTN->CanonicalTemplateName;
5943   }
5944 
5945   case TemplateName::SubstTemplateTemplateParm: {
5946     SubstTemplateTemplateParmStorage *subst
5947       = Name.getAsSubstTemplateTemplateParm();
5948     return getCanonicalTemplateName(subst->getReplacement());
5949   }
5950 
5951   case TemplateName::SubstTemplateTemplateParmPack: {
5952     SubstTemplateTemplateParmPackStorage *subst
5953                                   = Name.getAsSubstTemplateTemplateParmPack();
5954     TemplateTemplateParmDecl *canonParameter
5955       = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
5956     TemplateArgument canonArgPack
5957       = getCanonicalTemplateArgument(subst->getArgumentPack());
5958     return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
5959   }
5960   }
5961 
5962   llvm_unreachable("bad template name!");
5963 }
5964 
5965 bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
5966   X = getCanonicalTemplateName(X);
5967   Y = getCanonicalTemplateName(Y);
5968   return X.getAsVoidPointer() == Y.getAsVoidPointer();
5969 }
5970 
5971 TemplateArgument
5972 ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
5973   switch (Arg.getKind()) {
5974     case TemplateArgument::Null:
5975       return Arg;
5976 
5977     case TemplateArgument::Expression:
5978       return Arg;
5979 
5980     case TemplateArgument::Declaration: {
5981       auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
5982       return TemplateArgument(D, Arg.getParamTypeForDecl());
5983     }
5984 
5985     case TemplateArgument::NullPtr:
5986       return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
5987                               /*isNullPtr*/true);
5988 
5989     case TemplateArgument::Template:
5990       return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
5991 
5992     case TemplateArgument::TemplateExpansion:
5993       return TemplateArgument(getCanonicalTemplateName(
5994                                          Arg.getAsTemplateOrTemplatePattern()),
5995                               Arg.getNumTemplateExpansions());
5996 
5997     case TemplateArgument::Integral:
5998       return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
5999 
6000     case TemplateArgument::Type:
6001       return TemplateArgument(getCanonicalType(Arg.getAsType()));
6002 
6003     case TemplateArgument::Pack: {
6004       if (Arg.pack_size() == 0)
6005         return Arg;
6006 
6007       auto *CanonArgs = new (*this) TemplateArgument[Arg.pack_size()];
6008       unsigned Idx = 0;
6009       for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
6010                                         AEnd = Arg.pack_end();
6011            A != AEnd; (void)++A, ++Idx)
6012         CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
6013 
6014       return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
6015     }
6016   }
6017 
6018   // Silence GCC warning
6019   llvm_unreachable("Unhandled template argument kind");
6020 }
6021 
6022 NestedNameSpecifier *
6023 ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
6024   if (!NNS)
6025     return nullptr;
6026 
6027   switch (NNS->getKind()) {
6028   case NestedNameSpecifier::Identifier:
6029     // Canonicalize the prefix but keep the identifier the same.
6030     return NestedNameSpecifier::Create(*this,
6031                          getCanonicalNestedNameSpecifier(NNS->getPrefix()),
6032                                        NNS->getAsIdentifier());
6033 
6034   case NestedNameSpecifier::Namespace:
6035     // A namespace is canonical; build a nested-name-specifier with
6036     // this namespace and no prefix.
6037     return NestedNameSpecifier::Create(*this, nullptr,
6038                                  NNS->getAsNamespace()->getOriginalNamespace());
6039 
6040   case NestedNameSpecifier::NamespaceAlias:
6041     // A namespace is canonical; build a nested-name-specifier with
6042     // this namespace and no prefix.
6043     return NestedNameSpecifier::Create(*this, nullptr,
6044                                     NNS->getAsNamespaceAlias()->getNamespace()
6045                                                       ->getOriginalNamespace());
6046 
6047   case NestedNameSpecifier::TypeSpec:
6048   case NestedNameSpecifier::TypeSpecWithTemplate: {
6049     QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
6050 
6051     // If we have some kind of dependent-named type (e.g., "typename T::type"),
6052     // break it apart into its prefix and identifier, then reconsititute those
6053     // as the canonical nested-name-specifier. This is required to canonicalize
6054     // a dependent nested-name-specifier involving typedefs of dependent-name
6055     // types, e.g.,
6056     //   typedef typename T::type T1;
6057     //   typedef typename T1::type T2;
6058     if (const auto *DNT = T->getAs<DependentNameType>())
6059       return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
6060                            const_cast<IdentifierInfo *>(DNT->getIdentifier()));
6061 
6062     // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
6063     // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
6064     // first place?
6065     return NestedNameSpecifier::Create(*this, nullptr, false,
6066                                        const_cast<Type *>(T.getTypePtr()));
6067   }
6068 
6069   case NestedNameSpecifier::Global:
6070   case NestedNameSpecifier::Super:
6071     // The global specifier and __super specifer are canonical and unique.
6072     return NNS;
6073   }
6074 
6075   llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
6076 }
6077 
6078 const ArrayType *ASTContext::getAsArrayType(QualType T) const {
6079   // Handle the non-qualified case efficiently.
6080   if (!T.hasLocalQualifiers()) {
6081     // Handle the common positive case fast.
6082     if (const auto *AT = dyn_cast<ArrayType>(T))
6083       return AT;
6084   }
6085 
6086   // Handle the common negative case fast.
6087   if (!isa<ArrayType>(T.getCanonicalType()))
6088     return nullptr;
6089 
6090   // Apply any qualifiers from the array type to the element type.  This
6091   // implements C99 6.7.3p8: "If the specification of an array type includes
6092   // any type qualifiers, the element type is so qualified, not the array type."
6093 
6094   // If we get here, we either have type qualifiers on the type, or we have
6095   // sugar such as a typedef in the way.  If we have type qualifiers on the type
6096   // we must propagate them down into the element type.
6097 
6098   SplitQualType split = T.getSplitDesugaredType();
6099   Qualifiers qs = split.Quals;
6100 
6101   // If we have a simple case, just return now.
6102   const auto *ATy = dyn_cast<ArrayType>(split.Ty);
6103   if (!ATy || qs.empty())
6104     return ATy;
6105 
6106   // Otherwise, we have an array and we have qualifiers on it.  Push the
6107   // qualifiers into the array element type and return a new array type.
6108   QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
6109 
6110   if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy))
6111     return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
6112                                                 CAT->getSizeExpr(),
6113                                                 CAT->getSizeModifier(),
6114                                            CAT->getIndexTypeCVRQualifiers()));
6115   if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy))
6116     return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
6117                                                   IAT->getSizeModifier(),
6118                                            IAT->getIndexTypeCVRQualifiers()));
6119 
6120   if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy))
6121     return cast<ArrayType>(
6122                      getDependentSizedArrayType(NewEltTy,
6123                                                 DSAT->getSizeExpr(),
6124                                                 DSAT->getSizeModifier(),
6125                                               DSAT->getIndexTypeCVRQualifiers(),
6126                                                 DSAT->getBracketsRange()));
6127 
6128   const auto *VAT = cast<VariableArrayType>(ATy);
6129   return cast<ArrayType>(getVariableArrayType(NewEltTy,
6130                                               VAT->getSizeExpr(),
6131                                               VAT->getSizeModifier(),
6132                                               VAT->getIndexTypeCVRQualifiers(),
6133                                               VAT->getBracketsRange()));
6134 }
6135 
6136 QualType ASTContext::getAdjustedParameterType(QualType T) const {
6137   if (T->isArrayType() || T->isFunctionType())
6138     return getDecayedType(T);
6139   return T;
6140 }
6141 
6142 QualType ASTContext::getSignatureParameterType(QualType T) const {
6143   T = getVariableArrayDecayedType(T);
6144   T = getAdjustedParameterType(T);
6145   return T.getUnqualifiedType();
6146 }
6147 
6148 QualType ASTContext::getExceptionObjectType(QualType T) const {
6149   // C++ [except.throw]p3:
6150   //   A throw-expression initializes a temporary object, called the exception
6151   //   object, the type of which is determined by removing any top-level
6152   //   cv-qualifiers from the static type of the operand of throw and adjusting
6153   //   the type from "array of T" or "function returning T" to "pointer to T"
6154   //   or "pointer to function returning T", [...]
6155   T = getVariableArrayDecayedType(T);
6156   if (T->isArrayType() || T->isFunctionType())
6157     T = getDecayedType(T);
6158   return T.getUnqualifiedType();
6159 }
6160 
6161 /// getArrayDecayedType - Return the properly qualified result of decaying the
6162 /// specified array type to a pointer.  This operation is non-trivial when
6163 /// handling typedefs etc.  The canonical type of "T" must be an array type,
6164 /// this returns a pointer to a properly qualified element of the array.
6165 ///
6166 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
6167 QualType ASTContext::getArrayDecayedType(QualType Ty) const {
6168   // Get the element type with 'getAsArrayType' so that we don't lose any
6169   // typedefs in the element type of the array.  This also handles propagation
6170   // of type qualifiers from the array type into the element type if present
6171   // (C99 6.7.3p8).
6172   const ArrayType *PrettyArrayType = getAsArrayType(Ty);
6173   assert(PrettyArrayType && "Not an array type!");
6174 
6175   QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
6176 
6177   // int x[restrict 4] ->  int *restrict
6178   QualType Result = getQualifiedType(PtrTy,
6179                                      PrettyArrayType->getIndexTypeQualifiers());
6180 
6181   // int x[_Nullable] -> int * _Nullable
6182   if (auto Nullability = Ty->getNullability(*this)) {
6183     Result = const_cast<ASTContext *>(this)->getAttributedType(
6184         AttributedType::getNullabilityAttrKind(*Nullability), Result, Result);
6185   }
6186   return Result;
6187 }
6188 
6189 QualType ASTContext::getBaseElementType(const ArrayType *array) const {
6190   return getBaseElementType(array->getElementType());
6191 }
6192 
6193 QualType ASTContext::getBaseElementType(QualType type) const {
6194   Qualifiers qs;
6195   while (true) {
6196     SplitQualType split = type.getSplitDesugaredType();
6197     const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
6198     if (!array) break;
6199 
6200     type = array->getElementType();
6201     qs.addConsistentQualifiers(split.Quals);
6202   }
6203 
6204   return getQualifiedType(type, qs);
6205 }
6206 
6207 /// getConstantArrayElementCount - Returns number of constant array elements.
6208 uint64_t
6209 ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA)  const {
6210   uint64_t ElementCount = 1;
6211   do {
6212     ElementCount *= CA->getSize().getZExtValue();
6213     CA = dyn_cast_or_null<ConstantArrayType>(
6214       CA->getElementType()->getAsArrayTypeUnsafe());
6215   } while (CA);
6216   return ElementCount;
6217 }
6218 
6219 /// getFloatingRank - Return a relative rank for floating point types.
6220 /// This routine will assert if passed a built-in type that isn't a float.
6221 static FloatingRank getFloatingRank(QualType T) {
6222   if (const auto *CT = T->getAs<ComplexType>())
6223     return getFloatingRank(CT->getElementType());
6224 
6225   switch (T->castAs<BuiltinType>()->getKind()) {
6226   default: llvm_unreachable("getFloatingRank(): not a floating type");
6227   case BuiltinType::Float16:    return Float16Rank;
6228   case BuiltinType::Half:       return HalfRank;
6229   case BuiltinType::Float:      return FloatRank;
6230   case BuiltinType::Double:     return DoubleRank;
6231   case BuiltinType::LongDouble: return LongDoubleRank;
6232   case BuiltinType::Float128:   return Float128Rank;
6233   case BuiltinType::BFloat16:   return BFloat16Rank;
6234   }
6235 }
6236 
6237 /// getFloatingTypeOfSizeWithinDomain - Returns a real floating
6238 /// point or a complex type (based on typeDomain/typeSize).
6239 /// 'typeDomain' is a real floating point or complex type.
6240 /// 'typeSize' is a real floating point or complex type.
6241 QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
6242                                                        QualType Domain) const {
6243   FloatingRank EltRank = getFloatingRank(Size);
6244   if (Domain->isComplexType()) {
6245     switch (EltRank) {
6246     case BFloat16Rank: llvm_unreachable("Complex bfloat16 is not supported");
6247     case Float16Rank:
6248     case HalfRank: llvm_unreachable("Complex half is not supported");
6249     case FloatRank:      return FloatComplexTy;
6250     case DoubleRank:     return DoubleComplexTy;
6251     case LongDoubleRank: return LongDoubleComplexTy;
6252     case Float128Rank:   return Float128ComplexTy;
6253     }
6254   }
6255 
6256   assert(Domain->isRealFloatingType() && "Unknown domain!");
6257   switch (EltRank) {
6258   case Float16Rank:    return HalfTy;
6259   case BFloat16Rank:   return BFloat16Ty;
6260   case HalfRank:       return HalfTy;
6261   case FloatRank:      return FloatTy;
6262   case DoubleRank:     return DoubleTy;
6263   case LongDoubleRank: return LongDoubleTy;
6264   case Float128Rank:   return Float128Ty;
6265   }
6266   llvm_unreachable("getFloatingRank(): illegal value for rank");
6267 }
6268 
6269 /// getFloatingTypeOrder - Compare the rank of the two specified floating
6270 /// point types, ignoring the domain of the type (i.e. 'double' ==
6271 /// '_Complex double').  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
6272 /// LHS < RHS, return -1.
6273 int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
6274   FloatingRank LHSR = getFloatingRank(LHS);
6275   FloatingRank RHSR = getFloatingRank(RHS);
6276 
6277   if (LHSR == RHSR)
6278     return 0;
6279   if (LHSR > RHSR)
6280     return 1;
6281   return -1;
6282 }
6283 
6284 int ASTContext::getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const {
6285   if (&getFloatTypeSemantics(LHS) == &getFloatTypeSemantics(RHS))
6286     return 0;
6287   return getFloatingTypeOrder(LHS, RHS);
6288 }
6289 
6290 /// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
6291 /// routine will assert if passed a built-in type that isn't an integer or enum,
6292 /// or if it is not canonicalized.
6293 unsigned ASTContext::getIntegerRank(const Type *T) const {
6294   assert(T->isCanonicalUnqualified() && "T should be canonicalized");
6295 
6296   // Results in this 'losing' to any type of the same size, but winning if
6297   // larger.
6298   if (const auto *EIT = dyn_cast<ExtIntType>(T))
6299     return 0 + (EIT->getNumBits() << 3);
6300 
6301   switch (cast<BuiltinType>(T)->getKind()) {
6302   default: llvm_unreachable("getIntegerRank(): not a built-in integer");
6303   case BuiltinType::Bool:
6304     return 1 + (getIntWidth(BoolTy) << 3);
6305   case BuiltinType::Char_S:
6306   case BuiltinType::Char_U:
6307   case BuiltinType::SChar:
6308   case BuiltinType::UChar:
6309     return 2 + (getIntWidth(CharTy) << 3);
6310   case BuiltinType::Short:
6311   case BuiltinType::UShort:
6312     return 3 + (getIntWidth(ShortTy) << 3);
6313   case BuiltinType::Int:
6314   case BuiltinType::UInt:
6315     return 4 + (getIntWidth(IntTy) << 3);
6316   case BuiltinType::Long:
6317   case BuiltinType::ULong:
6318     return 5 + (getIntWidth(LongTy) << 3);
6319   case BuiltinType::LongLong:
6320   case BuiltinType::ULongLong:
6321     return 6 + (getIntWidth(LongLongTy) << 3);
6322   case BuiltinType::Int128:
6323   case BuiltinType::UInt128:
6324     return 7 + (getIntWidth(Int128Ty) << 3);
6325   }
6326 }
6327 
6328 /// Whether this is a promotable bitfield reference according
6329 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
6330 ///
6331 /// \returns the type this bit-field will promote to, or NULL if no
6332 /// promotion occurs.
6333 QualType ASTContext::isPromotableBitField(Expr *E) const {
6334   if (E->isTypeDependent() || E->isValueDependent())
6335     return {};
6336 
6337   // C++ [conv.prom]p5:
6338   //    If the bit-field has an enumerated type, it is treated as any other
6339   //    value of that type for promotion purposes.
6340   if (getLangOpts().CPlusPlus && E->getType()->isEnumeralType())
6341     return {};
6342 
6343   // FIXME: We should not do this unless E->refersToBitField() is true. This
6344   // matters in C where getSourceBitField() will find bit-fields for various
6345   // cases where the source expression is not a bit-field designator.
6346 
6347   FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
6348   if (!Field)
6349     return {};
6350 
6351   QualType FT = Field->getType();
6352 
6353   uint64_t BitWidth = Field->getBitWidthValue(*this);
6354   uint64_t IntSize = getTypeSize(IntTy);
6355   // C++ [conv.prom]p5:
6356   //   A prvalue for an integral bit-field can be converted to a prvalue of type
6357   //   int if int can represent all the values of the bit-field; otherwise, it
6358   //   can be converted to unsigned int if unsigned int can represent all the
6359   //   values of the bit-field. If the bit-field is larger yet, no integral
6360   //   promotion applies to it.
6361   // C11 6.3.1.1/2:
6362   //   [For a bit-field of type _Bool, int, signed int, or unsigned int:]
6363   //   If an int can represent all values of the original type (as restricted by
6364   //   the width, for a bit-field), the value is converted to an int; otherwise,
6365   //   it is converted to an unsigned int.
6366   //
6367   // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
6368   //        We perform that promotion here to match GCC and C++.
6369   // FIXME: C does not permit promotion of an enum bit-field whose rank is
6370   //        greater than that of 'int'. We perform that promotion to match GCC.
6371   if (BitWidth < IntSize)
6372     return IntTy;
6373 
6374   if (BitWidth == IntSize)
6375     return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
6376 
6377   // Bit-fields wider than int are not subject to promotions, and therefore act
6378   // like the base type. GCC has some weird bugs in this area that we
6379   // deliberately do not follow (GCC follows a pre-standard resolution to
6380   // C's DR315 which treats bit-width as being part of the type, and this leaks
6381   // into their semantics in some cases).
6382   return {};
6383 }
6384 
6385 /// getPromotedIntegerType - Returns the type that Promotable will
6386 /// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
6387 /// integer type.
6388 QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
6389   assert(!Promotable.isNull());
6390   assert(Promotable->isPromotableIntegerType());
6391   if (const auto *ET = Promotable->getAs<EnumType>())
6392     return ET->getDecl()->getPromotionType();
6393 
6394   if (const auto *BT = Promotable->getAs<BuiltinType>()) {
6395     // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
6396     // (3.9.1) can be converted to a prvalue of the first of the following
6397     // types that can represent all the values of its underlying type:
6398     // int, unsigned int, long int, unsigned long int, long long int, or
6399     // unsigned long long int [...]
6400     // FIXME: Is there some better way to compute this?
6401     if (BT->getKind() == BuiltinType::WChar_S ||
6402         BT->getKind() == BuiltinType::WChar_U ||
6403         BT->getKind() == BuiltinType::Char8 ||
6404         BT->getKind() == BuiltinType::Char16 ||
6405         BT->getKind() == BuiltinType::Char32) {
6406       bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
6407       uint64_t FromSize = getTypeSize(BT);
6408       QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
6409                                   LongLongTy, UnsignedLongLongTy };
6410       for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
6411         uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
6412         if (FromSize < ToSize ||
6413             (FromSize == ToSize &&
6414              FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
6415           return PromoteTypes[Idx];
6416       }
6417       llvm_unreachable("char type should fit into long long");
6418     }
6419   }
6420 
6421   // At this point, we should have a signed or unsigned integer type.
6422   if (Promotable->isSignedIntegerType())
6423     return IntTy;
6424   uint64_t PromotableSize = getIntWidth(Promotable);
6425   uint64_t IntSize = getIntWidth(IntTy);
6426   assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
6427   return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
6428 }
6429 
6430 /// Recurses in pointer/array types until it finds an objc retainable
6431 /// type and returns its ownership.
6432 Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
6433   while (!T.isNull()) {
6434     if (T.getObjCLifetime() != Qualifiers::OCL_None)
6435       return T.getObjCLifetime();
6436     if (T->isArrayType())
6437       T = getBaseElementType(T);
6438     else if (const auto *PT = T->getAs<PointerType>())
6439       T = PT->getPointeeType();
6440     else if (const auto *RT = T->getAs<ReferenceType>())
6441       T = RT->getPointeeType();
6442     else
6443       break;
6444   }
6445 
6446   return Qualifiers::OCL_None;
6447 }
6448 
6449 static const Type *getIntegerTypeForEnum(const EnumType *ET) {
6450   // Incomplete enum types are not treated as integer types.
6451   // FIXME: In C++, enum types are never integer types.
6452   if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
6453     return ET->getDecl()->getIntegerType().getTypePtr();
6454   return nullptr;
6455 }
6456 
6457 /// getIntegerTypeOrder - Returns the highest ranked integer type:
6458 /// C99 6.3.1.8p1.  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
6459 /// LHS < RHS, return -1.
6460 int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
6461   const Type *LHSC = getCanonicalType(LHS).getTypePtr();
6462   const Type *RHSC = getCanonicalType(RHS).getTypePtr();
6463 
6464   // Unwrap enums to their underlying type.
6465   if (const auto *ET = dyn_cast<EnumType>(LHSC))
6466     LHSC = getIntegerTypeForEnum(ET);
6467   if (const auto *ET = dyn_cast<EnumType>(RHSC))
6468     RHSC = getIntegerTypeForEnum(ET);
6469 
6470   if (LHSC == RHSC) return 0;
6471 
6472   bool LHSUnsigned = LHSC->isUnsignedIntegerType();
6473   bool RHSUnsigned = RHSC->isUnsignedIntegerType();
6474 
6475   unsigned LHSRank = getIntegerRank(LHSC);
6476   unsigned RHSRank = getIntegerRank(RHSC);
6477 
6478   if (LHSUnsigned == RHSUnsigned) {  // Both signed or both unsigned.
6479     if (LHSRank == RHSRank) return 0;
6480     return LHSRank > RHSRank ? 1 : -1;
6481   }
6482 
6483   // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
6484   if (LHSUnsigned) {
6485     // If the unsigned [LHS] type is larger, return it.
6486     if (LHSRank >= RHSRank)
6487       return 1;
6488 
6489     // If the signed type can represent all values of the unsigned type, it
6490     // wins.  Because we are dealing with 2's complement and types that are
6491     // powers of two larger than each other, this is always safe.
6492     return -1;
6493   }
6494 
6495   // If the unsigned [RHS] type is larger, return it.
6496   if (RHSRank >= LHSRank)
6497     return -1;
6498 
6499   // If the signed type can represent all values of the unsigned type, it
6500   // wins.  Because we are dealing with 2's complement and types that are
6501   // powers of two larger than each other, this is always safe.
6502   return 1;
6503 }
6504 
6505 TypedefDecl *ASTContext::getCFConstantStringDecl() const {
6506   if (CFConstantStringTypeDecl)
6507     return CFConstantStringTypeDecl;
6508 
6509   assert(!CFConstantStringTagDecl &&
6510          "tag and typedef should be initialized together");
6511   CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
6512   CFConstantStringTagDecl->startDefinition();
6513 
6514   struct {
6515     QualType Type;
6516     const char *Name;
6517   } Fields[5];
6518   unsigned Count = 0;
6519 
6520   /// Objective-C ABI
6521   ///
6522   ///    typedef struct __NSConstantString_tag {
6523   ///      const int *isa;
6524   ///      int flags;
6525   ///      const char *str;
6526   ///      long length;
6527   ///    } __NSConstantString;
6528   ///
6529   /// Swift ABI (4.1, 4.2)
6530   ///
6531   ///    typedef struct __NSConstantString_tag {
6532   ///      uintptr_t _cfisa;
6533   ///      uintptr_t _swift_rc;
6534   ///      _Atomic(uint64_t) _cfinfoa;
6535   ///      const char *_ptr;
6536   ///      uint32_t _length;
6537   ///    } __NSConstantString;
6538   ///
6539   /// Swift ABI (5.0)
6540   ///
6541   ///    typedef struct __NSConstantString_tag {
6542   ///      uintptr_t _cfisa;
6543   ///      uintptr_t _swift_rc;
6544   ///      _Atomic(uint64_t) _cfinfoa;
6545   ///      const char *_ptr;
6546   ///      uintptr_t _length;
6547   ///    } __NSConstantString;
6548 
6549   const auto CFRuntime = getLangOpts().CFRuntime;
6550   if (static_cast<unsigned>(CFRuntime) <
6551       static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) {
6552     Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" };
6553     Fields[Count++] = { IntTy, "flags" };
6554     Fields[Count++] = { getPointerType(CharTy.withConst()), "str" };
6555     Fields[Count++] = { LongTy, "length" };
6556   } else {
6557     Fields[Count++] = { getUIntPtrType(), "_cfisa" };
6558     Fields[Count++] = { getUIntPtrType(), "_swift_rc" };
6559     Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" };
6560     Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" };
6561     if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
6562         CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
6563       Fields[Count++] = { IntTy, "_ptr" };
6564     else
6565       Fields[Count++] = { getUIntPtrType(), "_ptr" };
6566   }
6567 
6568   // Create fields
6569   for (unsigned i = 0; i < Count; ++i) {
6570     FieldDecl *Field =
6571         FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(),
6572                           SourceLocation(), &Idents.get(Fields[i].Name),
6573                           Fields[i].Type, /*TInfo=*/nullptr,
6574                           /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
6575     Field->setAccess(AS_public);
6576     CFConstantStringTagDecl->addDecl(Field);
6577   }
6578 
6579   CFConstantStringTagDecl->completeDefinition();
6580   // This type is designed to be compatible with NSConstantString, but cannot
6581   // use the same name, since NSConstantString is an interface.
6582   auto tagType = getTagDeclType(CFConstantStringTagDecl);
6583   CFConstantStringTypeDecl =
6584       buildImplicitTypedef(tagType, "__NSConstantString");
6585 
6586   return CFConstantStringTypeDecl;
6587 }
6588 
6589 RecordDecl *ASTContext::getCFConstantStringTagDecl() const {
6590   if (!CFConstantStringTagDecl)
6591     getCFConstantStringDecl(); // Build the tag and the typedef.
6592   return CFConstantStringTagDecl;
6593 }
6594 
6595 // getCFConstantStringType - Return the type used for constant CFStrings.
6596 QualType ASTContext::getCFConstantStringType() const {
6597   return getTypedefType(getCFConstantStringDecl());
6598 }
6599 
6600 QualType ASTContext::getObjCSuperType() const {
6601   if (ObjCSuperType.isNull()) {
6602     RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
6603     TUDecl->addDecl(ObjCSuperTypeDecl);
6604     ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
6605   }
6606   return ObjCSuperType;
6607 }
6608 
6609 void ASTContext::setCFConstantStringType(QualType T) {
6610   const auto *TD = T->castAs<TypedefType>();
6611   CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl());
6612   const auto *TagType =
6613       CFConstantStringTypeDecl->getUnderlyingType()->castAs<RecordType>();
6614   CFConstantStringTagDecl = TagType->getDecl();
6615 }
6616 
6617 QualType ASTContext::getBlockDescriptorType() const {
6618   if (BlockDescriptorType)
6619     return getTagDeclType(BlockDescriptorType);
6620 
6621   RecordDecl *RD;
6622   // FIXME: Needs the FlagAppleBlock bit.
6623   RD = buildImplicitRecord("__block_descriptor");
6624   RD->startDefinition();
6625 
6626   QualType FieldTypes[] = {
6627     UnsignedLongTy,
6628     UnsignedLongTy,
6629   };
6630 
6631   static const char *const FieldNames[] = {
6632     "reserved",
6633     "Size"
6634   };
6635 
6636   for (size_t i = 0; i < 2; ++i) {
6637     FieldDecl *Field = FieldDecl::Create(
6638         *this, RD, SourceLocation(), SourceLocation(),
6639         &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
6640         /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
6641     Field->setAccess(AS_public);
6642     RD->addDecl(Field);
6643   }
6644 
6645   RD->completeDefinition();
6646 
6647   BlockDescriptorType = RD;
6648 
6649   return getTagDeclType(BlockDescriptorType);
6650 }
6651 
6652 QualType ASTContext::getBlockDescriptorExtendedType() const {
6653   if (BlockDescriptorExtendedType)
6654     return getTagDeclType(BlockDescriptorExtendedType);
6655 
6656   RecordDecl *RD;
6657   // FIXME: Needs the FlagAppleBlock bit.
6658   RD = buildImplicitRecord("__block_descriptor_withcopydispose");
6659   RD->startDefinition();
6660 
6661   QualType FieldTypes[] = {
6662     UnsignedLongTy,
6663     UnsignedLongTy,
6664     getPointerType(VoidPtrTy),
6665     getPointerType(VoidPtrTy)
6666   };
6667 
6668   static const char *const FieldNames[] = {
6669     "reserved",
6670     "Size",
6671     "CopyFuncPtr",
6672     "DestroyFuncPtr"
6673   };
6674 
6675   for (size_t i = 0; i < 4; ++i) {
6676     FieldDecl *Field = FieldDecl::Create(
6677         *this, RD, SourceLocation(), SourceLocation(),
6678         &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
6679         /*BitWidth=*/nullptr,
6680         /*Mutable=*/false, ICIS_NoInit);
6681     Field->setAccess(AS_public);
6682     RD->addDecl(Field);
6683   }
6684 
6685   RD->completeDefinition();
6686 
6687   BlockDescriptorExtendedType = RD;
6688   return getTagDeclType(BlockDescriptorExtendedType);
6689 }
6690 
6691 OpenCLTypeKind ASTContext::getOpenCLTypeKind(const Type *T) const {
6692   const auto *BT = dyn_cast<BuiltinType>(T);
6693 
6694   if (!BT) {
6695     if (isa<PipeType>(T))
6696       return OCLTK_Pipe;
6697 
6698     return OCLTK_Default;
6699   }
6700 
6701   switch (BT->getKind()) {
6702 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix)                   \
6703   case BuiltinType::Id:                                                        \
6704     return OCLTK_Image;
6705 #include "clang/Basic/OpenCLImageTypes.def"
6706 
6707   case BuiltinType::OCLClkEvent:
6708     return OCLTK_ClkEvent;
6709 
6710   case BuiltinType::OCLEvent:
6711     return OCLTK_Event;
6712 
6713   case BuiltinType::OCLQueue:
6714     return OCLTK_Queue;
6715 
6716   case BuiltinType::OCLReserveID:
6717     return OCLTK_ReserveID;
6718 
6719   case BuiltinType::OCLSampler:
6720     return OCLTK_Sampler;
6721 
6722   default:
6723     return OCLTK_Default;
6724   }
6725 }
6726 
6727 LangAS ASTContext::getOpenCLTypeAddrSpace(const Type *T) const {
6728   return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
6729 }
6730 
6731 /// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
6732 /// requires copy/dispose. Note that this must match the logic
6733 /// in buildByrefHelpers.
6734 bool ASTContext::BlockRequiresCopying(QualType Ty,
6735                                       const VarDecl *D) {
6736   if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
6737     const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr();
6738     if (!copyExpr && record->hasTrivialDestructor()) return false;
6739 
6740     return true;
6741   }
6742 
6743   // The block needs copy/destroy helpers if Ty is non-trivial to destructively
6744   // move or destroy.
6745   if (Ty.isNonTrivialToPrimitiveDestructiveMove() || Ty.isDestructedType())
6746     return true;
6747 
6748   if (!Ty->isObjCRetainableType()) return false;
6749 
6750   Qualifiers qs = Ty.getQualifiers();
6751 
6752   // If we have lifetime, that dominates.
6753   if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
6754     switch (lifetime) {
6755       case Qualifiers::OCL_None: llvm_unreachable("impossible");
6756 
6757       // These are just bits as far as the runtime is concerned.
6758       case Qualifiers::OCL_ExplicitNone:
6759       case Qualifiers::OCL_Autoreleasing:
6760         return false;
6761 
6762       // These cases should have been taken care of when checking the type's
6763       // non-triviality.
6764       case Qualifiers::OCL_Weak:
6765       case Qualifiers::OCL_Strong:
6766         llvm_unreachable("impossible");
6767     }
6768     llvm_unreachable("fell out of lifetime switch!");
6769   }
6770   return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
6771           Ty->isObjCObjectPointerType());
6772 }
6773 
6774 bool ASTContext::getByrefLifetime(QualType Ty,
6775                               Qualifiers::ObjCLifetime &LifeTime,
6776                               bool &HasByrefExtendedLayout) const {
6777   if (!getLangOpts().ObjC ||
6778       getLangOpts().getGC() != LangOptions::NonGC)
6779     return false;
6780 
6781   HasByrefExtendedLayout = false;
6782   if (Ty->isRecordType()) {
6783     HasByrefExtendedLayout = true;
6784     LifeTime = Qualifiers::OCL_None;
6785   } else if ((LifeTime = Ty.getObjCLifetime())) {
6786     // Honor the ARC qualifiers.
6787   } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
6788     // The MRR rule.
6789     LifeTime = Qualifiers::OCL_ExplicitNone;
6790   } else {
6791     LifeTime = Qualifiers::OCL_None;
6792   }
6793   return true;
6794 }
6795 
6796 CanQualType ASTContext::getNSUIntegerType() const {
6797   assert(Target && "Expected target to be initialized");
6798   const llvm::Triple &T = Target->getTriple();
6799   // Windows is LLP64 rather than LP64
6800   if (T.isOSWindows() && T.isArch64Bit())
6801     return UnsignedLongLongTy;
6802   return UnsignedLongTy;
6803 }
6804 
6805 CanQualType ASTContext::getNSIntegerType() const {
6806   assert(Target && "Expected target to be initialized");
6807   const llvm::Triple &T = Target->getTriple();
6808   // Windows is LLP64 rather than LP64
6809   if (T.isOSWindows() && T.isArch64Bit())
6810     return LongLongTy;
6811   return LongTy;
6812 }
6813 
6814 TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
6815   if (!ObjCInstanceTypeDecl)
6816     ObjCInstanceTypeDecl =
6817         buildImplicitTypedef(getObjCIdType(), "instancetype");
6818   return ObjCInstanceTypeDecl;
6819 }
6820 
6821 // This returns true if a type has been typedefed to BOOL:
6822 // typedef <type> BOOL;
6823 static bool isTypeTypedefedAsBOOL(QualType T) {
6824   if (const auto *TT = dyn_cast<TypedefType>(T))
6825     if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
6826       return II->isStr("BOOL");
6827 
6828   return false;
6829 }
6830 
6831 /// getObjCEncodingTypeSize returns size of type for objective-c encoding
6832 /// purpose.
6833 CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
6834   if (!type->isIncompleteArrayType() && type->isIncompleteType())
6835     return CharUnits::Zero();
6836 
6837   CharUnits sz = getTypeSizeInChars(type);
6838 
6839   // Make all integer and enum types at least as large as an int
6840   if (sz.isPositive() && type->isIntegralOrEnumerationType())
6841     sz = std::max(sz, getTypeSizeInChars(IntTy));
6842   // Treat arrays as pointers, since that's how they're passed in.
6843   else if (type->isArrayType())
6844     sz = getTypeSizeInChars(VoidPtrTy);
6845   return sz;
6846 }
6847 
6848 bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
6849   return getTargetInfo().getCXXABI().isMicrosoft() &&
6850          VD->isStaticDataMember() &&
6851          VD->getType()->isIntegralOrEnumerationType() &&
6852          !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
6853 }
6854 
6855 ASTContext::InlineVariableDefinitionKind
6856 ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const {
6857   if (!VD->isInline())
6858     return InlineVariableDefinitionKind::None;
6859 
6860   // In almost all cases, it's a weak definition.
6861   auto *First = VD->getFirstDecl();
6862   if (First->isInlineSpecified() || !First->isStaticDataMember())
6863     return InlineVariableDefinitionKind::Weak;
6864 
6865   // If there's a file-context declaration in this translation unit, it's a
6866   // non-discardable definition.
6867   for (auto *D : VD->redecls())
6868     if (D->getLexicalDeclContext()->isFileContext() &&
6869         !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
6870       return InlineVariableDefinitionKind::Strong;
6871 
6872   // If we've not seen one yet, we don't know.
6873   return InlineVariableDefinitionKind::WeakUnknown;
6874 }
6875 
6876 static std::string charUnitsToString(const CharUnits &CU) {
6877   return llvm::itostr(CU.getQuantity());
6878 }
6879 
6880 /// getObjCEncodingForBlock - Return the encoded type for this block
6881 /// declaration.
6882 std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
6883   std::string S;
6884 
6885   const BlockDecl *Decl = Expr->getBlockDecl();
6886   QualType BlockTy =
6887       Expr->getType()->castAs<BlockPointerType>()->getPointeeType();
6888   QualType BlockReturnTy = BlockTy->castAs<FunctionType>()->getReturnType();
6889   // Encode result type.
6890   if (getLangOpts().EncodeExtendedBlockSig)
6891     getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, BlockReturnTy, S,
6892                                       true /*Extended*/);
6893   else
6894     getObjCEncodingForType(BlockReturnTy, S);
6895   // Compute size of all parameters.
6896   // Start with computing size of a pointer in number of bytes.
6897   // FIXME: There might(should) be a better way of doing this computation!
6898   CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
6899   CharUnits ParmOffset = PtrSize;
6900   for (auto PI : Decl->parameters()) {
6901     QualType PType = PI->getType();
6902     CharUnits sz = getObjCEncodingTypeSize(PType);
6903     if (sz.isZero())
6904       continue;
6905     assert(sz.isPositive() && "BlockExpr - Incomplete param type");
6906     ParmOffset += sz;
6907   }
6908   // Size of the argument frame
6909   S += charUnitsToString(ParmOffset);
6910   // Block pointer and offset.
6911   S += "@?0";
6912 
6913   // Argument types.
6914   ParmOffset = PtrSize;
6915   for (auto PVDecl : Decl->parameters()) {
6916     QualType PType = PVDecl->getOriginalType();
6917     if (const auto *AT =
6918             dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
6919       // Use array's original type only if it has known number of
6920       // elements.
6921       if (!isa<ConstantArrayType>(AT))
6922         PType = PVDecl->getType();
6923     } else if (PType->isFunctionType())
6924       PType = PVDecl->getType();
6925     if (getLangOpts().EncodeExtendedBlockSig)
6926       getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
6927                                       S, true /*Extended*/);
6928     else
6929       getObjCEncodingForType(PType, S);
6930     S += charUnitsToString(ParmOffset);
6931     ParmOffset += getObjCEncodingTypeSize(PType);
6932   }
6933 
6934   return S;
6935 }
6936 
6937 std::string
6938 ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const {
6939   std::string S;
6940   // Encode result type.
6941   getObjCEncodingForType(Decl->getReturnType(), S);
6942   CharUnits ParmOffset;
6943   // Compute size of all parameters.
6944   for (auto PI : Decl->parameters()) {
6945     QualType PType = PI->getType();
6946     CharUnits sz = getObjCEncodingTypeSize(PType);
6947     if (sz.isZero())
6948       continue;
6949 
6950     assert(sz.isPositive() &&
6951            "getObjCEncodingForFunctionDecl - Incomplete param type");
6952     ParmOffset += sz;
6953   }
6954   S += charUnitsToString(ParmOffset);
6955   ParmOffset = CharUnits::Zero();
6956 
6957   // Argument types.
6958   for (auto PVDecl : Decl->parameters()) {
6959     QualType PType = PVDecl->getOriginalType();
6960     if (const auto *AT =
6961             dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
6962       // Use array's original type only if it has known number of
6963       // elements.
6964       if (!isa<ConstantArrayType>(AT))
6965         PType = PVDecl->getType();
6966     } else if (PType->isFunctionType())
6967       PType = PVDecl->getType();
6968     getObjCEncodingForType(PType, S);
6969     S += charUnitsToString(ParmOffset);
6970     ParmOffset += getObjCEncodingTypeSize(PType);
6971   }
6972 
6973   return S;
6974 }
6975 
6976 /// getObjCEncodingForMethodParameter - Return the encoded type for a single
6977 /// method parameter or return type. If Extended, include class names and
6978 /// block object types.
6979 void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
6980                                                    QualType T, std::string& S,
6981                                                    bool Extended) const {
6982   // Encode type qualifer, 'in', 'inout', etc. for the parameter.
6983   getObjCEncodingForTypeQualifier(QT, S);
6984   // Encode parameter type.
6985   ObjCEncOptions Options = ObjCEncOptions()
6986                                .setExpandPointedToStructures()
6987                                .setExpandStructures()
6988                                .setIsOutermostType();
6989   if (Extended)
6990     Options.setEncodeBlockParameters().setEncodeClassNames();
6991   getObjCEncodingForTypeImpl(T, S, Options, /*Field=*/nullptr);
6992 }
6993 
6994 /// getObjCEncodingForMethodDecl - Return the encoded type for this method
6995 /// declaration.
6996 std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
6997                                                      bool Extended) const {
6998   // FIXME: This is not very efficient.
6999   // Encode return type.
7000   std::string S;
7001   getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
7002                                     Decl->getReturnType(), S, Extended);
7003   // Compute size of all parameters.
7004   // Start with computing size of a pointer in number of bytes.
7005   // FIXME: There might(should) be a better way of doing this computation!
7006   CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
7007   // The first two arguments (self and _cmd) are pointers; account for
7008   // their size.
7009   CharUnits ParmOffset = 2 * PtrSize;
7010   for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
7011        E = Decl->sel_param_end(); PI != E; ++PI) {
7012     QualType PType = (*PI)->getType();
7013     CharUnits sz = getObjCEncodingTypeSize(PType);
7014     if (sz.isZero())
7015       continue;
7016 
7017     assert(sz.isPositive() &&
7018            "getObjCEncodingForMethodDecl - Incomplete param type");
7019     ParmOffset += sz;
7020   }
7021   S += charUnitsToString(ParmOffset);
7022   S += "@0:";
7023   S += charUnitsToString(PtrSize);
7024 
7025   // Argument types.
7026   ParmOffset = 2 * PtrSize;
7027   for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
7028        E = Decl->sel_param_end(); PI != E; ++PI) {
7029     const ParmVarDecl *PVDecl = *PI;
7030     QualType PType = PVDecl->getOriginalType();
7031     if (const auto *AT =
7032             dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
7033       // Use array's original type only if it has known number of
7034       // elements.
7035       if (!isa<ConstantArrayType>(AT))
7036         PType = PVDecl->getType();
7037     } else if (PType->isFunctionType())
7038       PType = PVDecl->getType();
7039     getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
7040                                       PType, S, Extended);
7041     S += charUnitsToString(ParmOffset);
7042     ParmOffset += getObjCEncodingTypeSize(PType);
7043   }
7044 
7045   return S;
7046 }
7047 
7048 ObjCPropertyImplDecl *
7049 ASTContext::getObjCPropertyImplDeclForPropertyDecl(
7050                                       const ObjCPropertyDecl *PD,
7051                                       const Decl *Container) const {
7052   if (!Container)
7053     return nullptr;
7054   if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) {
7055     for (auto *PID : CID->property_impls())
7056       if (PID->getPropertyDecl() == PD)
7057         return PID;
7058   } else {
7059     const auto *OID = cast<ObjCImplementationDecl>(Container);
7060     for (auto *PID : OID->property_impls())
7061       if (PID->getPropertyDecl() == PD)
7062         return PID;
7063   }
7064   return nullptr;
7065 }
7066 
7067 /// getObjCEncodingForPropertyDecl - Return the encoded type for this
7068 /// property declaration. If non-NULL, Container must be either an
7069 /// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
7070 /// NULL when getting encodings for protocol properties.
7071 /// Property attributes are stored as a comma-delimited C string. The simple
7072 /// attributes readonly and bycopy are encoded as single characters. The
7073 /// parametrized attributes, getter=name, setter=name, and ivar=name, are
7074 /// encoded as single characters, followed by an identifier. Property types
7075 /// are also encoded as a parametrized attribute. The characters used to encode
7076 /// these attributes are defined by the following enumeration:
7077 /// @code
7078 /// enum PropertyAttributes {
7079 /// kPropertyReadOnly = 'R',   // property is read-only.
7080 /// kPropertyBycopy = 'C',     // property is a copy of the value last assigned
7081 /// kPropertyByref = '&',  // property is a reference to the value last assigned
7082 /// kPropertyDynamic = 'D',    // property is dynamic
7083 /// kPropertyGetter = 'G',     // followed by getter selector name
7084 /// kPropertySetter = 'S',     // followed by setter selector name
7085 /// kPropertyInstanceVariable = 'V'  // followed by instance variable  name
7086 /// kPropertyType = 'T'              // followed by old-style type encoding.
7087 /// kPropertyWeak = 'W'              // 'weak' property
7088 /// kPropertyStrong = 'P'            // property GC'able
7089 /// kPropertyNonAtomic = 'N'         // property non-atomic
7090 /// };
7091 /// @endcode
7092 std::string
7093 ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
7094                                            const Decl *Container) const {
7095   // Collect information from the property implementation decl(s).
7096   bool Dynamic = false;
7097   ObjCPropertyImplDecl *SynthesizePID = nullptr;
7098 
7099   if (ObjCPropertyImplDecl *PropertyImpDecl =
7100       getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
7101     if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
7102       Dynamic = true;
7103     else
7104       SynthesizePID = PropertyImpDecl;
7105   }
7106 
7107   // FIXME: This is not very efficient.
7108   std::string S = "T";
7109 
7110   // Encode result type.
7111   // GCC has some special rules regarding encoding of properties which
7112   // closely resembles encoding of ivars.
7113   getObjCEncodingForPropertyType(PD->getType(), S);
7114 
7115   if (PD->isReadOnly()) {
7116     S += ",R";
7117     if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_copy)
7118       S += ",C";
7119     if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_retain)
7120       S += ",&";
7121     if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_weak)
7122       S += ",W";
7123   } else {
7124     switch (PD->getSetterKind()) {
7125     case ObjCPropertyDecl::Assign: break;
7126     case ObjCPropertyDecl::Copy:   S += ",C"; break;
7127     case ObjCPropertyDecl::Retain: S += ",&"; break;
7128     case ObjCPropertyDecl::Weak:   S += ",W"; break;
7129     }
7130   }
7131 
7132   // It really isn't clear at all what this means, since properties
7133   // are "dynamic by default".
7134   if (Dynamic)
7135     S += ",D";
7136 
7137   if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_nonatomic)
7138     S += ",N";
7139 
7140   if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_getter) {
7141     S += ",G";
7142     S += PD->getGetterName().getAsString();
7143   }
7144 
7145   if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_setter) {
7146     S += ",S";
7147     S += PD->getSetterName().getAsString();
7148   }
7149 
7150   if (SynthesizePID) {
7151     const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
7152     S += ",V";
7153     S += OID->getNameAsString();
7154   }
7155 
7156   // FIXME: OBJCGC: weak & strong
7157   return S;
7158 }
7159 
7160 /// getLegacyIntegralTypeEncoding -
7161 /// Another legacy compatibility encoding: 32-bit longs are encoded as
7162 /// 'l' or 'L' , but not always.  For typedefs, we need to use
7163 /// 'i' or 'I' instead if encoding a struct field, or a pointer!
7164 void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
7165   if (isa<TypedefType>(PointeeTy.getTypePtr())) {
7166     if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
7167       if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
7168         PointeeTy = UnsignedIntTy;
7169       else
7170         if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
7171           PointeeTy = IntTy;
7172     }
7173   }
7174 }
7175 
7176 void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
7177                                         const FieldDecl *Field,
7178                                         QualType *NotEncodedT) const {
7179   // We follow the behavior of gcc, expanding structures which are
7180   // directly pointed to, and expanding embedded structures. Note that
7181   // these rules are sufficient to prevent recursive encoding of the
7182   // same type.
7183   getObjCEncodingForTypeImpl(T, S,
7184                              ObjCEncOptions()
7185                                  .setExpandPointedToStructures()
7186                                  .setExpandStructures()
7187                                  .setIsOutermostType(),
7188                              Field, NotEncodedT);
7189 }
7190 
7191 void ASTContext::getObjCEncodingForPropertyType(QualType T,
7192                                                 std::string& S) const {
7193   // Encode result type.
7194   // GCC has some special rules regarding encoding of properties which
7195   // closely resembles encoding of ivars.
7196   getObjCEncodingForTypeImpl(T, S,
7197                              ObjCEncOptions()
7198                                  .setExpandPointedToStructures()
7199                                  .setExpandStructures()
7200                                  .setIsOutermostType()
7201                                  .setEncodingProperty(),
7202                              /*Field=*/nullptr);
7203 }
7204 
7205 static char getObjCEncodingForPrimitiveType(const ASTContext *C,
7206                                             const BuiltinType *BT) {
7207     BuiltinType::Kind kind = BT->getKind();
7208     switch (kind) {
7209     case BuiltinType::Void:       return 'v';
7210     case BuiltinType::Bool:       return 'B';
7211     case BuiltinType::Char8:
7212     case BuiltinType::Char_U:
7213     case BuiltinType::UChar:      return 'C';
7214     case BuiltinType::Char16:
7215     case BuiltinType::UShort:     return 'S';
7216     case BuiltinType::Char32:
7217     case BuiltinType::UInt:       return 'I';
7218     case BuiltinType::ULong:
7219         return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
7220     case BuiltinType::UInt128:    return 'T';
7221     case BuiltinType::ULongLong:  return 'Q';
7222     case BuiltinType::Char_S:
7223     case BuiltinType::SChar:      return 'c';
7224     case BuiltinType::Short:      return 's';
7225     case BuiltinType::WChar_S:
7226     case BuiltinType::WChar_U:
7227     case BuiltinType::Int:        return 'i';
7228     case BuiltinType::Long:
7229       return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
7230     case BuiltinType::LongLong:   return 'q';
7231     case BuiltinType::Int128:     return 't';
7232     case BuiltinType::Float:      return 'f';
7233     case BuiltinType::Double:     return 'd';
7234     case BuiltinType::LongDouble: return 'D';
7235     case BuiltinType::NullPtr:    return '*'; // like char*
7236 
7237     case BuiltinType::BFloat16:
7238     case BuiltinType::Float16:
7239     case BuiltinType::Float128:
7240     case BuiltinType::Half:
7241     case BuiltinType::ShortAccum:
7242     case BuiltinType::Accum:
7243     case BuiltinType::LongAccum:
7244     case BuiltinType::UShortAccum:
7245     case BuiltinType::UAccum:
7246     case BuiltinType::ULongAccum:
7247     case BuiltinType::ShortFract:
7248     case BuiltinType::Fract:
7249     case BuiltinType::LongFract:
7250     case BuiltinType::UShortFract:
7251     case BuiltinType::UFract:
7252     case BuiltinType::ULongFract:
7253     case BuiltinType::SatShortAccum:
7254     case BuiltinType::SatAccum:
7255     case BuiltinType::SatLongAccum:
7256     case BuiltinType::SatUShortAccum:
7257     case BuiltinType::SatUAccum:
7258     case BuiltinType::SatULongAccum:
7259     case BuiltinType::SatShortFract:
7260     case BuiltinType::SatFract:
7261     case BuiltinType::SatLongFract:
7262     case BuiltinType::SatUShortFract:
7263     case BuiltinType::SatUFract:
7264     case BuiltinType::SatULongFract:
7265       // FIXME: potentially need @encodes for these!
7266       return ' ';
7267 
7268 #define SVE_TYPE(Name, Id, SingletonId) \
7269     case BuiltinType::Id:
7270 #include "clang/Basic/AArch64SVEACLETypes.def"
7271 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
7272 #include "clang/Basic/RISCVVTypes.def"
7273       {
7274         DiagnosticsEngine &Diags = C->getDiagnostics();
7275         unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
7276                                                 "cannot yet @encode type %0");
7277         Diags.Report(DiagID) << BT->getName(C->getPrintingPolicy());
7278         return ' ';
7279       }
7280 
7281     case BuiltinType::ObjCId:
7282     case BuiltinType::ObjCClass:
7283     case BuiltinType::ObjCSel:
7284       llvm_unreachable("@encoding ObjC primitive type");
7285 
7286     // OpenCL and placeholder types don't need @encodings.
7287 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7288     case BuiltinType::Id:
7289 #include "clang/Basic/OpenCLImageTypes.def"
7290 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
7291     case BuiltinType::Id:
7292 #include "clang/Basic/OpenCLExtensionTypes.def"
7293     case BuiltinType::OCLEvent:
7294     case BuiltinType::OCLClkEvent:
7295     case BuiltinType::OCLQueue:
7296     case BuiltinType::OCLReserveID:
7297     case BuiltinType::OCLSampler:
7298     case BuiltinType::Dependent:
7299 #define PPC_VECTOR_TYPE(Name, Id, Size) \
7300     case BuiltinType::Id:
7301 #include "clang/Basic/PPCTypes.def"
7302 #define BUILTIN_TYPE(KIND, ID)
7303 #define PLACEHOLDER_TYPE(KIND, ID) \
7304     case BuiltinType::KIND:
7305 #include "clang/AST/BuiltinTypes.def"
7306       llvm_unreachable("invalid builtin type for @encode");
7307     }
7308     llvm_unreachable("invalid BuiltinType::Kind value");
7309 }
7310 
7311 static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
7312   EnumDecl *Enum = ET->getDecl();
7313 
7314   // The encoding of an non-fixed enum type is always 'i', regardless of size.
7315   if (!Enum->isFixed())
7316     return 'i';
7317 
7318   // The encoding of a fixed enum type matches its fixed underlying type.
7319   const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
7320   return getObjCEncodingForPrimitiveType(C, BT);
7321 }
7322 
7323 static void EncodeBitField(const ASTContext *Ctx, std::string& S,
7324                            QualType T, const FieldDecl *FD) {
7325   assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
7326   S += 'b';
7327   // The NeXT runtime encodes bit fields as b followed by the number of bits.
7328   // The GNU runtime requires more information; bitfields are encoded as b,
7329   // then the offset (in bits) of the first element, then the type of the
7330   // bitfield, then the size in bits.  For example, in this structure:
7331   //
7332   // struct
7333   // {
7334   //    int integer;
7335   //    int flags:2;
7336   // };
7337   // On a 32-bit system, the encoding for flags would be b2 for the NeXT
7338   // runtime, but b32i2 for the GNU runtime.  The reason for this extra
7339   // information is not especially sensible, but we're stuck with it for
7340   // compatibility with GCC, although providing it breaks anything that
7341   // actually uses runtime introspection and wants to work on both runtimes...
7342   if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
7343     uint64_t Offset;
7344 
7345     if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
7346       Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), nullptr,
7347                                          IVD);
7348     } else {
7349       const RecordDecl *RD = FD->getParent();
7350       const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
7351       Offset = RL.getFieldOffset(FD->getFieldIndex());
7352     }
7353 
7354     S += llvm::utostr(Offset);
7355 
7356     if (const auto *ET = T->getAs<EnumType>())
7357       S += ObjCEncodingForEnumType(Ctx, ET);
7358     else {
7359       const auto *BT = T->castAs<BuiltinType>();
7360       S += getObjCEncodingForPrimitiveType(Ctx, BT);
7361     }
7362   }
7363   S += llvm::utostr(FD->getBitWidthValue(*Ctx));
7364 }
7365 
7366 // Helper function for determining whether the encoded type string would include
7367 // a template specialization type.
7368 static bool hasTemplateSpecializationInEncodedString(const Type *T,
7369                                                      bool VisitBasesAndFields) {
7370   T = T->getBaseElementTypeUnsafe();
7371 
7372   if (auto *PT = T->getAs<PointerType>())
7373     return hasTemplateSpecializationInEncodedString(
7374         PT->getPointeeType().getTypePtr(), false);
7375 
7376   auto *CXXRD = T->getAsCXXRecordDecl();
7377 
7378   if (!CXXRD)
7379     return false;
7380 
7381   if (isa<ClassTemplateSpecializationDecl>(CXXRD))
7382     return true;
7383 
7384   if (!CXXRD->hasDefinition() || !VisitBasesAndFields)
7385     return false;
7386 
7387   for (auto B : CXXRD->bases())
7388     if (hasTemplateSpecializationInEncodedString(B.getType().getTypePtr(),
7389                                                  true))
7390       return true;
7391 
7392   for (auto *FD : CXXRD->fields())
7393     if (hasTemplateSpecializationInEncodedString(FD->getType().getTypePtr(),
7394                                                  true))
7395       return true;
7396 
7397   return false;
7398 }
7399 
7400 // FIXME: Use SmallString for accumulating string.
7401 void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
7402                                             const ObjCEncOptions Options,
7403                                             const FieldDecl *FD,
7404                                             QualType *NotEncodedT) const {
7405   CanQualType CT = getCanonicalType(T);
7406   switch (CT->getTypeClass()) {
7407   case Type::Builtin:
7408   case Type::Enum:
7409     if (FD && FD->isBitField())
7410       return EncodeBitField(this, S, T, FD);
7411     if (const auto *BT = dyn_cast<BuiltinType>(CT))
7412       S += getObjCEncodingForPrimitiveType(this, BT);
7413     else
7414       S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
7415     return;
7416 
7417   case Type::Complex:
7418     S += 'j';
7419     getObjCEncodingForTypeImpl(T->castAs<ComplexType>()->getElementType(), S,
7420                                ObjCEncOptions(),
7421                                /*Field=*/nullptr);
7422     return;
7423 
7424   case Type::Atomic:
7425     S += 'A';
7426     getObjCEncodingForTypeImpl(T->castAs<AtomicType>()->getValueType(), S,
7427                                ObjCEncOptions(),
7428                                /*Field=*/nullptr);
7429     return;
7430 
7431   // encoding for pointer or reference types.
7432   case Type::Pointer:
7433   case Type::LValueReference:
7434   case Type::RValueReference: {
7435     QualType PointeeTy;
7436     if (isa<PointerType>(CT)) {
7437       const auto *PT = T->castAs<PointerType>();
7438       if (PT->isObjCSelType()) {
7439         S += ':';
7440         return;
7441       }
7442       PointeeTy = PT->getPointeeType();
7443     } else {
7444       PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
7445     }
7446 
7447     bool isReadOnly = false;
7448     // For historical/compatibility reasons, the read-only qualifier of the
7449     // pointee gets emitted _before_ the '^'.  The read-only qualifier of
7450     // the pointer itself gets ignored, _unless_ we are looking at a typedef!
7451     // Also, do not emit the 'r' for anything but the outermost type!
7452     if (isa<TypedefType>(T.getTypePtr())) {
7453       if (Options.IsOutermostType() && T.isConstQualified()) {
7454         isReadOnly = true;
7455         S += 'r';
7456       }
7457     } else if (Options.IsOutermostType()) {
7458       QualType P = PointeeTy;
7459       while (auto PT = P->getAs<PointerType>())
7460         P = PT->getPointeeType();
7461       if (P.isConstQualified()) {
7462         isReadOnly = true;
7463         S += 'r';
7464       }
7465     }
7466     if (isReadOnly) {
7467       // Another legacy compatibility encoding. Some ObjC qualifier and type
7468       // combinations need to be rearranged.
7469       // Rewrite "in const" from "nr" to "rn"
7470       if (StringRef(S).endswith("nr"))
7471         S.replace(S.end()-2, S.end(), "rn");
7472     }
7473 
7474     if (PointeeTy->isCharType()) {
7475       // char pointer types should be encoded as '*' unless it is a
7476       // type that has been typedef'd to 'BOOL'.
7477       if (!isTypeTypedefedAsBOOL(PointeeTy)) {
7478         S += '*';
7479         return;
7480       }
7481     } else if (const auto *RTy = PointeeTy->getAs<RecordType>()) {
7482       // GCC binary compat: Need to convert "struct objc_class *" to "#".
7483       if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
7484         S += '#';
7485         return;
7486       }
7487       // GCC binary compat: Need to convert "struct objc_object *" to "@".
7488       if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
7489         S += '@';
7490         return;
7491       }
7492       // If the encoded string for the class includes template names, just emit
7493       // "^v" for pointers to the class.
7494       if (getLangOpts().CPlusPlus &&
7495           (!getLangOpts().EncodeCXXClassTemplateSpec &&
7496            hasTemplateSpecializationInEncodedString(
7497                RTy, Options.ExpandPointedToStructures()))) {
7498         S += "^v";
7499         return;
7500       }
7501       // fall through...
7502     }
7503     S += '^';
7504     getLegacyIntegralTypeEncoding(PointeeTy);
7505 
7506     ObjCEncOptions NewOptions;
7507     if (Options.ExpandPointedToStructures())
7508       NewOptions.setExpandStructures();
7509     getObjCEncodingForTypeImpl(PointeeTy, S, NewOptions,
7510                                /*Field=*/nullptr, NotEncodedT);
7511     return;
7512   }
7513 
7514   case Type::ConstantArray:
7515   case Type::IncompleteArray:
7516   case Type::VariableArray: {
7517     const auto *AT = cast<ArrayType>(CT);
7518 
7519     if (isa<IncompleteArrayType>(AT) && !Options.IsStructField()) {
7520       // Incomplete arrays are encoded as a pointer to the array element.
7521       S += '^';
7522 
7523       getObjCEncodingForTypeImpl(
7524           AT->getElementType(), S,
7525           Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD);
7526     } else {
7527       S += '[';
7528 
7529       if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
7530         S += llvm::utostr(CAT->getSize().getZExtValue());
7531       else {
7532         //Variable length arrays are encoded as a regular array with 0 elements.
7533         assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
7534                "Unknown array type!");
7535         S += '0';
7536       }
7537 
7538       getObjCEncodingForTypeImpl(
7539           AT->getElementType(), S,
7540           Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD,
7541           NotEncodedT);
7542       S += ']';
7543     }
7544     return;
7545   }
7546 
7547   case Type::FunctionNoProto:
7548   case Type::FunctionProto:
7549     S += '?';
7550     return;
7551 
7552   case Type::Record: {
7553     RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
7554     S += RDecl->isUnion() ? '(' : '{';
7555     // Anonymous structures print as '?'
7556     if (const IdentifierInfo *II = RDecl->getIdentifier()) {
7557       S += II->getName();
7558       if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
7559         const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
7560         llvm::raw_string_ostream OS(S);
7561         printTemplateArgumentList(OS, TemplateArgs.asArray(),
7562                                   getPrintingPolicy());
7563       }
7564     } else {
7565       S += '?';
7566     }
7567     if (Options.ExpandStructures()) {
7568       S += '=';
7569       if (!RDecl->isUnion()) {
7570         getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
7571       } else {
7572         for (const auto *Field : RDecl->fields()) {
7573           if (FD) {
7574             S += '"';
7575             S += Field->getNameAsString();
7576             S += '"';
7577           }
7578 
7579           // Special case bit-fields.
7580           if (Field->isBitField()) {
7581             getObjCEncodingForTypeImpl(Field->getType(), S,
7582                                        ObjCEncOptions().setExpandStructures(),
7583                                        Field);
7584           } else {
7585             QualType qt = Field->getType();
7586             getLegacyIntegralTypeEncoding(qt);
7587             getObjCEncodingForTypeImpl(
7588                 qt, S,
7589                 ObjCEncOptions().setExpandStructures().setIsStructField(), FD,
7590                 NotEncodedT);
7591           }
7592         }
7593       }
7594     }
7595     S += RDecl->isUnion() ? ')' : '}';
7596     return;
7597   }
7598 
7599   case Type::BlockPointer: {
7600     const auto *BT = T->castAs<BlockPointerType>();
7601     S += "@?"; // Unlike a pointer-to-function, which is "^?".
7602     if (Options.EncodeBlockParameters()) {
7603       const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
7604 
7605       S += '<';
7606       // Block return type
7607       getObjCEncodingForTypeImpl(FT->getReturnType(), S,
7608                                  Options.forComponentType(), FD, NotEncodedT);
7609       // Block self
7610       S += "@?";
7611       // Block parameters
7612       if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) {
7613         for (const auto &I : FPT->param_types())
7614           getObjCEncodingForTypeImpl(I, S, Options.forComponentType(), FD,
7615                                      NotEncodedT);
7616       }
7617       S += '>';
7618     }
7619     return;
7620   }
7621 
7622   case Type::ObjCObject: {
7623     // hack to match legacy encoding of *id and *Class
7624     QualType Ty = getObjCObjectPointerType(CT);
7625     if (Ty->isObjCIdType()) {
7626       S += "{objc_object=}";
7627       return;
7628     }
7629     else if (Ty->isObjCClassType()) {
7630       S += "{objc_class=}";
7631       return;
7632     }
7633     // TODO: Double check to make sure this intentionally falls through.
7634     LLVM_FALLTHROUGH;
7635   }
7636 
7637   case Type::ObjCInterface: {
7638     // Ignore protocol qualifiers when mangling at this level.
7639     // @encode(class_name)
7640     ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
7641     S += '{';
7642     S += OI->getObjCRuntimeNameAsString();
7643     if (Options.ExpandStructures()) {
7644       S += '=';
7645       SmallVector<const ObjCIvarDecl*, 32> Ivars;
7646       DeepCollectObjCIvars(OI, true, Ivars);
7647       for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
7648         const FieldDecl *Field = Ivars[i];
7649         if (Field->isBitField())
7650           getObjCEncodingForTypeImpl(Field->getType(), S,
7651                                      ObjCEncOptions().setExpandStructures(),
7652                                      Field);
7653         else
7654           getObjCEncodingForTypeImpl(Field->getType(), S,
7655                                      ObjCEncOptions().setExpandStructures(), FD,
7656                                      NotEncodedT);
7657       }
7658     }
7659     S += '}';
7660     return;
7661   }
7662 
7663   case Type::ObjCObjectPointer: {
7664     const auto *OPT = T->castAs<ObjCObjectPointerType>();
7665     if (OPT->isObjCIdType()) {
7666       S += '@';
7667       return;
7668     }
7669 
7670     if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
7671       // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
7672       // Since this is a binary compatibility issue, need to consult with
7673       // runtime folks. Fortunately, this is a *very* obscure construct.
7674       S += '#';
7675       return;
7676     }
7677 
7678     if (OPT->isObjCQualifiedIdType()) {
7679       getObjCEncodingForTypeImpl(
7680           getObjCIdType(), S,
7681           Options.keepingOnly(ObjCEncOptions()
7682                                   .setExpandPointedToStructures()
7683                                   .setExpandStructures()),
7684           FD);
7685       if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) {
7686         // Note that we do extended encoding of protocol qualifer list
7687         // Only when doing ivar or property encoding.
7688         S += '"';
7689         for (const auto *I : OPT->quals()) {
7690           S += '<';
7691           S += I->getObjCRuntimeNameAsString();
7692           S += '>';
7693         }
7694         S += '"';
7695       }
7696       return;
7697     }
7698 
7699     S += '@';
7700     if (OPT->getInterfaceDecl() &&
7701         (FD || Options.EncodingProperty() || Options.EncodeClassNames())) {
7702       S += '"';
7703       S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
7704       for (const auto *I : OPT->quals()) {
7705         S += '<';
7706         S += I->getObjCRuntimeNameAsString();
7707         S += '>';
7708       }
7709       S += '"';
7710     }
7711     return;
7712   }
7713 
7714   // gcc just blithely ignores member pointers.
7715   // FIXME: we should do better than that.  'M' is available.
7716   case Type::MemberPointer:
7717   // This matches gcc's encoding, even though technically it is insufficient.
7718   //FIXME. We should do a better job than gcc.
7719   case Type::Vector:
7720   case Type::ExtVector:
7721   // Until we have a coherent encoding of these three types, issue warning.
7722     if (NotEncodedT)
7723       *NotEncodedT = T;
7724     return;
7725 
7726   case Type::ConstantMatrix:
7727     if (NotEncodedT)
7728       *NotEncodedT = T;
7729     return;
7730 
7731   // We could see an undeduced auto type here during error recovery.
7732   // Just ignore it.
7733   case Type::Auto:
7734   case Type::DeducedTemplateSpecialization:
7735     return;
7736 
7737   case Type::Pipe:
7738   case Type::ExtInt:
7739 #define ABSTRACT_TYPE(KIND, BASE)
7740 #define TYPE(KIND, BASE)
7741 #define DEPENDENT_TYPE(KIND, BASE) \
7742   case Type::KIND:
7743 #define NON_CANONICAL_TYPE(KIND, BASE) \
7744   case Type::KIND:
7745 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
7746   case Type::KIND:
7747 #include "clang/AST/TypeNodes.inc"
7748     llvm_unreachable("@encode for dependent type!");
7749   }
7750   llvm_unreachable("bad type kind!");
7751 }
7752 
7753 void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
7754                                                  std::string &S,
7755                                                  const FieldDecl *FD,
7756                                                  bool includeVBases,
7757                                                  QualType *NotEncodedT) const {
7758   assert(RDecl && "Expected non-null RecordDecl");
7759   assert(!RDecl->isUnion() && "Should not be called for unions");
7760   if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
7761     return;
7762 
7763   const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
7764   std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
7765   const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
7766 
7767   if (CXXRec) {
7768     for (const auto &BI : CXXRec->bases()) {
7769       if (!BI.isVirtual()) {
7770         CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
7771         if (base->isEmpty())
7772           continue;
7773         uint64_t offs = toBits(layout.getBaseClassOffset(base));
7774         FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
7775                                   std::make_pair(offs, base));
7776       }
7777     }
7778   }
7779 
7780   unsigned i = 0;
7781   for (FieldDecl *Field : RDecl->fields()) {
7782     if (!Field->isZeroLengthBitField(*this) && Field->isZeroSize(*this))
7783       continue;
7784     uint64_t offs = layout.getFieldOffset(i);
7785     FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
7786                               std::make_pair(offs, Field));
7787     ++i;
7788   }
7789 
7790   if (CXXRec && includeVBases) {
7791     for (const auto &BI : CXXRec->vbases()) {
7792       CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
7793       if (base->isEmpty())
7794         continue;
7795       uint64_t offs = toBits(layout.getVBaseClassOffset(base));
7796       if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
7797           FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
7798         FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
7799                                   std::make_pair(offs, base));
7800     }
7801   }
7802 
7803   CharUnits size;
7804   if (CXXRec) {
7805     size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
7806   } else {
7807     size = layout.getSize();
7808   }
7809 
7810 #ifndef NDEBUG
7811   uint64_t CurOffs = 0;
7812 #endif
7813   std::multimap<uint64_t, NamedDecl *>::iterator
7814     CurLayObj = FieldOrBaseOffsets.begin();
7815 
7816   if (CXXRec && CXXRec->isDynamicClass() &&
7817       (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
7818     if (FD) {
7819       S += "\"_vptr$";
7820       std::string recname = CXXRec->getNameAsString();
7821       if (recname.empty()) recname = "?";
7822       S += recname;
7823       S += '"';
7824     }
7825     S += "^^?";
7826 #ifndef NDEBUG
7827     CurOffs += getTypeSize(VoidPtrTy);
7828 #endif
7829   }
7830 
7831   if (!RDecl->hasFlexibleArrayMember()) {
7832     // Mark the end of the structure.
7833     uint64_t offs = toBits(size);
7834     FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
7835                               std::make_pair(offs, nullptr));
7836   }
7837 
7838   for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
7839 #ifndef NDEBUG
7840     assert(CurOffs <= CurLayObj->first);
7841     if (CurOffs < CurLayObj->first) {
7842       uint64_t padding = CurLayObj->first - CurOffs;
7843       // FIXME: There doesn't seem to be a way to indicate in the encoding that
7844       // packing/alignment of members is different that normal, in which case
7845       // the encoding will be out-of-sync with the real layout.
7846       // If the runtime switches to just consider the size of types without
7847       // taking into account alignment, we could make padding explicit in the
7848       // encoding (e.g. using arrays of chars). The encoding strings would be
7849       // longer then though.
7850       CurOffs += padding;
7851     }
7852 #endif
7853 
7854     NamedDecl *dcl = CurLayObj->second;
7855     if (!dcl)
7856       break; // reached end of structure.
7857 
7858     if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) {
7859       // We expand the bases without their virtual bases since those are going
7860       // in the initial structure. Note that this differs from gcc which
7861       // expands virtual bases each time one is encountered in the hierarchy,
7862       // making the encoding type bigger than it really is.
7863       getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
7864                                       NotEncodedT);
7865       assert(!base->isEmpty());
7866 #ifndef NDEBUG
7867       CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
7868 #endif
7869     } else {
7870       const auto *field = cast<FieldDecl>(dcl);
7871       if (FD) {
7872         S += '"';
7873         S += field->getNameAsString();
7874         S += '"';
7875       }
7876 
7877       if (field->isBitField()) {
7878         EncodeBitField(this, S, field->getType(), field);
7879 #ifndef NDEBUG
7880         CurOffs += field->getBitWidthValue(*this);
7881 #endif
7882       } else {
7883         QualType qt = field->getType();
7884         getLegacyIntegralTypeEncoding(qt);
7885         getObjCEncodingForTypeImpl(
7886             qt, S, ObjCEncOptions().setExpandStructures().setIsStructField(),
7887             FD, NotEncodedT);
7888 #ifndef NDEBUG
7889         CurOffs += getTypeSize(field->getType());
7890 #endif
7891       }
7892     }
7893   }
7894 }
7895 
7896 void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
7897                                                  std::string& S) const {
7898   if (QT & Decl::OBJC_TQ_In)
7899     S += 'n';
7900   if (QT & Decl::OBJC_TQ_Inout)
7901     S += 'N';
7902   if (QT & Decl::OBJC_TQ_Out)
7903     S += 'o';
7904   if (QT & Decl::OBJC_TQ_Bycopy)
7905     S += 'O';
7906   if (QT & Decl::OBJC_TQ_Byref)
7907     S += 'R';
7908   if (QT & Decl::OBJC_TQ_Oneway)
7909     S += 'V';
7910 }
7911 
7912 TypedefDecl *ASTContext::getObjCIdDecl() const {
7913   if (!ObjCIdDecl) {
7914     QualType T = getObjCObjectType(ObjCBuiltinIdTy, {}, {});
7915     T = getObjCObjectPointerType(T);
7916     ObjCIdDecl = buildImplicitTypedef(T, "id");
7917   }
7918   return ObjCIdDecl;
7919 }
7920 
7921 TypedefDecl *ASTContext::getObjCSelDecl() const {
7922   if (!ObjCSelDecl) {
7923     QualType T = getPointerType(ObjCBuiltinSelTy);
7924     ObjCSelDecl = buildImplicitTypedef(T, "SEL");
7925   }
7926   return ObjCSelDecl;
7927 }
7928 
7929 TypedefDecl *ASTContext::getObjCClassDecl() const {
7930   if (!ObjCClassDecl) {
7931     QualType T = getObjCObjectType(ObjCBuiltinClassTy, {}, {});
7932     T = getObjCObjectPointerType(T);
7933     ObjCClassDecl = buildImplicitTypedef(T, "Class");
7934   }
7935   return ObjCClassDecl;
7936 }
7937 
7938 ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
7939   if (!ObjCProtocolClassDecl) {
7940     ObjCProtocolClassDecl
7941       = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
7942                                   SourceLocation(),
7943                                   &Idents.get("Protocol"),
7944                                   /*typeParamList=*/nullptr,
7945                                   /*PrevDecl=*/nullptr,
7946                                   SourceLocation(), true);
7947   }
7948 
7949   return ObjCProtocolClassDecl;
7950 }
7951 
7952 //===----------------------------------------------------------------------===//
7953 // __builtin_va_list Construction Functions
7954 //===----------------------------------------------------------------------===//
7955 
7956 static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
7957                                                  StringRef Name) {
7958   // typedef char* __builtin[_ms]_va_list;
7959   QualType T = Context->getPointerType(Context->CharTy);
7960   return Context->buildImplicitTypedef(T, Name);
7961 }
7962 
7963 static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
7964   return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
7965 }
7966 
7967 static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
7968   return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
7969 }
7970 
7971 static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
7972   // typedef void* __builtin_va_list;
7973   QualType T = Context->getPointerType(Context->VoidTy);
7974   return Context->buildImplicitTypedef(T, "__builtin_va_list");
7975 }
7976 
7977 static TypedefDecl *
7978 CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
7979   // struct __va_list
7980   RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
7981   if (Context->getLangOpts().CPlusPlus) {
7982     // namespace std { struct __va_list {
7983     NamespaceDecl *NS;
7984     NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
7985                                Context->getTranslationUnitDecl(),
7986                                /*Inline*/ false, SourceLocation(),
7987                                SourceLocation(), &Context->Idents.get("std"),
7988                                /*PrevDecl*/ nullptr);
7989     NS->setImplicit();
7990     VaListTagDecl->setDeclContext(NS);
7991   }
7992 
7993   VaListTagDecl->startDefinition();
7994 
7995   const size_t NumFields = 5;
7996   QualType FieldTypes[NumFields];
7997   const char *FieldNames[NumFields];
7998 
7999   // void *__stack;
8000   FieldTypes[0] = Context->getPointerType(Context->VoidTy);
8001   FieldNames[0] = "__stack";
8002 
8003   // void *__gr_top;
8004   FieldTypes[1] = Context->getPointerType(Context->VoidTy);
8005   FieldNames[1] = "__gr_top";
8006 
8007   // void *__vr_top;
8008   FieldTypes[2] = Context->getPointerType(Context->VoidTy);
8009   FieldNames[2] = "__vr_top";
8010 
8011   // int __gr_offs;
8012   FieldTypes[3] = Context->IntTy;
8013   FieldNames[3] = "__gr_offs";
8014 
8015   // int __vr_offs;
8016   FieldTypes[4] = Context->IntTy;
8017   FieldNames[4] = "__vr_offs";
8018 
8019   // Create fields
8020   for (unsigned i = 0; i < NumFields; ++i) {
8021     FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
8022                                          VaListTagDecl,
8023                                          SourceLocation(),
8024                                          SourceLocation(),
8025                                          &Context->Idents.get(FieldNames[i]),
8026                                          FieldTypes[i], /*TInfo=*/nullptr,
8027                                          /*BitWidth=*/nullptr,
8028                                          /*Mutable=*/false,
8029                                          ICIS_NoInit);
8030     Field->setAccess(AS_public);
8031     VaListTagDecl->addDecl(Field);
8032   }
8033   VaListTagDecl->completeDefinition();
8034   Context->VaListTagDecl = VaListTagDecl;
8035   QualType VaListTagType = Context->getRecordType(VaListTagDecl);
8036 
8037   // } __builtin_va_list;
8038   return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
8039 }
8040 
8041 static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
8042   // typedef struct __va_list_tag {
8043   RecordDecl *VaListTagDecl;
8044 
8045   VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
8046   VaListTagDecl->startDefinition();
8047 
8048   const size_t NumFields = 5;
8049   QualType FieldTypes[NumFields];
8050   const char *FieldNames[NumFields];
8051 
8052   //   unsigned char gpr;
8053   FieldTypes[0] = Context->UnsignedCharTy;
8054   FieldNames[0] = "gpr";
8055 
8056   //   unsigned char fpr;
8057   FieldTypes[1] = Context->UnsignedCharTy;
8058   FieldNames[1] = "fpr";
8059 
8060   //   unsigned short reserved;
8061   FieldTypes[2] = Context->UnsignedShortTy;
8062   FieldNames[2] = "reserved";
8063 
8064   //   void* overflow_arg_area;
8065   FieldTypes[3] = Context->getPointerType(Context->VoidTy);
8066   FieldNames[3] = "overflow_arg_area";
8067 
8068   //   void* reg_save_area;
8069   FieldTypes[4] = Context->getPointerType(Context->VoidTy);
8070   FieldNames[4] = "reg_save_area";
8071 
8072   // Create fields
8073   for (unsigned i = 0; i < NumFields; ++i) {
8074     FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
8075                                          SourceLocation(),
8076                                          SourceLocation(),
8077                                          &Context->Idents.get(FieldNames[i]),
8078                                          FieldTypes[i], /*TInfo=*/nullptr,
8079                                          /*BitWidth=*/nullptr,
8080                                          /*Mutable=*/false,
8081                                          ICIS_NoInit);
8082     Field->setAccess(AS_public);
8083     VaListTagDecl->addDecl(Field);
8084   }
8085   VaListTagDecl->completeDefinition();
8086   Context->VaListTagDecl = VaListTagDecl;
8087   QualType VaListTagType = Context->getRecordType(VaListTagDecl);
8088 
8089   // } __va_list_tag;
8090   TypedefDecl *VaListTagTypedefDecl =
8091       Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
8092 
8093   QualType VaListTagTypedefType =
8094     Context->getTypedefType(VaListTagTypedefDecl);
8095 
8096   // typedef __va_list_tag __builtin_va_list[1];
8097   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
8098   QualType VaListTagArrayType
8099     = Context->getConstantArrayType(VaListTagTypedefType,
8100                                     Size, nullptr, ArrayType::Normal, 0);
8101   return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
8102 }
8103 
8104 static TypedefDecl *
8105 CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
8106   // struct __va_list_tag {
8107   RecordDecl *VaListTagDecl;
8108   VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
8109   VaListTagDecl->startDefinition();
8110 
8111   const size_t NumFields = 4;
8112   QualType FieldTypes[NumFields];
8113   const char *FieldNames[NumFields];
8114 
8115   //   unsigned gp_offset;
8116   FieldTypes[0] = Context->UnsignedIntTy;
8117   FieldNames[0] = "gp_offset";
8118 
8119   //   unsigned fp_offset;
8120   FieldTypes[1] = Context->UnsignedIntTy;
8121   FieldNames[1] = "fp_offset";
8122 
8123   //   void* overflow_arg_area;
8124   FieldTypes[2] = Context->getPointerType(Context->VoidTy);
8125   FieldNames[2] = "overflow_arg_area";
8126 
8127   //   void* reg_save_area;
8128   FieldTypes[3] = Context->getPointerType(Context->VoidTy);
8129   FieldNames[3] = "reg_save_area";
8130 
8131   // Create fields
8132   for (unsigned i = 0; i < NumFields; ++i) {
8133     FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
8134                                          VaListTagDecl,
8135                                          SourceLocation(),
8136                                          SourceLocation(),
8137                                          &Context->Idents.get(FieldNames[i]),
8138                                          FieldTypes[i], /*TInfo=*/nullptr,
8139                                          /*BitWidth=*/nullptr,
8140                                          /*Mutable=*/false,
8141                                          ICIS_NoInit);
8142     Field->setAccess(AS_public);
8143     VaListTagDecl->addDecl(Field);
8144   }
8145   VaListTagDecl->completeDefinition();
8146   Context->VaListTagDecl = VaListTagDecl;
8147   QualType VaListTagType = Context->getRecordType(VaListTagDecl);
8148 
8149   // };
8150 
8151   // typedef struct __va_list_tag __builtin_va_list[1];
8152   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
8153   QualType VaListTagArrayType = Context->getConstantArrayType(
8154       VaListTagType, Size, nullptr, ArrayType::Normal, 0);
8155   return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
8156 }
8157 
8158 static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
8159   // typedef int __builtin_va_list[4];
8160   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
8161   QualType IntArrayType = Context->getConstantArrayType(
8162       Context->IntTy, Size, nullptr, ArrayType::Normal, 0);
8163   return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
8164 }
8165 
8166 static TypedefDecl *
8167 CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
8168   // struct __va_list
8169   RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
8170   if (Context->getLangOpts().CPlusPlus) {
8171     // namespace std { struct __va_list {
8172     NamespaceDecl *NS;
8173     NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
8174                                Context->getTranslationUnitDecl(),
8175                                /*Inline*/false, SourceLocation(),
8176                                SourceLocation(), &Context->Idents.get("std"),
8177                                /*PrevDecl*/ nullptr);
8178     NS->setImplicit();
8179     VaListDecl->setDeclContext(NS);
8180   }
8181 
8182   VaListDecl->startDefinition();
8183 
8184   // void * __ap;
8185   FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
8186                                        VaListDecl,
8187                                        SourceLocation(),
8188                                        SourceLocation(),
8189                                        &Context->Idents.get("__ap"),
8190                                        Context->getPointerType(Context->VoidTy),
8191                                        /*TInfo=*/nullptr,
8192                                        /*BitWidth=*/nullptr,
8193                                        /*Mutable=*/false,
8194                                        ICIS_NoInit);
8195   Field->setAccess(AS_public);
8196   VaListDecl->addDecl(Field);
8197 
8198   // };
8199   VaListDecl->completeDefinition();
8200   Context->VaListTagDecl = VaListDecl;
8201 
8202   // typedef struct __va_list __builtin_va_list;
8203   QualType T = Context->getRecordType(VaListDecl);
8204   return Context->buildImplicitTypedef(T, "__builtin_va_list");
8205 }
8206 
8207 static TypedefDecl *
8208 CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
8209   // struct __va_list_tag {
8210   RecordDecl *VaListTagDecl;
8211   VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
8212   VaListTagDecl->startDefinition();
8213 
8214   const size_t NumFields = 4;
8215   QualType FieldTypes[NumFields];
8216   const char *FieldNames[NumFields];
8217 
8218   //   long __gpr;
8219   FieldTypes[0] = Context->LongTy;
8220   FieldNames[0] = "__gpr";
8221 
8222   //   long __fpr;
8223   FieldTypes[1] = Context->LongTy;
8224   FieldNames[1] = "__fpr";
8225 
8226   //   void *__overflow_arg_area;
8227   FieldTypes[2] = Context->getPointerType(Context->VoidTy);
8228   FieldNames[2] = "__overflow_arg_area";
8229 
8230   //   void *__reg_save_area;
8231   FieldTypes[3] = Context->getPointerType(Context->VoidTy);
8232   FieldNames[3] = "__reg_save_area";
8233 
8234   // Create fields
8235   for (unsigned i = 0; i < NumFields; ++i) {
8236     FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
8237                                          VaListTagDecl,
8238                                          SourceLocation(),
8239                                          SourceLocation(),
8240                                          &Context->Idents.get(FieldNames[i]),
8241                                          FieldTypes[i], /*TInfo=*/nullptr,
8242                                          /*BitWidth=*/nullptr,
8243                                          /*Mutable=*/false,
8244                                          ICIS_NoInit);
8245     Field->setAccess(AS_public);
8246     VaListTagDecl->addDecl(Field);
8247   }
8248   VaListTagDecl->completeDefinition();
8249   Context->VaListTagDecl = VaListTagDecl;
8250   QualType VaListTagType = Context->getRecordType(VaListTagDecl);
8251 
8252   // };
8253 
8254   // typedef __va_list_tag __builtin_va_list[1];
8255   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
8256   QualType VaListTagArrayType = Context->getConstantArrayType(
8257       VaListTagType, Size, nullptr, ArrayType::Normal, 0);
8258 
8259   return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
8260 }
8261 
8262 static TypedefDecl *CreateHexagonBuiltinVaListDecl(const ASTContext *Context) {
8263   // typedef struct __va_list_tag {
8264   RecordDecl *VaListTagDecl;
8265   VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
8266   VaListTagDecl->startDefinition();
8267 
8268   const size_t NumFields = 3;
8269   QualType FieldTypes[NumFields];
8270   const char *FieldNames[NumFields];
8271 
8272   //   void *CurrentSavedRegisterArea;
8273   FieldTypes[0] = Context->getPointerType(Context->VoidTy);
8274   FieldNames[0] = "__current_saved_reg_area_pointer";
8275 
8276   //   void *SavedRegAreaEnd;
8277   FieldTypes[1] = Context->getPointerType(Context->VoidTy);
8278   FieldNames[1] = "__saved_reg_area_end_pointer";
8279 
8280   //   void *OverflowArea;
8281   FieldTypes[2] = Context->getPointerType(Context->VoidTy);
8282   FieldNames[2] = "__overflow_area_pointer";
8283 
8284   // Create fields
8285   for (unsigned i = 0; i < NumFields; ++i) {
8286     FieldDecl *Field = FieldDecl::Create(
8287         const_cast<ASTContext &>(*Context), VaListTagDecl, SourceLocation(),
8288         SourceLocation(), &Context->Idents.get(FieldNames[i]), FieldTypes[i],
8289         /*TInfo=*/0,
8290         /*BitWidth=*/0,
8291         /*Mutable=*/false, ICIS_NoInit);
8292     Field->setAccess(AS_public);
8293     VaListTagDecl->addDecl(Field);
8294   }
8295   VaListTagDecl->completeDefinition();
8296   Context->VaListTagDecl = VaListTagDecl;
8297   QualType VaListTagType = Context->getRecordType(VaListTagDecl);
8298 
8299   // } __va_list_tag;
8300   TypedefDecl *VaListTagTypedefDecl =
8301       Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
8302 
8303   QualType VaListTagTypedefType = Context->getTypedefType(VaListTagTypedefDecl);
8304 
8305   // typedef __va_list_tag __builtin_va_list[1];
8306   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
8307   QualType VaListTagArrayType = Context->getConstantArrayType(
8308       VaListTagTypedefType, Size, nullptr, ArrayType::Normal, 0);
8309 
8310   return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
8311 }
8312 
8313 static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
8314                                      TargetInfo::BuiltinVaListKind Kind) {
8315   switch (Kind) {
8316   case TargetInfo::CharPtrBuiltinVaList:
8317     return CreateCharPtrBuiltinVaListDecl(Context);
8318   case TargetInfo::VoidPtrBuiltinVaList:
8319     return CreateVoidPtrBuiltinVaListDecl(Context);
8320   case TargetInfo::AArch64ABIBuiltinVaList:
8321     return CreateAArch64ABIBuiltinVaListDecl(Context);
8322   case TargetInfo::PowerABIBuiltinVaList:
8323     return CreatePowerABIBuiltinVaListDecl(Context);
8324   case TargetInfo::X86_64ABIBuiltinVaList:
8325     return CreateX86_64ABIBuiltinVaListDecl(Context);
8326   case TargetInfo::PNaClABIBuiltinVaList:
8327     return CreatePNaClABIBuiltinVaListDecl(Context);
8328   case TargetInfo::AAPCSABIBuiltinVaList:
8329     return CreateAAPCSABIBuiltinVaListDecl(Context);
8330   case TargetInfo::SystemZBuiltinVaList:
8331     return CreateSystemZBuiltinVaListDecl(Context);
8332   case TargetInfo::HexagonBuiltinVaList:
8333     return CreateHexagonBuiltinVaListDecl(Context);
8334   }
8335 
8336   llvm_unreachable("Unhandled __builtin_va_list type kind");
8337 }
8338 
8339 TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
8340   if (!BuiltinVaListDecl) {
8341     BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
8342     assert(BuiltinVaListDecl->isImplicit());
8343   }
8344 
8345   return BuiltinVaListDecl;
8346 }
8347 
8348 Decl *ASTContext::getVaListTagDecl() const {
8349   // Force the creation of VaListTagDecl by building the __builtin_va_list
8350   // declaration.
8351   if (!VaListTagDecl)
8352     (void)getBuiltinVaListDecl();
8353 
8354   return VaListTagDecl;
8355 }
8356 
8357 TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
8358   if (!BuiltinMSVaListDecl)
8359     BuiltinMSVaListDecl = CreateMSVaListDecl(this);
8360 
8361   return BuiltinMSVaListDecl;
8362 }
8363 
8364 bool ASTContext::canBuiltinBeRedeclared(const FunctionDecl *FD) const {
8365   return BuiltinInfo.canBeRedeclared(FD->getBuiltinID());
8366 }
8367 
8368 void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
8369   assert(ObjCConstantStringType.isNull() &&
8370          "'NSConstantString' type already set!");
8371 
8372   ObjCConstantStringType = getObjCInterfaceType(Decl);
8373 }
8374 
8375 /// Retrieve the template name that corresponds to a non-empty
8376 /// lookup.
8377 TemplateName
8378 ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
8379                                       UnresolvedSetIterator End) const {
8380   unsigned size = End - Begin;
8381   assert(size > 1 && "set is not overloaded!");
8382 
8383   void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
8384                           size * sizeof(FunctionTemplateDecl*));
8385   auto *OT = new (memory) OverloadedTemplateStorage(size);
8386 
8387   NamedDecl **Storage = OT->getStorage();
8388   for (UnresolvedSetIterator I = Begin; I != End; ++I) {
8389     NamedDecl *D = *I;
8390     assert(isa<FunctionTemplateDecl>(D) ||
8391            isa<UnresolvedUsingValueDecl>(D) ||
8392            (isa<UsingShadowDecl>(D) &&
8393             isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
8394     *Storage++ = D;
8395   }
8396 
8397   return TemplateName(OT);
8398 }
8399 
8400 /// Retrieve a template name representing an unqualified-id that has been
8401 /// assumed to name a template for ADL purposes.
8402 TemplateName ASTContext::getAssumedTemplateName(DeclarationName Name) const {
8403   auto *OT = new (*this) AssumedTemplateStorage(Name);
8404   return TemplateName(OT);
8405 }
8406 
8407 /// Retrieve the template name that represents a qualified
8408 /// template name such as \c std::vector.
8409 TemplateName
8410 ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
8411                                      bool TemplateKeyword,
8412                                      TemplateDecl *Template) const {
8413   assert(NNS && "Missing nested-name-specifier in qualified template name");
8414 
8415   // FIXME: Canonicalization?
8416   llvm::FoldingSetNodeID ID;
8417   QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
8418 
8419   void *InsertPos = nullptr;
8420   QualifiedTemplateName *QTN =
8421     QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
8422   if (!QTN) {
8423     QTN = new (*this, alignof(QualifiedTemplateName))
8424         QualifiedTemplateName(NNS, TemplateKeyword, Template);
8425     QualifiedTemplateNames.InsertNode(QTN, InsertPos);
8426   }
8427 
8428   return TemplateName(QTN);
8429 }
8430 
8431 /// Retrieve the template name that represents a dependent
8432 /// template name such as \c MetaFun::template apply.
8433 TemplateName
8434 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
8435                                      const IdentifierInfo *Name) const {
8436   assert((!NNS || NNS->isDependent()) &&
8437          "Nested name specifier must be dependent");
8438 
8439   llvm::FoldingSetNodeID ID;
8440   DependentTemplateName::Profile(ID, NNS, Name);
8441 
8442   void *InsertPos = nullptr;
8443   DependentTemplateName *QTN =
8444     DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
8445 
8446   if (QTN)
8447     return TemplateName(QTN);
8448 
8449   NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
8450   if (CanonNNS == NNS) {
8451     QTN = new (*this, alignof(DependentTemplateName))
8452         DependentTemplateName(NNS, Name);
8453   } else {
8454     TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
8455     QTN = new (*this, alignof(DependentTemplateName))
8456         DependentTemplateName(NNS, Name, Canon);
8457     DependentTemplateName *CheckQTN =
8458       DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
8459     assert(!CheckQTN && "Dependent type name canonicalization broken");
8460     (void)CheckQTN;
8461   }
8462 
8463   DependentTemplateNames.InsertNode(QTN, InsertPos);
8464   return TemplateName(QTN);
8465 }
8466 
8467 /// Retrieve the template name that represents a dependent
8468 /// template name such as \c MetaFun::template operator+.
8469 TemplateName
8470 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
8471                                      OverloadedOperatorKind Operator) const {
8472   assert((!NNS || NNS->isDependent()) &&
8473          "Nested name specifier must be dependent");
8474 
8475   llvm::FoldingSetNodeID ID;
8476   DependentTemplateName::Profile(ID, NNS, Operator);
8477 
8478   void *InsertPos = nullptr;
8479   DependentTemplateName *QTN
8480     = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
8481 
8482   if (QTN)
8483     return TemplateName(QTN);
8484 
8485   NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
8486   if (CanonNNS == NNS) {
8487     QTN = new (*this, alignof(DependentTemplateName))
8488         DependentTemplateName(NNS, Operator);
8489   } else {
8490     TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
8491     QTN = new (*this, alignof(DependentTemplateName))
8492         DependentTemplateName(NNS, Operator, Canon);
8493 
8494     DependentTemplateName *CheckQTN
8495       = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
8496     assert(!CheckQTN && "Dependent template name canonicalization broken");
8497     (void)CheckQTN;
8498   }
8499 
8500   DependentTemplateNames.InsertNode(QTN, InsertPos);
8501   return TemplateName(QTN);
8502 }
8503 
8504 TemplateName
8505 ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
8506                                          TemplateName replacement) const {
8507   llvm::FoldingSetNodeID ID;
8508   SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
8509 
8510   void *insertPos = nullptr;
8511   SubstTemplateTemplateParmStorage *subst
8512     = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
8513 
8514   if (!subst) {
8515     subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
8516     SubstTemplateTemplateParms.InsertNode(subst, insertPos);
8517   }
8518 
8519   return TemplateName(subst);
8520 }
8521 
8522 TemplateName
8523 ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
8524                                        const TemplateArgument &ArgPack) const {
8525   auto &Self = const_cast<ASTContext &>(*this);
8526   llvm::FoldingSetNodeID ID;
8527   SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
8528 
8529   void *InsertPos = nullptr;
8530   SubstTemplateTemplateParmPackStorage *Subst
8531     = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
8532 
8533   if (!Subst) {
8534     Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
8535                                                            ArgPack.pack_size(),
8536                                                          ArgPack.pack_begin());
8537     SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
8538   }
8539 
8540   return TemplateName(Subst);
8541 }
8542 
8543 /// getFromTargetType - Given one of the integer types provided by
8544 /// TargetInfo, produce the corresponding type. The unsigned @p Type
8545 /// is actually a value of type @c TargetInfo::IntType.
8546 CanQualType ASTContext::getFromTargetType(unsigned Type) const {
8547   switch (Type) {
8548   case TargetInfo::NoInt: return {};
8549   case TargetInfo::SignedChar: return SignedCharTy;
8550   case TargetInfo::UnsignedChar: return UnsignedCharTy;
8551   case TargetInfo::SignedShort: return ShortTy;
8552   case TargetInfo::UnsignedShort: return UnsignedShortTy;
8553   case TargetInfo::SignedInt: return IntTy;
8554   case TargetInfo::UnsignedInt: return UnsignedIntTy;
8555   case TargetInfo::SignedLong: return LongTy;
8556   case TargetInfo::UnsignedLong: return UnsignedLongTy;
8557   case TargetInfo::SignedLongLong: return LongLongTy;
8558   case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
8559   }
8560 
8561   llvm_unreachable("Unhandled TargetInfo::IntType value");
8562 }
8563 
8564 //===----------------------------------------------------------------------===//
8565 //                        Type Predicates.
8566 //===----------------------------------------------------------------------===//
8567 
8568 /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
8569 /// garbage collection attribute.
8570 ///
8571 Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
8572   if (getLangOpts().getGC() == LangOptions::NonGC)
8573     return Qualifiers::GCNone;
8574 
8575   assert(getLangOpts().ObjC);
8576   Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
8577 
8578   // Default behaviour under objective-C's gc is for ObjC pointers
8579   // (or pointers to them) be treated as though they were declared
8580   // as __strong.
8581   if (GCAttrs == Qualifiers::GCNone) {
8582     if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
8583       return Qualifiers::Strong;
8584     else if (Ty->isPointerType())
8585       return getObjCGCAttrKind(Ty->castAs<PointerType>()->getPointeeType());
8586   } else {
8587     // It's not valid to set GC attributes on anything that isn't a
8588     // pointer.
8589 #ifndef NDEBUG
8590     QualType CT = Ty->getCanonicalTypeInternal();
8591     while (const auto *AT = dyn_cast<ArrayType>(CT))
8592       CT = AT->getElementType();
8593     assert(CT->isAnyPointerType() || CT->isBlockPointerType());
8594 #endif
8595   }
8596   return GCAttrs;
8597 }
8598 
8599 //===----------------------------------------------------------------------===//
8600 //                        Type Compatibility Testing
8601 //===----------------------------------------------------------------------===//
8602 
8603 /// areCompatVectorTypes - Return true if the two specified vector types are
8604 /// compatible.
8605 static bool areCompatVectorTypes(const VectorType *LHS,
8606                                  const VectorType *RHS) {
8607   assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
8608   return LHS->getElementType() == RHS->getElementType() &&
8609          LHS->getNumElements() == RHS->getNumElements();
8610 }
8611 
8612 /// areCompatMatrixTypes - Return true if the two specified matrix types are
8613 /// compatible.
8614 static bool areCompatMatrixTypes(const ConstantMatrixType *LHS,
8615                                  const ConstantMatrixType *RHS) {
8616   assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
8617   return LHS->getElementType() == RHS->getElementType() &&
8618          LHS->getNumRows() == RHS->getNumRows() &&
8619          LHS->getNumColumns() == RHS->getNumColumns();
8620 }
8621 
8622 bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
8623                                           QualType SecondVec) {
8624   assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
8625   assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
8626 
8627   if (hasSameUnqualifiedType(FirstVec, SecondVec))
8628     return true;
8629 
8630   // Treat Neon vector types and most AltiVec vector types as if they are the
8631   // equivalent GCC vector types.
8632   const auto *First = FirstVec->castAs<VectorType>();
8633   const auto *Second = SecondVec->castAs<VectorType>();
8634   if (First->getNumElements() == Second->getNumElements() &&
8635       hasSameType(First->getElementType(), Second->getElementType()) &&
8636       First->getVectorKind() != VectorType::AltiVecPixel &&
8637       First->getVectorKind() != VectorType::AltiVecBool &&
8638       Second->getVectorKind() != VectorType::AltiVecPixel &&
8639       Second->getVectorKind() != VectorType::AltiVecBool &&
8640       First->getVectorKind() != VectorType::SveFixedLengthDataVector &&
8641       First->getVectorKind() != VectorType::SveFixedLengthPredicateVector &&
8642       Second->getVectorKind() != VectorType::SveFixedLengthDataVector &&
8643       Second->getVectorKind() != VectorType::SveFixedLengthPredicateVector)
8644     return true;
8645 
8646   return false;
8647 }
8648 
8649 bool ASTContext::areCompatibleSveTypes(QualType FirstType,
8650                                        QualType SecondType) {
8651   assert(((FirstType->isSizelessBuiltinType() && SecondType->isVectorType()) ||
8652           (FirstType->isVectorType() && SecondType->isSizelessBuiltinType())) &&
8653          "Expected SVE builtin type and vector type!");
8654 
8655   auto IsValidCast = [this](QualType FirstType, QualType SecondType) {
8656     if (const auto *BT = FirstType->getAs<BuiltinType>()) {
8657       if (const auto *VT = SecondType->getAs<VectorType>()) {
8658         // Predicates have the same representation as uint8 so we also have to
8659         // check the kind to make these types incompatible.
8660         if (VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector)
8661           return BT->getKind() == BuiltinType::SveBool;
8662         else if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector)
8663           return VT->getElementType().getCanonicalType() ==
8664                  FirstType->getSveEltType(*this);
8665         else if (VT->getVectorKind() == VectorType::GenericVector)
8666           return getTypeSize(SecondType) == getLangOpts().ArmSveVectorBits &&
8667                  hasSameType(VT->getElementType(),
8668                              getBuiltinVectorTypeInfo(BT).ElementType);
8669       }
8670     }
8671     return false;
8672   };
8673 
8674   return IsValidCast(FirstType, SecondType) ||
8675          IsValidCast(SecondType, FirstType);
8676 }
8677 
8678 bool ASTContext::areLaxCompatibleSveTypes(QualType FirstType,
8679                                           QualType SecondType) {
8680   assert(((FirstType->isSizelessBuiltinType() && SecondType->isVectorType()) ||
8681           (FirstType->isVectorType() && SecondType->isSizelessBuiltinType())) &&
8682          "Expected SVE builtin type and vector type!");
8683 
8684   auto IsLaxCompatible = [this](QualType FirstType, QualType SecondType) {
8685     if (!FirstType->getAs<BuiltinType>())
8686       return false;
8687 
8688     const auto *VecTy = SecondType->getAs<VectorType>();
8689     if (VecTy &&
8690         (VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector ||
8691          VecTy->getVectorKind() == VectorType::GenericVector)) {
8692       const LangOptions::LaxVectorConversionKind LVCKind =
8693           getLangOpts().getLaxVectorConversions();
8694 
8695       // If __ARM_FEATURE_SVE_BITS != N do not allow GNU vector lax conversion.
8696       // "Whenever __ARM_FEATURE_SVE_BITS==N, GNUT implicitly
8697       // converts to VLAT and VLAT implicitly converts to GNUT."
8698       // ACLE Spec Version 00bet6, 3.7.3.2. Behavior common to vectors and
8699       // predicates.
8700       if (VecTy->getVectorKind() == VectorType::GenericVector &&
8701           getTypeSize(SecondType) != getLangOpts().ArmSveVectorBits)
8702         return false;
8703 
8704       // If -flax-vector-conversions=all is specified, the types are
8705       // certainly compatible.
8706       if (LVCKind == LangOptions::LaxVectorConversionKind::All)
8707         return true;
8708 
8709       // If -flax-vector-conversions=integer is specified, the types are
8710       // compatible if the elements are integer types.
8711       if (LVCKind == LangOptions::LaxVectorConversionKind::Integer)
8712         return VecTy->getElementType().getCanonicalType()->isIntegerType() &&
8713                FirstType->getSveEltType(*this)->isIntegerType();
8714     }
8715 
8716     return false;
8717   };
8718 
8719   return IsLaxCompatible(FirstType, SecondType) ||
8720          IsLaxCompatible(SecondType, FirstType);
8721 }
8722 
8723 bool ASTContext::hasDirectOwnershipQualifier(QualType Ty) const {
8724   while (true) {
8725     // __strong id
8726     if (const AttributedType *Attr = dyn_cast<AttributedType>(Ty)) {
8727       if (Attr->getAttrKind() == attr::ObjCOwnership)
8728         return true;
8729 
8730       Ty = Attr->getModifiedType();
8731 
8732     // X *__strong (...)
8733     } else if (const ParenType *Paren = dyn_cast<ParenType>(Ty)) {
8734       Ty = Paren->getInnerType();
8735 
8736     // We do not want to look through typedefs, typeof(expr),
8737     // typeof(type), or any other way that the type is somehow
8738     // abstracted.
8739     } else {
8740       return false;
8741     }
8742   }
8743 }
8744 
8745 //===----------------------------------------------------------------------===//
8746 // ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
8747 //===----------------------------------------------------------------------===//
8748 
8749 /// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
8750 /// inheritance hierarchy of 'rProto'.
8751 bool
8752 ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
8753                                            ObjCProtocolDecl *rProto) const {
8754   if (declaresSameEntity(lProto, rProto))
8755     return true;
8756   for (auto *PI : rProto->protocols())
8757     if (ProtocolCompatibleWithProtocol(lProto, PI))
8758       return true;
8759   return false;
8760 }
8761 
8762 /// ObjCQualifiedClassTypesAreCompatible - compare  Class<pr,...> and
8763 /// Class<pr1, ...>.
8764 bool ASTContext::ObjCQualifiedClassTypesAreCompatible(
8765     const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs) {
8766   for (auto *lhsProto : lhs->quals()) {
8767     bool match = false;
8768     for (auto *rhsProto : rhs->quals()) {
8769       if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
8770         match = true;
8771         break;
8772       }
8773     }
8774     if (!match)
8775       return false;
8776   }
8777   return true;
8778 }
8779 
8780 /// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
8781 /// ObjCQualifiedIDType.
8782 bool ASTContext::ObjCQualifiedIdTypesAreCompatible(
8783     const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs,
8784     bool compare) {
8785   // Allow id<P..> and an 'id' in all cases.
8786   if (lhs->isObjCIdType() || rhs->isObjCIdType())
8787     return true;
8788 
8789   // Don't allow id<P..> to convert to Class or Class<P..> in either direction.
8790   if (lhs->isObjCClassType() || lhs->isObjCQualifiedClassType() ||
8791       rhs->isObjCClassType() || rhs->isObjCQualifiedClassType())
8792     return false;
8793 
8794   if (lhs->isObjCQualifiedIdType()) {
8795     if (rhs->qual_empty()) {
8796       // If the RHS is a unqualified interface pointer "NSString*",
8797       // make sure we check the class hierarchy.
8798       if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
8799         for (auto *I : lhs->quals()) {
8800           // when comparing an id<P> on lhs with a static type on rhs,
8801           // see if static class implements all of id's protocols, directly or
8802           // through its super class and categories.
8803           if (!rhsID->ClassImplementsProtocol(I, true))
8804             return false;
8805         }
8806       }
8807       // If there are no qualifiers and no interface, we have an 'id'.
8808       return true;
8809     }
8810     // Both the right and left sides have qualifiers.
8811     for (auto *lhsProto : lhs->quals()) {
8812       bool match = false;
8813 
8814       // when comparing an id<P> on lhs with a static type on rhs,
8815       // see if static class implements all of id's protocols, directly or
8816       // through its super class and categories.
8817       for (auto *rhsProto : rhs->quals()) {
8818         if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
8819             (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
8820           match = true;
8821           break;
8822         }
8823       }
8824       // If the RHS is a qualified interface pointer "NSString<P>*",
8825       // make sure we check the class hierarchy.
8826       if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
8827         for (auto *I : lhs->quals()) {
8828           // when comparing an id<P> on lhs with a static type on rhs,
8829           // see if static class implements all of id's protocols, directly or
8830           // through its super class and categories.
8831           if (rhsID->ClassImplementsProtocol(I, true)) {
8832             match = true;
8833             break;
8834           }
8835         }
8836       }
8837       if (!match)
8838         return false;
8839     }
8840 
8841     return true;
8842   }
8843 
8844   assert(rhs->isObjCQualifiedIdType() && "One of the LHS/RHS should be id<x>");
8845 
8846   if (lhs->getInterfaceType()) {
8847     // If both the right and left sides have qualifiers.
8848     for (auto *lhsProto : lhs->quals()) {
8849       bool match = false;
8850 
8851       // when comparing an id<P> on rhs with a static type on lhs,
8852       // see if static class implements all of id's protocols, directly or
8853       // through its super class and categories.
8854       // First, lhs protocols in the qualifier list must be found, direct
8855       // or indirect in rhs's qualifier list or it is a mismatch.
8856       for (auto *rhsProto : rhs->quals()) {
8857         if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
8858             (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
8859           match = true;
8860           break;
8861         }
8862       }
8863       if (!match)
8864         return false;
8865     }
8866 
8867     // Static class's protocols, or its super class or category protocols
8868     // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
8869     if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) {
8870       llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
8871       CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
8872       // This is rather dubious but matches gcc's behavior. If lhs has
8873       // no type qualifier and its class has no static protocol(s)
8874       // assume that it is mismatch.
8875       if (LHSInheritedProtocols.empty() && lhs->qual_empty())
8876         return false;
8877       for (auto *lhsProto : LHSInheritedProtocols) {
8878         bool match = false;
8879         for (auto *rhsProto : rhs->quals()) {
8880           if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
8881               (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
8882             match = true;
8883             break;
8884           }
8885         }
8886         if (!match)
8887           return false;
8888       }
8889     }
8890     return true;
8891   }
8892   return false;
8893 }
8894 
8895 /// canAssignObjCInterfaces - Return true if the two interface types are
8896 /// compatible for assignment from RHS to LHS.  This handles validation of any
8897 /// protocol qualifiers on the LHS or RHS.
8898 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
8899                                          const ObjCObjectPointerType *RHSOPT) {
8900   const ObjCObjectType* LHS = LHSOPT->getObjectType();
8901   const ObjCObjectType* RHS = RHSOPT->getObjectType();
8902 
8903   // If either type represents the built-in 'id' type, return true.
8904   if (LHS->isObjCUnqualifiedId() || RHS->isObjCUnqualifiedId())
8905     return true;
8906 
8907   // Function object that propagates a successful result or handles
8908   // __kindof types.
8909   auto finish = [&](bool succeeded) -> bool {
8910     if (succeeded)
8911       return true;
8912 
8913     if (!RHS->isKindOfType())
8914       return false;
8915 
8916     // Strip off __kindof and protocol qualifiers, then check whether
8917     // we can assign the other way.
8918     return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
8919                                    LHSOPT->stripObjCKindOfTypeAndQuals(*this));
8920   };
8921 
8922   // Casts from or to id<P> are allowed when the other side has compatible
8923   // protocols.
8924   if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
8925     return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false));
8926   }
8927 
8928   // Verify protocol compatibility for casts from Class<P1> to Class<P2>.
8929   if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
8930     return finish(ObjCQualifiedClassTypesAreCompatible(LHSOPT, RHSOPT));
8931   }
8932 
8933   // Casts from Class to Class<Foo>, or vice-versa, are allowed.
8934   if (LHS->isObjCClass() && RHS->isObjCClass()) {
8935     return true;
8936   }
8937 
8938   // If we have 2 user-defined types, fall into that path.
8939   if (LHS->getInterface() && RHS->getInterface()) {
8940     return finish(canAssignObjCInterfaces(LHS, RHS));
8941   }
8942 
8943   return false;
8944 }
8945 
8946 /// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
8947 /// for providing type-safety for objective-c pointers used to pass/return
8948 /// arguments in block literals. When passed as arguments, passing 'A*' where
8949 /// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
8950 /// not OK. For the return type, the opposite is not OK.
8951 bool ASTContext::canAssignObjCInterfacesInBlockPointer(
8952                                          const ObjCObjectPointerType *LHSOPT,
8953                                          const ObjCObjectPointerType *RHSOPT,
8954                                          bool BlockReturnType) {
8955 
8956   // Function object that propagates a successful result or handles
8957   // __kindof types.
8958   auto finish = [&](bool succeeded) -> bool {
8959     if (succeeded)
8960       return true;
8961 
8962     const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
8963     if (!Expected->isKindOfType())
8964       return false;
8965 
8966     // Strip off __kindof and protocol qualifiers, then check whether
8967     // we can assign the other way.
8968     return canAssignObjCInterfacesInBlockPointer(
8969              RHSOPT->stripObjCKindOfTypeAndQuals(*this),
8970              LHSOPT->stripObjCKindOfTypeAndQuals(*this),
8971              BlockReturnType);
8972   };
8973 
8974   if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
8975     return true;
8976 
8977   if (LHSOPT->isObjCBuiltinType()) {
8978     return finish(RHSOPT->isObjCBuiltinType() ||
8979                   RHSOPT->isObjCQualifiedIdType());
8980   }
8981 
8982   if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) {
8983     if (getLangOpts().CompatibilityQualifiedIdBlockParamTypeChecking)
8984       // Use for block parameters previous type checking for compatibility.
8985       return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false) ||
8986                     // Or corrected type checking as in non-compat mode.
8987                     (!BlockReturnType &&
8988                      ObjCQualifiedIdTypesAreCompatible(RHSOPT, LHSOPT, false)));
8989     else
8990       return finish(ObjCQualifiedIdTypesAreCompatible(
8991           (BlockReturnType ? LHSOPT : RHSOPT),
8992           (BlockReturnType ? RHSOPT : LHSOPT), false));
8993   }
8994 
8995   const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
8996   const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
8997   if (LHS && RHS)  { // We have 2 user-defined types.
8998     if (LHS != RHS) {
8999       if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
9000         return finish(BlockReturnType);
9001       if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
9002         return finish(!BlockReturnType);
9003     }
9004     else
9005       return true;
9006   }
9007   return false;
9008 }
9009 
9010 /// Comparison routine for Objective-C protocols to be used with
9011 /// llvm::array_pod_sort.
9012 static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
9013                                       ObjCProtocolDecl * const *rhs) {
9014   return (*lhs)->getName().compare((*rhs)->getName());
9015 }
9016 
9017 /// getIntersectionOfProtocols - This routine finds the intersection of set
9018 /// of protocols inherited from two distinct objective-c pointer objects with
9019 /// the given common base.
9020 /// It is used to build composite qualifier list of the composite type of
9021 /// the conditional expression involving two objective-c pointer objects.
9022 static
9023 void getIntersectionOfProtocols(ASTContext &Context,
9024                                 const ObjCInterfaceDecl *CommonBase,
9025                                 const ObjCObjectPointerType *LHSOPT,
9026                                 const ObjCObjectPointerType *RHSOPT,
9027       SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
9028 
9029   const ObjCObjectType* LHS = LHSOPT->getObjectType();
9030   const ObjCObjectType* RHS = RHSOPT->getObjectType();
9031   assert(LHS->getInterface() && "LHS must have an interface base");
9032   assert(RHS->getInterface() && "RHS must have an interface base");
9033 
9034   // Add all of the protocols for the LHS.
9035   llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
9036 
9037   // Start with the protocol qualifiers.
9038   for (auto proto : LHS->quals()) {
9039     Context.CollectInheritedProtocols(proto, LHSProtocolSet);
9040   }
9041 
9042   // Also add the protocols associated with the LHS interface.
9043   Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
9044 
9045   // Add all of the protocols for the RHS.
9046   llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
9047 
9048   // Start with the protocol qualifiers.
9049   for (auto proto : RHS->quals()) {
9050     Context.CollectInheritedProtocols(proto, RHSProtocolSet);
9051   }
9052 
9053   // Also add the protocols associated with the RHS interface.
9054   Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
9055 
9056   // Compute the intersection of the collected protocol sets.
9057   for (auto proto : LHSProtocolSet) {
9058     if (RHSProtocolSet.count(proto))
9059       IntersectionSet.push_back(proto);
9060   }
9061 
9062   // Compute the set of protocols that is implied by either the common type or
9063   // the protocols within the intersection.
9064   llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
9065   Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
9066 
9067   // Remove any implied protocols from the list of inherited protocols.
9068   if (!ImpliedProtocols.empty()) {
9069     IntersectionSet.erase(
9070       std::remove_if(IntersectionSet.begin(),
9071                      IntersectionSet.end(),
9072                      [&](ObjCProtocolDecl *proto) -> bool {
9073                        return ImpliedProtocols.count(proto) > 0;
9074                      }),
9075       IntersectionSet.end());
9076   }
9077 
9078   // Sort the remaining protocols by name.
9079   llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
9080                        compareObjCProtocolsByName);
9081 }
9082 
9083 /// Determine whether the first type is a subtype of the second.
9084 static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
9085                                      QualType rhs) {
9086   // Common case: two object pointers.
9087   const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
9088   const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
9089   if (lhsOPT && rhsOPT)
9090     return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
9091 
9092   // Two block pointers.
9093   const auto *lhsBlock = lhs->getAs<BlockPointerType>();
9094   const auto *rhsBlock = rhs->getAs<BlockPointerType>();
9095   if (lhsBlock && rhsBlock)
9096     return ctx.typesAreBlockPointerCompatible(lhs, rhs);
9097 
9098   // If either is an unqualified 'id' and the other is a block, it's
9099   // acceptable.
9100   if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
9101       (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
9102     return true;
9103 
9104   return false;
9105 }
9106 
9107 // Check that the given Objective-C type argument lists are equivalent.
9108 static bool sameObjCTypeArgs(ASTContext &ctx,
9109                              const ObjCInterfaceDecl *iface,
9110                              ArrayRef<QualType> lhsArgs,
9111                              ArrayRef<QualType> rhsArgs,
9112                              bool stripKindOf) {
9113   if (lhsArgs.size() != rhsArgs.size())
9114     return false;
9115 
9116   ObjCTypeParamList *typeParams = iface->getTypeParamList();
9117   for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
9118     if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
9119       continue;
9120 
9121     switch (typeParams->begin()[i]->getVariance()) {
9122     case ObjCTypeParamVariance::Invariant:
9123       if (!stripKindOf ||
9124           !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
9125                            rhsArgs[i].stripObjCKindOfType(ctx))) {
9126         return false;
9127       }
9128       break;
9129 
9130     case ObjCTypeParamVariance::Covariant:
9131       if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
9132         return false;
9133       break;
9134 
9135     case ObjCTypeParamVariance::Contravariant:
9136       if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
9137         return false;
9138       break;
9139     }
9140   }
9141 
9142   return true;
9143 }
9144 
9145 QualType ASTContext::areCommonBaseCompatible(
9146            const ObjCObjectPointerType *Lptr,
9147            const ObjCObjectPointerType *Rptr) {
9148   const ObjCObjectType *LHS = Lptr->getObjectType();
9149   const ObjCObjectType *RHS = Rptr->getObjectType();
9150   const ObjCInterfaceDecl* LDecl = LHS->getInterface();
9151   const ObjCInterfaceDecl* RDecl = RHS->getInterface();
9152 
9153   if (!LDecl || !RDecl)
9154     return {};
9155 
9156   // When either LHS or RHS is a kindof type, we should return a kindof type.
9157   // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
9158   // kindof(A).
9159   bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
9160 
9161   // Follow the left-hand side up the class hierarchy until we either hit a
9162   // root or find the RHS. Record the ancestors in case we don't find it.
9163   llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
9164     LHSAncestors;
9165   while (true) {
9166     // Record this ancestor. We'll need this if the common type isn't in the
9167     // path from the LHS to the root.
9168     LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
9169 
9170     if (declaresSameEntity(LHS->getInterface(), RDecl)) {
9171       // Get the type arguments.
9172       ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
9173       bool anyChanges = false;
9174       if (LHS->isSpecialized() && RHS->isSpecialized()) {
9175         // Both have type arguments, compare them.
9176         if (!sameObjCTypeArgs(*this, LHS->getInterface(),
9177                               LHS->getTypeArgs(), RHS->getTypeArgs(),
9178                               /*stripKindOf=*/true))
9179           return {};
9180       } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
9181         // If only one has type arguments, the result will not have type
9182         // arguments.
9183         LHSTypeArgs = {};
9184         anyChanges = true;
9185       }
9186 
9187       // Compute the intersection of protocols.
9188       SmallVector<ObjCProtocolDecl *, 8> Protocols;
9189       getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
9190                                  Protocols);
9191       if (!Protocols.empty())
9192         anyChanges = true;
9193 
9194       // If anything in the LHS will have changed, build a new result type.
9195       // If we need to return a kindof type but LHS is not a kindof type, we
9196       // build a new result type.
9197       if (anyChanges || LHS->isKindOfType() != anyKindOf) {
9198         QualType Result = getObjCInterfaceType(LHS->getInterface());
9199         Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
9200                                    anyKindOf || LHS->isKindOfType());
9201         return getObjCObjectPointerType(Result);
9202       }
9203 
9204       return getObjCObjectPointerType(QualType(LHS, 0));
9205     }
9206 
9207     // Find the superclass.
9208     QualType LHSSuperType = LHS->getSuperClassType();
9209     if (LHSSuperType.isNull())
9210       break;
9211 
9212     LHS = LHSSuperType->castAs<ObjCObjectType>();
9213   }
9214 
9215   // We didn't find anything by following the LHS to its root; now check
9216   // the RHS against the cached set of ancestors.
9217   while (true) {
9218     auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
9219     if (KnownLHS != LHSAncestors.end()) {
9220       LHS = KnownLHS->second;
9221 
9222       // Get the type arguments.
9223       ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
9224       bool anyChanges = false;
9225       if (LHS->isSpecialized() && RHS->isSpecialized()) {
9226         // Both have type arguments, compare them.
9227         if (!sameObjCTypeArgs(*this, LHS->getInterface(),
9228                               LHS->getTypeArgs(), RHS->getTypeArgs(),
9229                               /*stripKindOf=*/true))
9230           return {};
9231       } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
9232         // If only one has type arguments, the result will not have type
9233         // arguments.
9234         RHSTypeArgs = {};
9235         anyChanges = true;
9236       }
9237 
9238       // Compute the intersection of protocols.
9239       SmallVector<ObjCProtocolDecl *, 8> Protocols;
9240       getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
9241                                  Protocols);
9242       if (!Protocols.empty())
9243         anyChanges = true;
9244 
9245       // If we need to return a kindof type but RHS is not a kindof type, we
9246       // build a new result type.
9247       if (anyChanges || RHS->isKindOfType() != anyKindOf) {
9248         QualType Result = getObjCInterfaceType(RHS->getInterface());
9249         Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
9250                                    anyKindOf || RHS->isKindOfType());
9251         return getObjCObjectPointerType(Result);
9252       }
9253 
9254       return getObjCObjectPointerType(QualType(RHS, 0));
9255     }
9256 
9257     // Find the superclass of the RHS.
9258     QualType RHSSuperType = RHS->getSuperClassType();
9259     if (RHSSuperType.isNull())
9260       break;
9261 
9262     RHS = RHSSuperType->castAs<ObjCObjectType>();
9263   }
9264 
9265   return {};
9266 }
9267 
9268 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
9269                                          const ObjCObjectType *RHS) {
9270   assert(LHS->getInterface() && "LHS is not an interface type");
9271   assert(RHS->getInterface() && "RHS is not an interface type");
9272 
9273   // Verify that the base decls are compatible: the RHS must be a subclass of
9274   // the LHS.
9275   ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
9276   bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
9277   if (!IsSuperClass)
9278     return false;
9279 
9280   // If the LHS has protocol qualifiers, determine whether all of them are
9281   // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
9282   // LHS).
9283   if (LHS->getNumProtocols() > 0) {
9284     // OK if conversion of LHS to SuperClass results in narrowing of types
9285     // ; i.e., SuperClass may implement at least one of the protocols
9286     // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
9287     // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
9288     llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
9289     CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
9290     // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
9291     // qualifiers.
9292     for (auto *RHSPI : RHS->quals())
9293       CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
9294     // If there is no protocols associated with RHS, it is not a match.
9295     if (SuperClassInheritedProtocols.empty())
9296       return false;
9297 
9298     for (const auto *LHSProto : LHS->quals()) {
9299       bool SuperImplementsProtocol = false;
9300       for (auto *SuperClassProto : SuperClassInheritedProtocols)
9301         if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
9302           SuperImplementsProtocol = true;
9303           break;
9304         }
9305       if (!SuperImplementsProtocol)
9306         return false;
9307     }
9308   }
9309 
9310   // If the LHS is specialized, we may need to check type arguments.
9311   if (LHS->isSpecialized()) {
9312     // Follow the superclass chain until we've matched the LHS class in the
9313     // hierarchy. This substitutes type arguments through.
9314     const ObjCObjectType *RHSSuper = RHS;
9315     while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
9316       RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
9317 
9318     // If the RHS is specializd, compare type arguments.
9319     if (RHSSuper->isSpecialized() &&
9320         !sameObjCTypeArgs(*this, LHS->getInterface(),
9321                           LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
9322                           /*stripKindOf=*/true)) {
9323       return false;
9324     }
9325   }
9326 
9327   return true;
9328 }
9329 
9330 bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
9331   // get the "pointed to" types
9332   const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
9333   const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
9334 
9335   if (!LHSOPT || !RHSOPT)
9336     return false;
9337 
9338   return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
9339          canAssignObjCInterfaces(RHSOPT, LHSOPT);
9340 }
9341 
9342 bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
9343   return canAssignObjCInterfaces(
9344       getObjCObjectPointerType(To)->castAs<ObjCObjectPointerType>(),
9345       getObjCObjectPointerType(From)->castAs<ObjCObjectPointerType>());
9346 }
9347 
9348 /// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
9349 /// both shall have the identically qualified version of a compatible type.
9350 /// C99 6.2.7p1: Two types have compatible types if their types are the
9351 /// same. See 6.7.[2,3,5] for additional rules.
9352 bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
9353                                     bool CompareUnqualified) {
9354   if (getLangOpts().CPlusPlus)
9355     return hasSameType(LHS, RHS);
9356 
9357   return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
9358 }
9359 
9360 bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
9361   return typesAreCompatible(LHS, RHS);
9362 }
9363 
9364 bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
9365   return !mergeTypes(LHS, RHS, true).isNull();
9366 }
9367 
9368 /// mergeTransparentUnionType - if T is a transparent union type and a member
9369 /// of T is compatible with SubType, return the merged type, else return
9370 /// QualType()
9371 QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
9372                                                bool OfBlockPointer,
9373                                                bool Unqualified) {
9374   if (const RecordType *UT = T->getAsUnionType()) {
9375     RecordDecl *UD = UT->getDecl();
9376     if (UD->hasAttr<TransparentUnionAttr>()) {
9377       for (const auto *I : UD->fields()) {
9378         QualType ET = I->getType().getUnqualifiedType();
9379         QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
9380         if (!MT.isNull())
9381           return MT;
9382       }
9383     }
9384   }
9385 
9386   return {};
9387 }
9388 
9389 /// mergeFunctionParameterTypes - merge two types which appear as function
9390 /// parameter types
9391 QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
9392                                                  bool OfBlockPointer,
9393                                                  bool Unqualified) {
9394   // GNU extension: two types are compatible if they appear as a function
9395   // argument, one of the types is a transparent union type and the other
9396   // type is compatible with a union member
9397   QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
9398                                               Unqualified);
9399   if (!lmerge.isNull())
9400     return lmerge;
9401 
9402   QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
9403                                               Unqualified);
9404   if (!rmerge.isNull())
9405     return rmerge;
9406 
9407   return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
9408 }
9409 
9410 QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
9411                                         bool OfBlockPointer, bool Unqualified,
9412                                         bool AllowCXX) {
9413   const auto *lbase = lhs->castAs<FunctionType>();
9414   const auto *rbase = rhs->castAs<FunctionType>();
9415   const auto *lproto = dyn_cast<FunctionProtoType>(lbase);
9416   const auto *rproto = dyn_cast<FunctionProtoType>(rbase);
9417   bool allLTypes = true;
9418   bool allRTypes = true;
9419 
9420   // Check return type
9421   QualType retType;
9422   if (OfBlockPointer) {
9423     QualType RHS = rbase->getReturnType();
9424     QualType LHS = lbase->getReturnType();
9425     bool UnqualifiedResult = Unqualified;
9426     if (!UnqualifiedResult)
9427       UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
9428     retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
9429   }
9430   else
9431     retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
9432                          Unqualified);
9433   if (retType.isNull())
9434     return {};
9435 
9436   if (Unqualified)
9437     retType = retType.getUnqualifiedType();
9438 
9439   CanQualType LRetType = getCanonicalType(lbase->getReturnType());
9440   CanQualType RRetType = getCanonicalType(rbase->getReturnType());
9441   if (Unqualified) {
9442     LRetType = LRetType.getUnqualifiedType();
9443     RRetType = RRetType.getUnqualifiedType();
9444   }
9445 
9446   if (getCanonicalType(retType) != LRetType)
9447     allLTypes = false;
9448   if (getCanonicalType(retType) != RRetType)
9449     allRTypes = false;
9450 
9451   // FIXME: double check this
9452   // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
9453   //                           rbase->getRegParmAttr() != 0 &&
9454   //                           lbase->getRegParmAttr() != rbase->getRegParmAttr()?
9455   FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
9456   FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
9457 
9458   // Compatible functions must have compatible calling conventions
9459   if (lbaseInfo.getCC() != rbaseInfo.getCC())
9460     return {};
9461 
9462   // Regparm is part of the calling convention.
9463   if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
9464     return {};
9465   if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
9466     return {};
9467 
9468   if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
9469     return {};
9470   if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
9471     return {};
9472   if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
9473     return {};
9474 
9475   // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
9476   bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
9477 
9478   if (lbaseInfo.getNoReturn() != NoReturn)
9479     allLTypes = false;
9480   if (rbaseInfo.getNoReturn() != NoReturn)
9481     allRTypes = false;
9482 
9483   FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
9484 
9485   if (lproto && rproto) { // two C99 style function prototypes
9486     assert((AllowCXX ||
9487             (!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec())) &&
9488            "C++ shouldn't be here");
9489     // Compatible functions must have the same number of parameters
9490     if (lproto->getNumParams() != rproto->getNumParams())
9491       return {};
9492 
9493     // Variadic and non-variadic functions aren't compatible
9494     if (lproto->isVariadic() != rproto->isVariadic())
9495       return {};
9496 
9497     if (lproto->getMethodQuals() != rproto->getMethodQuals())
9498       return {};
9499 
9500     SmallVector<FunctionProtoType::ExtParameterInfo, 4> newParamInfos;
9501     bool canUseLeft, canUseRight;
9502     if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight,
9503                                newParamInfos))
9504       return {};
9505 
9506     if (!canUseLeft)
9507       allLTypes = false;
9508     if (!canUseRight)
9509       allRTypes = false;
9510 
9511     // Check parameter type compatibility
9512     SmallVector<QualType, 10> types;
9513     for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
9514       QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
9515       QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
9516       QualType paramType = mergeFunctionParameterTypes(
9517           lParamType, rParamType, OfBlockPointer, Unqualified);
9518       if (paramType.isNull())
9519         return {};
9520 
9521       if (Unqualified)
9522         paramType = paramType.getUnqualifiedType();
9523 
9524       types.push_back(paramType);
9525       if (Unqualified) {
9526         lParamType = lParamType.getUnqualifiedType();
9527         rParamType = rParamType.getUnqualifiedType();
9528       }
9529 
9530       if (getCanonicalType(paramType) != getCanonicalType(lParamType))
9531         allLTypes = false;
9532       if (getCanonicalType(paramType) != getCanonicalType(rParamType))
9533         allRTypes = false;
9534     }
9535 
9536     if (allLTypes) return lhs;
9537     if (allRTypes) return rhs;
9538 
9539     FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
9540     EPI.ExtInfo = einfo;
9541     EPI.ExtParameterInfos =
9542         newParamInfos.empty() ? nullptr : newParamInfos.data();
9543     return getFunctionType(retType, types, EPI);
9544   }
9545 
9546   if (lproto) allRTypes = false;
9547   if (rproto) allLTypes = false;
9548 
9549   const FunctionProtoType *proto = lproto ? lproto : rproto;
9550   if (proto) {
9551     assert((AllowCXX || !proto->hasExceptionSpec()) && "C++ shouldn't be here");
9552     if (proto->isVariadic())
9553       return {};
9554     // Check that the types are compatible with the types that
9555     // would result from default argument promotions (C99 6.7.5.3p15).
9556     // The only types actually affected are promotable integer
9557     // types and floats, which would be passed as a different
9558     // type depending on whether the prototype is visible.
9559     for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
9560       QualType paramTy = proto->getParamType(i);
9561 
9562       // Look at the converted type of enum types, since that is the type used
9563       // to pass enum values.
9564       if (const auto *Enum = paramTy->getAs<EnumType>()) {
9565         paramTy = Enum->getDecl()->getIntegerType();
9566         if (paramTy.isNull())
9567           return {};
9568       }
9569 
9570       if (paramTy->isPromotableIntegerType() ||
9571           getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
9572         return {};
9573     }
9574 
9575     if (allLTypes) return lhs;
9576     if (allRTypes) return rhs;
9577 
9578     FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
9579     EPI.ExtInfo = einfo;
9580     return getFunctionType(retType, proto->getParamTypes(), EPI);
9581   }
9582 
9583   if (allLTypes) return lhs;
9584   if (allRTypes) return rhs;
9585   return getFunctionNoProtoType(retType, einfo);
9586 }
9587 
9588 /// Given that we have an enum type and a non-enum type, try to merge them.
9589 static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
9590                                      QualType other, bool isBlockReturnType) {
9591   // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
9592   // a signed integer type, or an unsigned integer type.
9593   // Compatibility is based on the underlying type, not the promotion
9594   // type.
9595   QualType underlyingType = ET->getDecl()->getIntegerType();
9596   if (underlyingType.isNull())
9597     return {};
9598   if (Context.hasSameType(underlyingType, other))
9599     return other;
9600 
9601   // In block return types, we're more permissive and accept any
9602   // integral type of the same size.
9603   if (isBlockReturnType && other->isIntegerType() &&
9604       Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
9605     return other;
9606 
9607   return {};
9608 }
9609 
9610 QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
9611                                 bool OfBlockPointer,
9612                                 bool Unqualified, bool BlockReturnType) {
9613   // C++ [expr]: If an expression initially has the type "reference to T", the
9614   // type is adjusted to "T" prior to any further analysis, the expression
9615   // designates the object or function denoted by the reference, and the
9616   // expression is an lvalue unless the reference is an rvalue reference and
9617   // the expression is a function call (possibly inside parentheses).
9618   if (LHS->getAs<ReferenceType>() || RHS->getAs<ReferenceType>())
9619     return {};
9620 
9621   if (Unqualified) {
9622     LHS = LHS.getUnqualifiedType();
9623     RHS = RHS.getUnqualifiedType();
9624   }
9625 
9626   QualType LHSCan = getCanonicalType(LHS),
9627            RHSCan = getCanonicalType(RHS);
9628 
9629   // If two types are identical, they are compatible.
9630   if (LHSCan == RHSCan)
9631     return LHS;
9632 
9633   // If the qualifiers are different, the types aren't compatible... mostly.
9634   Qualifiers LQuals = LHSCan.getLocalQualifiers();
9635   Qualifiers RQuals = RHSCan.getLocalQualifiers();
9636   if (LQuals != RQuals) {
9637     // If any of these qualifiers are different, we have a type
9638     // mismatch.
9639     if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
9640         LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
9641         LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
9642         LQuals.hasUnaligned() != RQuals.hasUnaligned())
9643       return {};
9644 
9645     // Exactly one GC qualifier difference is allowed: __strong is
9646     // okay if the other type has no GC qualifier but is an Objective
9647     // C object pointer (i.e. implicitly strong by default).  We fix
9648     // this by pretending that the unqualified type was actually
9649     // qualified __strong.
9650     Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
9651     Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
9652     assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
9653 
9654     if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
9655       return {};
9656 
9657     if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
9658       return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
9659     }
9660     if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
9661       return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
9662     }
9663     return {};
9664   }
9665 
9666   // Okay, qualifiers are equal.
9667 
9668   Type::TypeClass LHSClass = LHSCan->getTypeClass();
9669   Type::TypeClass RHSClass = RHSCan->getTypeClass();
9670 
9671   // We want to consider the two function types to be the same for these
9672   // comparisons, just force one to the other.
9673   if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
9674   if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
9675 
9676   // Same as above for arrays
9677   if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
9678     LHSClass = Type::ConstantArray;
9679   if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
9680     RHSClass = Type::ConstantArray;
9681 
9682   // ObjCInterfaces are just specialized ObjCObjects.
9683   if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
9684   if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
9685 
9686   // Canonicalize ExtVector -> Vector.
9687   if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
9688   if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
9689 
9690   // If the canonical type classes don't match.
9691   if (LHSClass != RHSClass) {
9692     // Note that we only have special rules for turning block enum
9693     // returns into block int returns, not vice-versa.
9694     if (const auto *ETy = LHS->getAs<EnumType>()) {
9695       return mergeEnumWithInteger(*this, ETy, RHS, false);
9696     }
9697     if (const EnumType* ETy = RHS->getAs<EnumType>()) {
9698       return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
9699     }
9700     // allow block pointer type to match an 'id' type.
9701     if (OfBlockPointer && !BlockReturnType) {
9702        if (LHS->isObjCIdType() && RHS->isBlockPointerType())
9703          return LHS;
9704       if (RHS->isObjCIdType() && LHS->isBlockPointerType())
9705         return RHS;
9706     }
9707 
9708     return {};
9709   }
9710 
9711   // The canonical type classes match.
9712   switch (LHSClass) {
9713 #define TYPE(Class, Base)
9714 #define ABSTRACT_TYPE(Class, Base)
9715 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
9716 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
9717 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
9718 #include "clang/AST/TypeNodes.inc"
9719     llvm_unreachable("Non-canonical and dependent types shouldn't get here");
9720 
9721   case Type::Auto:
9722   case Type::DeducedTemplateSpecialization:
9723   case Type::LValueReference:
9724   case Type::RValueReference:
9725   case Type::MemberPointer:
9726     llvm_unreachable("C++ should never be in mergeTypes");
9727 
9728   case Type::ObjCInterface:
9729   case Type::IncompleteArray:
9730   case Type::VariableArray:
9731   case Type::FunctionProto:
9732   case Type::ExtVector:
9733     llvm_unreachable("Types are eliminated above");
9734 
9735   case Type::Pointer:
9736   {
9737     // Merge two pointer types, while trying to preserve typedef info
9738     QualType LHSPointee = LHS->castAs<PointerType>()->getPointeeType();
9739     QualType RHSPointee = RHS->castAs<PointerType>()->getPointeeType();
9740     if (Unqualified) {
9741       LHSPointee = LHSPointee.getUnqualifiedType();
9742       RHSPointee = RHSPointee.getUnqualifiedType();
9743     }
9744     QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
9745                                      Unqualified);
9746     if (ResultType.isNull())
9747       return {};
9748     if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
9749       return LHS;
9750     if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
9751       return RHS;
9752     return getPointerType(ResultType);
9753   }
9754   case Type::BlockPointer:
9755   {
9756     // Merge two block pointer types, while trying to preserve typedef info
9757     QualType LHSPointee = LHS->castAs<BlockPointerType>()->getPointeeType();
9758     QualType RHSPointee = RHS->castAs<BlockPointerType>()->getPointeeType();
9759     if (Unqualified) {
9760       LHSPointee = LHSPointee.getUnqualifiedType();
9761       RHSPointee = RHSPointee.getUnqualifiedType();
9762     }
9763     if (getLangOpts().OpenCL) {
9764       Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
9765       Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
9766       // Blocks can't be an expression in a ternary operator (OpenCL v2.0
9767       // 6.12.5) thus the following check is asymmetric.
9768       if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual))
9769         return {};
9770       LHSPteeQual.removeAddressSpace();
9771       RHSPteeQual.removeAddressSpace();
9772       LHSPointee =
9773           QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
9774       RHSPointee =
9775           QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
9776     }
9777     QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
9778                                      Unqualified);
9779     if (ResultType.isNull())
9780       return {};
9781     if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
9782       return LHS;
9783     if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
9784       return RHS;
9785     return getBlockPointerType(ResultType);
9786   }
9787   case Type::Atomic:
9788   {
9789     // Merge two pointer types, while trying to preserve typedef info
9790     QualType LHSValue = LHS->castAs<AtomicType>()->getValueType();
9791     QualType RHSValue = RHS->castAs<AtomicType>()->getValueType();
9792     if (Unqualified) {
9793       LHSValue = LHSValue.getUnqualifiedType();
9794       RHSValue = RHSValue.getUnqualifiedType();
9795     }
9796     QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
9797                                      Unqualified);
9798     if (ResultType.isNull())
9799       return {};
9800     if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
9801       return LHS;
9802     if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
9803       return RHS;
9804     return getAtomicType(ResultType);
9805   }
9806   case Type::ConstantArray:
9807   {
9808     const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
9809     const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
9810     if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
9811       return {};
9812 
9813     QualType LHSElem = getAsArrayType(LHS)->getElementType();
9814     QualType RHSElem = getAsArrayType(RHS)->getElementType();
9815     if (Unqualified) {
9816       LHSElem = LHSElem.getUnqualifiedType();
9817       RHSElem = RHSElem.getUnqualifiedType();
9818     }
9819 
9820     QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
9821     if (ResultType.isNull())
9822       return {};
9823 
9824     const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
9825     const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
9826 
9827     // If either side is a variable array, and both are complete, check whether
9828     // the current dimension is definite.
9829     if (LVAT || RVAT) {
9830       auto SizeFetch = [this](const VariableArrayType* VAT,
9831           const ConstantArrayType* CAT)
9832           -> std::pair<bool,llvm::APInt> {
9833         if (VAT) {
9834           Optional<llvm::APSInt> TheInt;
9835           Expr *E = VAT->getSizeExpr();
9836           if (E && (TheInt = E->getIntegerConstantExpr(*this)))
9837             return std::make_pair(true, *TheInt);
9838           return std::make_pair(false, llvm::APSInt());
9839         }
9840         if (CAT)
9841           return std::make_pair(true, CAT->getSize());
9842         return std::make_pair(false, llvm::APInt());
9843       };
9844 
9845       bool HaveLSize, HaveRSize;
9846       llvm::APInt LSize, RSize;
9847       std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT);
9848       std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT);
9849       if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize))
9850         return {}; // Definite, but unequal, array dimension
9851     }
9852 
9853     if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
9854       return LHS;
9855     if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
9856       return RHS;
9857     if (LCAT)
9858       return getConstantArrayType(ResultType, LCAT->getSize(),
9859                                   LCAT->getSizeExpr(),
9860                                   ArrayType::ArraySizeModifier(), 0);
9861     if (RCAT)
9862       return getConstantArrayType(ResultType, RCAT->getSize(),
9863                                   RCAT->getSizeExpr(),
9864                                   ArrayType::ArraySizeModifier(), 0);
9865     if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
9866       return LHS;
9867     if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
9868       return RHS;
9869     if (LVAT) {
9870       // FIXME: This isn't correct! But tricky to implement because
9871       // the array's size has to be the size of LHS, but the type
9872       // has to be different.
9873       return LHS;
9874     }
9875     if (RVAT) {
9876       // FIXME: This isn't correct! But tricky to implement because
9877       // the array's size has to be the size of RHS, but the type
9878       // has to be different.
9879       return RHS;
9880     }
9881     if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
9882     if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
9883     return getIncompleteArrayType(ResultType,
9884                                   ArrayType::ArraySizeModifier(), 0);
9885   }
9886   case Type::FunctionNoProto:
9887     return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
9888   case Type::Record:
9889   case Type::Enum:
9890     return {};
9891   case Type::Builtin:
9892     // Only exactly equal builtin types are compatible, which is tested above.
9893     return {};
9894   case Type::Complex:
9895     // Distinct complex types are incompatible.
9896     return {};
9897   case Type::Vector:
9898     // FIXME: The merged type should be an ExtVector!
9899     if (areCompatVectorTypes(LHSCan->castAs<VectorType>(),
9900                              RHSCan->castAs<VectorType>()))
9901       return LHS;
9902     return {};
9903   case Type::ConstantMatrix:
9904     if (areCompatMatrixTypes(LHSCan->castAs<ConstantMatrixType>(),
9905                              RHSCan->castAs<ConstantMatrixType>()))
9906       return LHS;
9907     return {};
9908   case Type::ObjCObject: {
9909     // Check if the types are assignment compatible.
9910     // FIXME: This should be type compatibility, e.g. whether
9911     // "LHS x; RHS x;" at global scope is legal.
9912     if (canAssignObjCInterfaces(LHS->castAs<ObjCObjectType>(),
9913                                 RHS->castAs<ObjCObjectType>()))
9914       return LHS;
9915     return {};
9916   }
9917   case Type::ObjCObjectPointer:
9918     if (OfBlockPointer) {
9919       if (canAssignObjCInterfacesInBlockPointer(
9920               LHS->castAs<ObjCObjectPointerType>(),
9921               RHS->castAs<ObjCObjectPointerType>(), BlockReturnType))
9922         return LHS;
9923       return {};
9924     }
9925     if (canAssignObjCInterfaces(LHS->castAs<ObjCObjectPointerType>(),
9926                                 RHS->castAs<ObjCObjectPointerType>()))
9927       return LHS;
9928     return {};
9929   case Type::Pipe:
9930     assert(LHS != RHS &&
9931            "Equivalent pipe types should have already been handled!");
9932     return {};
9933   case Type::ExtInt: {
9934     // Merge two ext-int types, while trying to preserve typedef info.
9935     bool LHSUnsigned  = LHS->castAs<ExtIntType>()->isUnsigned();
9936     bool RHSUnsigned = RHS->castAs<ExtIntType>()->isUnsigned();
9937     unsigned LHSBits = LHS->castAs<ExtIntType>()->getNumBits();
9938     unsigned RHSBits = RHS->castAs<ExtIntType>()->getNumBits();
9939 
9940     // Like unsigned/int, shouldn't have a type if they dont match.
9941     if (LHSUnsigned != RHSUnsigned)
9942       return {};
9943 
9944     if (LHSBits != RHSBits)
9945       return {};
9946     return LHS;
9947   }
9948   }
9949 
9950   llvm_unreachable("Invalid Type::Class!");
9951 }
9952 
9953 bool ASTContext::mergeExtParameterInfo(
9954     const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
9955     bool &CanUseFirst, bool &CanUseSecond,
9956     SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos) {
9957   assert(NewParamInfos.empty() && "param info list not empty");
9958   CanUseFirst = CanUseSecond = true;
9959   bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
9960   bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
9961 
9962   // Fast path: if the first type doesn't have ext parameter infos,
9963   // we match if and only if the second type also doesn't have them.
9964   if (!FirstHasInfo && !SecondHasInfo)
9965     return true;
9966 
9967   bool NeedParamInfo = false;
9968   size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
9969                           : SecondFnType->getExtParameterInfos().size();
9970 
9971   for (size_t I = 0; I < E; ++I) {
9972     FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
9973     if (FirstHasInfo)
9974       FirstParam = FirstFnType->getExtParameterInfo(I);
9975     if (SecondHasInfo)
9976       SecondParam = SecondFnType->getExtParameterInfo(I);
9977 
9978     // Cannot merge unless everything except the noescape flag matches.
9979     if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false))
9980       return false;
9981 
9982     bool FirstNoEscape = FirstParam.isNoEscape();
9983     bool SecondNoEscape = SecondParam.isNoEscape();
9984     bool IsNoEscape = FirstNoEscape && SecondNoEscape;
9985     NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape));
9986     if (NewParamInfos.back().getOpaqueValue())
9987       NeedParamInfo = true;
9988     if (FirstNoEscape != IsNoEscape)
9989       CanUseFirst = false;
9990     if (SecondNoEscape != IsNoEscape)
9991       CanUseSecond = false;
9992   }
9993 
9994   if (!NeedParamInfo)
9995     NewParamInfos.clear();
9996 
9997   return true;
9998 }
9999 
10000 void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) {
10001   ObjCLayouts[CD] = nullptr;
10002 }
10003 
10004 /// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
10005 /// 'RHS' attributes and returns the merged version; including for function
10006 /// return types.
10007 QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
10008   QualType LHSCan = getCanonicalType(LHS),
10009   RHSCan = getCanonicalType(RHS);
10010   // If two types are identical, they are compatible.
10011   if (LHSCan == RHSCan)
10012     return LHS;
10013   if (RHSCan->isFunctionType()) {
10014     if (!LHSCan->isFunctionType())
10015       return {};
10016     QualType OldReturnType =
10017         cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
10018     QualType NewReturnType =
10019         cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
10020     QualType ResReturnType =
10021       mergeObjCGCQualifiers(NewReturnType, OldReturnType);
10022     if (ResReturnType.isNull())
10023       return {};
10024     if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
10025       // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
10026       // In either case, use OldReturnType to build the new function type.
10027       const auto *F = LHS->castAs<FunctionType>();
10028       if (const auto *FPT = cast<FunctionProtoType>(F)) {
10029         FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10030         EPI.ExtInfo = getFunctionExtInfo(LHS);
10031         QualType ResultType =
10032             getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
10033         return ResultType;
10034       }
10035     }
10036     return {};
10037   }
10038 
10039   // If the qualifiers are different, the types can still be merged.
10040   Qualifiers LQuals = LHSCan.getLocalQualifiers();
10041   Qualifiers RQuals = RHSCan.getLocalQualifiers();
10042   if (LQuals != RQuals) {
10043     // If any of these qualifiers are different, we have a type mismatch.
10044     if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
10045         LQuals.getAddressSpace() != RQuals.getAddressSpace())
10046       return {};
10047 
10048     // Exactly one GC qualifier difference is allowed: __strong is
10049     // okay if the other type has no GC qualifier but is an Objective
10050     // C object pointer (i.e. implicitly strong by default).  We fix
10051     // this by pretending that the unqualified type was actually
10052     // qualified __strong.
10053     Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
10054     Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
10055     assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
10056 
10057     if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
10058       return {};
10059 
10060     if (GC_L == Qualifiers::Strong)
10061       return LHS;
10062     if (GC_R == Qualifiers::Strong)
10063       return RHS;
10064     return {};
10065   }
10066 
10067   if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
10068     QualType LHSBaseQT = LHS->castAs<ObjCObjectPointerType>()->getPointeeType();
10069     QualType RHSBaseQT = RHS->castAs<ObjCObjectPointerType>()->getPointeeType();
10070     QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
10071     if (ResQT == LHSBaseQT)
10072       return LHS;
10073     if (ResQT == RHSBaseQT)
10074       return RHS;
10075   }
10076   return {};
10077 }
10078 
10079 //===----------------------------------------------------------------------===//
10080 //                         Integer Predicates
10081 //===----------------------------------------------------------------------===//
10082 
10083 unsigned ASTContext::getIntWidth(QualType T) const {
10084   if (const auto *ET = T->getAs<EnumType>())
10085     T = ET->getDecl()->getIntegerType();
10086   if (T->isBooleanType())
10087     return 1;
10088   if(const auto *EIT = T->getAs<ExtIntType>())
10089     return EIT->getNumBits();
10090   // For builtin types, just use the standard type sizing method
10091   return (unsigned)getTypeSize(T);
10092 }
10093 
10094 QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
10095   assert((T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) &&
10096          "Unexpected type");
10097 
10098   // Turn <4 x signed int> -> <4 x unsigned int>
10099   if (const auto *VTy = T->getAs<VectorType>())
10100     return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
10101                          VTy->getNumElements(), VTy->getVectorKind());
10102 
10103   // For _ExtInt, return an unsigned _ExtInt with same width.
10104   if (const auto *EITy = T->getAs<ExtIntType>())
10105     return getExtIntType(/*IsUnsigned=*/true, EITy->getNumBits());
10106 
10107   // For enums, get the underlying integer type of the enum, and let the general
10108   // integer type signchanging code handle it.
10109   if (const auto *ETy = T->getAs<EnumType>())
10110     T = ETy->getDecl()->getIntegerType();
10111 
10112   switch (T->castAs<BuiltinType>()->getKind()) {
10113   case BuiltinType::Char_S:
10114   case BuiltinType::SChar:
10115     return UnsignedCharTy;
10116   case BuiltinType::Short:
10117     return UnsignedShortTy;
10118   case BuiltinType::Int:
10119     return UnsignedIntTy;
10120   case BuiltinType::Long:
10121     return UnsignedLongTy;
10122   case BuiltinType::LongLong:
10123     return UnsignedLongLongTy;
10124   case BuiltinType::Int128:
10125     return UnsignedInt128Ty;
10126   // wchar_t is special. It is either signed or not, but when it's signed,
10127   // there's no matching "unsigned wchar_t". Therefore we return the unsigned
10128   // version of it's underlying type instead.
10129   case BuiltinType::WChar_S:
10130     return getUnsignedWCharType();
10131 
10132   case BuiltinType::ShortAccum:
10133     return UnsignedShortAccumTy;
10134   case BuiltinType::Accum:
10135     return UnsignedAccumTy;
10136   case BuiltinType::LongAccum:
10137     return UnsignedLongAccumTy;
10138   case BuiltinType::SatShortAccum:
10139     return SatUnsignedShortAccumTy;
10140   case BuiltinType::SatAccum:
10141     return SatUnsignedAccumTy;
10142   case BuiltinType::SatLongAccum:
10143     return SatUnsignedLongAccumTy;
10144   case BuiltinType::ShortFract:
10145     return UnsignedShortFractTy;
10146   case BuiltinType::Fract:
10147     return UnsignedFractTy;
10148   case BuiltinType::LongFract:
10149     return UnsignedLongFractTy;
10150   case BuiltinType::SatShortFract:
10151     return SatUnsignedShortFractTy;
10152   case BuiltinType::SatFract:
10153     return SatUnsignedFractTy;
10154   case BuiltinType::SatLongFract:
10155     return SatUnsignedLongFractTy;
10156   default:
10157     llvm_unreachable("Unexpected signed integer or fixed point type");
10158   }
10159 }
10160 
10161 QualType ASTContext::getCorrespondingSignedType(QualType T) const {
10162   assert((T->hasUnsignedIntegerRepresentation() ||
10163           T->isUnsignedFixedPointType()) &&
10164          "Unexpected type");
10165 
10166   // Turn <4 x unsigned int> -> <4 x signed int>
10167   if (const auto *VTy = T->getAs<VectorType>())
10168     return getVectorType(getCorrespondingSignedType(VTy->getElementType()),
10169                          VTy->getNumElements(), VTy->getVectorKind());
10170 
10171   // For _ExtInt, return a signed _ExtInt with same width.
10172   if (const auto *EITy = T->getAs<ExtIntType>())
10173     return getExtIntType(/*IsUnsigned=*/false, EITy->getNumBits());
10174 
10175   // For enums, get the underlying integer type of the enum, and let the general
10176   // integer type signchanging code handle it.
10177   if (const auto *ETy = T->getAs<EnumType>())
10178     T = ETy->getDecl()->getIntegerType();
10179 
10180   switch (T->castAs<BuiltinType>()->getKind()) {
10181   case BuiltinType::Char_U:
10182   case BuiltinType::UChar:
10183     return SignedCharTy;
10184   case BuiltinType::UShort:
10185     return ShortTy;
10186   case BuiltinType::UInt:
10187     return IntTy;
10188   case BuiltinType::ULong:
10189     return LongTy;
10190   case BuiltinType::ULongLong:
10191     return LongLongTy;
10192   case BuiltinType::UInt128:
10193     return Int128Ty;
10194   // wchar_t is special. It is either unsigned or not, but when it's unsigned,
10195   // there's no matching "signed wchar_t". Therefore we return the signed
10196   // version of it's underlying type instead.
10197   case BuiltinType::WChar_U:
10198     return getSignedWCharType();
10199 
10200   case BuiltinType::UShortAccum:
10201     return ShortAccumTy;
10202   case BuiltinType::UAccum:
10203     return AccumTy;
10204   case BuiltinType::ULongAccum:
10205     return LongAccumTy;
10206   case BuiltinType::SatUShortAccum:
10207     return SatShortAccumTy;
10208   case BuiltinType::SatUAccum:
10209     return SatAccumTy;
10210   case BuiltinType::SatULongAccum:
10211     return SatLongAccumTy;
10212   case BuiltinType::UShortFract:
10213     return ShortFractTy;
10214   case BuiltinType::UFract:
10215     return FractTy;
10216   case BuiltinType::ULongFract:
10217     return LongFractTy;
10218   case BuiltinType::SatUShortFract:
10219     return SatShortFractTy;
10220   case BuiltinType::SatUFract:
10221     return SatFractTy;
10222   case BuiltinType::SatULongFract:
10223     return SatLongFractTy;
10224   default:
10225     llvm_unreachable("Unexpected unsigned integer or fixed point type");
10226   }
10227 }
10228 
10229 ASTMutationListener::~ASTMutationListener() = default;
10230 
10231 void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
10232                                             QualType ReturnType) {}
10233 
10234 //===----------------------------------------------------------------------===//
10235 //                          Builtin Type Computation
10236 //===----------------------------------------------------------------------===//
10237 
10238 /// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
10239 /// pointer over the consumed characters.  This returns the resultant type.  If
10240 /// AllowTypeModifiers is false then modifier like * are not parsed, just basic
10241 /// types.  This allows "v2i*" to be parsed as a pointer to a v2i instead of
10242 /// a vector of "i*".
10243 ///
10244 /// RequiresICE is filled in on return to indicate whether the value is required
10245 /// to be an Integer Constant Expression.
10246 static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
10247                                   ASTContext::GetBuiltinTypeError &Error,
10248                                   bool &RequiresICE,
10249                                   bool AllowTypeModifiers) {
10250   // Modifiers.
10251   int HowLong = 0;
10252   bool Signed = false, Unsigned = false;
10253   RequiresICE = false;
10254 
10255   // Read the prefixed modifiers first.
10256   bool Done = false;
10257   #ifndef NDEBUG
10258   bool IsSpecial = false;
10259   #endif
10260   while (!Done) {
10261     switch (*Str++) {
10262     default: Done = true; --Str; break;
10263     case 'I':
10264       RequiresICE = true;
10265       break;
10266     case 'S':
10267       assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
10268       assert(!Signed && "Can't use 'S' modifier multiple times!");
10269       Signed = true;
10270       break;
10271     case 'U':
10272       assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
10273       assert(!Unsigned && "Can't use 'U' modifier multiple times!");
10274       Unsigned = true;
10275       break;
10276     case 'L':
10277       assert(!IsSpecial && "Can't use 'L' with 'W', 'N', 'Z' or 'O' modifiers");
10278       assert(HowLong <= 2 && "Can't have LLLL modifier");
10279       ++HowLong;
10280       break;
10281     case 'N':
10282       // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
10283       assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
10284       assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
10285       #ifndef NDEBUG
10286       IsSpecial = true;
10287       #endif
10288       if (Context.getTargetInfo().getLongWidth() == 32)
10289         ++HowLong;
10290       break;
10291     case 'W':
10292       // This modifier represents int64 type.
10293       assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
10294       assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
10295       #ifndef NDEBUG
10296       IsSpecial = true;
10297       #endif
10298       switch (Context.getTargetInfo().getInt64Type()) {
10299       default:
10300         llvm_unreachable("Unexpected integer type");
10301       case TargetInfo::SignedLong:
10302         HowLong = 1;
10303         break;
10304       case TargetInfo::SignedLongLong:
10305         HowLong = 2;
10306         break;
10307       }
10308       break;
10309     case 'Z':
10310       // This modifier represents int32 type.
10311       assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
10312       assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!");
10313       #ifndef NDEBUG
10314       IsSpecial = true;
10315       #endif
10316       switch (Context.getTargetInfo().getIntTypeByWidth(32, true)) {
10317       default:
10318         llvm_unreachable("Unexpected integer type");
10319       case TargetInfo::SignedInt:
10320         HowLong = 0;
10321         break;
10322       case TargetInfo::SignedLong:
10323         HowLong = 1;
10324         break;
10325       case TargetInfo::SignedLongLong:
10326         HowLong = 2;
10327         break;
10328       }
10329       break;
10330     case 'O':
10331       assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
10332       assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!");
10333       #ifndef NDEBUG
10334       IsSpecial = true;
10335       #endif
10336       if (Context.getLangOpts().OpenCL)
10337         HowLong = 1;
10338       else
10339         HowLong = 2;
10340       break;
10341     }
10342   }
10343 
10344   QualType Type;
10345 
10346   // Read the base type.
10347   switch (*Str++) {
10348   default: llvm_unreachable("Unknown builtin type letter!");
10349   case 'y':
10350     assert(HowLong == 0 && !Signed && !Unsigned &&
10351            "Bad modifiers used with 'y'!");
10352     Type = Context.BFloat16Ty;
10353     break;
10354   case 'v':
10355     assert(HowLong == 0 && !Signed && !Unsigned &&
10356            "Bad modifiers used with 'v'!");
10357     Type = Context.VoidTy;
10358     break;
10359   case 'h':
10360     assert(HowLong == 0 && !Signed && !Unsigned &&
10361            "Bad modifiers used with 'h'!");
10362     Type = Context.HalfTy;
10363     break;
10364   case 'f':
10365     assert(HowLong == 0 && !Signed && !Unsigned &&
10366            "Bad modifiers used with 'f'!");
10367     Type = Context.FloatTy;
10368     break;
10369   case 'd':
10370     assert(HowLong < 3 && !Signed && !Unsigned &&
10371            "Bad modifiers used with 'd'!");
10372     if (HowLong == 1)
10373       Type = Context.LongDoubleTy;
10374     else if (HowLong == 2)
10375       Type = Context.Float128Ty;
10376     else
10377       Type = Context.DoubleTy;
10378     break;
10379   case 's':
10380     assert(HowLong == 0 && "Bad modifiers used with 's'!");
10381     if (Unsigned)
10382       Type = Context.UnsignedShortTy;
10383     else
10384       Type = Context.ShortTy;
10385     break;
10386   case 'i':
10387     if (HowLong == 3)
10388       Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
10389     else if (HowLong == 2)
10390       Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
10391     else if (HowLong == 1)
10392       Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
10393     else
10394       Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
10395     break;
10396   case 'c':
10397     assert(HowLong == 0 && "Bad modifiers used with 'c'!");
10398     if (Signed)
10399       Type = Context.SignedCharTy;
10400     else if (Unsigned)
10401       Type = Context.UnsignedCharTy;
10402     else
10403       Type = Context.CharTy;
10404     break;
10405   case 'b': // boolean
10406     assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
10407     Type = Context.BoolTy;
10408     break;
10409   case 'z':  // size_t.
10410     assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
10411     Type = Context.getSizeType();
10412     break;
10413   case 'w':  // wchar_t.
10414     assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
10415     Type = Context.getWideCharType();
10416     break;
10417   case 'F':
10418     Type = Context.getCFConstantStringType();
10419     break;
10420   case 'G':
10421     Type = Context.getObjCIdType();
10422     break;
10423   case 'H':
10424     Type = Context.getObjCSelType();
10425     break;
10426   case 'M':
10427     Type = Context.getObjCSuperType();
10428     break;
10429   case 'a':
10430     Type = Context.getBuiltinVaListType();
10431     assert(!Type.isNull() && "builtin va list type not initialized!");
10432     break;
10433   case 'A':
10434     // This is a "reference" to a va_list; however, what exactly
10435     // this means depends on how va_list is defined. There are two
10436     // different kinds of va_list: ones passed by value, and ones
10437     // passed by reference.  An example of a by-value va_list is
10438     // x86, where va_list is a char*. An example of by-ref va_list
10439     // is x86-64, where va_list is a __va_list_tag[1]. For x86,
10440     // we want this argument to be a char*&; for x86-64, we want
10441     // it to be a __va_list_tag*.
10442     Type = Context.getBuiltinVaListType();
10443     assert(!Type.isNull() && "builtin va list type not initialized!");
10444     if (Type->isArrayType())
10445       Type = Context.getArrayDecayedType(Type);
10446     else
10447       Type = Context.getLValueReferenceType(Type);
10448     break;
10449   case 'q': {
10450     char *End;
10451     unsigned NumElements = strtoul(Str, &End, 10);
10452     assert(End != Str && "Missing vector size");
10453     Str = End;
10454 
10455     QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
10456                                              RequiresICE, false);
10457     assert(!RequiresICE && "Can't require vector ICE");
10458 
10459     Type = Context.getScalableVectorType(ElementType, NumElements);
10460     break;
10461   }
10462   case 'V': {
10463     char *End;
10464     unsigned NumElements = strtoul(Str, &End, 10);
10465     assert(End != Str && "Missing vector size");
10466     Str = End;
10467 
10468     QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
10469                                              RequiresICE, false);
10470     assert(!RequiresICE && "Can't require vector ICE");
10471 
10472     // TODO: No way to make AltiVec vectors in builtins yet.
10473     Type = Context.getVectorType(ElementType, NumElements,
10474                                  VectorType::GenericVector);
10475     break;
10476   }
10477   case 'E': {
10478     char *End;
10479 
10480     unsigned NumElements = strtoul(Str, &End, 10);
10481     assert(End != Str && "Missing vector size");
10482 
10483     Str = End;
10484 
10485     QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
10486                                              false);
10487     Type = Context.getExtVectorType(ElementType, NumElements);
10488     break;
10489   }
10490   case 'X': {
10491     QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
10492                                              false);
10493     assert(!RequiresICE && "Can't require complex ICE");
10494     Type = Context.getComplexType(ElementType);
10495     break;
10496   }
10497   case 'Y':
10498     Type = Context.getPointerDiffType();
10499     break;
10500   case 'P':
10501     Type = Context.getFILEType();
10502     if (Type.isNull()) {
10503       Error = ASTContext::GE_Missing_stdio;
10504       return {};
10505     }
10506     break;
10507   case 'J':
10508     if (Signed)
10509       Type = Context.getsigjmp_bufType();
10510     else
10511       Type = Context.getjmp_bufType();
10512 
10513     if (Type.isNull()) {
10514       Error = ASTContext::GE_Missing_setjmp;
10515       return {};
10516     }
10517     break;
10518   case 'K':
10519     assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
10520     Type = Context.getucontext_tType();
10521 
10522     if (Type.isNull()) {
10523       Error = ASTContext::GE_Missing_ucontext;
10524       return {};
10525     }
10526     break;
10527   case 'p':
10528     Type = Context.getProcessIDType();
10529     break;
10530   }
10531 
10532   // If there are modifiers and if we're allowed to parse them, go for it.
10533   Done = !AllowTypeModifiers;
10534   while (!Done) {
10535     switch (char c = *Str++) {
10536     default: Done = true; --Str; break;
10537     case '*':
10538     case '&': {
10539       // Both pointers and references can have their pointee types
10540       // qualified with an address space.
10541       char *End;
10542       unsigned AddrSpace = strtoul(Str, &End, 10);
10543       if (End != Str) {
10544         // Note AddrSpace == 0 is not the same as an unspecified address space.
10545         Type = Context.getAddrSpaceQualType(
10546           Type,
10547           Context.getLangASForBuiltinAddressSpace(AddrSpace));
10548         Str = End;
10549       }
10550       if (c == '*')
10551         Type = Context.getPointerType(Type);
10552       else
10553         Type = Context.getLValueReferenceType(Type);
10554       break;
10555     }
10556     // FIXME: There's no way to have a built-in with an rvalue ref arg.
10557     case 'C':
10558       Type = Type.withConst();
10559       break;
10560     case 'D':
10561       Type = Context.getVolatileType(Type);
10562       break;
10563     case 'R':
10564       Type = Type.withRestrict();
10565       break;
10566     }
10567   }
10568 
10569   assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
10570          "Integer constant 'I' type must be an integer");
10571 
10572   return Type;
10573 }
10574 
10575 // On some targets such as PowerPC, some of the builtins are defined with custom
10576 // type decriptors for target-dependent types. These descriptors are decoded in
10577 // other functions, but it may be useful to be able to fall back to default
10578 // descriptor decoding to define builtins mixing target-dependent and target-
10579 // independent types. This function allows decoding one type descriptor with
10580 // default decoding.
10581 QualType ASTContext::DecodeTypeStr(const char *&Str, const ASTContext &Context,
10582                                    GetBuiltinTypeError &Error, bool &RequireICE,
10583                                    bool AllowTypeModifiers) const {
10584   return DecodeTypeFromStr(Str, Context, Error, RequireICE, AllowTypeModifiers);
10585 }
10586 
10587 /// GetBuiltinType - Return the type for the specified builtin.
10588 QualType ASTContext::GetBuiltinType(unsigned Id,
10589                                     GetBuiltinTypeError &Error,
10590                                     unsigned *IntegerConstantArgs) const {
10591   const char *TypeStr = BuiltinInfo.getTypeString(Id);
10592   if (TypeStr[0] == '\0') {
10593     Error = GE_Missing_type;
10594     return {};
10595   }
10596 
10597   SmallVector<QualType, 8> ArgTypes;
10598 
10599   bool RequiresICE = false;
10600   Error = GE_None;
10601   QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
10602                                        RequiresICE, true);
10603   if (Error != GE_None)
10604     return {};
10605 
10606   assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
10607 
10608   while (TypeStr[0] && TypeStr[0] != '.') {
10609     QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
10610     if (Error != GE_None)
10611       return {};
10612 
10613     // If this argument is required to be an IntegerConstantExpression and the
10614     // caller cares, fill in the bitmask we return.
10615     if (RequiresICE && IntegerConstantArgs)
10616       *IntegerConstantArgs |= 1 << ArgTypes.size();
10617 
10618     // Do array -> pointer decay.  The builtin should use the decayed type.
10619     if (Ty->isArrayType())
10620       Ty = getArrayDecayedType(Ty);
10621 
10622     ArgTypes.push_back(Ty);
10623   }
10624 
10625   if (Id == Builtin::BI__GetExceptionInfo)
10626     return {};
10627 
10628   assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
10629          "'.' should only occur at end of builtin type list!");
10630 
10631   bool Variadic = (TypeStr[0] == '.');
10632 
10633   FunctionType::ExtInfo EI(getDefaultCallingConvention(
10634       Variadic, /*IsCXXMethod=*/false, /*IsBuiltin=*/true));
10635   if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
10636 
10637 
10638   // We really shouldn't be making a no-proto type here.
10639   if (ArgTypes.empty() && Variadic && !getLangOpts().CPlusPlus)
10640     return getFunctionNoProtoType(ResType, EI);
10641 
10642   FunctionProtoType::ExtProtoInfo EPI;
10643   EPI.ExtInfo = EI;
10644   EPI.Variadic = Variadic;
10645   if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id))
10646     EPI.ExceptionSpec.Type =
10647         getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
10648 
10649   return getFunctionType(ResType, ArgTypes, EPI);
10650 }
10651 
10652 static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
10653                                              const FunctionDecl *FD) {
10654   if (!FD->isExternallyVisible())
10655     return GVA_Internal;
10656 
10657   // Non-user-provided functions get emitted as weak definitions with every
10658   // use, no matter whether they've been explicitly instantiated etc.
10659   if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
10660     if (!MD->isUserProvided())
10661       return GVA_DiscardableODR;
10662 
10663   GVALinkage External;
10664   switch (FD->getTemplateSpecializationKind()) {
10665   case TSK_Undeclared:
10666   case TSK_ExplicitSpecialization:
10667     External = GVA_StrongExternal;
10668     break;
10669 
10670   case TSK_ExplicitInstantiationDefinition:
10671     return GVA_StrongODR;
10672 
10673   // C++11 [temp.explicit]p10:
10674   //   [ Note: The intent is that an inline function that is the subject of
10675   //   an explicit instantiation declaration will still be implicitly
10676   //   instantiated when used so that the body can be considered for
10677   //   inlining, but that no out-of-line copy of the inline function would be
10678   //   generated in the translation unit. -- end note ]
10679   case TSK_ExplicitInstantiationDeclaration:
10680     return GVA_AvailableExternally;
10681 
10682   case TSK_ImplicitInstantiation:
10683     External = GVA_DiscardableODR;
10684     break;
10685   }
10686 
10687   if (!FD->isInlined())
10688     return External;
10689 
10690   if ((!Context.getLangOpts().CPlusPlus &&
10691        !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
10692        !FD->hasAttr<DLLExportAttr>()) ||
10693       FD->hasAttr<GNUInlineAttr>()) {
10694     // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
10695 
10696     // GNU or C99 inline semantics. Determine whether this symbol should be
10697     // externally visible.
10698     if (FD->isInlineDefinitionExternallyVisible())
10699       return External;
10700 
10701     // C99 inline semantics, where the symbol is not externally visible.
10702     return GVA_AvailableExternally;
10703   }
10704 
10705   // Functions specified with extern and inline in -fms-compatibility mode
10706   // forcibly get emitted.  While the body of the function cannot be later
10707   // replaced, the function definition cannot be discarded.
10708   if (FD->isMSExternInline())
10709     return GVA_StrongODR;
10710 
10711   return GVA_DiscardableODR;
10712 }
10713 
10714 static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context,
10715                                                 const Decl *D, GVALinkage L) {
10716   // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
10717   // dllexport/dllimport on inline functions.
10718   if (D->hasAttr<DLLImportAttr>()) {
10719     if (L == GVA_DiscardableODR || L == GVA_StrongODR)
10720       return GVA_AvailableExternally;
10721   } else if (D->hasAttr<DLLExportAttr>()) {
10722     if (L == GVA_DiscardableODR)
10723       return GVA_StrongODR;
10724   } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice) {
10725     // Device-side functions with __global__ attribute must always be
10726     // visible externally so they can be launched from host.
10727     if (D->hasAttr<CUDAGlobalAttr>() &&
10728         (L == GVA_DiscardableODR || L == GVA_Internal))
10729       return GVA_StrongODR;
10730     // Single source offloading languages like CUDA/HIP need to be able to
10731     // access static device variables from host code of the same compilation
10732     // unit. This is done by externalizing the static variable with a shared
10733     // name between the host and device compilation which is the same for the
10734     // same compilation unit whereas different among different compilation
10735     // units.
10736     if (Context.shouldExternalizeStaticVar(D))
10737       return GVA_StrongExternal;
10738   }
10739   return L;
10740 }
10741 
10742 /// Adjust the GVALinkage for a declaration based on what an external AST source
10743 /// knows about whether there can be other definitions of this declaration.
10744 static GVALinkage
10745 adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D,
10746                                           GVALinkage L) {
10747   ExternalASTSource *Source = Ctx.getExternalSource();
10748   if (!Source)
10749     return L;
10750 
10751   switch (Source->hasExternalDefinitions(D)) {
10752   case ExternalASTSource::EK_Never:
10753     // Other translation units rely on us to provide the definition.
10754     if (L == GVA_DiscardableODR)
10755       return GVA_StrongODR;
10756     break;
10757 
10758   case ExternalASTSource::EK_Always:
10759     return GVA_AvailableExternally;
10760 
10761   case ExternalASTSource::EK_ReplyHazy:
10762     break;
10763   }
10764   return L;
10765 }
10766 
10767 GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
10768   return adjustGVALinkageForExternalDefinitionKind(*this, FD,
10769            adjustGVALinkageForAttributes(*this, FD,
10770              basicGVALinkageForFunction(*this, FD)));
10771 }
10772 
10773 static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
10774                                              const VarDecl *VD) {
10775   if (!VD->isExternallyVisible())
10776     return GVA_Internal;
10777 
10778   if (VD->isStaticLocal()) {
10779     const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
10780     while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
10781       LexicalContext = LexicalContext->getLexicalParent();
10782 
10783     // ObjC Blocks can create local variables that don't have a FunctionDecl
10784     // LexicalContext.
10785     if (!LexicalContext)
10786       return GVA_DiscardableODR;
10787 
10788     // Otherwise, let the static local variable inherit its linkage from the
10789     // nearest enclosing function.
10790     auto StaticLocalLinkage =
10791         Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
10792 
10793     // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
10794     // be emitted in any object with references to the symbol for the object it
10795     // contains, whether inline or out-of-line."
10796     // Similar behavior is observed with MSVC. An alternative ABI could use
10797     // StrongODR/AvailableExternally to match the function, but none are
10798     // known/supported currently.
10799     if (StaticLocalLinkage == GVA_StrongODR ||
10800         StaticLocalLinkage == GVA_AvailableExternally)
10801       return GVA_DiscardableODR;
10802     return StaticLocalLinkage;
10803   }
10804 
10805   // MSVC treats in-class initialized static data members as definitions.
10806   // By giving them non-strong linkage, out-of-line definitions won't
10807   // cause link errors.
10808   if (Context.isMSStaticDataMemberInlineDefinition(VD))
10809     return GVA_DiscardableODR;
10810 
10811   // Most non-template variables have strong linkage; inline variables are
10812   // linkonce_odr or (occasionally, for compatibility) weak_odr.
10813   GVALinkage StrongLinkage;
10814   switch (Context.getInlineVariableDefinitionKind(VD)) {
10815   case ASTContext::InlineVariableDefinitionKind::None:
10816     StrongLinkage = GVA_StrongExternal;
10817     break;
10818   case ASTContext::InlineVariableDefinitionKind::Weak:
10819   case ASTContext::InlineVariableDefinitionKind::WeakUnknown:
10820     StrongLinkage = GVA_DiscardableODR;
10821     break;
10822   case ASTContext::InlineVariableDefinitionKind::Strong:
10823     StrongLinkage = GVA_StrongODR;
10824     break;
10825   }
10826 
10827   switch (VD->getTemplateSpecializationKind()) {
10828   case TSK_Undeclared:
10829     return StrongLinkage;
10830 
10831   case TSK_ExplicitSpecialization:
10832     return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
10833                    VD->isStaticDataMember()
10834                ? GVA_StrongODR
10835                : StrongLinkage;
10836 
10837   case TSK_ExplicitInstantiationDefinition:
10838     return GVA_StrongODR;
10839 
10840   case TSK_ExplicitInstantiationDeclaration:
10841     return GVA_AvailableExternally;
10842 
10843   case TSK_ImplicitInstantiation:
10844     return GVA_DiscardableODR;
10845   }
10846 
10847   llvm_unreachable("Invalid Linkage!");
10848 }
10849 
10850 GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
10851   return adjustGVALinkageForExternalDefinitionKind(*this, VD,
10852            adjustGVALinkageForAttributes(*this, VD,
10853              basicGVALinkageForVariable(*this, VD)));
10854 }
10855 
10856 bool ASTContext::DeclMustBeEmitted(const Decl *D) {
10857   if (const auto *VD = dyn_cast<VarDecl>(D)) {
10858     if (!VD->isFileVarDecl())
10859       return false;
10860     // Global named register variables (GNU extension) are never emitted.
10861     if (VD->getStorageClass() == SC_Register)
10862       return false;
10863     if (VD->getDescribedVarTemplate() ||
10864         isa<VarTemplatePartialSpecializationDecl>(VD))
10865       return false;
10866   } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
10867     // We never need to emit an uninstantiated function template.
10868     if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
10869       return false;
10870   } else if (isa<PragmaCommentDecl>(D))
10871     return true;
10872   else if (isa<PragmaDetectMismatchDecl>(D))
10873     return true;
10874   else if (isa<OMPRequiresDecl>(D))
10875     return true;
10876   else if (isa<OMPThreadPrivateDecl>(D))
10877     return !D->getDeclContext()->isDependentContext();
10878   else if (isa<OMPAllocateDecl>(D))
10879     return !D->getDeclContext()->isDependentContext();
10880   else if (isa<OMPDeclareReductionDecl>(D) || isa<OMPDeclareMapperDecl>(D))
10881     return !D->getDeclContext()->isDependentContext();
10882   else if (isa<ImportDecl>(D))
10883     return true;
10884   else
10885     return false;
10886 
10887   // If this is a member of a class template, we do not need to emit it.
10888   if (D->getDeclContext()->isDependentContext())
10889     return false;
10890 
10891   // Weak references don't produce any output by themselves.
10892   if (D->hasAttr<WeakRefAttr>())
10893     return false;
10894 
10895   // Aliases and used decls are required.
10896   if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
10897     return true;
10898 
10899   if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
10900     // Forward declarations aren't required.
10901     if (!FD->doesThisDeclarationHaveABody())
10902       return FD->doesDeclarationForceExternallyVisibleDefinition();
10903 
10904     // Constructors and destructors are required.
10905     if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
10906       return true;
10907 
10908     // The key function for a class is required.  This rule only comes
10909     // into play when inline functions can be key functions, though.
10910     if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
10911       if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
10912         const CXXRecordDecl *RD = MD->getParent();
10913         if (MD->isOutOfLine() && RD->isDynamicClass()) {
10914           const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
10915           if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
10916             return true;
10917         }
10918       }
10919     }
10920 
10921     GVALinkage Linkage = GetGVALinkageForFunction(FD);
10922 
10923     // static, static inline, always_inline, and extern inline functions can
10924     // always be deferred.  Normal inline functions can be deferred in C99/C++.
10925     // Implicit template instantiations can also be deferred in C++.
10926     return !isDiscardableGVALinkage(Linkage);
10927   }
10928 
10929   const auto *VD = cast<VarDecl>(D);
10930   assert(VD->isFileVarDecl() && "Expected file scoped var");
10931 
10932   // If the decl is marked as `declare target to`, it should be emitted for the
10933   // host and for the device.
10934   if (LangOpts.OpenMP &&
10935       OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
10936     return true;
10937 
10938   if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
10939       !isMSStaticDataMemberInlineDefinition(VD))
10940     return false;
10941 
10942   // Variables that can be needed in other TUs are required.
10943   auto Linkage = GetGVALinkageForVariable(VD);
10944   if (!isDiscardableGVALinkage(Linkage))
10945     return true;
10946 
10947   // We never need to emit a variable that is available in another TU.
10948   if (Linkage == GVA_AvailableExternally)
10949     return false;
10950 
10951   // Variables that have destruction with side-effects are required.
10952   if (VD->needsDestruction(*this))
10953     return true;
10954 
10955   // Variables that have initialization with side-effects are required.
10956   if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
10957       // We can get a value-dependent initializer during error recovery.
10958       (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
10959     return true;
10960 
10961   // Likewise, variables with tuple-like bindings are required if their
10962   // bindings have side-effects.
10963   if (const auto *DD = dyn_cast<DecompositionDecl>(VD))
10964     for (const auto *BD : DD->bindings())
10965       if (const auto *BindingVD = BD->getHoldingVar())
10966         if (DeclMustBeEmitted(BindingVD))
10967           return true;
10968 
10969   return false;
10970 }
10971 
10972 void ASTContext::forEachMultiversionedFunctionVersion(
10973     const FunctionDecl *FD,
10974     llvm::function_ref<void(FunctionDecl *)> Pred) const {
10975   assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
10976   llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
10977   FD = FD->getMostRecentDecl();
10978   // FIXME: The order of traversal here matters and depends on the order of
10979   // lookup results, which happens to be (mostly) oldest-to-newest, but we
10980   // shouldn't rely on that.
10981   for (auto *CurDecl :
10982        FD->getDeclContext()->getRedeclContext()->lookup(FD->getDeclName())) {
10983     FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl();
10984     if (CurFD && hasSameType(CurFD->getType(), FD->getType()) &&
10985         std::end(SeenDecls) == llvm::find(SeenDecls, CurFD)) {
10986       SeenDecls.insert(CurFD);
10987       Pred(CurFD);
10988     }
10989   }
10990 }
10991 
10992 CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
10993                                                     bool IsCXXMethod,
10994                                                     bool IsBuiltin) const {
10995   // Pass through to the C++ ABI object
10996   if (IsCXXMethod)
10997     return ABI->getDefaultMethodCallConv(IsVariadic);
10998 
10999   // Builtins ignore user-specified default calling convention and remain the
11000   // Target's default calling convention.
11001   if (!IsBuiltin) {
11002     switch (LangOpts.getDefaultCallingConv()) {
11003     case LangOptions::DCC_None:
11004       break;
11005     case LangOptions::DCC_CDecl:
11006       return CC_C;
11007     case LangOptions::DCC_FastCall:
11008       if (getTargetInfo().hasFeature("sse2") && !IsVariadic)
11009         return CC_X86FastCall;
11010       break;
11011     case LangOptions::DCC_StdCall:
11012       if (!IsVariadic)
11013         return CC_X86StdCall;
11014       break;
11015     case LangOptions::DCC_VectorCall:
11016       // __vectorcall cannot be applied to variadic functions.
11017       if (!IsVariadic)
11018         return CC_X86VectorCall;
11019       break;
11020     case LangOptions::DCC_RegCall:
11021       // __regcall cannot be applied to variadic functions.
11022       if (!IsVariadic)
11023         return CC_X86RegCall;
11024       break;
11025     }
11026   }
11027   return Target->getDefaultCallingConv();
11028 }
11029 
11030 bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
11031   // Pass through to the C++ ABI object
11032   return ABI->isNearlyEmpty(RD);
11033 }
11034 
11035 VTableContextBase *ASTContext::getVTableContext() {
11036   if (!VTContext.get()) {
11037     auto ABI = Target->getCXXABI();
11038     if (ABI.isMicrosoft())
11039       VTContext.reset(new MicrosoftVTableContext(*this));
11040     else {
11041       auto ComponentLayout = getLangOpts().RelativeCXXABIVTables
11042                                  ? ItaniumVTableContext::Relative
11043                                  : ItaniumVTableContext::Pointer;
11044       VTContext.reset(new ItaniumVTableContext(*this, ComponentLayout));
11045     }
11046   }
11047   return VTContext.get();
11048 }
11049 
11050 MangleContext *ASTContext::createMangleContext(const TargetInfo *T) {
11051   if (!T)
11052     T = Target;
11053   switch (T->getCXXABI().getKind()) {
11054   case TargetCXXABI::AppleARM64:
11055   case TargetCXXABI::Fuchsia:
11056   case TargetCXXABI::GenericAArch64:
11057   case TargetCXXABI::GenericItanium:
11058   case TargetCXXABI::GenericARM:
11059   case TargetCXXABI::GenericMIPS:
11060   case TargetCXXABI::iOS:
11061   case TargetCXXABI::WebAssembly:
11062   case TargetCXXABI::WatchOS:
11063   case TargetCXXABI::XL:
11064     return ItaniumMangleContext::create(*this, getDiagnostics());
11065   case TargetCXXABI::Microsoft:
11066     return MicrosoftMangleContext::create(*this, getDiagnostics());
11067   }
11068   llvm_unreachable("Unsupported ABI");
11069 }
11070 
11071 CXXABI::~CXXABI() = default;
11072 
11073 size_t ASTContext::getSideTableAllocatedMemory() const {
11074   return ASTRecordLayouts.getMemorySize() +
11075          llvm::capacity_in_bytes(ObjCLayouts) +
11076          llvm::capacity_in_bytes(KeyFunctions) +
11077          llvm::capacity_in_bytes(ObjCImpls) +
11078          llvm::capacity_in_bytes(BlockVarCopyInits) +
11079          llvm::capacity_in_bytes(DeclAttrs) +
11080          llvm::capacity_in_bytes(TemplateOrInstantiation) +
11081          llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
11082          llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
11083          llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
11084          llvm::capacity_in_bytes(OverriddenMethods) +
11085          llvm::capacity_in_bytes(Types) +
11086          llvm::capacity_in_bytes(VariableArrayTypes);
11087 }
11088 
11089 /// getIntTypeForBitwidth -
11090 /// sets integer QualTy according to specified details:
11091 /// bitwidth, signed/unsigned.
11092 /// Returns empty type if there is no appropriate target types.
11093 QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
11094                                            unsigned Signed) const {
11095   TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
11096   CanQualType QualTy = getFromTargetType(Ty);
11097   if (!QualTy && DestWidth == 128)
11098     return Signed ? Int128Ty : UnsignedInt128Ty;
11099   return QualTy;
11100 }
11101 
11102 /// getRealTypeForBitwidth -
11103 /// sets floating point QualTy according to specified bitwidth.
11104 /// Returns empty type if there is no appropriate target types.
11105 QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth,
11106                                             bool ExplicitIEEE) const {
11107   TargetInfo::RealType Ty =
11108       getTargetInfo().getRealTypeByWidth(DestWidth, ExplicitIEEE);
11109   switch (Ty) {
11110   case TargetInfo::Float:
11111     return FloatTy;
11112   case TargetInfo::Double:
11113     return DoubleTy;
11114   case TargetInfo::LongDouble:
11115     return LongDoubleTy;
11116   case TargetInfo::Float128:
11117     return Float128Ty;
11118   case TargetInfo::NoFloat:
11119     return {};
11120   }
11121 
11122   llvm_unreachable("Unhandled TargetInfo::RealType value");
11123 }
11124 
11125 void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
11126   if (Number > 1)
11127     MangleNumbers[ND] = Number;
11128 }
11129 
11130 unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
11131   auto I = MangleNumbers.find(ND);
11132   return I != MangleNumbers.end() ? I->second : 1;
11133 }
11134 
11135 void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
11136   if (Number > 1)
11137     StaticLocalNumbers[VD] = Number;
11138 }
11139 
11140 unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
11141   auto I = StaticLocalNumbers.find(VD);
11142   return I != StaticLocalNumbers.end() ? I->second : 1;
11143 }
11144 
11145 MangleNumberingContext &
11146 ASTContext::getManglingNumberContext(const DeclContext *DC) {
11147   assert(LangOpts.CPlusPlus);  // We don't need mangling numbers for plain C.
11148   std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
11149   if (!MCtx)
11150     MCtx = createMangleNumberingContext();
11151   return *MCtx;
11152 }
11153 
11154 MangleNumberingContext &
11155 ASTContext::getManglingNumberContext(NeedExtraManglingDecl_t, const Decl *D) {
11156   assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
11157   std::unique_ptr<MangleNumberingContext> &MCtx =
11158       ExtraMangleNumberingContexts[D];
11159   if (!MCtx)
11160     MCtx = createMangleNumberingContext();
11161   return *MCtx;
11162 }
11163 
11164 std::unique_ptr<MangleNumberingContext>
11165 ASTContext::createMangleNumberingContext() const {
11166   return ABI->createMangleNumberingContext();
11167 }
11168 
11169 const CXXConstructorDecl *
11170 ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
11171   return ABI->getCopyConstructorForExceptionObject(
11172       cast<CXXRecordDecl>(RD->getFirstDecl()));
11173 }
11174 
11175 void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
11176                                                       CXXConstructorDecl *CD) {
11177   return ABI->addCopyConstructorForExceptionObject(
11178       cast<CXXRecordDecl>(RD->getFirstDecl()),
11179       cast<CXXConstructorDecl>(CD->getFirstDecl()));
11180 }
11181 
11182 void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
11183                                                  TypedefNameDecl *DD) {
11184   return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
11185 }
11186 
11187 TypedefNameDecl *
11188 ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
11189   return ABI->getTypedefNameForUnnamedTagDecl(TD);
11190 }
11191 
11192 void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
11193                                                 DeclaratorDecl *DD) {
11194   return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
11195 }
11196 
11197 DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
11198   return ABI->getDeclaratorForUnnamedTagDecl(TD);
11199 }
11200 
11201 void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
11202   ParamIndices[D] = index;
11203 }
11204 
11205 unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
11206   ParameterIndexTable::const_iterator I = ParamIndices.find(D);
11207   assert(I != ParamIndices.end() &&
11208          "ParmIndices lacks entry set by ParmVarDecl");
11209   return I->second;
11210 }
11211 
11212 QualType ASTContext::getStringLiteralArrayType(QualType EltTy,
11213                                                unsigned Length) const {
11214   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
11215   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
11216     EltTy = EltTy.withConst();
11217 
11218   EltTy = adjustStringLiteralBaseType(EltTy);
11219 
11220   // Get an array type for the string, according to C99 6.4.5. This includes
11221   // the null terminator character.
11222   return getConstantArrayType(EltTy, llvm::APInt(32, Length + 1), nullptr,
11223                               ArrayType::Normal, /*IndexTypeQuals*/ 0);
11224 }
11225 
11226 StringLiteral *
11227 ASTContext::getPredefinedStringLiteralFromCache(StringRef Key) const {
11228   StringLiteral *&Result = StringLiteralCache[Key];
11229   if (!Result)
11230     Result = StringLiteral::Create(
11231         *this, Key, StringLiteral::Ascii,
11232         /*Pascal*/ false, getStringLiteralArrayType(CharTy, Key.size()),
11233         SourceLocation());
11234   return Result;
11235 }
11236 
11237 MSGuidDecl *
11238 ASTContext::getMSGuidDecl(MSGuidDecl::Parts Parts) const {
11239   assert(MSGuidTagDecl && "building MS GUID without MS extensions?");
11240 
11241   llvm::FoldingSetNodeID ID;
11242   MSGuidDecl::Profile(ID, Parts);
11243 
11244   void *InsertPos;
11245   if (MSGuidDecl *Existing = MSGuidDecls.FindNodeOrInsertPos(ID, InsertPos))
11246     return Existing;
11247 
11248   QualType GUIDType = getMSGuidType().withConst();
11249   MSGuidDecl *New = MSGuidDecl::Create(*this, GUIDType, Parts);
11250   MSGuidDecls.InsertNode(New, InsertPos);
11251   return New;
11252 }
11253 
11254 TemplateParamObjectDecl *
11255 ASTContext::getTemplateParamObjectDecl(QualType T, const APValue &V) const {
11256   assert(T->isRecordType() && "template param object of unexpected type");
11257 
11258   // C++ [temp.param]p8:
11259   //   [...] a static storage duration object of type 'const T' [...]
11260   T.addConst();
11261 
11262   llvm::FoldingSetNodeID ID;
11263   TemplateParamObjectDecl::Profile(ID, T, V);
11264 
11265   void *InsertPos;
11266   if (TemplateParamObjectDecl *Existing =
11267           TemplateParamObjectDecls.FindNodeOrInsertPos(ID, InsertPos))
11268     return Existing;
11269 
11270   TemplateParamObjectDecl *New = TemplateParamObjectDecl::Create(*this, T, V);
11271   TemplateParamObjectDecls.InsertNode(New, InsertPos);
11272   return New;
11273 }
11274 
11275 bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
11276   const llvm::Triple &T = getTargetInfo().getTriple();
11277   if (!T.isOSDarwin())
11278     return false;
11279 
11280   if (!(T.isiOS() && T.isOSVersionLT(7)) &&
11281       !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
11282     return false;
11283 
11284   QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
11285   CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
11286   uint64_t Size = sizeChars.getQuantity();
11287   CharUnits alignChars = getTypeAlignInChars(AtomicTy);
11288   unsigned Align = alignChars.getQuantity();
11289   unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
11290   return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
11291 }
11292 
11293 bool
11294 ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
11295                                 const ObjCMethodDecl *MethodImpl) {
11296   // No point trying to match an unavailable/deprecated mothod.
11297   if (MethodDecl->hasAttr<UnavailableAttr>()
11298       || MethodDecl->hasAttr<DeprecatedAttr>())
11299     return false;
11300   if (MethodDecl->getObjCDeclQualifier() !=
11301       MethodImpl->getObjCDeclQualifier())
11302     return false;
11303   if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
11304     return false;
11305 
11306   if (MethodDecl->param_size() != MethodImpl->param_size())
11307     return false;
11308 
11309   for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
11310        IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
11311        EF = MethodDecl->param_end();
11312        IM != EM && IF != EF; ++IM, ++IF) {
11313     const ParmVarDecl *DeclVar = (*IF);
11314     const ParmVarDecl *ImplVar = (*IM);
11315     if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
11316       return false;
11317     if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
11318       return false;
11319   }
11320 
11321   return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
11322 }
11323 
11324 uint64_t ASTContext::getTargetNullPointerValue(QualType QT) const {
11325   LangAS AS;
11326   if (QT->getUnqualifiedDesugaredType()->isNullPtrType())
11327     AS = LangAS::Default;
11328   else
11329     AS = QT->getPointeeType().getAddressSpace();
11330 
11331   return getTargetInfo().getNullPointerValue(AS);
11332 }
11333 
11334 unsigned ASTContext::getTargetAddressSpace(LangAS AS) const {
11335   if (isTargetAddressSpace(AS))
11336     return toTargetAddressSpace(AS);
11337   else
11338     return (*AddrSpaceMap)[(unsigned)AS];
11339 }
11340 
11341 QualType ASTContext::getCorrespondingSaturatedType(QualType Ty) const {
11342   assert(Ty->isFixedPointType());
11343 
11344   if (Ty->isSaturatedFixedPointType()) return Ty;
11345 
11346   switch (Ty->castAs<BuiltinType>()->getKind()) {
11347     default:
11348       llvm_unreachable("Not a fixed point type!");
11349     case BuiltinType::ShortAccum:
11350       return SatShortAccumTy;
11351     case BuiltinType::Accum:
11352       return SatAccumTy;
11353     case BuiltinType::LongAccum:
11354       return SatLongAccumTy;
11355     case BuiltinType::UShortAccum:
11356       return SatUnsignedShortAccumTy;
11357     case BuiltinType::UAccum:
11358       return SatUnsignedAccumTy;
11359     case BuiltinType::ULongAccum:
11360       return SatUnsignedLongAccumTy;
11361     case BuiltinType::ShortFract:
11362       return SatShortFractTy;
11363     case BuiltinType::Fract:
11364       return SatFractTy;
11365     case BuiltinType::LongFract:
11366       return SatLongFractTy;
11367     case BuiltinType::UShortFract:
11368       return SatUnsignedShortFractTy;
11369     case BuiltinType::UFract:
11370       return SatUnsignedFractTy;
11371     case BuiltinType::ULongFract:
11372       return SatUnsignedLongFractTy;
11373   }
11374 }
11375 
11376 LangAS ASTContext::getLangASForBuiltinAddressSpace(unsigned AS) const {
11377   if (LangOpts.OpenCL)
11378     return getTargetInfo().getOpenCLBuiltinAddressSpace(AS);
11379 
11380   if (LangOpts.CUDA)
11381     return getTargetInfo().getCUDABuiltinAddressSpace(AS);
11382 
11383   return getLangASFromTargetAS(AS);
11384 }
11385 
11386 // Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
11387 // doesn't include ASTContext.h
11388 template
11389 clang::LazyGenerationalUpdatePtr<
11390     const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
11391 clang::LazyGenerationalUpdatePtr<
11392     const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
11393         const clang::ASTContext &Ctx, Decl *Value);
11394 
11395 unsigned char ASTContext::getFixedPointScale(QualType Ty) const {
11396   assert(Ty->isFixedPointType());
11397 
11398   const TargetInfo &Target = getTargetInfo();
11399   switch (Ty->castAs<BuiltinType>()->getKind()) {
11400     default:
11401       llvm_unreachable("Not a fixed point type!");
11402     case BuiltinType::ShortAccum:
11403     case BuiltinType::SatShortAccum:
11404       return Target.getShortAccumScale();
11405     case BuiltinType::Accum:
11406     case BuiltinType::SatAccum:
11407       return Target.getAccumScale();
11408     case BuiltinType::LongAccum:
11409     case BuiltinType::SatLongAccum:
11410       return Target.getLongAccumScale();
11411     case BuiltinType::UShortAccum:
11412     case BuiltinType::SatUShortAccum:
11413       return Target.getUnsignedShortAccumScale();
11414     case BuiltinType::UAccum:
11415     case BuiltinType::SatUAccum:
11416       return Target.getUnsignedAccumScale();
11417     case BuiltinType::ULongAccum:
11418     case BuiltinType::SatULongAccum:
11419       return Target.getUnsignedLongAccumScale();
11420     case BuiltinType::ShortFract:
11421     case BuiltinType::SatShortFract:
11422       return Target.getShortFractScale();
11423     case BuiltinType::Fract:
11424     case BuiltinType::SatFract:
11425       return Target.getFractScale();
11426     case BuiltinType::LongFract:
11427     case BuiltinType::SatLongFract:
11428       return Target.getLongFractScale();
11429     case BuiltinType::UShortFract:
11430     case BuiltinType::SatUShortFract:
11431       return Target.getUnsignedShortFractScale();
11432     case BuiltinType::UFract:
11433     case BuiltinType::SatUFract:
11434       return Target.getUnsignedFractScale();
11435     case BuiltinType::ULongFract:
11436     case BuiltinType::SatULongFract:
11437       return Target.getUnsignedLongFractScale();
11438   }
11439 }
11440 
11441 unsigned char ASTContext::getFixedPointIBits(QualType Ty) const {
11442   assert(Ty->isFixedPointType());
11443 
11444   const TargetInfo &Target = getTargetInfo();
11445   switch (Ty->castAs<BuiltinType>()->getKind()) {
11446     default:
11447       llvm_unreachable("Not a fixed point type!");
11448     case BuiltinType::ShortAccum:
11449     case BuiltinType::SatShortAccum:
11450       return Target.getShortAccumIBits();
11451     case BuiltinType::Accum:
11452     case BuiltinType::SatAccum:
11453       return Target.getAccumIBits();
11454     case BuiltinType::LongAccum:
11455     case BuiltinType::SatLongAccum:
11456       return Target.getLongAccumIBits();
11457     case BuiltinType::UShortAccum:
11458     case BuiltinType::SatUShortAccum:
11459       return Target.getUnsignedShortAccumIBits();
11460     case BuiltinType::UAccum:
11461     case BuiltinType::SatUAccum:
11462       return Target.getUnsignedAccumIBits();
11463     case BuiltinType::ULongAccum:
11464     case BuiltinType::SatULongAccum:
11465       return Target.getUnsignedLongAccumIBits();
11466     case BuiltinType::ShortFract:
11467     case BuiltinType::SatShortFract:
11468     case BuiltinType::Fract:
11469     case BuiltinType::SatFract:
11470     case BuiltinType::LongFract:
11471     case BuiltinType::SatLongFract:
11472     case BuiltinType::UShortFract:
11473     case BuiltinType::SatUShortFract:
11474     case BuiltinType::UFract:
11475     case BuiltinType::SatUFract:
11476     case BuiltinType::ULongFract:
11477     case BuiltinType::SatULongFract:
11478       return 0;
11479   }
11480 }
11481 
11482 llvm::FixedPointSemantics
11483 ASTContext::getFixedPointSemantics(QualType Ty) const {
11484   assert((Ty->isFixedPointType() || Ty->isIntegerType()) &&
11485          "Can only get the fixed point semantics for a "
11486          "fixed point or integer type.");
11487   if (Ty->isIntegerType())
11488     return llvm::FixedPointSemantics::GetIntegerSemantics(
11489         getIntWidth(Ty), Ty->isSignedIntegerType());
11490 
11491   bool isSigned = Ty->isSignedFixedPointType();
11492   return llvm::FixedPointSemantics(
11493       static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned,
11494       Ty->isSaturatedFixedPointType(),
11495       !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding());
11496 }
11497 
11498 llvm::APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const {
11499   assert(Ty->isFixedPointType());
11500   return llvm::APFixedPoint::getMax(getFixedPointSemantics(Ty));
11501 }
11502 
11503 llvm::APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const {
11504   assert(Ty->isFixedPointType());
11505   return llvm::APFixedPoint::getMin(getFixedPointSemantics(Ty));
11506 }
11507 
11508 QualType ASTContext::getCorrespondingSignedFixedPointType(QualType Ty) const {
11509   assert(Ty->isUnsignedFixedPointType() &&
11510          "Expected unsigned fixed point type");
11511 
11512   switch (Ty->castAs<BuiltinType>()->getKind()) {
11513   case BuiltinType::UShortAccum:
11514     return ShortAccumTy;
11515   case BuiltinType::UAccum:
11516     return AccumTy;
11517   case BuiltinType::ULongAccum:
11518     return LongAccumTy;
11519   case BuiltinType::SatUShortAccum:
11520     return SatShortAccumTy;
11521   case BuiltinType::SatUAccum:
11522     return SatAccumTy;
11523   case BuiltinType::SatULongAccum:
11524     return SatLongAccumTy;
11525   case BuiltinType::UShortFract:
11526     return ShortFractTy;
11527   case BuiltinType::UFract:
11528     return FractTy;
11529   case BuiltinType::ULongFract:
11530     return LongFractTy;
11531   case BuiltinType::SatUShortFract:
11532     return SatShortFractTy;
11533   case BuiltinType::SatUFract:
11534     return SatFractTy;
11535   case BuiltinType::SatULongFract:
11536     return SatLongFractTy;
11537   default:
11538     llvm_unreachable("Unexpected unsigned fixed point type");
11539   }
11540 }
11541 
11542 ParsedTargetAttr
11543 ASTContext::filterFunctionTargetAttrs(const TargetAttr *TD) const {
11544   assert(TD != nullptr);
11545   ParsedTargetAttr ParsedAttr = TD->parse();
11546 
11547   ParsedAttr.Features.erase(
11548       llvm::remove_if(ParsedAttr.Features,
11549                       [&](const std::string &Feat) {
11550                         return !Target->isValidFeatureName(
11551                             StringRef{Feat}.substr(1));
11552                       }),
11553       ParsedAttr.Features.end());
11554   return ParsedAttr;
11555 }
11556 
11557 void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
11558                                        const FunctionDecl *FD) const {
11559   if (FD)
11560     getFunctionFeatureMap(FeatureMap, GlobalDecl().getWithDecl(FD));
11561   else
11562     Target->initFeatureMap(FeatureMap, getDiagnostics(),
11563                            Target->getTargetOpts().CPU,
11564                            Target->getTargetOpts().Features);
11565 }
11566 
11567 // Fills in the supplied string map with the set of target features for the
11568 // passed in function.
11569 void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
11570                                        GlobalDecl GD) const {
11571   StringRef TargetCPU = Target->getTargetOpts().CPU;
11572   const FunctionDecl *FD = GD.getDecl()->getAsFunction();
11573   if (const auto *TD = FD->getAttr<TargetAttr>()) {
11574     ParsedTargetAttr ParsedAttr = filterFunctionTargetAttrs(TD);
11575 
11576     // Make a copy of the features as passed on the command line into the
11577     // beginning of the additional features from the function to override.
11578     ParsedAttr.Features.insert(
11579         ParsedAttr.Features.begin(),
11580         Target->getTargetOpts().FeaturesAsWritten.begin(),
11581         Target->getTargetOpts().FeaturesAsWritten.end());
11582 
11583     if (ParsedAttr.Architecture != "" &&
11584         Target->isValidCPUName(ParsedAttr.Architecture))
11585       TargetCPU = ParsedAttr.Architecture;
11586 
11587     // Now populate the feature map, first with the TargetCPU which is either
11588     // the default or a new one from the target attribute string. Then we'll use
11589     // the passed in features (FeaturesAsWritten) along with the new ones from
11590     // the attribute.
11591     Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU,
11592                            ParsedAttr.Features);
11593   } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) {
11594     llvm::SmallVector<StringRef, 32> FeaturesTmp;
11595     Target->getCPUSpecificCPUDispatchFeatures(
11596         SD->getCPUName(GD.getMultiVersionIndex())->getName(), FeaturesTmp);
11597     std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end());
11598     Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
11599   } else {
11600     FeatureMap = Target->getTargetOpts().FeatureMap;
11601   }
11602 }
11603 
11604 OMPTraitInfo &ASTContext::getNewOMPTraitInfo() {
11605   OMPTraitInfoVector.emplace_back(new OMPTraitInfo());
11606   return *OMPTraitInfoVector.back();
11607 }
11608 
11609 const StreamingDiagnostic &clang::
11610 operator<<(const StreamingDiagnostic &DB,
11611            const ASTContext::SectionInfo &Section) {
11612   if (Section.Decl)
11613     return DB << Section.Decl;
11614   return DB << "a prior #pragma section";
11615 }
11616 
11617 bool ASTContext::mayExternalizeStaticVar(const Decl *D) const {
11618   bool IsStaticVar =
11619       isa<VarDecl>(D) && cast<VarDecl>(D)->getStorageClass() == SC_Static;
11620   bool IsExplicitDeviceVar = (D->hasAttr<CUDADeviceAttr>() &&
11621                               !D->getAttr<CUDADeviceAttr>()->isImplicit()) ||
11622                              (D->hasAttr<CUDAConstantAttr>() &&
11623                               !D->getAttr<CUDAConstantAttr>()->isImplicit());
11624   // CUDA/HIP: static managed variables need to be externalized since it is
11625   // a declaration in IR, therefore cannot have internal linkage.
11626   return IsStaticVar &&
11627          (D->hasAttr<HIPManagedAttr>() || IsExplicitDeviceVar);
11628 }
11629 
11630 bool ASTContext::shouldExternalizeStaticVar(const Decl *D) const {
11631   return mayExternalizeStaticVar(D) &&
11632          (D->hasAttr<HIPManagedAttr>() ||
11633           CUDAStaticDeviceVarReferencedByHost.count(cast<VarDecl>(D)));
11634 }
11635 
11636 StringRef ASTContext::getCUIDHash() const {
11637   if (!CUIDHash.empty())
11638     return CUIDHash;
11639   if (LangOpts.CUID.empty())
11640     return StringRef();
11641   CUIDHash = llvm::utohexstr(llvm::MD5Hash(LangOpts.CUID), /*LowerCase=*/true);
11642   return CUIDHash;
11643 }
11644