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         10, // ptr32_sptr
935         11, // ptr32_uptr
936         12  // ptr64
937     };
938     return &FakeAddrSpaceMap;
939   } else {
940     return &T.getAddressSpaceMap();
941   }
942 }
943 
944 static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
945                                           const LangOptions &LangOpts) {
946   switch (LangOpts.getAddressSpaceMapMangling()) {
947   case LangOptions::ASMM_Target:
948     return TI.useAddressSpaceMapMangling();
949   case LangOptions::ASMM_On:
950     return true;
951   case LangOptions::ASMM_Off:
952     return false;
953   }
954   llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
955 }
956 
957 ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
958                        IdentifierTable &idents, SelectorTable &sels,
959                        Builtin::Context &builtins)
960     : ConstantArrayTypes(this_()), FunctionProtoTypes(this_()),
961       TemplateSpecializationTypes(this_()),
962       DependentTemplateSpecializationTypes(this_()), AutoTypes(this_()),
963       SubstTemplateTemplateParmPacks(this_()),
964       CanonTemplateTemplateParms(this_()), SourceMgr(SM), LangOpts(LOpts),
965       NoSanitizeL(new NoSanitizeList(LangOpts.NoSanitizeFiles, SM)),
966       XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
967                                         LangOpts.XRayNeverInstrumentFiles,
968                                         LangOpts.XRayAttrListFiles, SM)),
969       ProfList(new ProfileList(LangOpts.ProfileListFiles, SM)),
970       PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
971       BuiltinInfo(builtins), DeclarationNames(*this), Comments(SM),
972       CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
973       CompCategories(this_()), LastSDM(nullptr, 0) {
974   TUDecl = TranslationUnitDecl::Create(*this);
975   TraversalScope = {TUDecl};
976 }
977 
978 ASTContext::~ASTContext() {
979   // Release the DenseMaps associated with DeclContext objects.
980   // FIXME: Is this the ideal solution?
981   ReleaseDeclContextMaps();
982 
983   // Call all of the deallocation functions on all of their targets.
984   for (auto &Pair : Deallocations)
985     (Pair.first)(Pair.second);
986 
987   // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
988   // because they can contain DenseMaps.
989   for (llvm::DenseMap<const ObjCContainerDecl*,
990        const ASTRecordLayout*>::iterator
991        I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
992     // Increment in loop to prevent using deallocated memory.
993     if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
994       R->Destroy(*this);
995 
996   for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
997        I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
998     // Increment in loop to prevent using deallocated memory.
999     if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
1000       R->Destroy(*this);
1001   }
1002 
1003   for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
1004                                                     AEnd = DeclAttrs.end();
1005        A != AEnd; ++A)
1006     A->second->~AttrVec();
1007 
1008   for (const auto &Value : ModuleInitializers)
1009     Value.second->~PerModuleInitializers();
1010 }
1011 
1012 void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) {
1013   TraversalScope = TopLevelDecls;
1014   getParentMapContext().clear();
1015 }
1016 
1017 void ASTContext::AddDeallocation(void (*Callback)(void *), void *Data) const {
1018   Deallocations.push_back({Callback, Data});
1019 }
1020 
1021 void
1022 ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
1023   ExternalSource = std::move(Source);
1024 }
1025 
1026 void ASTContext::PrintStats() const {
1027   llvm::errs() << "\n*** AST Context Stats:\n";
1028   llvm::errs() << "  " << Types.size() << " types total.\n";
1029 
1030   unsigned counts[] = {
1031 #define TYPE(Name, Parent) 0,
1032 #define ABSTRACT_TYPE(Name, Parent)
1033 #include "clang/AST/TypeNodes.inc"
1034     0 // Extra
1035   };
1036 
1037   for (unsigned i = 0, e = Types.size(); i != e; ++i) {
1038     Type *T = Types[i];
1039     counts[(unsigned)T->getTypeClass()]++;
1040   }
1041 
1042   unsigned Idx = 0;
1043   unsigned TotalBytes = 0;
1044 #define TYPE(Name, Parent)                                              \
1045   if (counts[Idx])                                                      \
1046     llvm::errs() << "    " << counts[Idx] << " " << #Name               \
1047                  << " types, " << sizeof(Name##Type) << " each "        \
1048                  << "(" << counts[Idx] * sizeof(Name##Type)             \
1049                  << " bytes)\n";                                        \
1050   TotalBytes += counts[Idx] * sizeof(Name##Type);                       \
1051   ++Idx;
1052 #define ABSTRACT_TYPE(Name, Parent)
1053 #include "clang/AST/TypeNodes.inc"
1054 
1055   llvm::errs() << "Total bytes = " << TotalBytes << "\n";
1056 
1057   // Implicit special member functions.
1058   llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
1059                << NumImplicitDefaultConstructors
1060                << " implicit default constructors created\n";
1061   llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
1062                << NumImplicitCopyConstructors
1063                << " implicit copy constructors created\n";
1064   if (getLangOpts().CPlusPlus)
1065     llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
1066                  << NumImplicitMoveConstructors
1067                  << " implicit move constructors created\n";
1068   llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
1069                << NumImplicitCopyAssignmentOperators
1070                << " implicit copy assignment operators created\n";
1071   if (getLangOpts().CPlusPlus)
1072     llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
1073                  << NumImplicitMoveAssignmentOperators
1074                  << " implicit move assignment operators created\n";
1075   llvm::errs() << NumImplicitDestructorsDeclared << "/"
1076                << NumImplicitDestructors
1077                << " implicit destructors created\n";
1078 
1079   if (ExternalSource) {
1080     llvm::errs() << "\n";
1081     ExternalSource->PrintStats();
1082   }
1083 
1084   BumpAlloc.PrintStats();
1085 }
1086 
1087 void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
1088                                            bool NotifyListeners) {
1089   if (NotifyListeners)
1090     if (auto *Listener = getASTMutationListener())
1091       Listener->RedefinedHiddenDefinition(ND, M);
1092 
1093   MergedDefModules[cast<NamedDecl>(ND->getCanonicalDecl())].push_back(M);
1094 }
1095 
1096 void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
1097   auto It = MergedDefModules.find(cast<NamedDecl>(ND->getCanonicalDecl()));
1098   if (It == MergedDefModules.end())
1099     return;
1100 
1101   auto &Merged = It->second;
1102   llvm::DenseSet<Module*> Found;
1103   for (Module *&M : Merged)
1104     if (!Found.insert(M).second)
1105       M = nullptr;
1106   Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end());
1107 }
1108 
1109 ArrayRef<Module *>
1110 ASTContext::getModulesWithMergedDefinition(const NamedDecl *Def) {
1111   auto MergedIt =
1112       MergedDefModules.find(cast<NamedDecl>(Def->getCanonicalDecl()));
1113   if (MergedIt == MergedDefModules.end())
1114     return None;
1115   return MergedIt->second;
1116 }
1117 
1118 void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
1119   if (LazyInitializers.empty())
1120     return;
1121 
1122   auto *Source = Ctx.getExternalSource();
1123   assert(Source && "lazy initializers but no external source");
1124 
1125   auto LazyInits = std::move(LazyInitializers);
1126   LazyInitializers.clear();
1127 
1128   for (auto ID : LazyInits)
1129     Initializers.push_back(Source->GetExternalDecl(ID));
1130 
1131   assert(LazyInitializers.empty() &&
1132          "GetExternalDecl for lazy module initializer added more inits");
1133 }
1134 
1135 void ASTContext::addModuleInitializer(Module *M, Decl *D) {
1136   // One special case: if we add a module initializer that imports another
1137   // module, and that module's only initializer is an ImportDecl, simplify.
1138   if (const auto *ID = dyn_cast<ImportDecl>(D)) {
1139     auto It = ModuleInitializers.find(ID->getImportedModule());
1140 
1141     // Maybe the ImportDecl does nothing at all. (Common case.)
1142     if (It == ModuleInitializers.end())
1143       return;
1144 
1145     // Maybe the ImportDecl only imports another ImportDecl.
1146     auto &Imported = *It->second;
1147     if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
1148       Imported.resolve(*this);
1149       auto *OnlyDecl = Imported.Initializers.front();
1150       if (isa<ImportDecl>(OnlyDecl))
1151         D = OnlyDecl;
1152     }
1153   }
1154 
1155   auto *&Inits = ModuleInitializers[M];
1156   if (!Inits)
1157     Inits = new (*this) PerModuleInitializers;
1158   Inits->Initializers.push_back(D);
1159 }
1160 
1161 void ASTContext::addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs) {
1162   auto *&Inits = ModuleInitializers[M];
1163   if (!Inits)
1164     Inits = new (*this) PerModuleInitializers;
1165   Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
1166                                  IDs.begin(), IDs.end());
1167 }
1168 
1169 ArrayRef<Decl *> ASTContext::getModuleInitializers(Module *M) {
1170   auto It = ModuleInitializers.find(M);
1171   if (It == ModuleInitializers.end())
1172     return None;
1173 
1174   auto *Inits = It->second;
1175   Inits->resolve(*this);
1176   return Inits->Initializers;
1177 }
1178 
1179 ExternCContextDecl *ASTContext::getExternCContextDecl() const {
1180   if (!ExternCContext)
1181     ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
1182 
1183   return ExternCContext;
1184 }
1185 
1186 BuiltinTemplateDecl *
1187 ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
1188                                      const IdentifierInfo *II) const {
1189   auto *BuiltinTemplate = BuiltinTemplateDecl::Create(*this, TUDecl, II, BTK);
1190   BuiltinTemplate->setImplicit();
1191   TUDecl->addDecl(BuiltinTemplate);
1192 
1193   return BuiltinTemplate;
1194 }
1195 
1196 BuiltinTemplateDecl *
1197 ASTContext::getMakeIntegerSeqDecl() const {
1198   if (!MakeIntegerSeqDecl)
1199     MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq,
1200                                                   getMakeIntegerSeqName());
1201   return MakeIntegerSeqDecl;
1202 }
1203 
1204 BuiltinTemplateDecl *
1205 ASTContext::getTypePackElementDecl() const {
1206   if (!TypePackElementDecl)
1207     TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element,
1208                                                    getTypePackElementName());
1209   return TypePackElementDecl;
1210 }
1211 
1212 RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
1213                                             RecordDecl::TagKind TK) const {
1214   SourceLocation Loc;
1215   RecordDecl *NewDecl;
1216   if (getLangOpts().CPlusPlus)
1217     NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1218                                     Loc, &Idents.get(Name));
1219   else
1220     NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1221                                  &Idents.get(Name));
1222   NewDecl->setImplicit();
1223   NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1224       const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
1225   return NewDecl;
1226 }
1227 
1228 TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
1229                                               StringRef Name) const {
1230   TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
1231   TypedefDecl *NewDecl = TypedefDecl::Create(
1232       const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1233       SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1234   NewDecl->setImplicit();
1235   return NewDecl;
1236 }
1237 
1238 TypedefDecl *ASTContext::getInt128Decl() const {
1239   if (!Int128Decl)
1240     Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
1241   return Int128Decl;
1242 }
1243 
1244 TypedefDecl *ASTContext::getUInt128Decl() const {
1245   if (!UInt128Decl)
1246     UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
1247   return UInt128Decl;
1248 }
1249 
1250 void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
1251   auto *Ty = new (*this, TypeAlignment) BuiltinType(K);
1252   R = CanQualType::CreateUnsafe(QualType(Ty, 0));
1253   Types.push_back(Ty);
1254 }
1255 
1256 void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
1257                                   const TargetInfo *AuxTarget) {
1258   assert((!this->Target || this->Target == &Target) &&
1259          "Incorrect target reinitialization");
1260   assert(VoidTy.isNull() && "Context reinitialized?");
1261 
1262   this->Target = &Target;
1263   this->AuxTarget = AuxTarget;
1264 
1265   ABI.reset(createCXXABI(Target));
1266   AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
1267   AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
1268 
1269   // C99 6.2.5p19.
1270   InitBuiltinType(VoidTy,              BuiltinType::Void);
1271 
1272   // C99 6.2.5p2.
1273   InitBuiltinType(BoolTy,              BuiltinType::Bool);
1274   // C99 6.2.5p3.
1275   if (LangOpts.CharIsSigned)
1276     InitBuiltinType(CharTy,            BuiltinType::Char_S);
1277   else
1278     InitBuiltinType(CharTy,            BuiltinType::Char_U);
1279   // C99 6.2.5p4.
1280   InitBuiltinType(SignedCharTy,        BuiltinType::SChar);
1281   InitBuiltinType(ShortTy,             BuiltinType::Short);
1282   InitBuiltinType(IntTy,               BuiltinType::Int);
1283   InitBuiltinType(LongTy,              BuiltinType::Long);
1284   InitBuiltinType(LongLongTy,          BuiltinType::LongLong);
1285 
1286   // C99 6.2.5p6.
1287   InitBuiltinType(UnsignedCharTy,      BuiltinType::UChar);
1288   InitBuiltinType(UnsignedShortTy,     BuiltinType::UShort);
1289   InitBuiltinType(UnsignedIntTy,       BuiltinType::UInt);
1290   InitBuiltinType(UnsignedLongTy,      BuiltinType::ULong);
1291   InitBuiltinType(UnsignedLongLongTy,  BuiltinType::ULongLong);
1292 
1293   // C99 6.2.5p10.
1294   InitBuiltinType(FloatTy,             BuiltinType::Float);
1295   InitBuiltinType(DoubleTy,            BuiltinType::Double);
1296   InitBuiltinType(LongDoubleTy,        BuiltinType::LongDouble);
1297 
1298   // GNU extension, __float128 for IEEE quadruple precision
1299   InitBuiltinType(Float128Ty,          BuiltinType::Float128);
1300 
1301   // C11 extension ISO/IEC TS 18661-3
1302   InitBuiltinType(Float16Ty,           BuiltinType::Float16);
1303 
1304   // ISO/IEC JTC1 SC22 WG14 N1169 Extension
1305   InitBuiltinType(ShortAccumTy,            BuiltinType::ShortAccum);
1306   InitBuiltinType(AccumTy,                 BuiltinType::Accum);
1307   InitBuiltinType(LongAccumTy,             BuiltinType::LongAccum);
1308   InitBuiltinType(UnsignedShortAccumTy,    BuiltinType::UShortAccum);
1309   InitBuiltinType(UnsignedAccumTy,         BuiltinType::UAccum);
1310   InitBuiltinType(UnsignedLongAccumTy,     BuiltinType::ULongAccum);
1311   InitBuiltinType(ShortFractTy,            BuiltinType::ShortFract);
1312   InitBuiltinType(FractTy,                 BuiltinType::Fract);
1313   InitBuiltinType(LongFractTy,             BuiltinType::LongFract);
1314   InitBuiltinType(UnsignedShortFractTy,    BuiltinType::UShortFract);
1315   InitBuiltinType(UnsignedFractTy,         BuiltinType::UFract);
1316   InitBuiltinType(UnsignedLongFractTy,     BuiltinType::ULongFract);
1317   InitBuiltinType(SatShortAccumTy,         BuiltinType::SatShortAccum);
1318   InitBuiltinType(SatAccumTy,              BuiltinType::SatAccum);
1319   InitBuiltinType(SatLongAccumTy,          BuiltinType::SatLongAccum);
1320   InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum);
1321   InitBuiltinType(SatUnsignedAccumTy,      BuiltinType::SatUAccum);
1322   InitBuiltinType(SatUnsignedLongAccumTy,  BuiltinType::SatULongAccum);
1323   InitBuiltinType(SatShortFractTy,         BuiltinType::SatShortFract);
1324   InitBuiltinType(SatFractTy,              BuiltinType::SatFract);
1325   InitBuiltinType(SatLongFractTy,          BuiltinType::SatLongFract);
1326   InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract);
1327   InitBuiltinType(SatUnsignedFractTy,      BuiltinType::SatUFract);
1328   InitBuiltinType(SatUnsignedLongFractTy,  BuiltinType::SatULongFract);
1329 
1330   // GNU extension, 128-bit integers.
1331   InitBuiltinType(Int128Ty,            BuiltinType::Int128);
1332   InitBuiltinType(UnsignedInt128Ty,    BuiltinType::UInt128);
1333 
1334   // C++ 3.9.1p5
1335   if (TargetInfo::isTypeSigned(Target.getWCharType()))
1336     InitBuiltinType(WCharTy,           BuiltinType::WChar_S);
1337   else  // -fshort-wchar makes wchar_t be unsigned.
1338     InitBuiltinType(WCharTy,           BuiltinType::WChar_U);
1339   if (LangOpts.CPlusPlus && LangOpts.WChar)
1340     WideCharTy = WCharTy;
1341   else {
1342     // C99 (or C++ using -fno-wchar).
1343     WideCharTy = getFromTargetType(Target.getWCharType());
1344   }
1345 
1346   WIntTy = getFromTargetType(Target.getWIntType());
1347 
1348   // C++20 (proposed)
1349   InitBuiltinType(Char8Ty,              BuiltinType::Char8);
1350 
1351   if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1352     InitBuiltinType(Char16Ty,           BuiltinType::Char16);
1353   else // C99
1354     Char16Ty = getFromTargetType(Target.getChar16Type());
1355 
1356   if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1357     InitBuiltinType(Char32Ty,           BuiltinType::Char32);
1358   else // C99
1359     Char32Ty = getFromTargetType(Target.getChar32Type());
1360 
1361   // Placeholder type for type-dependent expressions whose type is
1362   // completely unknown. No code should ever check a type against
1363   // DependentTy and users should never see it; however, it is here to
1364   // help diagnose failures to properly check for type-dependent
1365   // expressions.
1366   InitBuiltinType(DependentTy,         BuiltinType::Dependent);
1367 
1368   // Placeholder type for functions.
1369   InitBuiltinType(OverloadTy,          BuiltinType::Overload);
1370 
1371   // Placeholder type for bound members.
1372   InitBuiltinType(BoundMemberTy,       BuiltinType::BoundMember);
1373 
1374   // Placeholder type for pseudo-objects.
1375   InitBuiltinType(PseudoObjectTy,      BuiltinType::PseudoObject);
1376 
1377   // "any" type; useful for debugger-like clients.
1378   InitBuiltinType(UnknownAnyTy,        BuiltinType::UnknownAny);
1379 
1380   // Placeholder type for unbridged ARC casts.
1381   InitBuiltinType(ARCUnbridgedCastTy,  BuiltinType::ARCUnbridgedCast);
1382 
1383   // Placeholder type for builtin functions.
1384   InitBuiltinType(BuiltinFnTy,  BuiltinType::BuiltinFn);
1385 
1386   // Placeholder type for OMP array sections.
1387   if (LangOpts.OpenMP) {
1388     InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
1389     InitBuiltinType(OMPArrayShapingTy, BuiltinType::OMPArrayShaping);
1390     InitBuiltinType(OMPIteratorTy, BuiltinType::OMPIterator);
1391   }
1392   if (LangOpts.MatrixTypes)
1393     InitBuiltinType(IncompleteMatrixIdxTy, BuiltinType::IncompleteMatrixIdx);
1394 
1395   // C99 6.2.5p11.
1396   FloatComplexTy      = getComplexType(FloatTy);
1397   DoubleComplexTy     = getComplexType(DoubleTy);
1398   LongDoubleComplexTy = getComplexType(LongDoubleTy);
1399   Float128ComplexTy   = getComplexType(Float128Ty);
1400 
1401   // Builtin types for 'id', 'Class', and 'SEL'.
1402   InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1403   InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
1404   InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
1405 
1406   if (LangOpts.OpenCL) {
1407 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1408     InitBuiltinType(SingletonId, BuiltinType::Id);
1409 #include "clang/Basic/OpenCLImageTypes.def"
1410 
1411     InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
1412     InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
1413     InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1414     InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
1415     InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
1416 
1417 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1418     InitBuiltinType(Id##Ty, BuiltinType::Id);
1419 #include "clang/Basic/OpenCLExtensionTypes.def"
1420   }
1421 
1422   if (Target.hasAArch64SVETypes()) {
1423 #define SVE_TYPE(Name, Id, SingletonId) \
1424     InitBuiltinType(SingletonId, BuiltinType::Id);
1425 #include "clang/Basic/AArch64SVEACLETypes.def"
1426   }
1427 
1428   if (Target.getTriple().isPPC64() &&
1429       Target.hasFeature("paired-vector-memops")) {
1430     if (Target.hasFeature("mma")) {
1431 #define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \
1432       InitBuiltinType(Id##Ty, BuiltinType::Id);
1433 #include "clang/Basic/PPCTypes.def"
1434     }
1435 #define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \
1436     InitBuiltinType(Id##Ty, BuiltinType::Id);
1437 #include "clang/Basic/PPCTypes.def"
1438   }
1439 
1440   if (Target.hasRISCVVTypes()) {
1441 #define RVV_TYPE(Name, Id, SingletonId)                                        \
1442   InitBuiltinType(SingletonId, BuiltinType::Id);
1443 #include "clang/Basic/RISCVVTypes.def"
1444   }
1445 
1446   // Builtin type for __objc_yes and __objc_no
1447   ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1448                        SignedCharTy : BoolTy);
1449 
1450   ObjCConstantStringType = QualType();
1451 
1452   ObjCSuperType = QualType();
1453 
1454   // void * type
1455   if (LangOpts.OpenCLGenericAddressSpace) {
1456     auto Q = VoidTy.getQualifiers();
1457     Q.setAddressSpace(LangAS::opencl_generic);
1458     VoidPtrTy = getPointerType(getCanonicalType(
1459         getQualifiedType(VoidTy.getUnqualifiedType(), Q)));
1460   } else {
1461     VoidPtrTy = getPointerType(VoidTy);
1462   }
1463 
1464   // nullptr type (C++0x 2.14.7)
1465   InitBuiltinType(NullPtrTy,           BuiltinType::NullPtr);
1466 
1467   // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1468   InitBuiltinType(HalfTy, BuiltinType::Half);
1469 
1470   InitBuiltinType(BFloat16Ty, BuiltinType::BFloat16);
1471 
1472   // Builtin type used to help define __builtin_va_list.
1473   VaListTagDecl = nullptr;
1474 
1475   // MSVC predeclares struct _GUID, and we need it to create MSGuidDecls.
1476   if (LangOpts.MicrosoftExt || LangOpts.Borland) {
1477     MSGuidTagDecl = buildImplicitRecord("_GUID");
1478     TUDecl->addDecl(MSGuidTagDecl);
1479   }
1480 }
1481 
1482 DiagnosticsEngine &ASTContext::getDiagnostics() const {
1483   return SourceMgr.getDiagnostics();
1484 }
1485 
1486 AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1487   AttrVec *&Result = DeclAttrs[D];
1488   if (!Result) {
1489     void *Mem = Allocate(sizeof(AttrVec));
1490     Result = new (Mem) AttrVec;
1491   }
1492 
1493   return *Result;
1494 }
1495 
1496 /// Erase the attributes corresponding to the given declaration.
1497 void ASTContext::eraseDeclAttrs(const Decl *D) {
1498   llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1499   if (Pos != DeclAttrs.end()) {
1500     Pos->second->~AttrVec();
1501     DeclAttrs.erase(Pos);
1502   }
1503 }
1504 
1505 // FIXME: Remove ?
1506 MemberSpecializationInfo *
1507 ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
1508   assert(Var->isStaticDataMember() && "Not a static data member");
1509   return getTemplateOrSpecializationInfo(Var)
1510       .dyn_cast<MemberSpecializationInfo *>();
1511 }
1512 
1513 ASTContext::TemplateOrSpecializationInfo
1514 ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1515   llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1516       TemplateOrInstantiation.find(Var);
1517   if (Pos == TemplateOrInstantiation.end())
1518     return {};
1519 
1520   return Pos->second;
1521 }
1522 
1523 void
1524 ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
1525                                                 TemplateSpecializationKind TSK,
1526                                           SourceLocation PointOfInstantiation) {
1527   assert(Inst->isStaticDataMember() && "Not a static data member");
1528   assert(Tmpl->isStaticDataMember() && "Not a static data member");
1529   setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1530                                             Tmpl, TSK, PointOfInstantiation));
1531 }
1532 
1533 void
1534 ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1535                                             TemplateOrSpecializationInfo TSI) {
1536   assert(!TemplateOrInstantiation[Inst] &&
1537          "Already noted what the variable was instantiated from");
1538   TemplateOrInstantiation[Inst] = TSI;
1539 }
1540 
1541 NamedDecl *
1542 ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) {
1543   auto Pos = InstantiatedFromUsingDecl.find(UUD);
1544   if (Pos == InstantiatedFromUsingDecl.end())
1545     return nullptr;
1546 
1547   return Pos->second;
1548 }
1549 
1550 void
1551 ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) {
1552   assert((isa<UsingDecl>(Pattern) ||
1553           isa<UnresolvedUsingValueDecl>(Pattern) ||
1554           isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1555          "pattern decl is not a using decl");
1556   assert((isa<UsingDecl>(Inst) ||
1557           isa<UnresolvedUsingValueDecl>(Inst) ||
1558           isa<UnresolvedUsingTypenameDecl>(Inst)) &&
1559          "instantiation did not produce a using decl");
1560   assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1561   InstantiatedFromUsingDecl[Inst] = Pattern;
1562 }
1563 
1564 UsingShadowDecl *
1565 ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1566   llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1567     = InstantiatedFromUsingShadowDecl.find(Inst);
1568   if (Pos == InstantiatedFromUsingShadowDecl.end())
1569     return nullptr;
1570 
1571   return Pos->second;
1572 }
1573 
1574 void
1575 ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1576                                                UsingShadowDecl *Pattern) {
1577   assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1578   InstantiatedFromUsingShadowDecl[Inst] = Pattern;
1579 }
1580 
1581 FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1582   llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1583     = InstantiatedFromUnnamedFieldDecl.find(Field);
1584   if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1585     return nullptr;
1586 
1587   return Pos->second;
1588 }
1589 
1590 void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1591                                                      FieldDecl *Tmpl) {
1592   assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1593   assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1594   assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1595          "Already noted what unnamed field was instantiated from");
1596 
1597   InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1598 }
1599 
1600 ASTContext::overridden_cxx_method_iterator
1601 ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1602   return overridden_methods(Method).begin();
1603 }
1604 
1605 ASTContext::overridden_cxx_method_iterator
1606 ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1607   return overridden_methods(Method).end();
1608 }
1609 
1610 unsigned
1611 ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1612   auto Range = overridden_methods(Method);
1613   return Range.end() - Range.begin();
1614 }
1615 
1616 ASTContext::overridden_method_range
1617 ASTContext::overridden_methods(const CXXMethodDecl *Method) const {
1618   llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1619       OverriddenMethods.find(Method->getCanonicalDecl());
1620   if (Pos == OverriddenMethods.end())
1621     return overridden_method_range(nullptr, nullptr);
1622   return overridden_method_range(Pos->second.begin(), Pos->second.end());
1623 }
1624 
1625 void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1626                                      const CXXMethodDecl *Overridden) {
1627   assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
1628   OverriddenMethods[Method].push_back(Overridden);
1629 }
1630 
1631 void ASTContext::getOverriddenMethods(
1632                       const NamedDecl *D,
1633                       SmallVectorImpl<const NamedDecl *> &Overridden) const {
1634   assert(D);
1635 
1636   if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
1637     Overridden.append(overridden_methods_begin(CXXMethod),
1638                       overridden_methods_end(CXXMethod));
1639     return;
1640   }
1641 
1642   const auto *Method = dyn_cast<ObjCMethodDecl>(D);
1643   if (!Method)
1644     return;
1645 
1646   SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1647   Method->getOverriddenMethods(OverDecls);
1648   Overridden.append(OverDecls.begin(), OverDecls.end());
1649 }
1650 
1651 void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1652   assert(!Import->getNextLocalImport() &&
1653          "Import declaration already in the chain");
1654   assert(!Import->isFromASTFile() && "Non-local import declaration");
1655   if (!FirstLocalImport) {
1656     FirstLocalImport = Import;
1657     LastLocalImport = Import;
1658     return;
1659   }
1660 
1661   LastLocalImport->setNextLocalImport(Import);
1662   LastLocalImport = Import;
1663 }
1664 
1665 //===----------------------------------------------------------------------===//
1666 //                         Type Sizing and Analysis
1667 //===----------------------------------------------------------------------===//
1668 
1669 /// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1670 /// scalar floating point type.
1671 const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
1672   switch (T->castAs<BuiltinType>()->getKind()) {
1673   default:
1674     llvm_unreachable("Not a floating point type!");
1675   case BuiltinType::BFloat16:
1676     return Target->getBFloat16Format();
1677   case BuiltinType::Float16:
1678   case BuiltinType::Half:
1679     return Target->getHalfFormat();
1680   case BuiltinType::Float:      return Target->getFloatFormat();
1681   case BuiltinType::Double:     return Target->getDoubleFormat();
1682   case BuiltinType::LongDouble:
1683     if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice)
1684       return AuxTarget->getLongDoubleFormat();
1685     return Target->getLongDoubleFormat();
1686   case BuiltinType::Float128:
1687     if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice)
1688       return AuxTarget->getFloat128Format();
1689     return Target->getFloat128Format();
1690   }
1691 }
1692 
1693 CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
1694   unsigned Align = Target->getCharWidth();
1695 
1696   bool UseAlignAttrOnly = false;
1697   if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1698     Align = AlignFromAttr;
1699 
1700     // __attribute__((aligned)) can increase or decrease alignment
1701     // *except* on a struct or struct member, where it only increases
1702     // alignment unless 'packed' is also specified.
1703     //
1704     // It is an error for alignas to decrease alignment, so we can
1705     // ignore that possibility;  Sema should diagnose it.
1706     if (isa<FieldDecl>(D)) {
1707       UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1708         cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1709     } else {
1710       UseAlignAttrOnly = true;
1711     }
1712   }
1713   else if (isa<FieldDecl>(D))
1714       UseAlignAttrOnly =
1715         D->hasAttr<PackedAttr>() ||
1716         cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1717 
1718   // If we're using the align attribute only, just ignore everything
1719   // else about the declaration and its type.
1720   if (UseAlignAttrOnly) {
1721     // do nothing
1722   } else if (const auto *VD = dyn_cast<ValueDecl>(D)) {
1723     QualType T = VD->getType();
1724     if (const auto *RT = T->getAs<ReferenceType>()) {
1725       if (ForAlignof)
1726         T = RT->getPointeeType();
1727       else
1728         T = getPointerType(RT->getPointeeType());
1729     }
1730     QualType BaseT = getBaseElementType(T);
1731     if (T->isFunctionType())
1732       Align = getTypeInfoImpl(T.getTypePtr()).Align;
1733     else if (!BaseT->isIncompleteType()) {
1734       // Adjust alignments of declarations with array type by the
1735       // large-array alignment on the target.
1736       if (const ArrayType *arrayType = getAsArrayType(T)) {
1737         unsigned MinWidth = Target->getLargeArrayMinWidth();
1738         if (!ForAlignof && MinWidth) {
1739           if (isa<VariableArrayType>(arrayType))
1740             Align = std::max(Align, Target->getLargeArrayAlign());
1741           else if (isa<ConstantArrayType>(arrayType) &&
1742                    MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1743             Align = std::max(Align, Target->getLargeArrayAlign());
1744         }
1745       }
1746       Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
1747       if (BaseT.getQualifiers().hasUnaligned())
1748         Align = Target->getCharWidth();
1749       if (const auto *VD = dyn_cast<VarDecl>(D)) {
1750         if (VD->hasGlobalStorage() && !ForAlignof) {
1751           uint64_t TypeSize = getTypeSize(T.getTypePtr());
1752           Align = std::max(Align, getTargetInfo().getMinGlobalAlign(TypeSize));
1753         }
1754       }
1755     }
1756 
1757     // Fields can be subject to extra alignment constraints, like if
1758     // the field is packed, the struct is packed, or the struct has a
1759     // a max-field-alignment constraint (#pragma pack).  So calculate
1760     // the actual alignment of the field within the struct, and then
1761     // (as we're expected to) constrain that by the alignment of the type.
1762     if (const auto *Field = dyn_cast<FieldDecl>(VD)) {
1763       const RecordDecl *Parent = Field->getParent();
1764       // We can only produce a sensible answer if the record is valid.
1765       if (!Parent->isInvalidDecl()) {
1766         const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
1767 
1768         // Start with the record's overall alignment.
1769         unsigned FieldAlign = toBits(Layout.getAlignment());
1770 
1771         // Use the GCD of that and the offset within the record.
1772         uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1773         if (Offset > 0) {
1774           // Alignment is always a power of 2, so the GCD will be a power of 2,
1775           // which means we get to do this crazy thing instead of Euclid's.
1776           uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1777           if (LowBitOfOffset < FieldAlign)
1778             FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1779         }
1780 
1781         Align = std::min(Align, FieldAlign);
1782       }
1783     }
1784   }
1785 
1786   // Some targets have hard limitation on the maximum requestable alignment in
1787   // aligned attribute for static variables.
1788   const unsigned MaxAlignedAttr = getTargetInfo().getMaxAlignedAttribute();
1789   const auto *VD = dyn_cast<VarDecl>(D);
1790   if (MaxAlignedAttr && VD && VD->getStorageClass() == SC_Static)
1791     Align = std::min(Align, MaxAlignedAttr);
1792 
1793   return toCharUnitsFromBits(Align);
1794 }
1795 
1796 CharUnits ASTContext::getExnObjectAlignment() const {
1797   return toCharUnitsFromBits(Target->getExnObjectAlignment());
1798 }
1799 
1800 // getTypeInfoDataSizeInChars - Return the size of a type, in
1801 // chars. If the type is a record, its data size is returned.  This is
1802 // the size of the memcpy that's performed when assigning this type
1803 // using a trivial copy/move assignment operator.
1804 TypeInfoChars ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1805   TypeInfoChars Info = getTypeInfoInChars(T);
1806 
1807   // In C++, objects can sometimes be allocated into the tail padding
1808   // of a base-class subobject.  We decide whether that's possible
1809   // during class layout, so here we can just trust the layout results.
1810   if (getLangOpts().CPlusPlus) {
1811     if (const auto *RT = T->getAs<RecordType>()) {
1812       const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1813       Info.Width = layout.getDataSize();
1814     }
1815   }
1816 
1817   return Info;
1818 }
1819 
1820 /// getConstantArrayInfoInChars - Performing the computation in CharUnits
1821 /// instead of in bits prevents overflowing the uint64_t for some large arrays.
1822 TypeInfoChars
1823 static getConstantArrayInfoInChars(const ASTContext &Context,
1824                                    const ConstantArrayType *CAT) {
1825   TypeInfoChars EltInfo = Context.getTypeInfoInChars(CAT->getElementType());
1826   uint64_t Size = CAT->getSize().getZExtValue();
1827   assert((Size == 0 || static_cast<uint64_t>(EltInfo.Width.getQuantity()) <=
1828               (uint64_t)(-1)/Size) &&
1829          "Overflow in array type char size evaluation");
1830   uint64_t Width = EltInfo.Width.getQuantity() * Size;
1831   unsigned Align = EltInfo.Align.getQuantity();
1832   if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1833       Context.getTargetInfo().getPointerWidth(0) == 64)
1834     Width = llvm::alignTo(Width, Align);
1835   return TypeInfoChars(CharUnits::fromQuantity(Width),
1836                        CharUnits::fromQuantity(Align),
1837                        EltInfo.AlignIsRequired);
1838 }
1839 
1840 TypeInfoChars ASTContext::getTypeInfoInChars(const Type *T) const {
1841   if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
1842     return getConstantArrayInfoInChars(*this, CAT);
1843   TypeInfo Info = getTypeInfo(T);
1844   return TypeInfoChars(toCharUnitsFromBits(Info.Width),
1845                        toCharUnitsFromBits(Info.Align),
1846                        Info.AlignIsRequired);
1847 }
1848 
1849 TypeInfoChars ASTContext::getTypeInfoInChars(QualType T) const {
1850   return getTypeInfoInChars(T.getTypePtr());
1851 }
1852 
1853 bool ASTContext::isAlignmentRequired(const Type *T) const {
1854   return getTypeInfo(T).AlignIsRequired;
1855 }
1856 
1857 bool ASTContext::isAlignmentRequired(QualType T) const {
1858   return isAlignmentRequired(T.getTypePtr());
1859 }
1860 
1861 unsigned ASTContext::getTypeAlignIfKnown(QualType T,
1862                                          bool NeedsPreferredAlignment) const {
1863   // An alignment on a typedef overrides anything else.
1864   if (const auto *TT = T->getAs<TypedefType>())
1865     if (unsigned Align = TT->getDecl()->getMaxAlignment())
1866       return Align;
1867 
1868   // If we have an (array of) complete type, we're done.
1869   T = getBaseElementType(T);
1870   if (!T->isIncompleteType())
1871     return NeedsPreferredAlignment ? getPreferredTypeAlign(T) : getTypeAlign(T);
1872 
1873   // If we had an array type, its element type might be a typedef
1874   // type with an alignment attribute.
1875   if (const auto *TT = T->getAs<TypedefType>())
1876     if (unsigned Align = TT->getDecl()->getMaxAlignment())
1877       return Align;
1878 
1879   // Otherwise, see if the declaration of the type had an attribute.
1880   if (const auto *TT = T->getAs<TagType>())
1881     return TT->getDecl()->getMaxAlignment();
1882 
1883   return 0;
1884 }
1885 
1886 TypeInfo ASTContext::getTypeInfo(const Type *T) const {
1887   TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1888   if (I != MemoizedTypeInfo.end())
1889     return I->second;
1890 
1891   // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1892   TypeInfo TI = getTypeInfoImpl(T);
1893   MemoizedTypeInfo[T] = TI;
1894   return TI;
1895 }
1896 
1897 /// getTypeInfoImpl - Return the size of the specified type, in bits.  This
1898 /// method does not work on incomplete types.
1899 ///
1900 /// FIXME: Pointers into different addr spaces could have different sizes and
1901 /// alignment requirements: getPointerInfo should take an AddrSpace, this
1902 /// should take a QualType, &c.
1903 TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1904   uint64_t Width = 0;
1905   unsigned Align = 8;
1906   bool AlignIsRequired = false;
1907   unsigned AS = 0;
1908   switch (T->getTypeClass()) {
1909 #define TYPE(Class, Base)
1910 #define ABSTRACT_TYPE(Class, Base)
1911 #define NON_CANONICAL_TYPE(Class, Base)
1912 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1913 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)                       \
1914   case Type::Class:                                                            \
1915   assert(!T->isDependentType() && "should not see dependent types here");      \
1916   return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
1917 #include "clang/AST/TypeNodes.inc"
1918     llvm_unreachable("Should not see dependent types");
1919 
1920   case Type::FunctionNoProto:
1921   case Type::FunctionProto:
1922     // GCC extension: alignof(function) = 32 bits
1923     Width = 0;
1924     Align = 32;
1925     break;
1926 
1927   case Type::IncompleteArray:
1928   case Type::VariableArray:
1929   case Type::ConstantArray: {
1930     // Model non-constant sized arrays as size zero, but track the alignment.
1931     uint64_t Size = 0;
1932     if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
1933       Size = CAT->getSize().getZExtValue();
1934 
1935     TypeInfo EltInfo = getTypeInfo(cast<ArrayType>(T)->getElementType());
1936     assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
1937            "Overflow in array type bit size evaluation");
1938     Width = EltInfo.Width * Size;
1939     Align = EltInfo.Align;
1940     AlignIsRequired = EltInfo.AlignIsRequired;
1941     if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1942         getTargetInfo().getPointerWidth(0) == 64)
1943       Width = llvm::alignTo(Width, Align);
1944     break;
1945   }
1946 
1947   case Type::ExtVector:
1948   case Type::Vector: {
1949     const auto *VT = cast<VectorType>(T);
1950     TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1951     Width = EltInfo.Width * VT->getNumElements();
1952     Align = Width;
1953     // If the alignment is not a power of 2, round up to the next power of 2.
1954     // This happens for non-power-of-2 length vectors.
1955     if (Align & (Align-1)) {
1956       Align = llvm::NextPowerOf2(Align);
1957       Width = llvm::alignTo(Width, Align);
1958     }
1959     // Adjust the alignment based on the target max.
1960     uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1961     if (TargetVectorAlign && TargetVectorAlign < Align)
1962       Align = TargetVectorAlign;
1963     if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector)
1964       // Adjust the alignment for fixed-length SVE vectors. This is important
1965       // for non-power-of-2 vector lengths.
1966       Align = 128;
1967     else if (VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector)
1968       // Adjust the alignment for fixed-length SVE predicates.
1969       Align = 16;
1970     break;
1971   }
1972 
1973   case Type::ConstantMatrix: {
1974     const auto *MT = cast<ConstantMatrixType>(T);
1975     TypeInfo ElementInfo = getTypeInfo(MT->getElementType());
1976     // The internal layout of a matrix value is implementation defined.
1977     // Initially be ABI compatible with arrays with respect to alignment and
1978     // size.
1979     Width = ElementInfo.Width * MT->getNumRows() * MT->getNumColumns();
1980     Align = ElementInfo.Align;
1981     break;
1982   }
1983 
1984   case Type::Builtin:
1985     switch (cast<BuiltinType>(T)->getKind()) {
1986     default: llvm_unreachable("Unknown builtin type!");
1987     case BuiltinType::Void:
1988       // GCC extension: alignof(void) = 8 bits.
1989       Width = 0;
1990       Align = 8;
1991       break;
1992     case BuiltinType::Bool:
1993       Width = Target->getBoolWidth();
1994       Align = Target->getBoolAlign();
1995       break;
1996     case BuiltinType::Char_S:
1997     case BuiltinType::Char_U:
1998     case BuiltinType::UChar:
1999     case BuiltinType::SChar:
2000     case BuiltinType::Char8:
2001       Width = Target->getCharWidth();
2002       Align = Target->getCharAlign();
2003       break;
2004     case BuiltinType::WChar_S:
2005     case BuiltinType::WChar_U:
2006       Width = Target->getWCharWidth();
2007       Align = Target->getWCharAlign();
2008       break;
2009     case BuiltinType::Char16:
2010       Width = Target->getChar16Width();
2011       Align = Target->getChar16Align();
2012       break;
2013     case BuiltinType::Char32:
2014       Width = Target->getChar32Width();
2015       Align = Target->getChar32Align();
2016       break;
2017     case BuiltinType::UShort:
2018     case BuiltinType::Short:
2019       Width = Target->getShortWidth();
2020       Align = Target->getShortAlign();
2021       break;
2022     case BuiltinType::UInt:
2023     case BuiltinType::Int:
2024       Width = Target->getIntWidth();
2025       Align = Target->getIntAlign();
2026       break;
2027     case BuiltinType::ULong:
2028     case BuiltinType::Long:
2029       Width = Target->getLongWidth();
2030       Align = Target->getLongAlign();
2031       break;
2032     case BuiltinType::ULongLong:
2033     case BuiltinType::LongLong:
2034       Width = Target->getLongLongWidth();
2035       Align = Target->getLongLongAlign();
2036       break;
2037     case BuiltinType::Int128:
2038     case BuiltinType::UInt128:
2039       Width = 128;
2040       Align = 128; // int128_t is 128-bit aligned on all targets.
2041       break;
2042     case BuiltinType::ShortAccum:
2043     case BuiltinType::UShortAccum:
2044     case BuiltinType::SatShortAccum:
2045     case BuiltinType::SatUShortAccum:
2046       Width = Target->getShortAccumWidth();
2047       Align = Target->getShortAccumAlign();
2048       break;
2049     case BuiltinType::Accum:
2050     case BuiltinType::UAccum:
2051     case BuiltinType::SatAccum:
2052     case BuiltinType::SatUAccum:
2053       Width = Target->getAccumWidth();
2054       Align = Target->getAccumAlign();
2055       break;
2056     case BuiltinType::LongAccum:
2057     case BuiltinType::ULongAccum:
2058     case BuiltinType::SatLongAccum:
2059     case BuiltinType::SatULongAccum:
2060       Width = Target->getLongAccumWidth();
2061       Align = Target->getLongAccumAlign();
2062       break;
2063     case BuiltinType::ShortFract:
2064     case BuiltinType::UShortFract:
2065     case BuiltinType::SatShortFract:
2066     case BuiltinType::SatUShortFract:
2067       Width = Target->getShortFractWidth();
2068       Align = Target->getShortFractAlign();
2069       break;
2070     case BuiltinType::Fract:
2071     case BuiltinType::UFract:
2072     case BuiltinType::SatFract:
2073     case BuiltinType::SatUFract:
2074       Width = Target->getFractWidth();
2075       Align = Target->getFractAlign();
2076       break;
2077     case BuiltinType::LongFract:
2078     case BuiltinType::ULongFract:
2079     case BuiltinType::SatLongFract:
2080     case BuiltinType::SatULongFract:
2081       Width = Target->getLongFractWidth();
2082       Align = Target->getLongFractAlign();
2083       break;
2084     case BuiltinType::BFloat16:
2085       Width = Target->getBFloat16Width();
2086       Align = Target->getBFloat16Align();
2087       break;
2088     case BuiltinType::Float16:
2089     case BuiltinType::Half:
2090       if (Target->hasFloat16Type() || !getLangOpts().OpenMP ||
2091           !getLangOpts().OpenMPIsDevice) {
2092         Width = Target->getHalfWidth();
2093         Align = Target->getHalfAlign();
2094       } else {
2095         assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
2096                "Expected OpenMP device compilation.");
2097         Width = AuxTarget->getHalfWidth();
2098         Align = AuxTarget->getHalfAlign();
2099       }
2100       break;
2101     case BuiltinType::Float:
2102       Width = Target->getFloatWidth();
2103       Align = Target->getFloatAlign();
2104       break;
2105     case BuiltinType::Double:
2106       Width = Target->getDoubleWidth();
2107       Align = Target->getDoubleAlign();
2108       break;
2109     case BuiltinType::LongDouble:
2110       if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
2111           (Target->getLongDoubleWidth() != AuxTarget->getLongDoubleWidth() ||
2112            Target->getLongDoubleAlign() != AuxTarget->getLongDoubleAlign())) {
2113         Width = AuxTarget->getLongDoubleWidth();
2114         Align = AuxTarget->getLongDoubleAlign();
2115       } else {
2116         Width = Target->getLongDoubleWidth();
2117         Align = Target->getLongDoubleAlign();
2118       }
2119       break;
2120     case BuiltinType::Float128:
2121       if (Target->hasFloat128Type() || !getLangOpts().OpenMP ||
2122           !getLangOpts().OpenMPIsDevice) {
2123         Width = Target->getFloat128Width();
2124         Align = Target->getFloat128Align();
2125       } else {
2126         assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
2127                "Expected OpenMP device compilation.");
2128         Width = AuxTarget->getFloat128Width();
2129         Align = AuxTarget->getFloat128Align();
2130       }
2131       break;
2132     case BuiltinType::NullPtr:
2133       Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
2134       Align = Target->getPointerAlign(0); //   == sizeof(void*)
2135       break;
2136     case BuiltinType::ObjCId:
2137     case BuiltinType::ObjCClass:
2138     case BuiltinType::ObjCSel:
2139       Width = Target->getPointerWidth(0);
2140       Align = Target->getPointerAlign(0);
2141       break;
2142     case BuiltinType::OCLSampler:
2143     case BuiltinType::OCLEvent:
2144     case BuiltinType::OCLClkEvent:
2145     case BuiltinType::OCLQueue:
2146     case BuiltinType::OCLReserveID:
2147 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2148     case BuiltinType::Id:
2149 #include "clang/Basic/OpenCLImageTypes.def"
2150 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2151   case BuiltinType::Id:
2152 #include "clang/Basic/OpenCLExtensionTypes.def"
2153       AS = getTargetAddressSpace(
2154           Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T)));
2155       Width = Target->getPointerWidth(AS);
2156       Align = Target->getPointerAlign(AS);
2157       break;
2158     // The SVE types are effectively target-specific.  The length of an
2159     // SVE_VECTOR_TYPE is only known at runtime, but it is always a multiple
2160     // of 128 bits.  There is one predicate bit for each vector byte, so the
2161     // length of an SVE_PREDICATE_TYPE is always a multiple of 16 bits.
2162     //
2163     // Because the length is only known at runtime, we use a dummy value
2164     // of 0 for the static length.  The alignment values are those defined
2165     // by the Procedure Call Standard for the Arm Architecture.
2166 #define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId, NumEls, ElBits,    \
2167                         IsSigned, IsFP, IsBF)                                  \
2168   case BuiltinType::Id:                                                        \
2169     Width = 0;                                                                 \
2170     Align = 128;                                                               \
2171     break;
2172 #define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId, NumEls)         \
2173   case BuiltinType::Id:                                                        \
2174     Width = 0;                                                                 \
2175     Align = 16;                                                                \
2176     break;
2177 #include "clang/Basic/AArch64SVEACLETypes.def"
2178 #define PPC_VECTOR_TYPE(Name, Id, Size)                                        \
2179   case BuiltinType::Id:                                                        \
2180     Width = Size;                                                              \
2181     Align = Size;                                                              \
2182     break;
2183 #include "clang/Basic/PPCTypes.def"
2184 #define RVV_VECTOR_TYPE(Name, Id, SingletonId, ElKind, ElBits, NF, IsSigned,   \
2185                         IsFP)                                                  \
2186   case BuiltinType::Id:                                                        \
2187     Width = 0;                                                                 \
2188     Align = ElBits;                                                            \
2189     break;
2190 #define RVV_PREDICATE_TYPE(Name, Id, SingletonId, ElKind)                      \
2191   case BuiltinType::Id:                                                        \
2192     Width = 0;                                                                 \
2193     Align = 8;                                                                 \
2194     break;
2195 #include "clang/Basic/RISCVVTypes.def"
2196     }
2197     break;
2198   case Type::ObjCObjectPointer:
2199     Width = Target->getPointerWidth(0);
2200     Align = Target->getPointerAlign(0);
2201     break;
2202   case Type::BlockPointer:
2203     AS = getTargetAddressSpace(cast<BlockPointerType>(T)->getPointeeType());
2204     Width = Target->getPointerWidth(AS);
2205     Align = Target->getPointerAlign(AS);
2206     break;
2207   case Type::LValueReference:
2208   case Type::RValueReference:
2209     // alignof and sizeof should never enter this code path here, so we go
2210     // the pointer route.
2211     AS = getTargetAddressSpace(cast<ReferenceType>(T)->getPointeeType());
2212     Width = Target->getPointerWidth(AS);
2213     Align = Target->getPointerAlign(AS);
2214     break;
2215   case Type::Pointer:
2216     AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
2217     Width = Target->getPointerWidth(AS);
2218     Align = Target->getPointerAlign(AS);
2219     break;
2220   case Type::MemberPointer: {
2221     const auto *MPT = cast<MemberPointerType>(T);
2222     CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT);
2223     Width = MPI.Width;
2224     Align = MPI.Align;
2225     break;
2226   }
2227   case Type::Complex: {
2228     // Complex types have the same alignment as their elements, but twice the
2229     // size.
2230     TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
2231     Width = EltInfo.Width * 2;
2232     Align = EltInfo.Align;
2233     break;
2234   }
2235   case Type::ObjCObject:
2236     return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
2237   case Type::Adjusted:
2238   case Type::Decayed:
2239     return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
2240   case Type::ObjCInterface: {
2241     const auto *ObjCI = cast<ObjCInterfaceType>(T);
2242     if (ObjCI->getDecl()->isInvalidDecl()) {
2243       Width = 8;
2244       Align = 8;
2245       break;
2246     }
2247     const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2248     Width = toBits(Layout.getSize());
2249     Align = toBits(Layout.getAlignment());
2250     break;
2251   }
2252   case Type::ExtInt: {
2253     const auto *EIT = cast<ExtIntType>(T);
2254     Align =
2255         std::min(static_cast<unsigned>(std::max(
2256                      getCharWidth(), llvm::PowerOf2Ceil(EIT->getNumBits()))),
2257                  Target->getLongLongAlign());
2258     Width = llvm::alignTo(EIT->getNumBits(), Align);
2259     break;
2260   }
2261   case Type::Record:
2262   case Type::Enum: {
2263     const auto *TT = cast<TagType>(T);
2264 
2265     if (TT->getDecl()->isInvalidDecl()) {
2266       Width = 8;
2267       Align = 8;
2268       break;
2269     }
2270 
2271     if (const auto *ET = dyn_cast<EnumType>(TT)) {
2272       const EnumDecl *ED = ET->getDecl();
2273       TypeInfo Info =
2274           getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
2275       if (unsigned AttrAlign = ED->getMaxAlignment()) {
2276         Info.Align = AttrAlign;
2277         Info.AlignIsRequired = true;
2278       }
2279       return Info;
2280     }
2281 
2282     const auto *RT = cast<RecordType>(TT);
2283     const RecordDecl *RD = RT->getDecl();
2284     const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2285     Width = toBits(Layout.getSize());
2286     Align = toBits(Layout.getAlignment());
2287     AlignIsRequired = RD->hasAttr<AlignedAttr>();
2288     break;
2289   }
2290 
2291   case Type::SubstTemplateTypeParm:
2292     return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
2293                        getReplacementType().getTypePtr());
2294 
2295   case Type::Auto:
2296   case Type::DeducedTemplateSpecialization: {
2297     const auto *A = cast<DeducedType>(T);
2298     assert(!A->getDeducedType().isNull() &&
2299            "cannot request the size of an undeduced or dependent auto type");
2300     return getTypeInfo(A->getDeducedType().getTypePtr());
2301   }
2302 
2303   case Type::Paren:
2304     return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
2305 
2306   case Type::MacroQualified:
2307     return getTypeInfo(
2308         cast<MacroQualifiedType>(T)->getUnderlyingType().getTypePtr());
2309 
2310   case Type::ObjCTypeParam:
2311     return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
2312 
2313   case Type::Typedef: {
2314     const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
2315     TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
2316     // If the typedef has an aligned attribute on it, it overrides any computed
2317     // alignment we have.  This violates the GCC documentation (which says that
2318     // attribute(aligned) can only round up) but matches its implementation.
2319     if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
2320       Align = AttrAlign;
2321       AlignIsRequired = true;
2322     } else {
2323       Align = Info.Align;
2324       AlignIsRequired = Info.AlignIsRequired;
2325     }
2326     Width = Info.Width;
2327     break;
2328   }
2329 
2330   case Type::Elaborated:
2331     return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
2332 
2333   case Type::Attributed:
2334     return getTypeInfo(
2335                   cast<AttributedType>(T)->getEquivalentType().getTypePtr());
2336 
2337   case Type::Atomic: {
2338     // Start with the base type information.
2339     TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
2340     Width = Info.Width;
2341     Align = Info.Align;
2342 
2343     if (!Width) {
2344       // An otherwise zero-sized type should still generate an
2345       // atomic operation.
2346       Width = Target->getCharWidth();
2347       assert(Align);
2348     } else if (Width <= Target->getMaxAtomicPromoteWidth()) {
2349       // If the size of the type doesn't exceed the platform's max
2350       // atomic promotion width, make the size and alignment more
2351       // favorable to atomic operations:
2352 
2353       // Round the size up to a power of 2.
2354       if (!llvm::isPowerOf2_64(Width))
2355         Width = llvm::NextPowerOf2(Width);
2356 
2357       // Set the alignment equal to the size.
2358       Align = static_cast<unsigned>(Width);
2359     }
2360   }
2361   break;
2362 
2363   case Type::Pipe:
2364     Width = Target->getPointerWidth(getTargetAddressSpace(LangAS::opencl_global));
2365     Align = Target->getPointerAlign(getTargetAddressSpace(LangAS::opencl_global));
2366     break;
2367   }
2368 
2369   assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
2370   return TypeInfo(Width, Align, AlignIsRequired);
2371 }
2372 
2373 unsigned ASTContext::getTypeUnadjustedAlign(const Type *T) const {
2374   UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T);
2375   if (I != MemoizedUnadjustedAlign.end())
2376     return I->second;
2377 
2378   unsigned UnadjustedAlign;
2379   if (const auto *RT = T->getAs<RecordType>()) {
2380     const RecordDecl *RD = RT->getDecl();
2381     const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2382     UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2383   } else if (const auto *ObjCI = T->getAs<ObjCInterfaceType>()) {
2384     const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2385     UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2386   } else {
2387     UnadjustedAlign = getTypeAlign(T->getUnqualifiedDesugaredType());
2388   }
2389 
2390   MemoizedUnadjustedAlign[T] = UnadjustedAlign;
2391   return UnadjustedAlign;
2392 }
2393 
2394 unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
2395   unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
2396   return SimdAlign;
2397 }
2398 
2399 /// toCharUnitsFromBits - Convert a size in bits to a size in characters.
2400 CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
2401   return CharUnits::fromQuantity(BitSize / getCharWidth());
2402 }
2403 
2404 /// toBits - Convert a size in characters to a size in characters.
2405 int64_t ASTContext::toBits(CharUnits CharSize) const {
2406   return CharSize.getQuantity() * getCharWidth();
2407 }
2408 
2409 /// getTypeSizeInChars - Return the size of the specified type, in characters.
2410 /// This method does not work on incomplete types.
2411 CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
2412   return getTypeInfoInChars(T).Width;
2413 }
2414 CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
2415   return getTypeInfoInChars(T).Width;
2416 }
2417 
2418 /// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
2419 /// characters. This method does not work on incomplete types.
2420 CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
2421   return toCharUnitsFromBits(getTypeAlign(T));
2422 }
2423 CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
2424   return toCharUnitsFromBits(getTypeAlign(T));
2425 }
2426 
2427 /// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a
2428 /// type, in characters, before alignment adustments. This method does
2429 /// not work on incomplete types.
2430 CharUnits ASTContext::getTypeUnadjustedAlignInChars(QualType T) const {
2431   return toCharUnitsFromBits(getTypeUnadjustedAlign(T));
2432 }
2433 CharUnits ASTContext::getTypeUnadjustedAlignInChars(const Type *T) const {
2434   return toCharUnitsFromBits(getTypeUnadjustedAlign(T));
2435 }
2436 
2437 /// getPreferredTypeAlign - Return the "preferred" alignment of the specified
2438 /// type for the current target in bits.  This can be different than the ABI
2439 /// alignment in cases where it is beneficial for performance or backwards
2440 /// compatibility preserving to overalign a data type. (Note: despite the name,
2441 /// the preferred alignment is ABI-impacting, and not an optimization.)
2442 unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
2443   TypeInfo TI = getTypeInfo(T);
2444   unsigned ABIAlign = TI.Align;
2445 
2446   T = T->getBaseElementTypeUnsafe();
2447 
2448   // The preferred alignment of member pointers is that of a pointer.
2449   if (T->isMemberPointerType())
2450     return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
2451 
2452   if (!Target->allowsLargerPreferedTypeAlignment())
2453     return ABIAlign;
2454 
2455   if (const auto *RT = T->getAs<RecordType>()) {
2456     if (TI.AlignIsRequired || RT->getDecl()->isInvalidDecl())
2457       return ABIAlign;
2458 
2459     unsigned PreferredAlign = static_cast<unsigned>(
2460         toBits(getASTRecordLayout(RT->getDecl()).PreferredAlignment));
2461     assert(PreferredAlign >= ABIAlign &&
2462            "PreferredAlign should be at least as large as ABIAlign.");
2463     return PreferredAlign;
2464   }
2465 
2466   // Double (and, for targets supporting AIX `power` alignment, long double) and
2467   // long long should be naturally aligned (despite requiring less alignment) if
2468   // possible.
2469   if (const auto *CT = T->getAs<ComplexType>())
2470     T = CT->getElementType().getTypePtr();
2471   if (const auto *ET = T->getAs<EnumType>())
2472     T = ET->getDecl()->getIntegerType().getTypePtr();
2473   if (T->isSpecificBuiltinType(BuiltinType::Double) ||
2474       T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2475       T->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2476       (T->isSpecificBuiltinType(BuiltinType::LongDouble) &&
2477        Target->defaultsToAIXPowerAlignment()))
2478     // Don't increase the alignment if an alignment attribute was specified on a
2479     // typedef declaration.
2480     if (!TI.AlignIsRequired)
2481       return std::max(ABIAlign, (unsigned)getTypeSize(T));
2482 
2483   return ABIAlign;
2484 }
2485 
2486 /// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2487 /// for __attribute__((aligned)) on this target, to be used if no alignment
2488 /// value is specified.
2489 unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const {
2490   return getTargetInfo().getDefaultAlignForAttributeAligned();
2491 }
2492 
2493 /// getAlignOfGlobalVar - Return the alignment in bits that should be given
2494 /// to a global variable of the specified type.
2495 unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
2496   uint64_t TypeSize = getTypeSize(T.getTypePtr());
2497   return std::max(getPreferredTypeAlign(T),
2498                   getTargetInfo().getMinGlobalAlign(TypeSize));
2499 }
2500 
2501 /// getAlignOfGlobalVarInChars - Return the alignment in characters that
2502 /// should be given to a global variable of the specified type.
2503 CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
2504   return toCharUnitsFromBits(getAlignOfGlobalVar(T));
2505 }
2506 
2507 CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
2508   CharUnits Offset = CharUnits::Zero();
2509   const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2510   while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2511     Offset += Layout->getBaseClassOffset(Base);
2512     Layout = &getASTRecordLayout(Base);
2513   }
2514   return Offset;
2515 }
2516 
2517 CharUnits ASTContext::getMemberPointerPathAdjustment(const APValue &MP) const {
2518   const ValueDecl *MPD = MP.getMemberPointerDecl();
2519   CharUnits ThisAdjustment = CharUnits::Zero();
2520   ArrayRef<const CXXRecordDecl*> Path = MP.getMemberPointerPath();
2521   bool DerivedMember = MP.isMemberPointerToDerivedMember();
2522   const CXXRecordDecl *RD = cast<CXXRecordDecl>(MPD->getDeclContext());
2523   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
2524     const CXXRecordDecl *Base = RD;
2525     const CXXRecordDecl *Derived = Path[I];
2526     if (DerivedMember)
2527       std::swap(Base, Derived);
2528     ThisAdjustment += getASTRecordLayout(Derived).getBaseClassOffset(Base);
2529     RD = Path[I];
2530   }
2531   if (DerivedMember)
2532     ThisAdjustment = -ThisAdjustment;
2533   return ThisAdjustment;
2534 }
2535 
2536 /// DeepCollectObjCIvars -
2537 /// This routine first collects all declared, but not synthesized, ivars in
2538 /// super class and then collects all ivars, including those synthesized for
2539 /// current class. This routine is used for implementation of current class
2540 /// when all ivars, declared and synthesized are known.
2541 void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
2542                                       bool leafClass,
2543                             SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
2544   if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2545     DeepCollectObjCIvars(SuperClass, false, Ivars);
2546   if (!leafClass) {
2547     for (const auto *I : OI->ivars())
2548       Ivars.push_back(I);
2549   } else {
2550     auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
2551     for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
2552          Iv= Iv->getNextIvar())
2553       Ivars.push_back(Iv);
2554   }
2555 }
2556 
2557 /// CollectInheritedProtocols - Collect all protocols in current class and
2558 /// those inherited by it.
2559 void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
2560                           llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
2561   if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
2562     // We can use protocol_iterator here instead of
2563     // all_referenced_protocol_iterator since we are walking all categories.
2564     for (auto *Proto : OI->all_referenced_protocols()) {
2565       CollectInheritedProtocols(Proto, Protocols);
2566     }
2567 
2568     // Categories of this Interface.
2569     for (const auto *Cat : OI->visible_categories())
2570       CollectInheritedProtocols(Cat, Protocols);
2571 
2572     if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2573       while (SD) {
2574         CollectInheritedProtocols(SD, Protocols);
2575         SD = SD->getSuperClass();
2576       }
2577   } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
2578     for (auto *Proto : OC->protocols()) {
2579       CollectInheritedProtocols(Proto, Protocols);
2580     }
2581   } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
2582     // Insert the protocol.
2583     if (!Protocols.insert(
2584           const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2585       return;
2586 
2587     for (auto *Proto : OP->protocols())
2588       CollectInheritedProtocols(Proto, Protocols);
2589   }
2590 }
2591 
2592 static bool unionHasUniqueObjectRepresentations(const ASTContext &Context,
2593                                                 const RecordDecl *RD) {
2594   assert(RD->isUnion() && "Must be union type");
2595   CharUnits UnionSize = Context.getTypeSizeInChars(RD->getTypeForDecl());
2596 
2597   for (const auto *Field : RD->fields()) {
2598     if (!Context.hasUniqueObjectRepresentations(Field->getType()))
2599       return false;
2600     CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType());
2601     if (FieldSize != UnionSize)
2602       return false;
2603   }
2604   return !RD->field_empty();
2605 }
2606 
2607 static bool isStructEmpty(QualType Ty) {
2608   const RecordDecl *RD = Ty->castAs<RecordType>()->getDecl();
2609 
2610   if (!RD->field_empty())
2611     return false;
2612 
2613   if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD))
2614     return ClassDecl->isEmpty();
2615 
2616   return true;
2617 }
2618 
2619 static llvm::Optional<int64_t>
2620 structHasUniqueObjectRepresentations(const ASTContext &Context,
2621                                      const RecordDecl *RD) {
2622   assert(!RD->isUnion() && "Must be struct/class type");
2623   const auto &Layout = Context.getASTRecordLayout(RD);
2624 
2625   int64_t CurOffsetInBits = 0;
2626   if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) {
2627     if (ClassDecl->isDynamicClass())
2628       return llvm::None;
2629 
2630     SmallVector<std::pair<QualType, int64_t>, 4> Bases;
2631     for (const auto &Base : ClassDecl->bases()) {
2632       // Empty types can be inherited from, and non-empty types can potentially
2633       // have tail padding, so just make sure there isn't an error.
2634       if (!isStructEmpty(Base.getType())) {
2635         llvm::Optional<int64_t> Size = structHasUniqueObjectRepresentations(
2636             Context, Base.getType()->castAs<RecordType>()->getDecl());
2637         if (!Size)
2638           return llvm::None;
2639         Bases.emplace_back(Base.getType(), Size.getValue());
2640       }
2641     }
2642 
2643     llvm::sort(Bases, [&](const std::pair<QualType, int64_t> &L,
2644                           const std::pair<QualType, int64_t> &R) {
2645       return Layout.getBaseClassOffset(L.first->getAsCXXRecordDecl()) <
2646              Layout.getBaseClassOffset(R.first->getAsCXXRecordDecl());
2647     });
2648 
2649     for (const auto &Base : Bases) {
2650       int64_t BaseOffset = Context.toBits(
2651           Layout.getBaseClassOffset(Base.first->getAsCXXRecordDecl()));
2652       int64_t BaseSize = Base.second;
2653       if (BaseOffset != CurOffsetInBits)
2654         return llvm::None;
2655       CurOffsetInBits = BaseOffset + BaseSize;
2656     }
2657   }
2658 
2659   for (const auto *Field : RD->fields()) {
2660     if (!Field->getType()->isReferenceType() &&
2661         !Context.hasUniqueObjectRepresentations(Field->getType()))
2662       return llvm::None;
2663 
2664     int64_t FieldSizeInBits =
2665         Context.toBits(Context.getTypeSizeInChars(Field->getType()));
2666     if (Field->isBitField()) {
2667       int64_t BitfieldSize = Field->getBitWidthValue(Context);
2668 
2669       if (BitfieldSize > FieldSizeInBits)
2670         return llvm::None;
2671       FieldSizeInBits = BitfieldSize;
2672     }
2673 
2674     int64_t FieldOffsetInBits = Context.getFieldOffset(Field);
2675 
2676     if (FieldOffsetInBits != CurOffsetInBits)
2677       return llvm::None;
2678 
2679     CurOffsetInBits = FieldSizeInBits + FieldOffsetInBits;
2680   }
2681 
2682   return CurOffsetInBits;
2683 }
2684 
2685 bool ASTContext::hasUniqueObjectRepresentations(QualType Ty) const {
2686   // C++17 [meta.unary.prop]:
2687   //   The predicate condition for a template specialization
2688   //   has_unique_object_representations<T> shall be
2689   //   satisfied if and only if:
2690   //     (9.1) - T is trivially copyable, and
2691   //     (9.2) - any two objects of type T with the same value have the same
2692   //     object representation, where two objects
2693   //   of array or non-union class type are considered to have the same value
2694   //   if their respective sequences of
2695   //   direct subobjects have the same values, and two objects of union type
2696   //   are considered to have the same
2697   //   value if they have the same active member and the corresponding members
2698   //   have the same value.
2699   //   The set of scalar types for which this condition holds is
2700   //   implementation-defined. [ Note: If a type has padding
2701   //   bits, the condition does not hold; otherwise, the condition holds true
2702   //   for unsigned integral types. -- end note ]
2703   assert(!Ty.isNull() && "Null QualType sent to unique object rep check");
2704 
2705   // Arrays are unique only if their element type is unique.
2706   if (Ty->isArrayType())
2707     return hasUniqueObjectRepresentations(getBaseElementType(Ty));
2708 
2709   // (9.1) - T is trivially copyable...
2710   if (!Ty.isTriviallyCopyableType(*this))
2711     return false;
2712 
2713   // All integrals and enums are unique.
2714   if (Ty->isIntegralOrEnumerationType())
2715     return true;
2716 
2717   // All other pointers are unique.
2718   if (Ty->isPointerType())
2719     return true;
2720 
2721   if (Ty->isMemberPointerType()) {
2722     const auto *MPT = Ty->getAs<MemberPointerType>();
2723     return !ABI->getMemberPointerInfo(MPT).HasPadding;
2724   }
2725 
2726   if (Ty->isRecordType()) {
2727     const RecordDecl *Record = Ty->castAs<RecordType>()->getDecl();
2728 
2729     if (Record->isInvalidDecl())
2730       return false;
2731 
2732     if (Record->isUnion())
2733       return unionHasUniqueObjectRepresentations(*this, Record);
2734 
2735     Optional<int64_t> StructSize =
2736         structHasUniqueObjectRepresentations(*this, Record);
2737 
2738     return StructSize &&
2739            StructSize.getValue() == static_cast<int64_t>(getTypeSize(Ty));
2740   }
2741 
2742   // FIXME: More cases to handle here (list by rsmith):
2743   // vectors (careful about, eg, vector of 3 foo)
2744   // _Complex int and friends
2745   // _Atomic T
2746   // Obj-C block pointers
2747   // Obj-C object pointers
2748   // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t,
2749   // clk_event_t, queue_t, reserve_id_t)
2750   // There're also Obj-C class types and the Obj-C selector type, but I think it
2751   // makes sense for those to return false here.
2752 
2753   return false;
2754 }
2755 
2756 unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
2757   unsigned count = 0;
2758   // Count ivars declared in class extension.
2759   for (const auto *Ext : OI->known_extensions())
2760     count += Ext->ivar_size();
2761 
2762   // Count ivar defined in this class's implementation.  This
2763   // includes synthesized ivars.
2764   if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
2765     count += ImplDecl->ivar_size();
2766 
2767   return count;
2768 }
2769 
2770 bool ASTContext::isSentinelNullExpr(const Expr *E) {
2771   if (!E)
2772     return false;
2773 
2774   // nullptr_t is always treated as null.
2775   if (E->getType()->isNullPtrType()) return true;
2776 
2777   if (E->getType()->isAnyPointerType() &&
2778       E->IgnoreParenCasts()->isNullPointerConstant(*this,
2779                                                 Expr::NPC_ValueDependentIsNull))
2780     return true;
2781 
2782   // Unfortunately, __null has type 'int'.
2783   if (isa<GNUNullExpr>(E)) return true;
2784 
2785   return false;
2786 }
2787 
2788 /// Get the implementation of ObjCInterfaceDecl, or nullptr if none
2789 /// exists.
2790 ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
2791   llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2792     I = ObjCImpls.find(D);
2793   if (I != ObjCImpls.end())
2794     return cast<ObjCImplementationDecl>(I->second);
2795   return nullptr;
2796 }
2797 
2798 /// Get the implementation of ObjCCategoryDecl, or nullptr if none
2799 /// exists.
2800 ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
2801   llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2802     I = ObjCImpls.find(D);
2803   if (I != ObjCImpls.end())
2804     return cast<ObjCCategoryImplDecl>(I->second);
2805   return nullptr;
2806 }
2807 
2808 /// Set the implementation of ObjCInterfaceDecl.
2809 void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2810                            ObjCImplementationDecl *ImplD) {
2811   assert(IFaceD && ImplD && "Passed null params");
2812   ObjCImpls[IFaceD] = ImplD;
2813 }
2814 
2815 /// Set the implementation of ObjCCategoryDecl.
2816 void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
2817                            ObjCCategoryImplDecl *ImplD) {
2818   assert(CatD && ImplD && "Passed null params");
2819   ObjCImpls[CatD] = ImplD;
2820 }
2821 
2822 const ObjCMethodDecl *
2823 ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const {
2824   return ObjCMethodRedecls.lookup(MD);
2825 }
2826 
2827 void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2828                                             const ObjCMethodDecl *Redecl) {
2829   assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
2830   ObjCMethodRedecls[MD] = Redecl;
2831 }
2832 
2833 const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
2834                                               const NamedDecl *ND) const {
2835   if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
2836     return ID;
2837   if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
2838     return CD->getClassInterface();
2839   if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
2840     return IMD->getClassInterface();
2841 
2842   return nullptr;
2843 }
2844 
2845 /// Get the copy initialization expression of VarDecl, or nullptr if
2846 /// none exists.
2847 BlockVarCopyInit ASTContext::getBlockVarCopyInit(const VarDecl *VD) const {
2848   assert(VD && "Passed null params");
2849   assert(VD->hasAttr<BlocksAttr>() &&
2850          "getBlockVarCopyInits - not __block var");
2851   auto I = BlockVarCopyInits.find(VD);
2852   if (I != BlockVarCopyInits.end())
2853     return I->second;
2854   return {nullptr, false};
2855 }
2856 
2857 /// Set the copy initialization expression of a block var decl.
2858 void ASTContext::setBlockVarCopyInit(const VarDecl*VD, Expr *CopyExpr,
2859                                      bool CanThrow) {
2860   assert(VD && CopyExpr && "Passed null params");
2861   assert(VD->hasAttr<BlocksAttr>() &&
2862          "setBlockVarCopyInits - not __block var");
2863   BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow);
2864 }
2865 
2866 TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
2867                                                  unsigned DataSize) const {
2868   if (!DataSize)
2869     DataSize = TypeLoc::getFullDataSizeForType(T);
2870   else
2871     assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
2872            "incorrect data size provided to CreateTypeSourceInfo!");
2873 
2874   auto *TInfo =
2875     (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2876   new (TInfo) TypeSourceInfo(T);
2877   return TInfo;
2878 }
2879 
2880 TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
2881                                                      SourceLocation L) const {
2882   TypeSourceInfo *DI = CreateTypeSourceInfo(T);
2883   DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
2884   return DI;
2885 }
2886 
2887 const ASTRecordLayout &
2888 ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
2889   return getObjCLayout(D, nullptr);
2890 }
2891 
2892 const ASTRecordLayout &
2893 ASTContext::getASTObjCImplementationLayout(
2894                                         const ObjCImplementationDecl *D) const {
2895   return getObjCLayout(D->getClassInterface(), D);
2896 }
2897 
2898 //===----------------------------------------------------------------------===//
2899 //                   Type creation/memoization methods
2900 //===----------------------------------------------------------------------===//
2901 
2902 QualType
2903 ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2904   unsigned fastQuals = quals.getFastQualifiers();
2905   quals.removeFastQualifiers();
2906 
2907   // Check if we've already instantiated this type.
2908   llvm::FoldingSetNodeID ID;
2909   ExtQuals::Profile(ID, baseType, quals);
2910   void *insertPos = nullptr;
2911   if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2912     assert(eq->getQualifiers() == quals);
2913     return QualType(eq, fastQuals);
2914   }
2915 
2916   // If the base type is not canonical, make the appropriate canonical type.
2917   QualType canon;
2918   if (!baseType->isCanonicalUnqualified()) {
2919     SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
2920     canonSplit.Quals.addConsistentQualifiers(quals);
2921     canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
2922 
2923     // Re-find the insert position.
2924     (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2925   }
2926 
2927   auto *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2928   ExtQualNodes.InsertNode(eq, insertPos);
2929   return QualType(eq, fastQuals);
2930 }
2931 
2932 QualType ASTContext::getAddrSpaceQualType(QualType T,
2933                                           LangAS AddressSpace) const {
2934   QualType CanT = getCanonicalType(T);
2935   if (CanT.getAddressSpace() == AddressSpace)
2936     return T;
2937 
2938   // If we are composing extended qualifiers together, merge together
2939   // into one ExtQuals node.
2940   QualifierCollector Quals;
2941   const Type *TypeNode = Quals.strip(T);
2942 
2943   // If this type already has an address space specified, it cannot get
2944   // another one.
2945   assert(!Quals.hasAddressSpace() &&
2946          "Type cannot be in multiple addr spaces!");
2947   Quals.addAddressSpace(AddressSpace);
2948 
2949   return getExtQualType(TypeNode, Quals);
2950 }
2951 
2952 QualType ASTContext::removeAddrSpaceQualType(QualType T) const {
2953   // If the type is not qualified with an address space, just return it
2954   // immediately.
2955   if (!T.hasAddressSpace())
2956     return T;
2957 
2958   // If we are composing extended qualifiers together, merge together
2959   // into one ExtQuals node.
2960   QualifierCollector Quals;
2961   const Type *TypeNode;
2962 
2963   while (T.hasAddressSpace()) {
2964     TypeNode = Quals.strip(T);
2965 
2966     // If the type no longer has an address space after stripping qualifiers,
2967     // jump out.
2968     if (!QualType(TypeNode, 0).hasAddressSpace())
2969       break;
2970 
2971     // There might be sugar in the way. Strip it and try again.
2972     T = T.getSingleStepDesugaredType(*this);
2973   }
2974 
2975   Quals.removeAddressSpace();
2976 
2977   // Removal of the address space can mean there are no longer any
2978   // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
2979   // or required.
2980   if (Quals.hasNonFastQualifiers())
2981     return getExtQualType(TypeNode, Quals);
2982   else
2983     return QualType(TypeNode, Quals.getFastQualifiers());
2984 }
2985 
2986 QualType ASTContext::getObjCGCQualType(QualType T,
2987                                        Qualifiers::GC GCAttr) const {
2988   QualType CanT = getCanonicalType(T);
2989   if (CanT.getObjCGCAttr() == GCAttr)
2990     return T;
2991 
2992   if (const auto *ptr = T->getAs<PointerType>()) {
2993     QualType Pointee = ptr->getPointeeType();
2994     if (Pointee->isAnyPointerType()) {
2995       QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2996       return getPointerType(ResultType);
2997     }
2998   }
2999 
3000   // If we are composing extended qualifiers together, merge together
3001   // into one ExtQuals node.
3002   QualifierCollector Quals;
3003   const Type *TypeNode = Quals.strip(T);
3004 
3005   // If this type already has an ObjCGC specified, it cannot get
3006   // another one.
3007   assert(!Quals.hasObjCGCAttr() &&
3008          "Type cannot have multiple ObjCGCs!");
3009   Quals.addObjCGCAttr(GCAttr);
3010 
3011   return getExtQualType(TypeNode, Quals);
3012 }
3013 
3014 QualType ASTContext::removePtrSizeAddrSpace(QualType T) const {
3015   if (const PointerType *Ptr = T->getAs<PointerType>()) {
3016     QualType Pointee = Ptr->getPointeeType();
3017     if (isPtrSizeAddressSpace(Pointee.getAddressSpace())) {
3018       return getPointerType(removeAddrSpaceQualType(Pointee));
3019     }
3020   }
3021   return T;
3022 }
3023 
3024 const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
3025                                                    FunctionType::ExtInfo Info) {
3026   if (T->getExtInfo() == Info)
3027     return T;
3028 
3029   QualType Result;
3030   if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
3031     Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
3032   } else {
3033     const auto *FPT = cast<FunctionProtoType>(T);
3034     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
3035     EPI.ExtInfo = Info;
3036     Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
3037   }
3038 
3039   return cast<FunctionType>(Result.getTypePtr());
3040 }
3041 
3042 void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
3043                                                  QualType ResultType) {
3044   FD = FD->getMostRecentDecl();
3045   while (true) {
3046     const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
3047     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
3048     FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
3049     if (FunctionDecl *Next = FD->getPreviousDecl())
3050       FD = Next;
3051     else
3052       break;
3053   }
3054   if (ASTMutationListener *L = getASTMutationListener())
3055     L->DeducedReturnType(FD, ResultType);
3056 }
3057 
3058 /// Get a function type and produce the equivalent function type with the
3059 /// specified exception specification. Type sugar that can be present on a
3060 /// declaration of a function with an exception specification is permitted
3061 /// and preserved. Other type sugar (for instance, typedefs) is not.
3062 QualType ASTContext::getFunctionTypeWithExceptionSpec(
3063     QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) {
3064   // Might have some parens.
3065   if (const auto *PT = dyn_cast<ParenType>(Orig))
3066     return getParenType(
3067         getFunctionTypeWithExceptionSpec(PT->getInnerType(), ESI));
3068 
3069   // Might be wrapped in a macro qualified type.
3070   if (const auto *MQT = dyn_cast<MacroQualifiedType>(Orig))
3071     return getMacroQualifiedType(
3072         getFunctionTypeWithExceptionSpec(MQT->getUnderlyingType(), ESI),
3073         MQT->getMacroIdentifier());
3074 
3075   // Might have a calling-convention attribute.
3076   if (const auto *AT = dyn_cast<AttributedType>(Orig))
3077     return getAttributedType(
3078         AT->getAttrKind(),
3079         getFunctionTypeWithExceptionSpec(AT->getModifiedType(), ESI),
3080         getFunctionTypeWithExceptionSpec(AT->getEquivalentType(), ESI));
3081 
3082   // Anything else must be a function type. Rebuild it with the new exception
3083   // specification.
3084   const auto *Proto = Orig->castAs<FunctionProtoType>();
3085   return getFunctionType(
3086       Proto->getReturnType(), Proto->getParamTypes(),
3087       Proto->getExtProtoInfo().withExceptionSpec(ESI));
3088 }
3089 
3090 bool ASTContext::hasSameFunctionTypeIgnoringExceptionSpec(QualType T,
3091                                                           QualType U) {
3092   return hasSameType(T, U) ||
3093          (getLangOpts().CPlusPlus17 &&
3094           hasSameType(getFunctionTypeWithExceptionSpec(T, EST_None),
3095                       getFunctionTypeWithExceptionSpec(U, EST_None)));
3096 }
3097 
3098 QualType ASTContext::getFunctionTypeWithoutPtrSizes(QualType T) {
3099   if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3100     QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3101     SmallVector<QualType, 16> Args(Proto->param_types());
3102     for (unsigned i = 0, n = Args.size(); i != n; ++i)
3103       Args[i] = removePtrSizeAddrSpace(Args[i]);
3104     return getFunctionType(RetTy, Args, Proto->getExtProtoInfo());
3105   }
3106 
3107   if (const FunctionNoProtoType *Proto = T->getAs<FunctionNoProtoType>()) {
3108     QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3109     return getFunctionNoProtoType(RetTy, Proto->getExtInfo());
3110   }
3111 
3112   return T;
3113 }
3114 
3115 bool ASTContext::hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U) {
3116   return hasSameType(T, U) ||
3117          hasSameType(getFunctionTypeWithoutPtrSizes(T),
3118                      getFunctionTypeWithoutPtrSizes(U));
3119 }
3120 
3121 void ASTContext::adjustExceptionSpec(
3122     FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
3123     bool AsWritten) {
3124   // Update the type.
3125   QualType Updated =
3126       getFunctionTypeWithExceptionSpec(FD->getType(), ESI);
3127   FD->setType(Updated);
3128 
3129   if (!AsWritten)
3130     return;
3131 
3132   // Update the type in the type source information too.
3133   if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
3134     // If the type and the type-as-written differ, we may need to update
3135     // the type-as-written too.
3136     if (TSInfo->getType() != FD->getType())
3137       Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI);
3138 
3139     // FIXME: When we get proper type location information for exceptions,
3140     // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
3141     // up the TypeSourceInfo;
3142     assert(TypeLoc::getFullDataSizeForType(Updated) ==
3143                TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
3144            "TypeLoc size mismatch from updating exception specification");
3145     TSInfo->overrideType(Updated);
3146   }
3147 }
3148 
3149 /// getComplexType - Return the uniqued reference to the type for a complex
3150 /// number with the specified element type.
3151 QualType ASTContext::getComplexType(QualType T) const {
3152   // Unique pointers, to guarantee there is only one pointer of a particular
3153   // structure.
3154   llvm::FoldingSetNodeID ID;
3155   ComplexType::Profile(ID, T);
3156 
3157   void *InsertPos = nullptr;
3158   if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
3159     return QualType(CT, 0);
3160 
3161   // If the pointee type isn't canonical, this won't be a canonical type either,
3162   // so fill in the canonical type field.
3163   QualType Canonical;
3164   if (!T.isCanonical()) {
3165     Canonical = getComplexType(getCanonicalType(T));
3166 
3167     // Get the new insert position for the node we care about.
3168     ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
3169     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3170   }
3171   auto *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
3172   Types.push_back(New);
3173   ComplexTypes.InsertNode(New, InsertPos);
3174   return QualType(New, 0);
3175 }
3176 
3177 /// getPointerType - Return the uniqued reference to the type for a pointer to
3178 /// the specified type.
3179 QualType ASTContext::getPointerType(QualType T) const {
3180   // Unique pointers, to guarantee there is only one pointer of a particular
3181   // structure.
3182   llvm::FoldingSetNodeID ID;
3183   PointerType::Profile(ID, T);
3184 
3185   void *InsertPos = nullptr;
3186   if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3187     return QualType(PT, 0);
3188 
3189   // If the pointee type isn't canonical, this won't be a canonical type either,
3190   // so fill in the canonical type field.
3191   QualType Canonical;
3192   if (!T.isCanonical()) {
3193     Canonical = getPointerType(getCanonicalType(T));
3194 
3195     // Get the new insert position for the node we care about.
3196     PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3197     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3198   }
3199   auto *New = new (*this, TypeAlignment) PointerType(T, Canonical);
3200   Types.push_back(New);
3201   PointerTypes.InsertNode(New, InsertPos);
3202   return QualType(New, 0);
3203 }
3204 
3205 QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
3206   llvm::FoldingSetNodeID ID;
3207   AdjustedType::Profile(ID, Orig, New);
3208   void *InsertPos = nullptr;
3209   AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3210   if (AT)
3211     return QualType(AT, 0);
3212 
3213   QualType Canonical = getCanonicalType(New);
3214 
3215   // Get the new insert position for the node we care about.
3216   AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3217   assert(!AT && "Shouldn't be in the map!");
3218 
3219   AT = new (*this, TypeAlignment)
3220       AdjustedType(Type::Adjusted, Orig, New, Canonical);
3221   Types.push_back(AT);
3222   AdjustedTypes.InsertNode(AT, InsertPos);
3223   return QualType(AT, 0);
3224 }
3225 
3226 QualType ASTContext::getDecayedType(QualType T) const {
3227   assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
3228 
3229   QualType Decayed;
3230 
3231   // C99 6.7.5.3p7:
3232   //   A declaration of a parameter as "array of type" shall be
3233   //   adjusted to "qualified pointer to type", where the type
3234   //   qualifiers (if any) are those specified within the [ and ] of
3235   //   the array type derivation.
3236   if (T->isArrayType())
3237     Decayed = getArrayDecayedType(T);
3238 
3239   // C99 6.7.5.3p8:
3240   //   A declaration of a parameter as "function returning type"
3241   //   shall be adjusted to "pointer to function returning type", as
3242   //   in 6.3.2.1.
3243   if (T->isFunctionType())
3244     Decayed = getPointerType(T);
3245 
3246   llvm::FoldingSetNodeID ID;
3247   AdjustedType::Profile(ID, T, Decayed);
3248   void *InsertPos = nullptr;
3249   AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3250   if (AT)
3251     return QualType(AT, 0);
3252 
3253   QualType Canonical = getCanonicalType(Decayed);
3254 
3255   // Get the new insert position for the node we care about.
3256   AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3257   assert(!AT && "Shouldn't be in the map!");
3258 
3259   AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
3260   Types.push_back(AT);
3261   AdjustedTypes.InsertNode(AT, InsertPos);
3262   return QualType(AT, 0);
3263 }
3264 
3265 /// getBlockPointerType - Return the uniqued reference to the type for
3266 /// a pointer to the specified block.
3267 QualType ASTContext::getBlockPointerType(QualType T) const {
3268   assert(T->isFunctionType() && "block of function types only");
3269   // Unique pointers, to guarantee there is only one block of a particular
3270   // structure.
3271   llvm::FoldingSetNodeID ID;
3272   BlockPointerType::Profile(ID, T);
3273 
3274   void *InsertPos = nullptr;
3275   if (BlockPointerType *PT =
3276         BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3277     return QualType(PT, 0);
3278 
3279   // If the block pointee type isn't canonical, this won't be a canonical
3280   // type either so fill in the canonical type field.
3281   QualType Canonical;
3282   if (!T.isCanonical()) {
3283     Canonical = getBlockPointerType(getCanonicalType(T));
3284 
3285     // Get the new insert position for the node we care about.
3286     BlockPointerType *NewIP =
3287       BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3288     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3289   }
3290   auto *New = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
3291   Types.push_back(New);
3292   BlockPointerTypes.InsertNode(New, InsertPos);
3293   return QualType(New, 0);
3294 }
3295 
3296 /// getLValueReferenceType - Return the uniqued reference to the type for an
3297 /// lvalue reference to the specified type.
3298 QualType
3299 ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
3300   assert(getCanonicalType(T) != OverloadTy &&
3301          "Unresolved overloaded function type");
3302 
3303   // Unique pointers, to guarantee there is only one pointer of a particular
3304   // structure.
3305   llvm::FoldingSetNodeID ID;
3306   ReferenceType::Profile(ID, T, SpelledAsLValue);
3307 
3308   void *InsertPos = nullptr;
3309   if (LValueReferenceType *RT =
3310         LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
3311     return QualType(RT, 0);
3312 
3313   const auto *InnerRef = T->getAs<ReferenceType>();
3314 
3315   // If the referencee type isn't canonical, this won't be a canonical type
3316   // either, so fill in the canonical type field.
3317   QualType Canonical;
3318   if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
3319     QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
3320     Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
3321 
3322     // Get the new insert position for the node we care about.
3323     LValueReferenceType *NewIP =
3324       LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
3325     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3326   }
3327 
3328   auto *New = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
3329                                                              SpelledAsLValue);
3330   Types.push_back(New);
3331   LValueReferenceTypes.InsertNode(New, InsertPos);
3332 
3333   return QualType(New, 0);
3334 }
3335 
3336 /// getRValueReferenceType - Return the uniqued reference to the type for an
3337 /// rvalue reference to the specified type.
3338 QualType ASTContext::getRValueReferenceType(QualType T) const {
3339   // Unique pointers, to guarantee there is only one pointer of a particular
3340   // structure.
3341   llvm::FoldingSetNodeID ID;
3342   ReferenceType::Profile(ID, T, false);
3343 
3344   void *InsertPos = nullptr;
3345   if (RValueReferenceType *RT =
3346         RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
3347     return QualType(RT, 0);
3348 
3349   const auto *InnerRef = T->getAs<ReferenceType>();
3350 
3351   // If the referencee type isn't canonical, this won't be a canonical type
3352   // either, so fill in the canonical type field.
3353   QualType Canonical;
3354   if (InnerRef || !T.isCanonical()) {
3355     QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
3356     Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
3357 
3358     // Get the new insert position for the node we care about.
3359     RValueReferenceType *NewIP =
3360       RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
3361     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3362   }
3363 
3364   auto *New = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
3365   Types.push_back(New);
3366   RValueReferenceTypes.InsertNode(New, InsertPos);
3367   return QualType(New, 0);
3368 }
3369 
3370 /// getMemberPointerType - Return the uniqued reference to the type for a
3371 /// member pointer to the specified type, in the specified class.
3372 QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
3373   // Unique pointers, to guarantee there is only one pointer of a particular
3374   // structure.
3375   llvm::FoldingSetNodeID ID;
3376   MemberPointerType::Profile(ID, T, Cls);
3377 
3378   void *InsertPos = nullptr;
3379   if (MemberPointerType *PT =
3380       MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3381     return QualType(PT, 0);
3382 
3383   // If the pointee or class type isn't canonical, this won't be a canonical
3384   // type either, so fill in the canonical type field.
3385   QualType Canonical;
3386   if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
3387     Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
3388 
3389     // Get the new insert position for the node we care about.
3390     MemberPointerType *NewIP =
3391       MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3392     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3393   }
3394   auto *New = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
3395   Types.push_back(New);
3396   MemberPointerTypes.InsertNode(New, InsertPos);
3397   return QualType(New, 0);
3398 }
3399 
3400 /// getConstantArrayType - Return the unique reference to the type for an
3401 /// array of the specified element type.
3402 QualType ASTContext::getConstantArrayType(QualType EltTy,
3403                                           const llvm::APInt &ArySizeIn,
3404                                           const Expr *SizeExpr,
3405                                           ArrayType::ArraySizeModifier ASM,
3406                                           unsigned IndexTypeQuals) const {
3407   assert((EltTy->isDependentType() ||
3408           EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
3409          "Constant array of VLAs is illegal!");
3410 
3411   // We only need the size as part of the type if it's instantiation-dependent.
3412   if (SizeExpr && !SizeExpr->isInstantiationDependent())
3413     SizeExpr = nullptr;
3414 
3415   // Convert the array size into a canonical width matching the pointer size for
3416   // the target.
3417   llvm::APInt ArySize(ArySizeIn);
3418   ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
3419 
3420   llvm::FoldingSetNodeID ID;
3421   ConstantArrayType::Profile(ID, *this, EltTy, ArySize, SizeExpr, ASM,
3422                              IndexTypeQuals);
3423 
3424   void *InsertPos = nullptr;
3425   if (ConstantArrayType *ATP =
3426       ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
3427     return QualType(ATP, 0);
3428 
3429   // If the element type isn't canonical or has qualifiers, or the array bound
3430   // is instantiation-dependent, this won't be a canonical type either, so fill
3431   // in the canonical type field.
3432   QualType Canon;
3433   if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers() || SizeExpr) {
3434     SplitQualType canonSplit = getCanonicalType(EltTy).split();
3435     Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize, nullptr,
3436                                  ASM, IndexTypeQuals);
3437     Canon = getQualifiedType(Canon, canonSplit.Quals);
3438 
3439     // Get the new insert position for the node we care about.
3440     ConstantArrayType *NewIP =
3441       ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
3442     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3443   }
3444 
3445   void *Mem = Allocate(
3446       ConstantArrayType::totalSizeToAlloc<const Expr *>(SizeExpr ? 1 : 0),
3447       TypeAlignment);
3448   auto *New = new (Mem)
3449     ConstantArrayType(EltTy, Canon, ArySize, SizeExpr, ASM, IndexTypeQuals);
3450   ConstantArrayTypes.InsertNode(New, InsertPos);
3451   Types.push_back(New);
3452   return QualType(New, 0);
3453 }
3454 
3455 /// getVariableArrayDecayedType - Turns the given type, which may be
3456 /// variably-modified, into the corresponding type with all the known
3457 /// sizes replaced with [*].
3458 QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
3459   // Vastly most common case.
3460   if (!type->isVariablyModifiedType()) return type;
3461 
3462   QualType result;
3463 
3464   SplitQualType split = type.getSplitDesugaredType();
3465   const Type *ty = split.Ty;
3466   switch (ty->getTypeClass()) {
3467 #define TYPE(Class, Base)
3468 #define ABSTRACT_TYPE(Class, Base)
3469 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3470 #include "clang/AST/TypeNodes.inc"
3471     llvm_unreachable("didn't desugar past all non-canonical types?");
3472 
3473   // These types should never be variably-modified.
3474   case Type::Builtin:
3475   case Type::Complex:
3476   case Type::Vector:
3477   case Type::DependentVector:
3478   case Type::ExtVector:
3479   case Type::DependentSizedExtVector:
3480   case Type::ConstantMatrix:
3481   case Type::DependentSizedMatrix:
3482   case Type::DependentAddressSpace:
3483   case Type::ObjCObject:
3484   case Type::ObjCInterface:
3485   case Type::ObjCObjectPointer:
3486   case Type::Record:
3487   case Type::Enum:
3488   case Type::UnresolvedUsing:
3489   case Type::TypeOfExpr:
3490   case Type::TypeOf:
3491   case Type::Decltype:
3492   case Type::UnaryTransform:
3493   case Type::DependentName:
3494   case Type::InjectedClassName:
3495   case Type::TemplateSpecialization:
3496   case Type::DependentTemplateSpecialization:
3497   case Type::TemplateTypeParm:
3498   case Type::SubstTemplateTypeParmPack:
3499   case Type::Auto:
3500   case Type::DeducedTemplateSpecialization:
3501   case Type::PackExpansion:
3502   case Type::ExtInt:
3503   case Type::DependentExtInt:
3504     llvm_unreachable("type should never be variably-modified");
3505 
3506   // These types can be variably-modified but should never need to
3507   // further decay.
3508   case Type::FunctionNoProto:
3509   case Type::FunctionProto:
3510   case Type::BlockPointer:
3511   case Type::MemberPointer:
3512   case Type::Pipe:
3513     return type;
3514 
3515   // These types can be variably-modified.  All these modifications
3516   // preserve structure except as noted by comments.
3517   // TODO: if we ever care about optimizing VLAs, there are no-op
3518   // optimizations available here.
3519   case Type::Pointer:
3520     result = getPointerType(getVariableArrayDecayedType(
3521                               cast<PointerType>(ty)->getPointeeType()));
3522     break;
3523 
3524   case Type::LValueReference: {
3525     const auto *lv = cast<LValueReferenceType>(ty);
3526     result = getLValueReferenceType(
3527                  getVariableArrayDecayedType(lv->getPointeeType()),
3528                                     lv->isSpelledAsLValue());
3529     break;
3530   }
3531 
3532   case Type::RValueReference: {
3533     const auto *lv = cast<RValueReferenceType>(ty);
3534     result = getRValueReferenceType(
3535                  getVariableArrayDecayedType(lv->getPointeeType()));
3536     break;
3537   }
3538 
3539   case Type::Atomic: {
3540     const auto *at = cast<AtomicType>(ty);
3541     result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
3542     break;
3543   }
3544 
3545   case Type::ConstantArray: {
3546     const auto *cat = cast<ConstantArrayType>(ty);
3547     result = getConstantArrayType(
3548                  getVariableArrayDecayedType(cat->getElementType()),
3549                                   cat->getSize(),
3550                                   cat->getSizeExpr(),
3551                                   cat->getSizeModifier(),
3552                                   cat->getIndexTypeCVRQualifiers());
3553     break;
3554   }
3555 
3556   case Type::DependentSizedArray: {
3557     const auto *dat = cast<DependentSizedArrayType>(ty);
3558     result = getDependentSizedArrayType(
3559                  getVariableArrayDecayedType(dat->getElementType()),
3560                                         dat->getSizeExpr(),
3561                                         dat->getSizeModifier(),
3562                                         dat->getIndexTypeCVRQualifiers(),
3563                                         dat->getBracketsRange());
3564     break;
3565   }
3566 
3567   // Turn incomplete types into [*] types.
3568   case Type::IncompleteArray: {
3569     const auto *iat = cast<IncompleteArrayType>(ty);
3570     result = getVariableArrayType(
3571                  getVariableArrayDecayedType(iat->getElementType()),
3572                                   /*size*/ nullptr,
3573                                   ArrayType::Normal,
3574                                   iat->getIndexTypeCVRQualifiers(),
3575                                   SourceRange());
3576     break;
3577   }
3578 
3579   // Turn VLA types into [*] types.
3580   case Type::VariableArray: {
3581     const auto *vat = cast<VariableArrayType>(ty);
3582     result = getVariableArrayType(
3583                  getVariableArrayDecayedType(vat->getElementType()),
3584                                   /*size*/ nullptr,
3585                                   ArrayType::Star,
3586                                   vat->getIndexTypeCVRQualifiers(),
3587                                   vat->getBracketsRange());
3588     break;
3589   }
3590   }
3591 
3592   // Apply the top-level qualifiers from the original.
3593   return getQualifiedType(result, split.Quals);
3594 }
3595 
3596 /// getVariableArrayType - Returns a non-unique reference to the type for a
3597 /// variable array of the specified element type.
3598 QualType ASTContext::getVariableArrayType(QualType EltTy,
3599                                           Expr *NumElts,
3600                                           ArrayType::ArraySizeModifier ASM,
3601                                           unsigned IndexTypeQuals,
3602                                           SourceRange Brackets) const {
3603   // Since we don't unique expressions, it isn't possible to unique VLA's
3604   // that have an expression provided for their size.
3605   QualType Canon;
3606 
3607   // Be sure to pull qualifiers off the element type.
3608   if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
3609     SplitQualType canonSplit = getCanonicalType(EltTy).split();
3610     Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
3611                                  IndexTypeQuals, Brackets);
3612     Canon = getQualifiedType(Canon, canonSplit.Quals);
3613   }
3614 
3615   auto *New = new (*this, TypeAlignment)
3616     VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
3617 
3618   VariableArrayTypes.push_back(New);
3619   Types.push_back(New);
3620   return QualType(New, 0);
3621 }
3622 
3623 /// getDependentSizedArrayType - Returns a non-unique reference to
3624 /// the type for a dependently-sized array of the specified element
3625 /// type.
3626 QualType ASTContext::getDependentSizedArrayType(QualType elementType,
3627                                                 Expr *numElements,
3628                                                 ArrayType::ArraySizeModifier ASM,
3629                                                 unsigned elementTypeQuals,
3630                                                 SourceRange brackets) const {
3631   assert((!numElements || numElements->isTypeDependent() ||
3632           numElements->isValueDependent()) &&
3633          "Size must be type- or value-dependent!");
3634 
3635   // Dependently-sized array types that do not have a specified number
3636   // of elements will have their sizes deduced from a dependent
3637   // initializer.  We do no canonicalization here at all, which is okay
3638   // because they can't be used in most locations.
3639   if (!numElements) {
3640     auto *newType
3641       = new (*this, TypeAlignment)
3642           DependentSizedArrayType(*this, elementType, QualType(),
3643                                   numElements, ASM, elementTypeQuals,
3644                                   brackets);
3645     Types.push_back(newType);
3646     return QualType(newType, 0);
3647   }
3648 
3649   // Otherwise, we actually build a new type every time, but we
3650   // also build a canonical type.
3651 
3652   SplitQualType canonElementType = getCanonicalType(elementType).split();
3653 
3654   void *insertPos = nullptr;
3655   llvm::FoldingSetNodeID ID;
3656   DependentSizedArrayType::Profile(ID, *this,
3657                                    QualType(canonElementType.Ty, 0),
3658                                    ASM, elementTypeQuals, numElements);
3659 
3660   // Look for an existing type with these properties.
3661   DependentSizedArrayType *canonTy =
3662     DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
3663 
3664   // If we don't have one, build one.
3665   if (!canonTy) {
3666     canonTy = new (*this, TypeAlignment)
3667       DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
3668                               QualType(), numElements, ASM, elementTypeQuals,
3669                               brackets);
3670     DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
3671     Types.push_back(canonTy);
3672   }
3673 
3674   // Apply qualifiers from the element type to the array.
3675   QualType canon = getQualifiedType(QualType(canonTy,0),
3676                                     canonElementType.Quals);
3677 
3678   // If we didn't need extra canonicalization for the element type or the size
3679   // expression, then just use that as our result.
3680   if (QualType(canonElementType.Ty, 0) == elementType &&
3681       canonTy->getSizeExpr() == numElements)
3682     return canon;
3683 
3684   // Otherwise, we need to build a type which follows the spelling
3685   // of the element type.
3686   auto *sugaredType
3687     = new (*this, TypeAlignment)
3688         DependentSizedArrayType(*this, elementType, canon, numElements,
3689                                 ASM, elementTypeQuals, brackets);
3690   Types.push_back(sugaredType);
3691   return QualType(sugaredType, 0);
3692 }
3693 
3694 QualType ASTContext::getIncompleteArrayType(QualType elementType,
3695                                             ArrayType::ArraySizeModifier ASM,
3696                                             unsigned elementTypeQuals) const {
3697   llvm::FoldingSetNodeID ID;
3698   IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
3699 
3700   void *insertPos = nullptr;
3701   if (IncompleteArrayType *iat =
3702        IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
3703     return QualType(iat, 0);
3704 
3705   // If the element type isn't canonical, this won't be a canonical type
3706   // either, so fill in the canonical type field.  We also have to pull
3707   // qualifiers off the element type.
3708   QualType canon;
3709 
3710   if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
3711     SplitQualType canonSplit = getCanonicalType(elementType).split();
3712     canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
3713                                    ASM, elementTypeQuals);
3714     canon = getQualifiedType(canon, canonSplit.Quals);
3715 
3716     // Get the new insert position for the node we care about.
3717     IncompleteArrayType *existing =
3718       IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
3719     assert(!existing && "Shouldn't be in the map!"); (void) existing;
3720   }
3721 
3722   auto *newType = new (*this, TypeAlignment)
3723     IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
3724 
3725   IncompleteArrayTypes.InsertNode(newType, insertPos);
3726   Types.push_back(newType);
3727   return QualType(newType, 0);
3728 }
3729 
3730 ASTContext::BuiltinVectorTypeInfo
3731 ASTContext::getBuiltinVectorTypeInfo(const BuiltinType *Ty) const {
3732 #define SVE_INT_ELTTY(BITS, ELTS, SIGNED, NUMVECTORS)                          \
3733   {getIntTypeForBitwidth(BITS, SIGNED), llvm::ElementCount::getScalable(ELTS), \
3734    NUMVECTORS};
3735 
3736 #define SVE_ELTTY(ELTTY, ELTS, NUMVECTORS)                                     \
3737   {ELTTY, llvm::ElementCount::getScalable(ELTS), NUMVECTORS};
3738 
3739   switch (Ty->getKind()) {
3740   default:
3741     llvm_unreachable("Unsupported builtin vector type");
3742   case BuiltinType::SveInt8:
3743     return SVE_INT_ELTTY(8, 16, true, 1);
3744   case BuiltinType::SveUint8:
3745     return SVE_INT_ELTTY(8, 16, false, 1);
3746   case BuiltinType::SveInt8x2:
3747     return SVE_INT_ELTTY(8, 16, true, 2);
3748   case BuiltinType::SveUint8x2:
3749     return SVE_INT_ELTTY(8, 16, false, 2);
3750   case BuiltinType::SveInt8x3:
3751     return SVE_INT_ELTTY(8, 16, true, 3);
3752   case BuiltinType::SveUint8x3:
3753     return SVE_INT_ELTTY(8, 16, false, 3);
3754   case BuiltinType::SveInt8x4:
3755     return SVE_INT_ELTTY(8, 16, true, 4);
3756   case BuiltinType::SveUint8x4:
3757     return SVE_INT_ELTTY(8, 16, false, 4);
3758   case BuiltinType::SveInt16:
3759     return SVE_INT_ELTTY(16, 8, true, 1);
3760   case BuiltinType::SveUint16:
3761     return SVE_INT_ELTTY(16, 8, false, 1);
3762   case BuiltinType::SveInt16x2:
3763     return SVE_INT_ELTTY(16, 8, true, 2);
3764   case BuiltinType::SveUint16x2:
3765     return SVE_INT_ELTTY(16, 8, false, 2);
3766   case BuiltinType::SveInt16x3:
3767     return SVE_INT_ELTTY(16, 8, true, 3);
3768   case BuiltinType::SveUint16x3:
3769     return SVE_INT_ELTTY(16, 8, false, 3);
3770   case BuiltinType::SveInt16x4:
3771     return SVE_INT_ELTTY(16, 8, true, 4);
3772   case BuiltinType::SveUint16x4:
3773     return SVE_INT_ELTTY(16, 8, false, 4);
3774   case BuiltinType::SveInt32:
3775     return SVE_INT_ELTTY(32, 4, true, 1);
3776   case BuiltinType::SveUint32:
3777     return SVE_INT_ELTTY(32, 4, false, 1);
3778   case BuiltinType::SveInt32x2:
3779     return SVE_INT_ELTTY(32, 4, true, 2);
3780   case BuiltinType::SveUint32x2:
3781     return SVE_INT_ELTTY(32, 4, false, 2);
3782   case BuiltinType::SveInt32x3:
3783     return SVE_INT_ELTTY(32, 4, true, 3);
3784   case BuiltinType::SveUint32x3:
3785     return SVE_INT_ELTTY(32, 4, false, 3);
3786   case BuiltinType::SveInt32x4:
3787     return SVE_INT_ELTTY(32, 4, true, 4);
3788   case BuiltinType::SveUint32x4:
3789     return SVE_INT_ELTTY(32, 4, false, 4);
3790   case BuiltinType::SveInt64:
3791     return SVE_INT_ELTTY(64, 2, true, 1);
3792   case BuiltinType::SveUint64:
3793     return SVE_INT_ELTTY(64, 2, false, 1);
3794   case BuiltinType::SveInt64x2:
3795     return SVE_INT_ELTTY(64, 2, true, 2);
3796   case BuiltinType::SveUint64x2:
3797     return SVE_INT_ELTTY(64, 2, false, 2);
3798   case BuiltinType::SveInt64x3:
3799     return SVE_INT_ELTTY(64, 2, true, 3);
3800   case BuiltinType::SveUint64x3:
3801     return SVE_INT_ELTTY(64, 2, false, 3);
3802   case BuiltinType::SveInt64x4:
3803     return SVE_INT_ELTTY(64, 2, true, 4);
3804   case BuiltinType::SveUint64x4:
3805     return SVE_INT_ELTTY(64, 2, false, 4);
3806   case BuiltinType::SveBool:
3807     return SVE_ELTTY(BoolTy, 16, 1);
3808   case BuiltinType::SveFloat16:
3809     return SVE_ELTTY(HalfTy, 8, 1);
3810   case BuiltinType::SveFloat16x2:
3811     return SVE_ELTTY(HalfTy, 8, 2);
3812   case BuiltinType::SveFloat16x3:
3813     return SVE_ELTTY(HalfTy, 8, 3);
3814   case BuiltinType::SveFloat16x4:
3815     return SVE_ELTTY(HalfTy, 8, 4);
3816   case BuiltinType::SveFloat32:
3817     return SVE_ELTTY(FloatTy, 4, 1);
3818   case BuiltinType::SveFloat32x2:
3819     return SVE_ELTTY(FloatTy, 4, 2);
3820   case BuiltinType::SveFloat32x3:
3821     return SVE_ELTTY(FloatTy, 4, 3);
3822   case BuiltinType::SveFloat32x4:
3823     return SVE_ELTTY(FloatTy, 4, 4);
3824   case BuiltinType::SveFloat64:
3825     return SVE_ELTTY(DoubleTy, 2, 1);
3826   case BuiltinType::SveFloat64x2:
3827     return SVE_ELTTY(DoubleTy, 2, 2);
3828   case BuiltinType::SveFloat64x3:
3829     return SVE_ELTTY(DoubleTy, 2, 3);
3830   case BuiltinType::SveFloat64x4:
3831     return SVE_ELTTY(DoubleTy, 2, 4);
3832   case BuiltinType::SveBFloat16:
3833     return SVE_ELTTY(BFloat16Ty, 8, 1);
3834   case BuiltinType::SveBFloat16x2:
3835     return SVE_ELTTY(BFloat16Ty, 8, 2);
3836   case BuiltinType::SveBFloat16x3:
3837     return SVE_ELTTY(BFloat16Ty, 8, 3);
3838   case BuiltinType::SveBFloat16x4:
3839     return SVE_ELTTY(BFloat16Ty, 8, 4);
3840 #define RVV_VECTOR_TYPE_INT(Name, Id, SingletonId, NumEls, ElBits, NF,         \
3841                             IsSigned)                                          \
3842   case BuiltinType::Id:                                                        \
3843     return {getIntTypeForBitwidth(ElBits, IsSigned),                           \
3844             llvm::ElementCount::getScalable(NumEls), NF};
3845 #define RVV_VECTOR_TYPE_FLOAT(Name, Id, SingletonId, NumEls, ElBits, NF)       \
3846   case BuiltinType::Id:                                                        \
3847     return {ElBits == 16 ? HalfTy : (ElBits == 32 ? FloatTy : DoubleTy),       \
3848             llvm::ElementCount::getScalable(NumEls), NF};
3849 #define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls)                      \
3850   case BuiltinType::Id:                                                        \
3851     return {BoolTy, llvm::ElementCount::getScalable(NumEls), 1};
3852 #include "clang/Basic/RISCVVTypes.def"
3853   }
3854 }
3855 
3856 /// getScalableVectorType - Return the unique reference to a scalable vector
3857 /// type of the specified element type and size. VectorType must be a built-in
3858 /// type.
3859 QualType ASTContext::getScalableVectorType(QualType EltTy,
3860                                            unsigned NumElts) const {
3861   if (Target->hasAArch64SVETypes()) {
3862     uint64_t EltTySize = getTypeSize(EltTy);
3863 #define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId, NumEls, ElBits,    \
3864                         IsSigned, IsFP, IsBF)                                  \
3865   if (!EltTy->isBooleanType() &&                                               \
3866       ((EltTy->hasIntegerRepresentation() &&                                   \
3867         EltTy->hasSignedIntegerRepresentation() == IsSigned) ||                \
3868        (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() &&      \
3869         IsFP && !IsBF) ||                                                      \
3870        (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() &&       \
3871         IsBF && !IsFP)) &&                                                     \
3872       EltTySize == ElBits && NumElts == NumEls) {                              \
3873     return SingletonId;                                                        \
3874   }
3875 #define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId, NumEls)         \
3876   if (EltTy->isBooleanType() && NumElts == NumEls)                             \
3877     return SingletonId;
3878 #include "clang/Basic/AArch64SVEACLETypes.def"
3879   } else if (Target->hasRISCVVTypes()) {
3880     uint64_t EltTySize = getTypeSize(EltTy);
3881 #define RVV_VECTOR_TYPE(Name, Id, SingletonId, NumEls, ElBits, NF, IsSigned,   \
3882                         IsFP)                                                  \
3883     if (!EltTy->isBooleanType() &&                                             \
3884         ((EltTy->hasIntegerRepresentation() &&                                 \
3885           EltTy->hasSignedIntegerRepresentation() == IsSigned) ||              \
3886          (EltTy->hasFloatingRepresentation() && IsFP)) &&                      \
3887         EltTySize == ElBits && NumElts == NumEls)                              \
3888       return SingletonId;
3889 #define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls)                      \
3890     if (EltTy->isBooleanType() && NumElts == NumEls)                           \
3891       return SingletonId;
3892 #include "clang/Basic/RISCVVTypes.def"
3893   }
3894   return QualType();
3895 }
3896 
3897 /// getVectorType - Return the unique reference to a vector type of
3898 /// the specified element type and size. VectorType must be a built-in type.
3899 QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
3900                                    VectorType::VectorKind VecKind) const {
3901   assert(vecType->isBuiltinType());
3902 
3903   // Check if we've already instantiated a vector of this type.
3904   llvm::FoldingSetNodeID ID;
3905   VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
3906 
3907   void *InsertPos = nullptr;
3908   if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3909     return QualType(VTP, 0);
3910 
3911   // If the element type isn't canonical, this won't be a canonical type either,
3912   // so fill in the canonical type field.
3913   QualType Canonical;
3914   if (!vecType.isCanonical()) {
3915     Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
3916 
3917     // Get the new insert position for the node we care about.
3918     VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3919     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3920   }
3921   auto *New = new (*this, TypeAlignment)
3922     VectorType(vecType, NumElts, Canonical, VecKind);
3923   VectorTypes.InsertNode(New, InsertPos);
3924   Types.push_back(New);
3925   return QualType(New, 0);
3926 }
3927 
3928 QualType
3929 ASTContext::getDependentVectorType(QualType VecType, Expr *SizeExpr,
3930                                    SourceLocation AttrLoc,
3931                                    VectorType::VectorKind VecKind) const {
3932   llvm::FoldingSetNodeID ID;
3933   DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr,
3934                                VecKind);
3935   void *InsertPos = nullptr;
3936   DependentVectorType *Canon =
3937       DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3938   DependentVectorType *New;
3939 
3940   if (Canon) {
3941     New = new (*this, TypeAlignment) DependentVectorType(
3942         *this, VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind);
3943   } else {
3944     QualType CanonVecTy = getCanonicalType(VecType);
3945     if (CanonVecTy == VecType) {
3946       New = new (*this, TypeAlignment) DependentVectorType(
3947           *this, VecType, QualType(), SizeExpr, AttrLoc, VecKind);
3948 
3949       DependentVectorType *CanonCheck =
3950           DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3951       assert(!CanonCheck &&
3952              "Dependent-sized vector_size canonical type broken");
3953       (void)CanonCheck;
3954       DependentVectorTypes.InsertNode(New, InsertPos);
3955     } else {
3956       QualType CanonTy = getDependentVectorType(CanonVecTy, SizeExpr,
3957                                                 SourceLocation(), VecKind);
3958       New = new (*this, TypeAlignment) DependentVectorType(
3959           *this, VecType, CanonTy, SizeExpr, AttrLoc, VecKind);
3960     }
3961   }
3962 
3963   Types.push_back(New);
3964   return QualType(New, 0);
3965 }
3966 
3967 /// getExtVectorType - Return the unique reference to an extended vector type of
3968 /// the specified element type and size. VectorType must be a built-in type.
3969 QualType
3970 ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
3971   assert(vecType->isBuiltinType() || vecType->isDependentType());
3972 
3973   // Check if we've already instantiated a vector of this type.
3974   llvm::FoldingSetNodeID ID;
3975   VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
3976                       VectorType::GenericVector);
3977   void *InsertPos = nullptr;
3978   if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3979     return QualType(VTP, 0);
3980 
3981   // If the element type isn't canonical, this won't be a canonical type either,
3982   // so fill in the canonical type field.
3983   QualType Canonical;
3984   if (!vecType.isCanonical()) {
3985     Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
3986 
3987     // Get the new insert position for the node we care about.
3988     VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3989     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3990   }
3991   auto *New = new (*this, TypeAlignment)
3992     ExtVectorType(vecType, NumElts, Canonical);
3993   VectorTypes.InsertNode(New, InsertPos);
3994   Types.push_back(New);
3995   return QualType(New, 0);
3996 }
3997 
3998 QualType
3999 ASTContext::getDependentSizedExtVectorType(QualType vecType,
4000                                            Expr *SizeExpr,
4001                                            SourceLocation AttrLoc) const {
4002   llvm::FoldingSetNodeID ID;
4003   DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
4004                                        SizeExpr);
4005 
4006   void *InsertPos = nullptr;
4007   DependentSizedExtVectorType *Canon
4008     = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4009   DependentSizedExtVectorType *New;
4010   if (Canon) {
4011     // We already have a canonical version of this array type; use it as
4012     // the canonical type for a newly-built type.
4013     New = new (*this, TypeAlignment)
4014       DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
4015                                   SizeExpr, AttrLoc);
4016   } else {
4017     QualType CanonVecTy = getCanonicalType(vecType);
4018     if (CanonVecTy == vecType) {
4019       New = new (*this, TypeAlignment)
4020         DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
4021                                     AttrLoc);
4022 
4023       DependentSizedExtVectorType *CanonCheck
4024         = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4025       assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
4026       (void)CanonCheck;
4027       DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
4028     } else {
4029       QualType CanonExtTy = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
4030                                                            SourceLocation());
4031       New = new (*this, TypeAlignment) DependentSizedExtVectorType(
4032           *this, vecType, CanonExtTy, SizeExpr, AttrLoc);
4033     }
4034   }
4035 
4036   Types.push_back(New);
4037   return QualType(New, 0);
4038 }
4039 
4040 QualType ASTContext::getConstantMatrixType(QualType ElementTy, unsigned NumRows,
4041                                            unsigned NumColumns) const {
4042   llvm::FoldingSetNodeID ID;
4043   ConstantMatrixType::Profile(ID, ElementTy, NumRows, NumColumns,
4044                               Type::ConstantMatrix);
4045 
4046   assert(MatrixType::isValidElementType(ElementTy) &&
4047          "need a valid element type");
4048   assert(ConstantMatrixType::isDimensionValid(NumRows) &&
4049          ConstantMatrixType::isDimensionValid(NumColumns) &&
4050          "need valid matrix dimensions");
4051   void *InsertPos = nullptr;
4052   if (ConstantMatrixType *MTP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos))
4053     return QualType(MTP, 0);
4054 
4055   QualType Canonical;
4056   if (!ElementTy.isCanonical()) {
4057     Canonical =
4058         getConstantMatrixType(getCanonicalType(ElementTy), NumRows, NumColumns);
4059 
4060     ConstantMatrixType *NewIP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4061     assert(!NewIP && "Matrix type shouldn't already exist in the map");
4062     (void)NewIP;
4063   }
4064 
4065   auto *New = new (*this, TypeAlignment)
4066       ConstantMatrixType(ElementTy, NumRows, NumColumns, Canonical);
4067   MatrixTypes.InsertNode(New, InsertPos);
4068   Types.push_back(New);
4069   return QualType(New, 0);
4070 }
4071 
4072 QualType ASTContext::getDependentSizedMatrixType(QualType ElementTy,
4073                                                  Expr *RowExpr,
4074                                                  Expr *ColumnExpr,
4075                                                  SourceLocation AttrLoc) const {
4076   QualType CanonElementTy = getCanonicalType(ElementTy);
4077   llvm::FoldingSetNodeID ID;
4078   DependentSizedMatrixType::Profile(ID, *this, CanonElementTy, RowExpr,
4079                                     ColumnExpr);
4080 
4081   void *InsertPos = nullptr;
4082   DependentSizedMatrixType *Canon =
4083       DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4084 
4085   if (!Canon) {
4086     Canon = new (*this, TypeAlignment) DependentSizedMatrixType(
4087         *this, CanonElementTy, QualType(), RowExpr, ColumnExpr, AttrLoc);
4088 #ifndef NDEBUG
4089     DependentSizedMatrixType *CanonCheck =
4090         DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4091     assert(!CanonCheck && "Dependent-sized matrix canonical type broken");
4092 #endif
4093     DependentSizedMatrixTypes.InsertNode(Canon, InsertPos);
4094     Types.push_back(Canon);
4095   }
4096 
4097   // Already have a canonical version of the matrix type
4098   //
4099   // If it exactly matches the requested type, use it directly.
4100   if (Canon->getElementType() == ElementTy && Canon->getRowExpr() == RowExpr &&
4101       Canon->getRowExpr() == ColumnExpr)
4102     return QualType(Canon, 0);
4103 
4104   // Use Canon as the canonical type for newly-built type.
4105   DependentSizedMatrixType *New = new (*this, TypeAlignment)
4106       DependentSizedMatrixType(*this, ElementTy, QualType(Canon, 0), RowExpr,
4107                                ColumnExpr, AttrLoc);
4108   Types.push_back(New);
4109   return QualType(New, 0);
4110 }
4111 
4112 QualType ASTContext::getDependentAddressSpaceType(QualType PointeeType,
4113                                                   Expr *AddrSpaceExpr,
4114                                                   SourceLocation AttrLoc) const {
4115   assert(AddrSpaceExpr->isInstantiationDependent());
4116 
4117   QualType canonPointeeType = getCanonicalType(PointeeType);
4118 
4119   void *insertPos = nullptr;
4120   llvm::FoldingSetNodeID ID;
4121   DependentAddressSpaceType::Profile(ID, *this, canonPointeeType,
4122                                      AddrSpaceExpr);
4123 
4124   DependentAddressSpaceType *canonTy =
4125     DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos);
4126 
4127   if (!canonTy) {
4128     canonTy = new (*this, TypeAlignment)
4129       DependentAddressSpaceType(*this, canonPointeeType,
4130                                 QualType(), AddrSpaceExpr, AttrLoc);
4131     DependentAddressSpaceTypes.InsertNode(canonTy, insertPos);
4132     Types.push_back(canonTy);
4133   }
4134 
4135   if (canonPointeeType == PointeeType &&
4136       canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
4137     return QualType(canonTy, 0);
4138 
4139   auto *sugaredType
4140     = new (*this, TypeAlignment)
4141         DependentAddressSpaceType(*this, PointeeType, QualType(canonTy, 0),
4142                                   AddrSpaceExpr, AttrLoc);
4143   Types.push_back(sugaredType);
4144   return QualType(sugaredType, 0);
4145 }
4146 
4147 /// Determine whether \p T is canonical as the result type of a function.
4148 static bool isCanonicalResultType(QualType T) {
4149   return T.isCanonical() &&
4150          (T.getObjCLifetime() == Qualifiers::OCL_None ||
4151           T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
4152 }
4153 
4154 /// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
4155 QualType
4156 ASTContext::getFunctionNoProtoType(QualType ResultTy,
4157                                    const FunctionType::ExtInfo &Info) const {
4158   // Unique functions, to guarantee there is only one function of a particular
4159   // structure.
4160   llvm::FoldingSetNodeID ID;
4161   FunctionNoProtoType::Profile(ID, ResultTy, Info);
4162 
4163   void *InsertPos = nullptr;
4164   if (FunctionNoProtoType *FT =
4165         FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
4166     return QualType(FT, 0);
4167 
4168   QualType Canonical;
4169   if (!isCanonicalResultType(ResultTy)) {
4170     Canonical =
4171       getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info);
4172 
4173     // Get the new insert position for the node we care about.
4174     FunctionNoProtoType *NewIP =
4175       FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
4176     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4177   }
4178 
4179   auto *New = new (*this, TypeAlignment)
4180     FunctionNoProtoType(ResultTy, Canonical, Info);
4181   Types.push_back(New);
4182   FunctionNoProtoTypes.InsertNode(New, InsertPos);
4183   return QualType(New, 0);
4184 }
4185 
4186 CanQualType
4187 ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
4188   CanQualType CanResultType = getCanonicalType(ResultType);
4189 
4190   // Canonical result types do not have ARC lifetime qualifiers.
4191   if (CanResultType.getQualifiers().hasObjCLifetime()) {
4192     Qualifiers Qs = CanResultType.getQualifiers();
4193     Qs.removeObjCLifetime();
4194     return CanQualType::CreateUnsafe(
4195              getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
4196   }
4197 
4198   return CanResultType;
4199 }
4200 
4201 static bool isCanonicalExceptionSpecification(
4202     const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
4203   if (ESI.Type == EST_None)
4204     return true;
4205   if (!NoexceptInType)
4206     return false;
4207 
4208   // C++17 onwards: exception specification is part of the type, as a simple
4209   // boolean "can this function type throw".
4210   if (ESI.Type == EST_BasicNoexcept)
4211     return true;
4212 
4213   // A noexcept(expr) specification is (possibly) canonical if expr is
4214   // value-dependent.
4215   if (ESI.Type == EST_DependentNoexcept)
4216     return true;
4217 
4218   // A dynamic exception specification is canonical if it only contains pack
4219   // expansions (so we can't tell whether it's non-throwing) and all its
4220   // contained types are canonical.
4221   if (ESI.Type == EST_Dynamic) {
4222     bool AnyPackExpansions = false;
4223     for (QualType ET : ESI.Exceptions) {
4224       if (!ET.isCanonical())
4225         return false;
4226       if (ET->getAs<PackExpansionType>())
4227         AnyPackExpansions = true;
4228     }
4229     return AnyPackExpansions;
4230   }
4231 
4232   return false;
4233 }
4234 
4235 QualType ASTContext::getFunctionTypeInternal(
4236     QualType ResultTy, ArrayRef<QualType> ArgArray,
4237     const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
4238   size_t NumArgs = ArgArray.size();
4239 
4240   // Unique functions, to guarantee there is only one function of a particular
4241   // structure.
4242   llvm::FoldingSetNodeID ID;
4243   FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
4244                              *this, true);
4245 
4246   QualType Canonical;
4247   bool Unique = false;
4248 
4249   void *InsertPos = nullptr;
4250   if (FunctionProtoType *FPT =
4251         FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
4252     QualType Existing = QualType(FPT, 0);
4253 
4254     // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
4255     // it so long as our exception specification doesn't contain a dependent
4256     // noexcept expression, or we're just looking for a canonical type.
4257     // Otherwise, we're going to need to create a type
4258     // sugar node to hold the concrete expression.
4259     if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) ||
4260         EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
4261       return Existing;
4262 
4263     // We need a new type sugar node for this one, to hold the new noexcept
4264     // expression. We do no canonicalization here, but that's OK since we don't
4265     // expect to see the same noexcept expression much more than once.
4266     Canonical = getCanonicalType(Existing);
4267     Unique = true;
4268   }
4269 
4270   bool NoexceptInType = getLangOpts().CPlusPlus17;
4271   bool IsCanonicalExceptionSpec =
4272       isCanonicalExceptionSpecification(EPI.ExceptionSpec, NoexceptInType);
4273 
4274   // Determine whether the type being created is already canonical or not.
4275   bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
4276                      isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
4277   for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
4278     if (!ArgArray[i].isCanonicalAsParam())
4279       isCanonical = false;
4280 
4281   if (OnlyWantCanonical)
4282     assert(isCanonical &&
4283            "given non-canonical parameters constructing canonical type");
4284 
4285   // If this type isn't canonical, get the canonical version of it if we don't
4286   // already have it. The exception spec is only partially part of the
4287   // canonical type, and only in C++17 onwards.
4288   if (!isCanonical && Canonical.isNull()) {
4289     SmallVector<QualType, 16> CanonicalArgs;
4290     CanonicalArgs.reserve(NumArgs);
4291     for (unsigned i = 0; i != NumArgs; ++i)
4292       CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
4293 
4294     llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
4295     FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
4296     CanonicalEPI.HasTrailingReturn = false;
4297 
4298     if (IsCanonicalExceptionSpec) {
4299       // Exception spec is already OK.
4300     } else if (NoexceptInType) {
4301       switch (EPI.ExceptionSpec.Type) {
4302       case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated:
4303         // We don't know yet. It shouldn't matter what we pick here; no-one
4304         // should ever look at this.
4305         LLVM_FALLTHROUGH;
4306       case EST_None: case EST_MSAny: case EST_NoexceptFalse:
4307         CanonicalEPI.ExceptionSpec.Type = EST_None;
4308         break;
4309 
4310         // A dynamic exception specification is almost always "not noexcept",
4311         // with the exception that a pack expansion might expand to no types.
4312       case EST_Dynamic: {
4313         bool AnyPacks = false;
4314         for (QualType ET : EPI.ExceptionSpec.Exceptions) {
4315           if (ET->getAs<PackExpansionType>())
4316             AnyPacks = true;
4317           ExceptionTypeStorage.push_back(getCanonicalType(ET));
4318         }
4319         if (!AnyPacks)
4320           CanonicalEPI.ExceptionSpec.Type = EST_None;
4321         else {
4322           CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
4323           CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
4324         }
4325         break;
4326       }
4327 
4328       case EST_DynamicNone:
4329       case EST_BasicNoexcept:
4330       case EST_NoexceptTrue:
4331       case EST_NoThrow:
4332         CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
4333         break;
4334 
4335       case EST_DependentNoexcept:
4336         llvm_unreachable("dependent noexcept is already canonical");
4337       }
4338     } else {
4339       CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
4340     }
4341 
4342     // Adjust the canonical function result type.
4343     CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
4344     Canonical =
4345         getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
4346 
4347     // Get the new insert position for the node we care about.
4348     FunctionProtoType *NewIP =
4349       FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
4350     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4351   }
4352 
4353   // Compute the needed size to hold this FunctionProtoType and the
4354   // various trailing objects.
4355   auto ESH = FunctionProtoType::getExceptionSpecSize(
4356       EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size());
4357   size_t Size = FunctionProtoType::totalSizeToAlloc<
4358       QualType, SourceLocation, FunctionType::FunctionTypeExtraBitfields,
4359       FunctionType::ExceptionType, Expr *, FunctionDecl *,
4360       FunctionProtoType::ExtParameterInfo, Qualifiers>(
4361       NumArgs, EPI.Variadic,
4362       FunctionProtoType::hasExtraBitfields(EPI.ExceptionSpec.Type),
4363       ESH.NumExceptionType, ESH.NumExprPtr, ESH.NumFunctionDeclPtr,
4364       EPI.ExtParameterInfos ? NumArgs : 0,
4365       EPI.TypeQuals.hasNonFastQualifiers() ? 1 : 0);
4366 
4367   auto *FTP = (FunctionProtoType *)Allocate(Size, TypeAlignment);
4368   FunctionProtoType::ExtProtoInfo newEPI = EPI;
4369   new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
4370   Types.push_back(FTP);
4371   if (!Unique)
4372     FunctionProtoTypes.InsertNode(FTP, InsertPos);
4373   return QualType(FTP, 0);
4374 }
4375 
4376 QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
4377   llvm::FoldingSetNodeID ID;
4378   PipeType::Profile(ID, T, ReadOnly);
4379 
4380   void *InsertPos = nullptr;
4381   if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
4382     return QualType(PT, 0);
4383 
4384   // If the pipe element type isn't canonical, this won't be a canonical type
4385   // either, so fill in the canonical type field.
4386   QualType Canonical;
4387   if (!T.isCanonical()) {
4388     Canonical = getPipeType(getCanonicalType(T), ReadOnly);
4389 
4390     // Get the new insert position for the node we care about.
4391     PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
4392     assert(!NewIP && "Shouldn't be in the map!");
4393     (void)NewIP;
4394   }
4395   auto *New = new (*this, TypeAlignment) PipeType(T, Canonical, ReadOnly);
4396   Types.push_back(New);
4397   PipeTypes.InsertNode(New, InsertPos);
4398   return QualType(New, 0);
4399 }
4400 
4401 QualType ASTContext::adjustStringLiteralBaseType(QualType Ty) const {
4402   // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
4403   return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant)
4404                          : Ty;
4405 }
4406 
4407 QualType ASTContext::getReadPipeType(QualType T) const {
4408   return getPipeType(T, true);
4409 }
4410 
4411 QualType ASTContext::getWritePipeType(QualType T) const {
4412   return getPipeType(T, false);
4413 }
4414 
4415 QualType ASTContext::getExtIntType(bool IsUnsigned, unsigned NumBits) const {
4416   llvm::FoldingSetNodeID ID;
4417   ExtIntType::Profile(ID, IsUnsigned, NumBits);
4418 
4419   void *InsertPos = nullptr;
4420   if (ExtIntType *EIT = ExtIntTypes.FindNodeOrInsertPos(ID, InsertPos))
4421     return QualType(EIT, 0);
4422 
4423   auto *New = new (*this, TypeAlignment) ExtIntType(IsUnsigned, NumBits);
4424   ExtIntTypes.InsertNode(New, InsertPos);
4425   Types.push_back(New);
4426   return QualType(New, 0);
4427 }
4428 
4429 QualType ASTContext::getDependentExtIntType(bool IsUnsigned,
4430                                             Expr *NumBitsExpr) const {
4431   assert(NumBitsExpr->isInstantiationDependent() && "Only good for dependent");
4432   llvm::FoldingSetNodeID ID;
4433   DependentExtIntType::Profile(ID, *this, IsUnsigned, NumBitsExpr);
4434 
4435   void *InsertPos = nullptr;
4436   if (DependentExtIntType *Existing =
4437           DependentExtIntTypes.FindNodeOrInsertPos(ID, InsertPos))
4438     return QualType(Existing, 0);
4439 
4440   auto *New = new (*this, TypeAlignment)
4441       DependentExtIntType(*this, IsUnsigned, NumBitsExpr);
4442   DependentExtIntTypes.InsertNode(New, InsertPos);
4443 
4444   Types.push_back(New);
4445   return QualType(New, 0);
4446 }
4447 
4448 #ifndef NDEBUG
4449 static bool NeedsInjectedClassNameType(const RecordDecl *D) {
4450   if (!isa<CXXRecordDecl>(D)) return false;
4451   const auto *RD = cast<CXXRecordDecl>(D);
4452   if (isa<ClassTemplatePartialSpecializationDecl>(RD))
4453     return true;
4454   if (RD->getDescribedClassTemplate() &&
4455       !isa<ClassTemplateSpecializationDecl>(RD))
4456     return true;
4457   return false;
4458 }
4459 #endif
4460 
4461 /// getInjectedClassNameType - Return the unique reference to the
4462 /// injected class name type for the specified templated declaration.
4463 QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
4464                                               QualType TST) const {
4465   assert(NeedsInjectedClassNameType(Decl));
4466   if (Decl->TypeForDecl) {
4467     assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
4468   } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
4469     assert(PrevDecl->TypeForDecl && "previous declaration has no type");
4470     Decl->TypeForDecl = PrevDecl->TypeForDecl;
4471     assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
4472   } else {
4473     Type *newType =
4474       new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
4475     Decl->TypeForDecl = newType;
4476     Types.push_back(newType);
4477   }
4478   return QualType(Decl->TypeForDecl, 0);
4479 }
4480 
4481 /// getTypeDeclType - Return the unique reference to the type for the
4482 /// specified type declaration.
4483 QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
4484   assert(Decl && "Passed null for Decl param");
4485   assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
4486 
4487   if (const auto *Typedef = dyn_cast<TypedefNameDecl>(Decl))
4488     return getTypedefType(Typedef);
4489 
4490   assert(!isa<TemplateTypeParmDecl>(Decl) &&
4491          "Template type parameter types are always available.");
4492 
4493   if (const auto *Record = dyn_cast<RecordDecl>(Decl)) {
4494     assert(Record->isFirstDecl() && "struct/union has previous declaration");
4495     assert(!NeedsInjectedClassNameType(Record));
4496     return getRecordType(Record);
4497   } else if (const auto *Enum = dyn_cast<EnumDecl>(Decl)) {
4498     assert(Enum->isFirstDecl() && "enum has previous declaration");
4499     return getEnumType(Enum);
4500   } else if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
4501     Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
4502     Decl->TypeForDecl = newType;
4503     Types.push_back(newType);
4504   } else
4505     llvm_unreachable("TypeDecl without a type?");
4506 
4507   return QualType(Decl->TypeForDecl, 0);
4508 }
4509 
4510 /// getTypedefType - Return the unique reference to the type for the
4511 /// specified typedef name decl.
4512 QualType ASTContext::getTypedefType(const TypedefNameDecl *Decl,
4513                                     QualType Underlying) const {
4514   if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
4515 
4516   if (Underlying.isNull())
4517     Underlying = Decl->getUnderlyingType();
4518   QualType Canonical = getCanonicalType(Underlying);
4519   auto *newType = new (*this, TypeAlignment)
4520       TypedefType(Type::Typedef, Decl, Underlying, Canonical);
4521   Decl->TypeForDecl = newType;
4522   Types.push_back(newType);
4523   return QualType(newType, 0);
4524 }
4525 
4526 QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
4527   if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
4528 
4529   if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
4530     if (PrevDecl->TypeForDecl)
4531       return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
4532 
4533   auto *newType = new (*this, TypeAlignment) RecordType(Decl);
4534   Decl->TypeForDecl = newType;
4535   Types.push_back(newType);
4536   return QualType(newType, 0);
4537 }
4538 
4539 QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
4540   if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
4541 
4542   if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
4543     if (PrevDecl->TypeForDecl)
4544       return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
4545 
4546   auto *newType = new (*this, TypeAlignment) EnumType(Decl);
4547   Decl->TypeForDecl = newType;
4548   Types.push_back(newType);
4549   return QualType(newType, 0);
4550 }
4551 
4552 QualType ASTContext::getAttributedType(attr::Kind attrKind,
4553                                        QualType modifiedType,
4554                                        QualType equivalentType) {
4555   llvm::FoldingSetNodeID id;
4556   AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
4557 
4558   void *insertPos = nullptr;
4559   AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
4560   if (type) return QualType(type, 0);
4561 
4562   QualType canon = getCanonicalType(equivalentType);
4563   type = new (*this, TypeAlignment)
4564       AttributedType(canon, attrKind, modifiedType, equivalentType);
4565 
4566   Types.push_back(type);
4567   AttributedTypes.InsertNode(type, insertPos);
4568 
4569   return QualType(type, 0);
4570 }
4571 
4572 /// Retrieve a substitution-result type.
4573 QualType
4574 ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
4575                                          QualType Replacement) const {
4576   assert(Replacement.isCanonical()
4577          && "replacement types must always be canonical");
4578 
4579   llvm::FoldingSetNodeID ID;
4580   SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
4581   void *InsertPos = nullptr;
4582   SubstTemplateTypeParmType *SubstParm
4583     = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4584 
4585   if (!SubstParm) {
4586     SubstParm = new (*this, TypeAlignment)
4587       SubstTemplateTypeParmType(Parm, Replacement);
4588     Types.push_back(SubstParm);
4589     SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
4590   }
4591 
4592   return QualType(SubstParm, 0);
4593 }
4594 
4595 /// Retrieve a
4596 QualType ASTContext::getSubstTemplateTypeParmPackType(
4597                                           const TemplateTypeParmType *Parm,
4598                                               const TemplateArgument &ArgPack) {
4599 #ifndef NDEBUG
4600   for (const auto &P : ArgPack.pack_elements()) {
4601     assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
4602     assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
4603   }
4604 #endif
4605 
4606   llvm::FoldingSetNodeID ID;
4607   SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
4608   void *InsertPos = nullptr;
4609   if (SubstTemplateTypeParmPackType *SubstParm
4610         = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
4611     return QualType(SubstParm, 0);
4612 
4613   QualType Canon;
4614   if (!Parm->isCanonicalUnqualified()) {
4615     Canon = getCanonicalType(QualType(Parm, 0));
4616     Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
4617                                              ArgPack);
4618     SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
4619   }
4620 
4621   auto *SubstParm
4622     = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
4623                                                                ArgPack);
4624   Types.push_back(SubstParm);
4625   SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos);
4626   return QualType(SubstParm, 0);
4627 }
4628 
4629 /// Retrieve the template type parameter type for a template
4630 /// parameter or parameter pack with the given depth, index, and (optionally)
4631 /// name.
4632 QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
4633                                              bool ParameterPack,
4634                                              TemplateTypeParmDecl *TTPDecl) const {
4635   llvm::FoldingSetNodeID ID;
4636   TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
4637   void *InsertPos = nullptr;
4638   TemplateTypeParmType *TypeParm
4639     = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4640 
4641   if (TypeParm)
4642     return QualType(TypeParm, 0);
4643 
4644   if (TTPDecl) {
4645     QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
4646     TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
4647 
4648     TemplateTypeParmType *TypeCheck
4649       = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4650     assert(!TypeCheck && "Template type parameter canonical type broken");
4651     (void)TypeCheck;
4652   } else
4653     TypeParm = new (*this, TypeAlignment)
4654       TemplateTypeParmType(Depth, Index, ParameterPack);
4655 
4656   Types.push_back(TypeParm);
4657   TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
4658 
4659   return QualType(TypeParm, 0);
4660 }
4661 
4662 TypeSourceInfo *
4663 ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
4664                                               SourceLocation NameLoc,
4665                                         const TemplateArgumentListInfo &Args,
4666                                               QualType Underlying) const {
4667   assert(!Name.getAsDependentTemplateName() &&
4668          "No dependent template names here!");
4669   QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
4670 
4671   TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
4672   TemplateSpecializationTypeLoc TL =
4673       DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
4674   TL.setTemplateKeywordLoc(SourceLocation());
4675   TL.setTemplateNameLoc(NameLoc);
4676   TL.setLAngleLoc(Args.getLAngleLoc());
4677   TL.setRAngleLoc(Args.getRAngleLoc());
4678   for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
4679     TL.setArgLocInfo(i, Args[i].getLocInfo());
4680   return DI;
4681 }
4682 
4683 QualType
4684 ASTContext::getTemplateSpecializationType(TemplateName Template,
4685                                           const TemplateArgumentListInfo &Args,
4686                                           QualType Underlying) const {
4687   assert(!Template.getAsDependentTemplateName() &&
4688          "No dependent template names here!");
4689 
4690   SmallVector<TemplateArgument, 4> ArgVec;
4691   ArgVec.reserve(Args.size());
4692   for (const TemplateArgumentLoc &Arg : Args.arguments())
4693     ArgVec.push_back(Arg.getArgument());
4694 
4695   return getTemplateSpecializationType(Template, ArgVec, Underlying);
4696 }
4697 
4698 #ifndef NDEBUG
4699 static bool hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) {
4700   for (const TemplateArgument &Arg : Args)
4701     if (Arg.isPackExpansion())
4702       return true;
4703 
4704   return true;
4705 }
4706 #endif
4707 
4708 QualType
4709 ASTContext::getTemplateSpecializationType(TemplateName Template,
4710                                           ArrayRef<TemplateArgument> Args,
4711                                           QualType Underlying) const {
4712   assert(!Template.getAsDependentTemplateName() &&
4713          "No dependent template names here!");
4714   // Look through qualified template names.
4715   if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
4716     Template = TemplateName(QTN->getTemplateDecl());
4717 
4718   bool IsTypeAlias =
4719     Template.getAsTemplateDecl() &&
4720     isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
4721   QualType CanonType;
4722   if (!Underlying.isNull())
4723     CanonType = getCanonicalType(Underlying);
4724   else {
4725     // We can get here with an alias template when the specialization contains
4726     // a pack expansion that does not match up with a parameter pack.
4727     assert((!IsTypeAlias || hasAnyPackExpansions(Args)) &&
4728            "Caller must compute aliased type");
4729     IsTypeAlias = false;
4730     CanonType = getCanonicalTemplateSpecializationType(Template, Args);
4731   }
4732 
4733   // Allocate the (non-canonical) template specialization type, but don't
4734   // try to unique it: these types typically have location information that
4735   // we don't unique and don't want to lose.
4736   void *Mem = Allocate(sizeof(TemplateSpecializationType) +
4737                        sizeof(TemplateArgument) * Args.size() +
4738                        (IsTypeAlias? sizeof(QualType) : 0),
4739                        TypeAlignment);
4740   auto *Spec
4741     = new (Mem) TemplateSpecializationType(Template, Args, CanonType,
4742                                          IsTypeAlias ? Underlying : QualType());
4743 
4744   Types.push_back(Spec);
4745   return QualType(Spec, 0);
4746 }
4747 
4748 QualType ASTContext::getCanonicalTemplateSpecializationType(
4749     TemplateName Template, ArrayRef<TemplateArgument> Args) const {
4750   assert(!Template.getAsDependentTemplateName() &&
4751          "No dependent template names here!");
4752 
4753   // Look through qualified template names.
4754   if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
4755     Template = TemplateName(QTN->getTemplateDecl());
4756 
4757   // Build the canonical template specialization type.
4758   TemplateName CanonTemplate = getCanonicalTemplateName(Template);
4759   SmallVector<TemplateArgument, 4> CanonArgs;
4760   unsigned NumArgs = Args.size();
4761   CanonArgs.reserve(NumArgs);
4762   for (const TemplateArgument &Arg : Args)
4763     CanonArgs.push_back(getCanonicalTemplateArgument(Arg));
4764 
4765   // Determine whether this canonical template specialization type already
4766   // exists.
4767   llvm::FoldingSetNodeID ID;
4768   TemplateSpecializationType::Profile(ID, CanonTemplate,
4769                                       CanonArgs, *this);
4770 
4771   void *InsertPos = nullptr;
4772   TemplateSpecializationType *Spec
4773     = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
4774 
4775   if (!Spec) {
4776     // Allocate a new canonical template specialization type.
4777     void *Mem = Allocate((sizeof(TemplateSpecializationType) +
4778                           sizeof(TemplateArgument) * NumArgs),
4779                          TypeAlignment);
4780     Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
4781                                                 CanonArgs,
4782                                                 QualType(), QualType());
4783     Types.push_back(Spec);
4784     TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
4785   }
4786 
4787   assert(Spec->isDependentType() &&
4788          "Non-dependent template-id type must have a canonical type");
4789   return QualType(Spec, 0);
4790 }
4791 
4792 QualType ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
4793                                        NestedNameSpecifier *NNS,
4794                                        QualType NamedType,
4795                                        TagDecl *OwnedTagDecl) const {
4796   llvm::FoldingSetNodeID ID;
4797   ElaboratedType::Profile(ID, Keyword, NNS, NamedType, OwnedTagDecl);
4798 
4799   void *InsertPos = nullptr;
4800   ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
4801   if (T)
4802     return QualType(T, 0);
4803 
4804   QualType Canon = NamedType;
4805   if (!Canon.isCanonical()) {
4806     Canon = getCanonicalType(NamedType);
4807     ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
4808     assert(!CheckT && "Elaborated canonical type broken");
4809     (void)CheckT;
4810   }
4811 
4812   void *Mem = Allocate(ElaboratedType::totalSizeToAlloc<TagDecl *>(!!OwnedTagDecl),
4813                        TypeAlignment);
4814   T = new (Mem) ElaboratedType(Keyword, NNS, NamedType, Canon, OwnedTagDecl);
4815 
4816   Types.push_back(T);
4817   ElaboratedTypes.InsertNode(T, InsertPos);
4818   return QualType(T, 0);
4819 }
4820 
4821 QualType
4822 ASTContext::getParenType(QualType InnerType) const {
4823   llvm::FoldingSetNodeID ID;
4824   ParenType::Profile(ID, InnerType);
4825 
4826   void *InsertPos = nullptr;
4827   ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
4828   if (T)
4829     return QualType(T, 0);
4830 
4831   QualType Canon = InnerType;
4832   if (!Canon.isCanonical()) {
4833     Canon = getCanonicalType(InnerType);
4834     ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
4835     assert(!CheckT && "Paren canonical type broken");
4836     (void)CheckT;
4837   }
4838 
4839   T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
4840   Types.push_back(T);
4841   ParenTypes.InsertNode(T, InsertPos);
4842   return QualType(T, 0);
4843 }
4844 
4845 QualType
4846 ASTContext::getMacroQualifiedType(QualType UnderlyingTy,
4847                                   const IdentifierInfo *MacroII) const {
4848   QualType Canon = UnderlyingTy;
4849   if (!Canon.isCanonical())
4850     Canon = getCanonicalType(UnderlyingTy);
4851 
4852   auto *newType = new (*this, TypeAlignment)
4853       MacroQualifiedType(UnderlyingTy, Canon, MacroII);
4854   Types.push_back(newType);
4855   return QualType(newType, 0);
4856 }
4857 
4858 QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
4859                                           NestedNameSpecifier *NNS,
4860                                           const IdentifierInfo *Name,
4861                                           QualType Canon) const {
4862   if (Canon.isNull()) {
4863     NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4864     if (CanonNNS != NNS)
4865       Canon = getDependentNameType(Keyword, CanonNNS, Name);
4866   }
4867 
4868   llvm::FoldingSetNodeID ID;
4869   DependentNameType::Profile(ID, Keyword, NNS, Name);
4870 
4871   void *InsertPos = nullptr;
4872   DependentNameType *T
4873     = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
4874   if (T)
4875     return QualType(T, 0);
4876 
4877   T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
4878   Types.push_back(T);
4879   DependentNameTypes.InsertNode(T, InsertPos);
4880   return QualType(T, 0);
4881 }
4882 
4883 QualType
4884 ASTContext::getDependentTemplateSpecializationType(
4885                                  ElaboratedTypeKeyword Keyword,
4886                                  NestedNameSpecifier *NNS,
4887                                  const IdentifierInfo *Name,
4888                                  const TemplateArgumentListInfo &Args) const {
4889   // TODO: avoid this copy
4890   SmallVector<TemplateArgument, 16> ArgCopy;
4891   for (unsigned I = 0, E = Args.size(); I != E; ++I)
4892     ArgCopy.push_back(Args[I].getArgument());
4893   return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy);
4894 }
4895 
4896 QualType
4897 ASTContext::getDependentTemplateSpecializationType(
4898                                  ElaboratedTypeKeyword Keyword,
4899                                  NestedNameSpecifier *NNS,
4900                                  const IdentifierInfo *Name,
4901                                  ArrayRef<TemplateArgument> Args) const {
4902   assert((!NNS || NNS->isDependent()) &&
4903          "nested-name-specifier must be dependent");
4904 
4905   llvm::FoldingSetNodeID ID;
4906   DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
4907                                                Name, Args);
4908 
4909   void *InsertPos = nullptr;
4910   DependentTemplateSpecializationType *T
4911     = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
4912   if (T)
4913     return QualType(T, 0);
4914 
4915   NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4916 
4917   ElaboratedTypeKeyword CanonKeyword = Keyword;
4918   if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
4919 
4920   bool AnyNonCanonArgs = false;
4921   unsigned NumArgs = Args.size();
4922   SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
4923   for (unsigned I = 0; I != NumArgs; ++I) {
4924     CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
4925     if (!CanonArgs[I].structurallyEquals(Args[I]))
4926       AnyNonCanonArgs = true;
4927   }
4928 
4929   QualType Canon;
4930   if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
4931     Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
4932                                                    Name,
4933                                                    CanonArgs);
4934 
4935     // Find the insert position again.
4936     DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
4937   }
4938 
4939   void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
4940                         sizeof(TemplateArgument) * NumArgs),
4941                        TypeAlignment);
4942   T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
4943                                                     Name, Args, Canon);
4944   Types.push_back(T);
4945   DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
4946   return QualType(T, 0);
4947 }
4948 
4949 TemplateArgument ASTContext::getInjectedTemplateArg(NamedDecl *Param) {
4950   TemplateArgument Arg;
4951   if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
4952     QualType ArgType = getTypeDeclType(TTP);
4953     if (TTP->isParameterPack())
4954       ArgType = getPackExpansionType(ArgType, None);
4955 
4956     Arg = TemplateArgument(ArgType);
4957   } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4958     QualType T =
4959         NTTP->getType().getNonPackExpansionType().getNonLValueExprType(*this);
4960     // For class NTTPs, ensure we include the 'const' so the type matches that
4961     // of a real template argument.
4962     // FIXME: It would be more faithful to model this as something like an
4963     // lvalue-to-rvalue conversion applied to a const-qualified lvalue.
4964     if (T->isRecordType())
4965       T.addConst();
4966     Expr *E = new (*this) DeclRefExpr(
4967         *this, NTTP, /*enclosing*/ false, T,
4968         Expr::getValueKindForType(NTTP->getType()), NTTP->getLocation());
4969 
4970     if (NTTP->isParameterPack())
4971       E = new (*this) PackExpansionExpr(DependentTy, E, NTTP->getLocation(),
4972                                         None);
4973     Arg = TemplateArgument(E);
4974   } else {
4975     auto *TTP = cast<TemplateTemplateParmDecl>(Param);
4976     if (TTP->isParameterPack())
4977       Arg = TemplateArgument(TemplateName(TTP), Optional<unsigned>());
4978     else
4979       Arg = TemplateArgument(TemplateName(TTP));
4980   }
4981 
4982   if (Param->isTemplateParameterPack())
4983     Arg = TemplateArgument::CreatePackCopy(*this, Arg);
4984 
4985   return Arg;
4986 }
4987 
4988 void
4989 ASTContext::getInjectedTemplateArgs(const TemplateParameterList *Params,
4990                                     SmallVectorImpl<TemplateArgument> &Args) {
4991   Args.reserve(Args.size() + Params->size());
4992 
4993   for (NamedDecl *Param : *Params)
4994     Args.push_back(getInjectedTemplateArg(Param));
4995 }
4996 
4997 QualType ASTContext::getPackExpansionType(QualType Pattern,
4998                                           Optional<unsigned> NumExpansions,
4999                                           bool ExpectPackInType) {
5000   assert((!ExpectPackInType || Pattern->containsUnexpandedParameterPack()) &&
5001          "Pack expansions must expand one or more parameter packs");
5002 
5003   llvm::FoldingSetNodeID ID;
5004   PackExpansionType::Profile(ID, Pattern, NumExpansions);
5005 
5006   void *InsertPos = nullptr;
5007   PackExpansionType *T = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
5008   if (T)
5009     return QualType(T, 0);
5010 
5011   QualType Canon;
5012   if (!Pattern.isCanonical()) {
5013     Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions,
5014                                  /*ExpectPackInType=*/false);
5015 
5016     // Find the insert position again, in case we inserted an element into
5017     // PackExpansionTypes and invalidated our insert position.
5018     PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
5019   }
5020 
5021   T = new (*this, TypeAlignment)
5022       PackExpansionType(Pattern, Canon, NumExpansions);
5023   Types.push_back(T);
5024   PackExpansionTypes.InsertNode(T, InsertPos);
5025   return QualType(T, 0);
5026 }
5027 
5028 /// CmpProtocolNames - Comparison predicate for sorting protocols
5029 /// alphabetically.
5030 static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
5031                             ObjCProtocolDecl *const *RHS) {
5032   return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
5033 }
5034 
5035 static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) {
5036   if (Protocols.empty()) return true;
5037 
5038   if (Protocols[0]->getCanonicalDecl() != Protocols[0])
5039     return false;
5040 
5041   for (unsigned i = 1; i != Protocols.size(); ++i)
5042     if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
5043         Protocols[i]->getCanonicalDecl() != Protocols[i])
5044       return false;
5045   return true;
5046 }
5047 
5048 static void
5049 SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
5050   // Sort protocols, keyed by name.
5051   llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
5052 
5053   // Canonicalize.
5054   for (ObjCProtocolDecl *&P : Protocols)
5055     P = P->getCanonicalDecl();
5056 
5057   // Remove duplicates.
5058   auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
5059   Protocols.erase(ProtocolsEnd, Protocols.end());
5060 }
5061 
5062 QualType ASTContext::getObjCObjectType(QualType BaseType,
5063                                        ObjCProtocolDecl * const *Protocols,
5064                                        unsigned NumProtocols) const {
5065   return getObjCObjectType(BaseType, {},
5066                            llvm::makeArrayRef(Protocols, NumProtocols),
5067                            /*isKindOf=*/false);
5068 }
5069 
5070 QualType ASTContext::getObjCObjectType(
5071            QualType baseType,
5072            ArrayRef<QualType> typeArgs,
5073            ArrayRef<ObjCProtocolDecl *> protocols,
5074            bool isKindOf) const {
5075   // If the base type is an interface and there aren't any protocols or
5076   // type arguments to add, then the interface type will do just fine.
5077   if (typeArgs.empty() && protocols.empty() && !isKindOf &&
5078       isa<ObjCInterfaceType>(baseType))
5079     return baseType;
5080 
5081   // Look in the folding set for an existing type.
5082   llvm::FoldingSetNodeID ID;
5083   ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
5084   void *InsertPos = nullptr;
5085   if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
5086     return QualType(QT, 0);
5087 
5088   // Determine the type arguments to be used for canonicalization,
5089   // which may be explicitly specified here or written on the base
5090   // type.
5091   ArrayRef<QualType> effectiveTypeArgs = typeArgs;
5092   if (effectiveTypeArgs.empty()) {
5093     if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
5094       effectiveTypeArgs = baseObject->getTypeArgs();
5095   }
5096 
5097   // Build the canonical type, which has the canonical base type and a
5098   // sorted-and-uniqued list of protocols and the type arguments
5099   // canonicalized.
5100   QualType canonical;
5101   bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(),
5102                                           effectiveTypeArgs.end(),
5103                                           [&](QualType type) {
5104                                             return type.isCanonical();
5105                                           });
5106   bool protocolsSorted = areSortedAndUniqued(protocols);
5107   if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
5108     // Determine the canonical type arguments.
5109     ArrayRef<QualType> canonTypeArgs;
5110     SmallVector<QualType, 4> canonTypeArgsVec;
5111     if (!typeArgsAreCanonical) {
5112       canonTypeArgsVec.reserve(effectiveTypeArgs.size());
5113       for (auto typeArg : effectiveTypeArgs)
5114         canonTypeArgsVec.push_back(getCanonicalType(typeArg));
5115       canonTypeArgs = canonTypeArgsVec;
5116     } else {
5117       canonTypeArgs = effectiveTypeArgs;
5118     }
5119 
5120     ArrayRef<ObjCProtocolDecl *> canonProtocols;
5121     SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
5122     if (!protocolsSorted) {
5123       canonProtocolsVec.append(protocols.begin(), protocols.end());
5124       SortAndUniqueProtocols(canonProtocolsVec);
5125       canonProtocols = canonProtocolsVec;
5126     } else {
5127       canonProtocols = protocols;
5128     }
5129 
5130     canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
5131                                   canonProtocols, isKindOf);
5132 
5133     // Regenerate InsertPos.
5134     ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
5135   }
5136 
5137   unsigned size = sizeof(ObjCObjectTypeImpl);
5138   size += typeArgs.size() * sizeof(QualType);
5139   size += protocols.size() * sizeof(ObjCProtocolDecl *);
5140   void *mem = Allocate(size, TypeAlignment);
5141   auto *T =
5142     new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
5143                                  isKindOf);
5144 
5145   Types.push_back(T);
5146   ObjCObjectTypes.InsertNode(T, InsertPos);
5147   return QualType(T, 0);
5148 }
5149 
5150 /// Apply Objective-C protocol qualifiers to the given type.
5151 /// If this is for the canonical type of a type parameter, we can apply
5152 /// protocol qualifiers on the ObjCObjectPointerType.
5153 QualType
5154 ASTContext::applyObjCProtocolQualifiers(QualType type,
5155                   ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
5156                   bool allowOnPointerType) const {
5157   hasError = false;
5158 
5159   if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
5160     return getObjCTypeParamType(objT->getDecl(), protocols);
5161   }
5162 
5163   // Apply protocol qualifiers to ObjCObjectPointerType.
5164   if (allowOnPointerType) {
5165     if (const auto *objPtr =
5166             dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
5167       const ObjCObjectType *objT = objPtr->getObjectType();
5168       // Merge protocol lists and construct ObjCObjectType.
5169       SmallVector<ObjCProtocolDecl*, 8> protocolsVec;
5170       protocolsVec.append(objT->qual_begin(),
5171                           objT->qual_end());
5172       protocolsVec.append(protocols.begin(), protocols.end());
5173       ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
5174       type = getObjCObjectType(
5175              objT->getBaseType(),
5176              objT->getTypeArgsAsWritten(),
5177              protocols,
5178              objT->isKindOfTypeAsWritten());
5179       return getObjCObjectPointerType(type);
5180     }
5181   }
5182 
5183   // Apply protocol qualifiers to ObjCObjectType.
5184   if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
5185     // FIXME: Check for protocols to which the class type is already
5186     // known to conform.
5187 
5188     return getObjCObjectType(objT->getBaseType(),
5189                              objT->getTypeArgsAsWritten(),
5190                              protocols,
5191                              objT->isKindOfTypeAsWritten());
5192   }
5193 
5194   // If the canonical type is ObjCObjectType, ...
5195   if (type->isObjCObjectType()) {
5196     // Silently overwrite any existing protocol qualifiers.
5197     // TODO: determine whether that's the right thing to do.
5198 
5199     // FIXME: Check for protocols to which the class type is already
5200     // known to conform.
5201     return getObjCObjectType(type, {}, protocols, false);
5202   }
5203 
5204   // id<protocol-list>
5205   if (type->isObjCIdType()) {
5206     const auto *objPtr = type->castAs<ObjCObjectPointerType>();
5207     type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols,
5208                                  objPtr->isKindOfType());
5209     return getObjCObjectPointerType(type);
5210   }
5211 
5212   // Class<protocol-list>
5213   if (type->isObjCClassType()) {
5214     const auto *objPtr = type->castAs<ObjCObjectPointerType>();
5215     type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols,
5216                                  objPtr->isKindOfType());
5217     return getObjCObjectPointerType(type);
5218   }
5219 
5220   hasError = true;
5221   return type;
5222 }
5223 
5224 QualType
5225 ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
5226                                  ArrayRef<ObjCProtocolDecl *> protocols) const {
5227   // Look in the folding set for an existing type.
5228   llvm::FoldingSetNodeID ID;
5229   ObjCTypeParamType::Profile(ID, Decl, Decl->getUnderlyingType(), protocols);
5230   void *InsertPos = nullptr;
5231   if (ObjCTypeParamType *TypeParam =
5232       ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
5233     return QualType(TypeParam, 0);
5234 
5235   // We canonicalize to the underlying type.
5236   QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
5237   if (!protocols.empty()) {
5238     // Apply the protocol qualifers.
5239     bool hasError;
5240     Canonical = getCanonicalType(applyObjCProtocolQualifiers(
5241         Canonical, protocols, hasError, true /*allowOnPointerType*/));
5242     assert(!hasError && "Error when apply protocol qualifier to bound type");
5243   }
5244 
5245   unsigned size = sizeof(ObjCTypeParamType);
5246   size += protocols.size() * sizeof(ObjCProtocolDecl *);
5247   void *mem = Allocate(size, TypeAlignment);
5248   auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
5249 
5250   Types.push_back(newType);
5251   ObjCTypeParamTypes.InsertNode(newType, InsertPos);
5252   return QualType(newType, 0);
5253 }
5254 
5255 void ASTContext::adjustObjCTypeParamBoundType(const ObjCTypeParamDecl *Orig,
5256                                               ObjCTypeParamDecl *New) const {
5257   New->setTypeSourceInfo(getTrivialTypeSourceInfo(Orig->getUnderlyingType()));
5258   // Update TypeForDecl after updating TypeSourceInfo.
5259   auto NewTypeParamTy = cast<ObjCTypeParamType>(New->getTypeForDecl());
5260   SmallVector<ObjCProtocolDecl *, 8> protocols;
5261   protocols.append(NewTypeParamTy->qual_begin(), NewTypeParamTy->qual_end());
5262   QualType UpdatedTy = getObjCTypeParamType(New, protocols);
5263   New->setTypeForDecl(UpdatedTy.getTypePtr());
5264 }
5265 
5266 /// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
5267 /// protocol list adopt all protocols in QT's qualified-id protocol
5268 /// list.
5269 bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
5270                                                 ObjCInterfaceDecl *IC) {
5271   if (!QT->isObjCQualifiedIdType())
5272     return false;
5273 
5274   if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
5275     // If both the right and left sides have qualifiers.
5276     for (auto *Proto : OPT->quals()) {
5277       if (!IC->ClassImplementsProtocol(Proto, false))
5278         return false;
5279     }
5280     return true;
5281   }
5282   return false;
5283 }
5284 
5285 /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
5286 /// QT's qualified-id protocol list adopt all protocols in IDecl's list
5287 /// of protocols.
5288 bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
5289                                                 ObjCInterfaceDecl *IDecl) {
5290   if (!QT->isObjCQualifiedIdType())
5291     return false;
5292   const auto *OPT = QT->getAs<ObjCObjectPointerType>();
5293   if (!OPT)
5294     return false;
5295   if (!IDecl->hasDefinition())
5296     return false;
5297   llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
5298   CollectInheritedProtocols(IDecl, InheritedProtocols);
5299   if (InheritedProtocols.empty())
5300     return false;
5301   // Check that if every protocol in list of id<plist> conforms to a protocol
5302   // of IDecl's, then bridge casting is ok.
5303   bool Conforms = false;
5304   for (auto *Proto : OPT->quals()) {
5305     Conforms = false;
5306     for (auto *PI : InheritedProtocols) {
5307       if (ProtocolCompatibleWithProtocol(Proto, PI)) {
5308         Conforms = true;
5309         break;
5310       }
5311     }
5312     if (!Conforms)
5313       break;
5314   }
5315   if (Conforms)
5316     return true;
5317 
5318   for (auto *PI : InheritedProtocols) {
5319     // If both the right and left sides have qualifiers.
5320     bool Adopts = false;
5321     for (auto *Proto : OPT->quals()) {
5322       // return 'true' if 'PI' is in the inheritance hierarchy of Proto
5323       if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
5324         break;
5325     }
5326     if (!Adopts)
5327       return false;
5328   }
5329   return true;
5330 }
5331 
5332 /// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
5333 /// the given object type.
5334 QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
5335   llvm::FoldingSetNodeID ID;
5336   ObjCObjectPointerType::Profile(ID, ObjectT);
5337 
5338   void *InsertPos = nullptr;
5339   if (ObjCObjectPointerType *QT =
5340               ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
5341     return QualType(QT, 0);
5342 
5343   // Find the canonical object type.
5344   QualType Canonical;
5345   if (!ObjectT.isCanonical()) {
5346     Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
5347 
5348     // Regenerate InsertPos.
5349     ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
5350   }
5351 
5352   // No match.
5353   void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
5354   auto *QType =
5355     new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
5356 
5357   Types.push_back(QType);
5358   ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
5359   return QualType(QType, 0);
5360 }
5361 
5362 /// getObjCInterfaceType - Return the unique reference to the type for the
5363 /// specified ObjC interface decl. The list of protocols is optional.
5364 QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
5365                                           ObjCInterfaceDecl *PrevDecl) const {
5366   if (Decl->TypeForDecl)
5367     return QualType(Decl->TypeForDecl, 0);
5368 
5369   if (PrevDecl) {
5370     assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
5371     Decl->TypeForDecl = PrevDecl->TypeForDecl;
5372     return QualType(PrevDecl->TypeForDecl, 0);
5373   }
5374 
5375   // Prefer the definition, if there is one.
5376   if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
5377     Decl = Def;
5378 
5379   void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
5380   auto *T = new (Mem) ObjCInterfaceType(Decl);
5381   Decl->TypeForDecl = T;
5382   Types.push_back(T);
5383   return QualType(T, 0);
5384 }
5385 
5386 /// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
5387 /// TypeOfExprType AST's (since expression's are never shared). For example,
5388 /// multiple declarations that refer to "typeof(x)" all contain different
5389 /// DeclRefExpr's. This doesn't effect the type checker, since it operates
5390 /// on canonical type's (which are always unique).
5391 QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
5392   TypeOfExprType *toe;
5393   if (tofExpr->isTypeDependent()) {
5394     llvm::FoldingSetNodeID ID;
5395     DependentTypeOfExprType::Profile(ID, *this, tofExpr);
5396 
5397     void *InsertPos = nullptr;
5398     DependentTypeOfExprType *Canon
5399       = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
5400     if (Canon) {
5401       // We already have a "canonical" version of an identical, dependent
5402       // typeof(expr) type. Use that as our canonical type.
5403       toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
5404                                           QualType((TypeOfExprType*)Canon, 0));
5405     } else {
5406       // Build a new, canonical typeof(expr) type.
5407       Canon
5408         = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
5409       DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
5410       toe = Canon;
5411     }
5412   } else {
5413     QualType Canonical = getCanonicalType(tofExpr->getType());
5414     toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
5415   }
5416   Types.push_back(toe);
5417   return QualType(toe, 0);
5418 }
5419 
5420 /// getTypeOfType -  Unlike many "get<Type>" functions, we don't unique
5421 /// TypeOfType nodes. The only motivation to unique these nodes would be
5422 /// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
5423 /// an issue. This doesn't affect the type checker, since it operates
5424 /// on canonical types (which are always unique).
5425 QualType ASTContext::getTypeOfType(QualType tofType) const {
5426   QualType Canonical = getCanonicalType(tofType);
5427   auto *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
5428   Types.push_back(tot);
5429   return QualType(tot, 0);
5430 }
5431 
5432 /// Unlike many "get<Type>" functions, we don't unique DecltypeType
5433 /// nodes. This would never be helpful, since each such type has its own
5434 /// expression, and would not give a significant memory saving, since there
5435 /// is an Expr tree under each such type.
5436 QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
5437   DecltypeType *dt;
5438 
5439   // C++11 [temp.type]p2:
5440   //   If an expression e involves a template parameter, decltype(e) denotes a
5441   //   unique dependent type. Two such decltype-specifiers refer to the same
5442   //   type only if their expressions are equivalent (14.5.6.1).
5443   if (e->isInstantiationDependent()) {
5444     llvm::FoldingSetNodeID ID;
5445     DependentDecltypeType::Profile(ID, *this, e);
5446 
5447     void *InsertPos = nullptr;
5448     DependentDecltypeType *Canon
5449       = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
5450     if (!Canon) {
5451       // Build a new, canonical decltype(expr) type.
5452       Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
5453       DependentDecltypeTypes.InsertNode(Canon, InsertPos);
5454     }
5455     dt = new (*this, TypeAlignment)
5456         DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
5457   } else {
5458     dt = new (*this, TypeAlignment)
5459         DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
5460   }
5461   Types.push_back(dt);
5462   return QualType(dt, 0);
5463 }
5464 
5465 /// getUnaryTransformationType - We don't unique these, since the memory
5466 /// savings are minimal and these are rare.
5467 QualType ASTContext::getUnaryTransformType(QualType BaseType,
5468                                            QualType UnderlyingType,
5469                                            UnaryTransformType::UTTKind Kind)
5470     const {
5471   UnaryTransformType *ut = nullptr;
5472 
5473   if (BaseType->isDependentType()) {
5474     // Look in the folding set for an existing type.
5475     llvm::FoldingSetNodeID ID;
5476     DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind);
5477 
5478     void *InsertPos = nullptr;
5479     DependentUnaryTransformType *Canon
5480       = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
5481 
5482     if (!Canon) {
5483       // Build a new, canonical __underlying_type(type) type.
5484       Canon = new (*this, TypeAlignment)
5485              DependentUnaryTransformType(*this, getCanonicalType(BaseType),
5486                                          Kind);
5487       DependentUnaryTransformTypes.InsertNode(Canon, InsertPos);
5488     }
5489     ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
5490                                                         QualType(), Kind,
5491                                                         QualType(Canon, 0));
5492   } else {
5493     QualType CanonType = getCanonicalType(UnderlyingType);
5494     ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
5495                                                         UnderlyingType, Kind,
5496                                                         CanonType);
5497   }
5498   Types.push_back(ut);
5499   return QualType(ut, 0);
5500 }
5501 
5502 /// getAutoType - Return the uniqued reference to the 'auto' type which has been
5503 /// deduced to the given type, or to the canonical undeduced 'auto' type, or the
5504 /// canonical deduced-but-dependent 'auto' type.
5505 QualType
5506 ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
5507                         bool IsDependent, bool IsPack,
5508                         ConceptDecl *TypeConstraintConcept,
5509                         ArrayRef<TemplateArgument> TypeConstraintArgs) const {
5510   assert((!IsPack || IsDependent) && "only use IsPack for a dependent pack");
5511   if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto &&
5512       !TypeConstraintConcept && !IsDependent)
5513     return getAutoDeductType();
5514 
5515   // Look in the folding set for an existing type.
5516   void *InsertPos = nullptr;
5517   llvm::FoldingSetNodeID ID;
5518   AutoType::Profile(ID, *this, DeducedType, Keyword, IsDependent,
5519                     TypeConstraintConcept, TypeConstraintArgs);
5520   if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
5521     return QualType(AT, 0);
5522 
5523   void *Mem = Allocate(sizeof(AutoType) +
5524                        sizeof(TemplateArgument) * TypeConstraintArgs.size(),
5525                        TypeAlignment);
5526   auto *AT = new (Mem) AutoType(
5527       DeducedType, Keyword,
5528       (IsDependent ? TypeDependence::DependentInstantiation
5529                    : TypeDependence::None) |
5530           (IsPack ? TypeDependence::UnexpandedPack : TypeDependence::None),
5531       TypeConstraintConcept, TypeConstraintArgs);
5532   Types.push_back(AT);
5533   if (InsertPos)
5534     AutoTypes.InsertNode(AT, InsertPos);
5535   return QualType(AT, 0);
5536 }
5537 
5538 /// Return the uniqued reference to the deduced template specialization type
5539 /// which has been deduced to the given type, or to the canonical undeduced
5540 /// such type, or the canonical deduced-but-dependent such type.
5541 QualType ASTContext::getDeducedTemplateSpecializationType(
5542     TemplateName Template, QualType DeducedType, bool IsDependent) const {
5543   // Look in the folding set for an existing type.
5544   void *InsertPos = nullptr;
5545   llvm::FoldingSetNodeID ID;
5546   DeducedTemplateSpecializationType::Profile(ID, Template, DeducedType,
5547                                              IsDependent);
5548   if (DeducedTemplateSpecializationType *DTST =
5549           DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
5550     return QualType(DTST, 0);
5551 
5552   auto *DTST = new (*this, TypeAlignment)
5553       DeducedTemplateSpecializationType(Template, DeducedType, IsDependent);
5554   Types.push_back(DTST);
5555   if (InsertPos)
5556     DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
5557   return QualType(DTST, 0);
5558 }
5559 
5560 /// getAtomicType - Return the uniqued reference to the atomic type for
5561 /// the given value type.
5562 QualType ASTContext::getAtomicType(QualType T) const {
5563   // Unique pointers, to guarantee there is only one pointer of a particular
5564   // structure.
5565   llvm::FoldingSetNodeID ID;
5566   AtomicType::Profile(ID, T);
5567 
5568   void *InsertPos = nullptr;
5569   if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
5570     return QualType(AT, 0);
5571 
5572   // If the atomic value type isn't canonical, this won't be a canonical type
5573   // either, so fill in the canonical type field.
5574   QualType Canonical;
5575   if (!T.isCanonical()) {
5576     Canonical = getAtomicType(getCanonicalType(T));
5577 
5578     // Get the new insert position for the node we care about.
5579     AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
5580     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
5581   }
5582   auto *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
5583   Types.push_back(New);
5584   AtomicTypes.InsertNode(New, InsertPos);
5585   return QualType(New, 0);
5586 }
5587 
5588 /// getAutoDeductType - Get type pattern for deducing against 'auto'.
5589 QualType ASTContext::getAutoDeductType() const {
5590   if (AutoDeductTy.isNull())
5591     AutoDeductTy = QualType(new (*this, TypeAlignment)
5592                                 AutoType(QualType(), AutoTypeKeyword::Auto,
5593                                          TypeDependence::None,
5594                                          /*concept*/ nullptr, /*args*/ {}),
5595                             0);
5596   return AutoDeductTy;
5597 }
5598 
5599 /// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
5600 QualType ASTContext::getAutoRRefDeductType() const {
5601   if (AutoRRefDeductTy.isNull())
5602     AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
5603   assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
5604   return AutoRRefDeductTy;
5605 }
5606 
5607 /// getTagDeclType - Return the unique reference to the type for the
5608 /// specified TagDecl (struct/union/class/enum) decl.
5609 QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
5610   assert(Decl);
5611   // FIXME: What is the design on getTagDeclType when it requires casting
5612   // away const?  mutable?
5613   return getTypeDeclType(const_cast<TagDecl*>(Decl));
5614 }
5615 
5616 /// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
5617 /// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
5618 /// needs to agree with the definition in <stddef.h>.
5619 CanQualType ASTContext::getSizeType() const {
5620   return getFromTargetType(Target->getSizeType());
5621 }
5622 
5623 /// Return the unique signed counterpart of the integer type
5624 /// corresponding to size_t.
5625 CanQualType ASTContext::getSignedSizeType() const {
5626   return getFromTargetType(Target->getSignedSizeType());
5627 }
5628 
5629 /// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
5630 CanQualType ASTContext::getIntMaxType() const {
5631   return getFromTargetType(Target->getIntMaxType());
5632 }
5633 
5634 /// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
5635 CanQualType ASTContext::getUIntMaxType() const {
5636   return getFromTargetType(Target->getUIntMaxType());
5637 }
5638 
5639 /// getSignedWCharType - Return the type of "signed wchar_t".
5640 /// Used when in C++, as a GCC extension.
5641 QualType ASTContext::getSignedWCharType() const {
5642   // FIXME: derive from "Target" ?
5643   return WCharTy;
5644 }
5645 
5646 /// getUnsignedWCharType - Return the type of "unsigned wchar_t".
5647 /// Used when in C++, as a GCC extension.
5648 QualType ASTContext::getUnsignedWCharType() const {
5649   // FIXME: derive from "Target" ?
5650   return UnsignedIntTy;
5651 }
5652 
5653 QualType ASTContext::getIntPtrType() const {
5654   return getFromTargetType(Target->getIntPtrType());
5655 }
5656 
5657 QualType ASTContext::getUIntPtrType() const {
5658   return getCorrespondingUnsignedType(getIntPtrType());
5659 }
5660 
5661 /// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
5662 /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
5663 QualType ASTContext::getPointerDiffType() const {
5664   return getFromTargetType(Target->getPtrDiffType(0));
5665 }
5666 
5667 /// Return the unique unsigned counterpart of "ptrdiff_t"
5668 /// integer type. The standard (C11 7.21.6.1p7) refers to this type
5669 /// in the definition of %tu format specifier.
5670 QualType ASTContext::getUnsignedPointerDiffType() const {
5671   return getFromTargetType(Target->getUnsignedPtrDiffType(0));
5672 }
5673 
5674 /// Return the unique type for "pid_t" defined in
5675 /// <sys/types.h>. We need this to compute the correct type for vfork().
5676 QualType ASTContext::getProcessIDType() const {
5677   return getFromTargetType(Target->getProcessIDType());
5678 }
5679 
5680 //===----------------------------------------------------------------------===//
5681 //                              Type Operators
5682 //===----------------------------------------------------------------------===//
5683 
5684 CanQualType ASTContext::getCanonicalParamType(QualType T) const {
5685   // Push qualifiers into arrays, and then discard any remaining
5686   // qualifiers.
5687   T = getCanonicalType(T);
5688   T = getVariableArrayDecayedType(T);
5689   const Type *Ty = T.getTypePtr();
5690   QualType Result;
5691   if (isa<ArrayType>(Ty)) {
5692     Result = getArrayDecayedType(QualType(Ty,0));
5693   } else if (isa<FunctionType>(Ty)) {
5694     Result = getPointerType(QualType(Ty, 0));
5695   } else {
5696     Result = QualType(Ty, 0);
5697   }
5698 
5699   return CanQualType::CreateUnsafe(Result);
5700 }
5701 
5702 QualType ASTContext::getUnqualifiedArrayType(QualType type,
5703                                              Qualifiers &quals) {
5704   SplitQualType splitType = type.getSplitUnqualifiedType();
5705 
5706   // FIXME: getSplitUnqualifiedType() actually walks all the way to
5707   // the unqualified desugared type and then drops it on the floor.
5708   // We then have to strip that sugar back off with
5709   // getUnqualifiedDesugaredType(), which is silly.
5710   const auto *AT =
5711       dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
5712 
5713   // If we don't have an array, just use the results in splitType.
5714   if (!AT) {
5715     quals = splitType.Quals;
5716     return QualType(splitType.Ty, 0);
5717   }
5718 
5719   // Otherwise, recurse on the array's element type.
5720   QualType elementType = AT->getElementType();
5721   QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
5722 
5723   // If that didn't change the element type, AT has no qualifiers, so we
5724   // can just use the results in splitType.
5725   if (elementType == unqualElementType) {
5726     assert(quals.empty()); // from the recursive call
5727     quals = splitType.Quals;
5728     return QualType(splitType.Ty, 0);
5729   }
5730 
5731   // Otherwise, add in the qualifiers from the outermost type, then
5732   // build the type back up.
5733   quals.addConsistentQualifiers(splitType.Quals);
5734 
5735   if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
5736     return getConstantArrayType(unqualElementType, CAT->getSize(),
5737                                 CAT->getSizeExpr(), CAT->getSizeModifier(), 0);
5738   }
5739 
5740   if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) {
5741     return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
5742   }
5743 
5744   if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) {
5745     return getVariableArrayType(unqualElementType,
5746                                 VAT->getSizeExpr(),
5747                                 VAT->getSizeModifier(),
5748                                 VAT->getIndexTypeCVRQualifiers(),
5749                                 VAT->getBracketsRange());
5750   }
5751 
5752   const auto *DSAT = cast<DependentSizedArrayType>(AT);
5753   return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
5754                                     DSAT->getSizeModifier(), 0,
5755                                     SourceRange());
5756 }
5757 
5758 /// Attempt to unwrap two types that may both be array types with the same bound
5759 /// (or both be array types of unknown bound) for the purpose of comparing the
5760 /// cv-decomposition of two types per C++ [conv.qual].
5761 bool ASTContext::UnwrapSimilarArrayTypes(QualType &T1, QualType &T2) {
5762   bool UnwrappedAny = false;
5763   while (true) {
5764     auto *AT1 = getAsArrayType(T1);
5765     if (!AT1) return UnwrappedAny;
5766 
5767     auto *AT2 = getAsArrayType(T2);
5768     if (!AT2) return UnwrappedAny;
5769 
5770     // If we don't have two array types with the same constant bound nor two
5771     // incomplete array types, we've unwrapped everything we can.
5772     if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) {
5773       auto *CAT2 = dyn_cast<ConstantArrayType>(AT2);
5774       if (!CAT2 || CAT1->getSize() != CAT2->getSize())
5775         return UnwrappedAny;
5776     } else if (!isa<IncompleteArrayType>(AT1) ||
5777                !isa<IncompleteArrayType>(AT2)) {
5778       return UnwrappedAny;
5779     }
5780 
5781     T1 = AT1->getElementType();
5782     T2 = AT2->getElementType();
5783     UnwrappedAny = true;
5784   }
5785 }
5786 
5787 /// Attempt to unwrap two types that may be similar (C++ [conv.qual]).
5788 ///
5789 /// If T1 and T2 are both pointer types of the same kind, or both array types
5790 /// with the same bound, unwraps layers from T1 and T2 until a pointer type is
5791 /// unwrapped. Top-level qualifiers on T1 and T2 are ignored.
5792 ///
5793 /// This function will typically be called in a loop that successively
5794 /// "unwraps" pointer and pointer-to-member types to compare them at each
5795 /// level.
5796 ///
5797 /// \return \c true if a pointer type was unwrapped, \c false if we reached a
5798 /// pair of types that can't be unwrapped further.
5799 bool ASTContext::UnwrapSimilarTypes(QualType &T1, QualType &T2) {
5800   UnwrapSimilarArrayTypes(T1, T2);
5801 
5802   const auto *T1PtrType = T1->getAs<PointerType>();
5803   const auto *T2PtrType = T2->getAs<PointerType>();
5804   if (T1PtrType && T2PtrType) {
5805     T1 = T1PtrType->getPointeeType();
5806     T2 = T2PtrType->getPointeeType();
5807     return true;
5808   }
5809 
5810   const auto *T1MPType = T1->getAs<MemberPointerType>();
5811   const auto *T2MPType = T2->getAs<MemberPointerType>();
5812   if (T1MPType && T2MPType &&
5813       hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
5814                              QualType(T2MPType->getClass(), 0))) {
5815     T1 = T1MPType->getPointeeType();
5816     T2 = T2MPType->getPointeeType();
5817     return true;
5818   }
5819 
5820   if (getLangOpts().ObjC) {
5821     const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
5822     const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
5823     if (T1OPType && T2OPType) {
5824       T1 = T1OPType->getPointeeType();
5825       T2 = T2OPType->getPointeeType();
5826       return true;
5827     }
5828   }
5829 
5830   // FIXME: Block pointers, too?
5831 
5832   return false;
5833 }
5834 
5835 bool ASTContext::hasSimilarType(QualType T1, QualType T2) {
5836   while (true) {
5837     Qualifiers Quals;
5838     T1 = getUnqualifiedArrayType(T1, Quals);
5839     T2 = getUnqualifiedArrayType(T2, Quals);
5840     if (hasSameType(T1, T2))
5841       return true;
5842     if (!UnwrapSimilarTypes(T1, T2))
5843       return false;
5844   }
5845 }
5846 
5847 bool ASTContext::hasCvrSimilarType(QualType T1, QualType T2) {
5848   while (true) {
5849     Qualifiers Quals1, Quals2;
5850     T1 = getUnqualifiedArrayType(T1, Quals1);
5851     T2 = getUnqualifiedArrayType(T2, Quals2);
5852 
5853     Quals1.removeCVRQualifiers();
5854     Quals2.removeCVRQualifiers();
5855     if (Quals1 != Quals2)
5856       return false;
5857 
5858     if (hasSameType(T1, T2))
5859       return true;
5860 
5861     if (!UnwrapSimilarTypes(T1, T2))
5862       return false;
5863   }
5864 }
5865 
5866 DeclarationNameInfo
5867 ASTContext::getNameForTemplate(TemplateName Name,
5868                                SourceLocation NameLoc) const {
5869   switch (Name.getKind()) {
5870   case TemplateName::QualifiedTemplate:
5871   case TemplateName::Template:
5872     // DNInfo work in progress: CHECKME: what about DNLoc?
5873     return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
5874                                NameLoc);
5875 
5876   case TemplateName::OverloadedTemplate: {
5877     OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
5878     // DNInfo work in progress: CHECKME: what about DNLoc?
5879     return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
5880   }
5881 
5882   case TemplateName::AssumedTemplate: {
5883     AssumedTemplateStorage *Storage = Name.getAsAssumedTemplateName();
5884     return DeclarationNameInfo(Storage->getDeclName(), NameLoc);
5885   }
5886 
5887   case TemplateName::DependentTemplate: {
5888     DependentTemplateName *DTN = Name.getAsDependentTemplateName();
5889     DeclarationName DName;
5890     if (DTN->isIdentifier()) {
5891       DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
5892       return DeclarationNameInfo(DName, NameLoc);
5893     } else {
5894       DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
5895       // DNInfo work in progress: FIXME: source locations?
5896       DeclarationNameLoc DNLoc =
5897           DeclarationNameLoc::makeCXXOperatorNameLoc(SourceRange());
5898       return DeclarationNameInfo(DName, NameLoc, DNLoc);
5899     }
5900   }
5901 
5902   case TemplateName::SubstTemplateTemplateParm: {
5903     SubstTemplateTemplateParmStorage *subst
5904       = Name.getAsSubstTemplateTemplateParm();
5905     return DeclarationNameInfo(subst->getParameter()->getDeclName(),
5906                                NameLoc);
5907   }
5908 
5909   case TemplateName::SubstTemplateTemplateParmPack: {
5910     SubstTemplateTemplateParmPackStorage *subst
5911       = Name.getAsSubstTemplateTemplateParmPack();
5912     return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
5913                                NameLoc);
5914   }
5915   }
5916 
5917   llvm_unreachable("bad template name kind!");
5918 }
5919 
5920 TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
5921   switch (Name.getKind()) {
5922   case TemplateName::QualifiedTemplate:
5923   case TemplateName::Template: {
5924     TemplateDecl *Template = Name.getAsTemplateDecl();
5925     if (auto *TTP  = dyn_cast<TemplateTemplateParmDecl>(Template))
5926       Template = getCanonicalTemplateTemplateParmDecl(TTP);
5927 
5928     // The canonical template name is the canonical template declaration.
5929     return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
5930   }
5931 
5932   case TemplateName::OverloadedTemplate:
5933   case TemplateName::AssumedTemplate:
5934     llvm_unreachable("cannot canonicalize unresolved template");
5935 
5936   case TemplateName::DependentTemplate: {
5937     DependentTemplateName *DTN = Name.getAsDependentTemplateName();
5938     assert(DTN && "Non-dependent template names must refer to template decls.");
5939     return DTN->CanonicalTemplateName;
5940   }
5941 
5942   case TemplateName::SubstTemplateTemplateParm: {
5943     SubstTemplateTemplateParmStorage *subst
5944       = Name.getAsSubstTemplateTemplateParm();
5945     return getCanonicalTemplateName(subst->getReplacement());
5946   }
5947 
5948   case TemplateName::SubstTemplateTemplateParmPack: {
5949     SubstTemplateTemplateParmPackStorage *subst
5950                                   = Name.getAsSubstTemplateTemplateParmPack();
5951     TemplateTemplateParmDecl *canonParameter
5952       = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
5953     TemplateArgument canonArgPack
5954       = getCanonicalTemplateArgument(subst->getArgumentPack());
5955     return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
5956   }
5957   }
5958 
5959   llvm_unreachable("bad template name!");
5960 }
5961 
5962 bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
5963   X = getCanonicalTemplateName(X);
5964   Y = getCanonicalTemplateName(Y);
5965   return X.getAsVoidPointer() == Y.getAsVoidPointer();
5966 }
5967 
5968 TemplateArgument
5969 ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
5970   switch (Arg.getKind()) {
5971     case TemplateArgument::Null:
5972       return Arg;
5973 
5974     case TemplateArgument::Expression:
5975       return Arg;
5976 
5977     case TemplateArgument::Declaration: {
5978       auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
5979       return TemplateArgument(D, Arg.getParamTypeForDecl());
5980     }
5981 
5982     case TemplateArgument::NullPtr:
5983       return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
5984                               /*isNullPtr*/true);
5985 
5986     case TemplateArgument::Template:
5987       return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
5988 
5989     case TemplateArgument::TemplateExpansion:
5990       return TemplateArgument(getCanonicalTemplateName(
5991                                          Arg.getAsTemplateOrTemplatePattern()),
5992                               Arg.getNumTemplateExpansions());
5993 
5994     case TemplateArgument::Integral:
5995       return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
5996 
5997     case TemplateArgument::Type:
5998       return TemplateArgument(getCanonicalType(Arg.getAsType()));
5999 
6000     case TemplateArgument::Pack: {
6001       if (Arg.pack_size() == 0)
6002         return Arg;
6003 
6004       auto *CanonArgs = new (*this) TemplateArgument[Arg.pack_size()];
6005       unsigned Idx = 0;
6006       for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
6007                                         AEnd = Arg.pack_end();
6008            A != AEnd; (void)++A, ++Idx)
6009         CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
6010 
6011       return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
6012     }
6013   }
6014 
6015   // Silence GCC warning
6016   llvm_unreachable("Unhandled template argument kind");
6017 }
6018 
6019 NestedNameSpecifier *
6020 ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
6021   if (!NNS)
6022     return nullptr;
6023 
6024   switch (NNS->getKind()) {
6025   case NestedNameSpecifier::Identifier:
6026     // Canonicalize the prefix but keep the identifier the same.
6027     return NestedNameSpecifier::Create(*this,
6028                          getCanonicalNestedNameSpecifier(NNS->getPrefix()),
6029                                        NNS->getAsIdentifier());
6030 
6031   case NestedNameSpecifier::Namespace:
6032     // A namespace is canonical; build a nested-name-specifier with
6033     // this namespace and no prefix.
6034     return NestedNameSpecifier::Create(*this, nullptr,
6035                                  NNS->getAsNamespace()->getOriginalNamespace());
6036 
6037   case NestedNameSpecifier::NamespaceAlias:
6038     // A namespace is canonical; build a nested-name-specifier with
6039     // this namespace and no prefix.
6040     return NestedNameSpecifier::Create(*this, nullptr,
6041                                     NNS->getAsNamespaceAlias()->getNamespace()
6042                                                       ->getOriginalNamespace());
6043 
6044   case NestedNameSpecifier::TypeSpec:
6045   case NestedNameSpecifier::TypeSpecWithTemplate: {
6046     QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
6047 
6048     // If we have some kind of dependent-named type (e.g., "typename T::type"),
6049     // break it apart into its prefix and identifier, then reconsititute those
6050     // as the canonical nested-name-specifier. This is required to canonicalize
6051     // a dependent nested-name-specifier involving typedefs of dependent-name
6052     // types, e.g.,
6053     //   typedef typename T::type T1;
6054     //   typedef typename T1::type T2;
6055     if (const auto *DNT = T->getAs<DependentNameType>())
6056       return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
6057                            const_cast<IdentifierInfo *>(DNT->getIdentifier()));
6058 
6059     // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
6060     // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
6061     // first place?
6062     return NestedNameSpecifier::Create(*this, nullptr, false,
6063                                        const_cast<Type *>(T.getTypePtr()));
6064   }
6065 
6066   case NestedNameSpecifier::Global:
6067   case NestedNameSpecifier::Super:
6068     // The global specifier and __super specifer are canonical and unique.
6069     return NNS;
6070   }
6071 
6072   llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
6073 }
6074 
6075 const ArrayType *ASTContext::getAsArrayType(QualType T) const {
6076   // Handle the non-qualified case efficiently.
6077   if (!T.hasLocalQualifiers()) {
6078     // Handle the common positive case fast.
6079     if (const auto *AT = dyn_cast<ArrayType>(T))
6080       return AT;
6081   }
6082 
6083   // Handle the common negative case fast.
6084   if (!isa<ArrayType>(T.getCanonicalType()))
6085     return nullptr;
6086 
6087   // Apply any qualifiers from the array type to the element type.  This
6088   // implements C99 6.7.3p8: "If the specification of an array type includes
6089   // any type qualifiers, the element type is so qualified, not the array type."
6090 
6091   // If we get here, we either have type qualifiers on the type, or we have
6092   // sugar such as a typedef in the way.  If we have type qualifiers on the type
6093   // we must propagate them down into the element type.
6094 
6095   SplitQualType split = T.getSplitDesugaredType();
6096   Qualifiers qs = split.Quals;
6097 
6098   // If we have a simple case, just return now.
6099   const auto *ATy = dyn_cast<ArrayType>(split.Ty);
6100   if (!ATy || qs.empty())
6101     return ATy;
6102 
6103   // Otherwise, we have an array and we have qualifiers on it.  Push the
6104   // qualifiers into the array element type and return a new array type.
6105   QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
6106 
6107   if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy))
6108     return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
6109                                                 CAT->getSizeExpr(),
6110                                                 CAT->getSizeModifier(),
6111                                            CAT->getIndexTypeCVRQualifiers()));
6112   if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy))
6113     return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
6114                                                   IAT->getSizeModifier(),
6115                                            IAT->getIndexTypeCVRQualifiers()));
6116 
6117   if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy))
6118     return cast<ArrayType>(
6119                      getDependentSizedArrayType(NewEltTy,
6120                                                 DSAT->getSizeExpr(),
6121                                                 DSAT->getSizeModifier(),
6122                                               DSAT->getIndexTypeCVRQualifiers(),
6123                                                 DSAT->getBracketsRange()));
6124 
6125   const auto *VAT = cast<VariableArrayType>(ATy);
6126   return cast<ArrayType>(getVariableArrayType(NewEltTy,
6127                                               VAT->getSizeExpr(),
6128                                               VAT->getSizeModifier(),
6129                                               VAT->getIndexTypeCVRQualifiers(),
6130                                               VAT->getBracketsRange()));
6131 }
6132 
6133 QualType ASTContext::getAdjustedParameterType(QualType T) const {
6134   if (T->isArrayType() || T->isFunctionType())
6135     return getDecayedType(T);
6136   return T;
6137 }
6138 
6139 QualType ASTContext::getSignatureParameterType(QualType T) const {
6140   T = getVariableArrayDecayedType(T);
6141   T = getAdjustedParameterType(T);
6142   return T.getUnqualifiedType();
6143 }
6144 
6145 QualType ASTContext::getExceptionObjectType(QualType T) const {
6146   // C++ [except.throw]p3:
6147   //   A throw-expression initializes a temporary object, called the exception
6148   //   object, the type of which is determined by removing any top-level
6149   //   cv-qualifiers from the static type of the operand of throw and adjusting
6150   //   the type from "array of T" or "function returning T" to "pointer to T"
6151   //   or "pointer to function returning T", [...]
6152   T = getVariableArrayDecayedType(T);
6153   if (T->isArrayType() || T->isFunctionType())
6154     T = getDecayedType(T);
6155   return T.getUnqualifiedType();
6156 }
6157 
6158 /// getArrayDecayedType - Return the properly qualified result of decaying the
6159 /// specified array type to a pointer.  This operation is non-trivial when
6160 /// handling typedefs etc.  The canonical type of "T" must be an array type,
6161 /// this returns a pointer to a properly qualified element of the array.
6162 ///
6163 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
6164 QualType ASTContext::getArrayDecayedType(QualType Ty) const {
6165   // Get the element type with 'getAsArrayType' so that we don't lose any
6166   // typedefs in the element type of the array.  This also handles propagation
6167   // of type qualifiers from the array type into the element type if present
6168   // (C99 6.7.3p8).
6169   const ArrayType *PrettyArrayType = getAsArrayType(Ty);
6170   assert(PrettyArrayType && "Not an array type!");
6171 
6172   QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
6173 
6174   // int x[restrict 4] ->  int *restrict
6175   QualType Result = getQualifiedType(PtrTy,
6176                                      PrettyArrayType->getIndexTypeQualifiers());
6177 
6178   // int x[_Nullable] -> int * _Nullable
6179   if (auto Nullability = Ty->getNullability(*this)) {
6180     Result = const_cast<ASTContext *>(this)->getAttributedType(
6181         AttributedType::getNullabilityAttrKind(*Nullability), Result, Result);
6182   }
6183   return Result;
6184 }
6185 
6186 QualType ASTContext::getBaseElementType(const ArrayType *array) const {
6187   return getBaseElementType(array->getElementType());
6188 }
6189 
6190 QualType ASTContext::getBaseElementType(QualType type) const {
6191   Qualifiers qs;
6192   while (true) {
6193     SplitQualType split = type.getSplitDesugaredType();
6194     const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
6195     if (!array) break;
6196 
6197     type = array->getElementType();
6198     qs.addConsistentQualifiers(split.Quals);
6199   }
6200 
6201   return getQualifiedType(type, qs);
6202 }
6203 
6204 /// getConstantArrayElementCount - Returns number of constant array elements.
6205 uint64_t
6206 ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA)  const {
6207   uint64_t ElementCount = 1;
6208   do {
6209     ElementCount *= CA->getSize().getZExtValue();
6210     CA = dyn_cast_or_null<ConstantArrayType>(
6211       CA->getElementType()->getAsArrayTypeUnsafe());
6212   } while (CA);
6213   return ElementCount;
6214 }
6215 
6216 /// getFloatingRank - Return a relative rank for floating point types.
6217 /// This routine will assert if passed a built-in type that isn't a float.
6218 static FloatingRank getFloatingRank(QualType T) {
6219   if (const auto *CT = T->getAs<ComplexType>())
6220     return getFloatingRank(CT->getElementType());
6221 
6222   switch (T->castAs<BuiltinType>()->getKind()) {
6223   default: llvm_unreachable("getFloatingRank(): not a floating type");
6224   case BuiltinType::Float16:    return Float16Rank;
6225   case BuiltinType::Half:       return HalfRank;
6226   case BuiltinType::Float:      return FloatRank;
6227   case BuiltinType::Double:     return DoubleRank;
6228   case BuiltinType::LongDouble: return LongDoubleRank;
6229   case BuiltinType::Float128:   return Float128Rank;
6230   case BuiltinType::BFloat16:   return BFloat16Rank;
6231   }
6232 }
6233 
6234 /// getFloatingTypeOfSizeWithinDomain - Returns a real floating
6235 /// point or a complex type (based on typeDomain/typeSize).
6236 /// 'typeDomain' is a real floating point or complex type.
6237 /// 'typeSize' is a real floating point or complex type.
6238 QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
6239                                                        QualType Domain) const {
6240   FloatingRank EltRank = getFloatingRank(Size);
6241   if (Domain->isComplexType()) {
6242     switch (EltRank) {
6243     case BFloat16Rank: llvm_unreachable("Complex bfloat16 is not supported");
6244     case Float16Rank:
6245     case HalfRank: llvm_unreachable("Complex half is not supported");
6246     case FloatRank:      return FloatComplexTy;
6247     case DoubleRank:     return DoubleComplexTy;
6248     case LongDoubleRank: return LongDoubleComplexTy;
6249     case Float128Rank:   return Float128ComplexTy;
6250     }
6251   }
6252 
6253   assert(Domain->isRealFloatingType() && "Unknown domain!");
6254   switch (EltRank) {
6255   case Float16Rank:    return HalfTy;
6256   case BFloat16Rank:   return BFloat16Ty;
6257   case HalfRank:       return HalfTy;
6258   case FloatRank:      return FloatTy;
6259   case DoubleRank:     return DoubleTy;
6260   case LongDoubleRank: return LongDoubleTy;
6261   case Float128Rank:   return Float128Ty;
6262   }
6263   llvm_unreachable("getFloatingRank(): illegal value for rank");
6264 }
6265 
6266 /// getFloatingTypeOrder - Compare the rank of the two specified floating
6267 /// point types, ignoring the domain of the type (i.e. 'double' ==
6268 /// '_Complex double').  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
6269 /// LHS < RHS, return -1.
6270 int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
6271   FloatingRank LHSR = getFloatingRank(LHS);
6272   FloatingRank RHSR = getFloatingRank(RHS);
6273 
6274   if (LHSR == RHSR)
6275     return 0;
6276   if (LHSR > RHSR)
6277     return 1;
6278   return -1;
6279 }
6280 
6281 int ASTContext::getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const {
6282   if (&getFloatTypeSemantics(LHS) == &getFloatTypeSemantics(RHS))
6283     return 0;
6284   return getFloatingTypeOrder(LHS, RHS);
6285 }
6286 
6287 /// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
6288 /// routine will assert if passed a built-in type that isn't an integer or enum,
6289 /// or if it is not canonicalized.
6290 unsigned ASTContext::getIntegerRank(const Type *T) const {
6291   assert(T->isCanonicalUnqualified() && "T should be canonicalized");
6292 
6293   // Results in this 'losing' to any type of the same size, but winning if
6294   // larger.
6295   if (const auto *EIT = dyn_cast<ExtIntType>(T))
6296     return 0 + (EIT->getNumBits() << 3);
6297 
6298   switch (cast<BuiltinType>(T)->getKind()) {
6299   default: llvm_unreachable("getIntegerRank(): not a built-in integer");
6300   case BuiltinType::Bool:
6301     return 1 + (getIntWidth(BoolTy) << 3);
6302   case BuiltinType::Char_S:
6303   case BuiltinType::Char_U:
6304   case BuiltinType::SChar:
6305   case BuiltinType::UChar:
6306     return 2 + (getIntWidth(CharTy) << 3);
6307   case BuiltinType::Short:
6308   case BuiltinType::UShort:
6309     return 3 + (getIntWidth(ShortTy) << 3);
6310   case BuiltinType::Int:
6311   case BuiltinType::UInt:
6312     return 4 + (getIntWidth(IntTy) << 3);
6313   case BuiltinType::Long:
6314   case BuiltinType::ULong:
6315     return 5 + (getIntWidth(LongTy) << 3);
6316   case BuiltinType::LongLong:
6317   case BuiltinType::ULongLong:
6318     return 6 + (getIntWidth(LongLongTy) << 3);
6319   case BuiltinType::Int128:
6320   case BuiltinType::UInt128:
6321     return 7 + (getIntWidth(Int128Ty) << 3);
6322   }
6323 }
6324 
6325 /// Whether this is a promotable bitfield reference according
6326 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
6327 ///
6328 /// \returns the type this bit-field will promote to, or NULL if no
6329 /// promotion occurs.
6330 QualType ASTContext::isPromotableBitField(Expr *E) const {
6331   if (E->isTypeDependent() || E->isValueDependent())
6332     return {};
6333 
6334   // C++ [conv.prom]p5:
6335   //    If the bit-field has an enumerated type, it is treated as any other
6336   //    value of that type for promotion purposes.
6337   if (getLangOpts().CPlusPlus && E->getType()->isEnumeralType())
6338     return {};
6339 
6340   // FIXME: We should not do this unless E->refersToBitField() is true. This
6341   // matters in C where getSourceBitField() will find bit-fields for various
6342   // cases where the source expression is not a bit-field designator.
6343 
6344   FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
6345   if (!Field)
6346     return {};
6347 
6348   QualType FT = Field->getType();
6349 
6350   uint64_t BitWidth = Field->getBitWidthValue(*this);
6351   uint64_t IntSize = getTypeSize(IntTy);
6352   // C++ [conv.prom]p5:
6353   //   A prvalue for an integral bit-field can be converted to a prvalue of type
6354   //   int if int can represent all the values of the bit-field; otherwise, it
6355   //   can be converted to unsigned int if unsigned int can represent all the
6356   //   values of the bit-field. If the bit-field is larger yet, no integral
6357   //   promotion applies to it.
6358   // C11 6.3.1.1/2:
6359   //   [For a bit-field of type _Bool, int, signed int, or unsigned int:]
6360   //   If an int can represent all values of the original type (as restricted by
6361   //   the width, for a bit-field), the value is converted to an int; otherwise,
6362   //   it is converted to an unsigned int.
6363   //
6364   // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
6365   //        We perform that promotion here to match GCC and C++.
6366   // FIXME: C does not permit promotion of an enum bit-field whose rank is
6367   //        greater than that of 'int'. We perform that promotion to match GCC.
6368   if (BitWidth < IntSize)
6369     return IntTy;
6370 
6371   if (BitWidth == IntSize)
6372     return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
6373 
6374   // Bit-fields wider than int are not subject to promotions, and therefore act
6375   // like the base type. GCC has some weird bugs in this area that we
6376   // deliberately do not follow (GCC follows a pre-standard resolution to
6377   // C's DR315 which treats bit-width as being part of the type, and this leaks
6378   // into their semantics in some cases).
6379   return {};
6380 }
6381 
6382 /// getPromotedIntegerType - Returns the type that Promotable will
6383 /// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
6384 /// integer type.
6385 QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
6386   assert(!Promotable.isNull());
6387   assert(Promotable->isPromotableIntegerType());
6388   if (const auto *ET = Promotable->getAs<EnumType>())
6389     return ET->getDecl()->getPromotionType();
6390 
6391   if (const auto *BT = Promotable->getAs<BuiltinType>()) {
6392     // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
6393     // (3.9.1) can be converted to a prvalue of the first of the following
6394     // types that can represent all the values of its underlying type:
6395     // int, unsigned int, long int, unsigned long int, long long int, or
6396     // unsigned long long int [...]
6397     // FIXME: Is there some better way to compute this?
6398     if (BT->getKind() == BuiltinType::WChar_S ||
6399         BT->getKind() == BuiltinType::WChar_U ||
6400         BT->getKind() == BuiltinType::Char8 ||
6401         BT->getKind() == BuiltinType::Char16 ||
6402         BT->getKind() == BuiltinType::Char32) {
6403       bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
6404       uint64_t FromSize = getTypeSize(BT);
6405       QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
6406                                   LongLongTy, UnsignedLongLongTy };
6407       for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
6408         uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
6409         if (FromSize < ToSize ||
6410             (FromSize == ToSize &&
6411              FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
6412           return PromoteTypes[Idx];
6413       }
6414       llvm_unreachable("char type should fit into long long");
6415     }
6416   }
6417 
6418   // At this point, we should have a signed or unsigned integer type.
6419   if (Promotable->isSignedIntegerType())
6420     return IntTy;
6421   uint64_t PromotableSize = getIntWidth(Promotable);
6422   uint64_t IntSize = getIntWidth(IntTy);
6423   assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
6424   return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
6425 }
6426 
6427 /// Recurses in pointer/array types until it finds an objc retainable
6428 /// type and returns its ownership.
6429 Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
6430   while (!T.isNull()) {
6431     if (T.getObjCLifetime() != Qualifiers::OCL_None)
6432       return T.getObjCLifetime();
6433     if (T->isArrayType())
6434       T = getBaseElementType(T);
6435     else if (const auto *PT = T->getAs<PointerType>())
6436       T = PT->getPointeeType();
6437     else if (const auto *RT = T->getAs<ReferenceType>())
6438       T = RT->getPointeeType();
6439     else
6440       break;
6441   }
6442 
6443   return Qualifiers::OCL_None;
6444 }
6445 
6446 static const Type *getIntegerTypeForEnum(const EnumType *ET) {
6447   // Incomplete enum types are not treated as integer types.
6448   // FIXME: In C++, enum types are never integer types.
6449   if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
6450     return ET->getDecl()->getIntegerType().getTypePtr();
6451   return nullptr;
6452 }
6453 
6454 /// getIntegerTypeOrder - Returns the highest ranked integer type:
6455 /// C99 6.3.1.8p1.  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
6456 /// LHS < RHS, return -1.
6457 int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
6458   const Type *LHSC = getCanonicalType(LHS).getTypePtr();
6459   const Type *RHSC = getCanonicalType(RHS).getTypePtr();
6460 
6461   // Unwrap enums to their underlying type.
6462   if (const auto *ET = dyn_cast<EnumType>(LHSC))
6463     LHSC = getIntegerTypeForEnum(ET);
6464   if (const auto *ET = dyn_cast<EnumType>(RHSC))
6465     RHSC = getIntegerTypeForEnum(ET);
6466 
6467   if (LHSC == RHSC) return 0;
6468 
6469   bool LHSUnsigned = LHSC->isUnsignedIntegerType();
6470   bool RHSUnsigned = RHSC->isUnsignedIntegerType();
6471 
6472   unsigned LHSRank = getIntegerRank(LHSC);
6473   unsigned RHSRank = getIntegerRank(RHSC);
6474 
6475   if (LHSUnsigned == RHSUnsigned) {  // Both signed or both unsigned.
6476     if (LHSRank == RHSRank) return 0;
6477     return LHSRank > RHSRank ? 1 : -1;
6478   }
6479 
6480   // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
6481   if (LHSUnsigned) {
6482     // If the unsigned [LHS] type is larger, return it.
6483     if (LHSRank >= RHSRank)
6484       return 1;
6485 
6486     // If the signed type can represent all values of the unsigned type, it
6487     // wins.  Because we are dealing with 2's complement and types that are
6488     // powers of two larger than each other, this is always safe.
6489     return -1;
6490   }
6491 
6492   // If the unsigned [RHS] type is larger, return it.
6493   if (RHSRank >= LHSRank)
6494     return -1;
6495 
6496   // If the signed type can represent all values of the unsigned type, it
6497   // wins.  Because we are dealing with 2's complement and types that are
6498   // powers of two larger than each other, this is always safe.
6499   return 1;
6500 }
6501 
6502 TypedefDecl *ASTContext::getCFConstantStringDecl() const {
6503   if (CFConstantStringTypeDecl)
6504     return CFConstantStringTypeDecl;
6505 
6506   assert(!CFConstantStringTagDecl &&
6507          "tag and typedef should be initialized together");
6508   CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
6509   CFConstantStringTagDecl->startDefinition();
6510 
6511   struct {
6512     QualType Type;
6513     const char *Name;
6514   } Fields[5];
6515   unsigned Count = 0;
6516 
6517   /// Objective-C ABI
6518   ///
6519   ///    typedef struct __NSConstantString_tag {
6520   ///      const int *isa;
6521   ///      int flags;
6522   ///      const char *str;
6523   ///      long length;
6524   ///    } __NSConstantString;
6525   ///
6526   /// Swift ABI (4.1, 4.2)
6527   ///
6528   ///    typedef struct __NSConstantString_tag {
6529   ///      uintptr_t _cfisa;
6530   ///      uintptr_t _swift_rc;
6531   ///      _Atomic(uint64_t) _cfinfoa;
6532   ///      const char *_ptr;
6533   ///      uint32_t _length;
6534   ///    } __NSConstantString;
6535   ///
6536   /// Swift ABI (5.0)
6537   ///
6538   ///    typedef struct __NSConstantString_tag {
6539   ///      uintptr_t _cfisa;
6540   ///      uintptr_t _swift_rc;
6541   ///      _Atomic(uint64_t) _cfinfoa;
6542   ///      const char *_ptr;
6543   ///      uintptr_t _length;
6544   ///    } __NSConstantString;
6545 
6546   const auto CFRuntime = getLangOpts().CFRuntime;
6547   if (static_cast<unsigned>(CFRuntime) <
6548       static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) {
6549     Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" };
6550     Fields[Count++] = { IntTy, "flags" };
6551     Fields[Count++] = { getPointerType(CharTy.withConst()), "str" };
6552     Fields[Count++] = { LongTy, "length" };
6553   } else {
6554     Fields[Count++] = { getUIntPtrType(), "_cfisa" };
6555     Fields[Count++] = { getUIntPtrType(), "_swift_rc" };
6556     Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" };
6557     Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" };
6558     if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
6559         CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
6560       Fields[Count++] = { IntTy, "_ptr" };
6561     else
6562       Fields[Count++] = { getUIntPtrType(), "_ptr" };
6563   }
6564 
6565   // Create fields
6566   for (unsigned i = 0; i < Count; ++i) {
6567     FieldDecl *Field =
6568         FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(),
6569                           SourceLocation(), &Idents.get(Fields[i].Name),
6570                           Fields[i].Type, /*TInfo=*/nullptr,
6571                           /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
6572     Field->setAccess(AS_public);
6573     CFConstantStringTagDecl->addDecl(Field);
6574   }
6575 
6576   CFConstantStringTagDecl->completeDefinition();
6577   // This type is designed to be compatible with NSConstantString, but cannot
6578   // use the same name, since NSConstantString is an interface.
6579   auto tagType = getTagDeclType(CFConstantStringTagDecl);
6580   CFConstantStringTypeDecl =
6581       buildImplicitTypedef(tagType, "__NSConstantString");
6582 
6583   return CFConstantStringTypeDecl;
6584 }
6585 
6586 RecordDecl *ASTContext::getCFConstantStringTagDecl() const {
6587   if (!CFConstantStringTagDecl)
6588     getCFConstantStringDecl(); // Build the tag and the typedef.
6589   return CFConstantStringTagDecl;
6590 }
6591 
6592 // getCFConstantStringType - Return the type used for constant CFStrings.
6593 QualType ASTContext::getCFConstantStringType() const {
6594   return getTypedefType(getCFConstantStringDecl());
6595 }
6596 
6597 QualType ASTContext::getObjCSuperType() const {
6598   if (ObjCSuperType.isNull()) {
6599     RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
6600     TUDecl->addDecl(ObjCSuperTypeDecl);
6601     ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
6602   }
6603   return ObjCSuperType;
6604 }
6605 
6606 void ASTContext::setCFConstantStringType(QualType T) {
6607   const auto *TD = T->castAs<TypedefType>();
6608   CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl());
6609   const auto *TagType =
6610       CFConstantStringTypeDecl->getUnderlyingType()->castAs<RecordType>();
6611   CFConstantStringTagDecl = TagType->getDecl();
6612 }
6613 
6614 QualType ASTContext::getBlockDescriptorType() const {
6615   if (BlockDescriptorType)
6616     return getTagDeclType(BlockDescriptorType);
6617 
6618   RecordDecl *RD;
6619   // FIXME: Needs the FlagAppleBlock bit.
6620   RD = buildImplicitRecord("__block_descriptor");
6621   RD->startDefinition();
6622 
6623   QualType FieldTypes[] = {
6624     UnsignedLongTy,
6625     UnsignedLongTy,
6626   };
6627 
6628   static const char *const FieldNames[] = {
6629     "reserved",
6630     "Size"
6631   };
6632 
6633   for (size_t i = 0; i < 2; ++i) {
6634     FieldDecl *Field = FieldDecl::Create(
6635         *this, RD, SourceLocation(), SourceLocation(),
6636         &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
6637         /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
6638     Field->setAccess(AS_public);
6639     RD->addDecl(Field);
6640   }
6641 
6642   RD->completeDefinition();
6643 
6644   BlockDescriptorType = RD;
6645 
6646   return getTagDeclType(BlockDescriptorType);
6647 }
6648 
6649 QualType ASTContext::getBlockDescriptorExtendedType() const {
6650   if (BlockDescriptorExtendedType)
6651     return getTagDeclType(BlockDescriptorExtendedType);
6652 
6653   RecordDecl *RD;
6654   // FIXME: Needs the FlagAppleBlock bit.
6655   RD = buildImplicitRecord("__block_descriptor_withcopydispose");
6656   RD->startDefinition();
6657 
6658   QualType FieldTypes[] = {
6659     UnsignedLongTy,
6660     UnsignedLongTy,
6661     getPointerType(VoidPtrTy),
6662     getPointerType(VoidPtrTy)
6663   };
6664 
6665   static const char *const FieldNames[] = {
6666     "reserved",
6667     "Size",
6668     "CopyFuncPtr",
6669     "DestroyFuncPtr"
6670   };
6671 
6672   for (size_t i = 0; i < 4; ++i) {
6673     FieldDecl *Field = FieldDecl::Create(
6674         *this, RD, SourceLocation(), SourceLocation(),
6675         &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
6676         /*BitWidth=*/nullptr,
6677         /*Mutable=*/false, ICIS_NoInit);
6678     Field->setAccess(AS_public);
6679     RD->addDecl(Field);
6680   }
6681 
6682   RD->completeDefinition();
6683 
6684   BlockDescriptorExtendedType = RD;
6685   return getTagDeclType(BlockDescriptorExtendedType);
6686 }
6687 
6688 OpenCLTypeKind ASTContext::getOpenCLTypeKind(const Type *T) const {
6689   const auto *BT = dyn_cast<BuiltinType>(T);
6690 
6691   if (!BT) {
6692     if (isa<PipeType>(T))
6693       return OCLTK_Pipe;
6694 
6695     return OCLTK_Default;
6696   }
6697 
6698   switch (BT->getKind()) {
6699 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix)                   \
6700   case BuiltinType::Id:                                                        \
6701     return OCLTK_Image;
6702 #include "clang/Basic/OpenCLImageTypes.def"
6703 
6704   case BuiltinType::OCLClkEvent:
6705     return OCLTK_ClkEvent;
6706 
6707   case BuiltinType::OCLEvent:
6708     return OCLTK_Event;
6709 
6710   case BuiltinType::OCLQueue:
6711     return OCLTK_Queue;
6712 
6713   case BuiltinType::OCLReserveID:
6714     return OCLTK_ReserveID;
6715 
6716   case BuiltinType::OCLSampler:
6717     return OCLTK_Sampler;
6718 
6719   default:
6720     return OCLTK_Default;
6721   }
6722 }
6723 
6724 LangAS ASTContext::getOpenCLTypeAddrSpace(const Type *T) const {
6725   return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
6726 }
6727 
6728 /// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
6729 /// requires copy/dispose. Note that this must match the logic
6730 /// in buildByrefHelpers.
6731 bool ASTContext::BlockRequiresCopying(QualType Ty,
6732                                       const VarDecl *D) {
6733   if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
6734     const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr();
6735     if (!copyExpr && record->hasTrivialDestructor()) return false;
6736 
6737     return true;
6738   }
6739 
6740   // The block needs copy/destroy helpers if Ty is non-trivial to destructively
6741   // move or destroy.
6742   if (Ty.isNonTrivialToPrimitiveDestructiveMove() || Ty.isDestructedType())
6743     return true;
6744 
6745   if (!Ty->isObjCRetainableType()) return false;
6746 
6747   Qualifiers qs = Ty.getQualifiers();
6748 
6749   // If we have lifetime, that dominates.
6750   if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
6751     switch (lifetime) {
6752       case Qualifiers::OCL_None: llvm_unreachable("impossible");
6753 
6754       // These are just bits as far as the runtime is concerned.
6755       case Qualifiers::OCL_ExplicitNone:
6756       case Qualifiers::OCL_Autoreleasing:
6757         return false;
6758 
6759       // These cases should have been taken care of when checking the type's
6760       // non-triviality.
6761       case Qualifiers::OCL_Weak:
6762       case Qualifiers::OCL_Strong:
6763         llvm_unreachable("impossible");
6764     }
6765     llvm_unreachable("fell out of lifetime switch!");
6766   }
6767   return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
6768           Ty->isObjCObjectPointerType());
6769 }
6770 
6771 bool ASTContext::getByrefLifetime(QualType Ty,
6772                               Qualifiers::ObjCLifetime &LifeTime,
6773                               bool &HasByrefExtendedLayout) const {
6774   if (!getLangOpts().ObjC ||
6775       getLangOpts().getGC() != LangOptions::NonGC)
6776     return false;
6777 
6778   HasByrefExtendedLayout = false;
6779   if (Ty->isRecordType()) {
6780     HasByrefExtendedLayout = true;
6781     LifeTime = Qualifiers::OCL_None;
6782   } else if ((LifeTime = Ty.getObjCLifetime())) {
6783     // Honor the ARC qualifiers.
6784   } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
6785     // The MRR rule.
6786     LifeTime = Qualifiers::OCL_ExplicitNone;
6787   } else {
6788     LifeTime = Qualifiers::OCL_None;
6789   }
6790   return true;
6791 }
6792 
6793 CanQualType ASTContext::getNSUIntegerType() const {
6794   assert(Target && "Expected target to be initialized");
6795   const llvm::Triple &T = Target->getTriple();
6796   // Windows is LLP64 rather than LP64
6797   if (T.isOSWindows() && T.isArch64Bit())
6798     return UnsignedLongLongTy;
6799   return UnsignedLongTy;
6800 }
6801 
6802 CanQualType ASTContext::getNSIntegerType() const {
6803   assert(Target && "Expected target to be initialized");
6804   const llvm::Triple &T = Target->getTriple();
6805   // Windows is LLP64 rather than LP64
6806   if (T.isOSWindows() && T.isArch64Bit())
6807     return LongLongTy;
6808   return LongTy;
6809 }
6810 
6811 TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
6812   if (!ObjCInstanceTypeDecl)
6813     ObjCInstanceTypeDecl =
6814         buildImplicitTypedef(getObjCIdType(), "instancetype");
6815   return ObjCInstanceTypeDecl;
6816 }
6817 
6818 // This returns true if a type has been typedefed to BOOL:
6819 // typedef <type> BOOL;
6820 static bool isTypeTypedefedAsBOOL(QualType T) {
6821   if (const auto *TT = dyn_cast<TypedefType>(T))
6822     if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
6823       return II->isStr("BOOL");
6824 
6825   return false;
6826 }
6827 
6828 /// getObjCEncodingTypeSize returns size of type for objective-c encoding
6829 /// purpose.
6830 CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
6831   if (!type->isIncompleteArrayType() && type->isIncompleteType())
6832     return CharUnits::Zero();
6833 
6834   CharUnits sz = getTypeSizeInChars(type);
6835 
6836   // Make all integer and enum types at least as large as an int
6837   if (sz.isPositive() && type->isIntegralOrEnumerationType())
6838     sz = std::max(sz, getTypeSizeInChars(IntTy));
6839   // Treat arrays as pointers, since that's how they're passed in.
6840   else if (type->isArrayType())
6841     sz = getTypeSizeInChars(VoidPtrTy);
6842   return sz;
6843 }
6844 
6845 bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
6846   return getTargetInfo().getCXXABI().isMicrosoft() &&
6847          VD->isStaticDataMember() &&
6848          VD->getType()->isIntegralOrEnumerationType() &&
6849          !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
6850 }
6851 
6852 ASTContext::InlineVariableDefinitionKind
6853 ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const {
6854   if (!VD->isInline())
6855     return InlineVariableDefinitionKind::None;
6856 
6857   // In almost all cases, it's a weak definition.
6858   auto *First = VD->getFirstDecl();
6859   if (First->isInlineSpecified() || !First->isStaticDataMember())
6860     return InlineVariableDefinitionKind::Weak;
6861 
6862   // If there's a file-context declaration in this translation unit, it's a
6863   // non-discardable definition.
6864   for (auto *D : VD->redecls())
6865     if (D->getLexicalDeclContext()->isFileContext() &&
6866         !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
6867       return InlineVariableDefinitionKind::Strong;
6868 
6869   // If we've not seen one yet, we don't know.
6870   return InlineVariableDefinitionKind::WeakUnknown;
6871 }
6872 
6873 static std::string charUnitsToString(const CharUnits &CU) {
6874   return llvm::itostr(CU.getQuantity());
6875 }
6876 
6877 /// getObjCEncodingForBlock - Return the encoded type for this block
6878 /// declaration.
6879 std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
6880   std::string S;
6881 
6882   const BlockDecl *Decl = Expr->getBlockDecl();
6883   QualType BlockTy =
6884       Expr->getType()->castAs<BlockPointerType>()->getPointeeType();
6885   QualType BlockReturnTy = BlockTy->castAs<FunctionType>()->getReturnType();
6886   // Encode result type.
6887   if (getLangOpts().EncodeExtendedBlockSig)
6888     getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, BlockReturnTy, S,
6889                                       true /*Extended*/);
6890   else
6891     getObjCEncodingForType(BlockReturnTy, S);
6892   // Compute size of all parameters.
6893   // Start with computing size of a pointer in number of bytes.
6894   // FIXME: There might(should) be a better way of doing this computation!
6895   CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
6896   CharUnits ParmOffset = PtrSize;
6897   for (auto PI : Decl->parameters()) {
6898     QualType PType = PI->getType();
6899     CharUnits sz = getObjCEncodingTypeSize(PType);
6900     if (sz.isZero())
6901       continue;
6902     assert(sz.isPositive() && "BlockExpr - Incomplete param type");
6903     ParmOffset += sz;
6904   }
6905   // Size of the argument frame
6906   S += charUnitsToString(ParmOffset);
6907   // Block pointer and offset.
6908   S += "@?0";
6909 
6910   // Argument types.
6911   ParmOffset = PtrSize;
6912   for (auto PVDecl : Decl->parameters()) {
6913     QualType PType = PVDecl->getOriginalType();
6914     if (const auto *AT =
6915             dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
6916       // Use array's original type only if it has known number of
6917       // elements.
6918       if (!isa<ConstantArrayType>(AT))
6919         PType = PVDecl->getType();
6920     } else if (PType->isFunctionType())
6921       PType = PVDecl->getType();
6922     if (getLangOpts().EncodeExtendedBlockSig)
6923       getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
6924                                       S, true /*Extended*/);
6925     else
6926       getObjCEncodingForType(PType, S);
6927     S += charUnitsToString(ParmOffset);
6928     ParmOffset += getObjCEncodingTypeSize(PType);
6929   }
6930 
6931   return S;
6932 }
6933 
6934 std::string
6935 ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const {
6936   std::string S;
6937   // Encode result type.
6938   getObjCEncodingForType(Decl->getReturnType(), S);
6939   CharUnits ParmOffset;
6940   // Compute size of all parameters.
6941   for (auto PI : Decl->parameters()) {
6942     QualType PType = PI->getType();
6943     CharUnits sz = getObjCEncodingTypeSize(PType);
6944     if (sz.isZero())
6945       continue;
6946 
6947     assert(sz.isPositive() &&
6948            "getObjCEncodingForFunctionDecl - Incomplete param type");
6949     ParmOffset += sz;
6950   }
6951   S += charUnitsToString(ParmOffset);
6952   ParmOffset = CharUnits::Zero();
6953 
6954   // Argument types.
6955   for (auto PVDecl : Decl->parameters()) {
6956     QualType PType = PVDecl->getOriginalType();
6957     if (const auto *AT =
6958             dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
6959       // Use array's original type only if it has known number of
6960       // elements.
6961       if (!isa<ConstantArrayType>(AT))
6962         PType = PVDecl->getType();
6963     } else if (PType->isFunctionType())
6964       PType = PVDecl->getType();
6965     getObjCEncodingForType(PType, S);
6966     S += charUnitsToString(ParmOffset);
6967     ParmOffset += getObjCEncodingTypeSize(PType);
6968   }
6969 
6970   return S;
6971 }
6972 
6973 /// getObjCEncodingForMethodParameter - Return the encoded type for a single
6974 /// method parameter or return type. If Extended, include class names and
6975 /// block object types.
6976 void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
6977                                                    QualType T, std::string& S,
6978                                                    bool Extended) const {
6979   // Encode type qualifer, 'in', 'inout', etc. for the parameter.
6980   getObjCEncodingForTypeQualifier(QT, S);
6981   // Encode parameter type.
6982   ObjCEncOptions Options = ObjCEncOptions()
6983                                .setExpandPointedToStructures()
6984                                .setExpandStructures()
6985                                .setIsOutermostType();
6986   if (Extended)
6987     Options.setEncodeBlockParameters().setEncodeClassNames();
6988   getObjCEncodingForTypeImpl(T, S, Options, /*Field=*/nullptr);
6989 }
6990 
6991 /// getObjCEncodingForMethodDecl - Return the encoded type for this method
6992 /// declaration.
6993 std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
6994                                                      bool Extended) const {
6995   // FIXME: This is not very efficient.
6996   // Encode return type.
6997   std::string S;
6998   getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
6999                                     Decl->getReturnType(), S, Extended);
7000   // Compute size of all parameters.
7001   // Start with computing size of a pointer in number of bytes.
7002   // FIXME: There might(should) be a better way of doing this computation!
7003   CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
7004   // The first two arguments (self and _cmd) are pointers; account for
7005   // their size.
7006   CharUnits ParmOffset = 2 * PtrSize;
7007   for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
7008        E = Decl->sel_param_end(); PI != E; ++PI) {
7009     QualType PType = (*PI)->getType();
7010     CharUnits sz = getObjCEncodingTypeSize(PType);
7011     if (sz.isZero())
7012       continue;
7013 
7014     assert(sz.isPositive() &&
7015            "getObjCEncodingForMethodDecl - Incomplete param type");
7016     ParmOffset += sz;
7017   }
7018   S += charUnitsToString(ParmOffset);
7019   S += "@0:";
7020   S += charUnitsToString(PtrSize);
7021 
7022   // Argument types.
7023   ParmOffset = 2 * PtrSize;
7024   for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
7025        E = Decl->sel_param_end(); PI != E; ++PI) {
7026     const ParmVarDecl *PVDecl = *PI;
7027     QualType PType = PVDecl->getOriginalType();
7028     if (const auto *AT =
7029             dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
7030       // Use array's original type only if it has known number of
7031       // elements.
7032       if (!isa<ConstantArrayType>(AT))
7033         PType = PVDecl->getType();
7034     } else if (PType->isFunctionType())
7035       PType = PVDecl->getType();
7036     getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
7037                                       PType, S, Extended);
7038     S += charUnitsToString(ParmOffset);
7039     ParmOffset += getObjCEncodingTypeSize(PType);
7040   }
7041 
7042   return S;
7043 }
7044 
7045 ObjCPropertyImplDecl *
7046 ASTContext::getObjCPropertyImplDeclForPropertyDecl(
7047                                       const ObjCPropertyDecl *PD,
7048                                       const Decl *Container) const {
7049   if (!Container)
7050     return nullptr;
7051   if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) {
7052     for (auto *PID : CID->property_impls())
7053       if (PID->getPropertyDecl() == PD)
7054         return PID;
7055   } else {
7056     const auto *OID = cast<ObjCImplementationDecl>(Container);
7057     for (auto *PID : OID->property_impls())
7058       if (PID->getPropertyDecl() == PD)
7059         return PID;
7060   }
7061   return nullptr;
7062 }
7063 
7064 /// getObjCEncodingForPropertyDecl - Return the encoded type for this
7065 /// property declaration. If non-NULL, Container must be either an
7066 /// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
7067 /// NULL when getting encodings for protocol properties.
7068 /// Property attributes are stored as a comma-delimited C string. The simple
7069 /// attributes readonly and bycopy are encoded as single characters. The
7070 /// parametrized attributes, getter=name, setter=name, and ivar=name, are
7071 /// encoded as single characters, followed by an identifier. Property types
7072 /// are also encoded as a parametrized attribute. The characters used to encode
7073 /// these attributes are defined by the following enumeration:
7074 /// @code
7075 /// enum PropertyAttributes {
7076 /// kPropertyReadOnly = 'R',   // property is read-only.
7077 /// kPropertyBycopy = 'C',     // property is a copy of the value last assigned
7078 /// kPropertyByref = '&',  // property is a reference to the value last assigned
7079 /// kPropertyDynamic = 'D',    // property is dynamic
7080 /// kPropertyGetter = 'G',     // followed by getter selector name
7081 /// kPropertySetter = 'S',     // followed by setter selector name
7082 /// kPropertyInstanceVariable = 'V'  // followed by instance variable  name
7083 /// kPropertyType = 'T'              // followed by old-style type encoding.
7084 /// kPropertyWeak = 'W'              // 'weak' property
7085 /// kPropertyStrong = 'P'            // property GC'able
7086 /// kPropertyNonAtomic = 'N'         // property non-atomic
7087 /// };
7088 /// @endcode
7089 std::string
7090 ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
7091                                            const Decl *Container) const {
7092   // Collect information from the property implementation decl(s).
7093   bool Dynamic = false;
7094   ObjCPropertyImplDecl *SynthesizePID = nullptr;
7095 
7096   if (ObjCPropertyImplDecl *PropertyImpDecl =
7097       getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
7098     if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
7099       Dynamic = true;
7100     else
7101       SynthesizePID = PropertyImpDecl;
7102   }
7103 
7104   // FIXME: This is not very efficient.
7105   std::string S = "T";
7106 
7107   // Encode result type.
7108   // GCC has some special rules regarding encoding of properties which
7109   // closely resembles encoding of ivars.
7110   getObjCEncodingForPropertyType(PD->getType(), S);
7111 
7112   if (PD->isReadOnly()) {
7113     S += ",R";
7114     if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_copy)
7115       S += ",C";
7116     if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_retain)
7117       S += ",&";
7118     if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_weak)
7119       S += ",W";
7120   } else {
7121     switch (PD->getSetterKind()) {
7122     case ObjCPropertyDecl::Assign: break;
7123     case ObjCPropertyDecl::Copy:   S += ",C"; break;
7124     case ObjCPropertyDecl::Retain: S += ",&"; break;
7125     case ObjCPropertyDecl::Weak:   S += ",W"; break;
7126     }
7127   }
7128 
7129   // It really isn't clear at all what this means, since properties
7130   // are "dynamic by default".
7131   if (Dynamic)
7132     S += ",D";
7133 
7134   if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_nonatomic)
7135     S += ",N";
7136 
7137   if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_getter) {
7138     S += ",G";
7139     S += PD->getGetterName().getAsString();
7140   }
7141 
7142   if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_setter) {
7143     S += ",S";
7144     S += PD->getSetterName().getAsString();
7145   }
7146 
7147   if (SynthesizePID) {
7148     const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
7149     S += ",V";
7150     S += OID->getNameAsString();
7151   }
7152 
7153   // FIXME: OBJCGC: weak & strong
7154   return S;
7155 }
7156 
7157 /// getLegacyIntegralTypeEncoding -
7158 /// Another legacy compatibility encoding: 32-bit longs are encoded as
7159 /// 'l' or 'L' , but not always.  For typedefs, we need to use
7160 /// 'i' or 'I' instead if encoding a struct field, or a pointer!
7161 void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
7162   if (isa<TypedefType>(PointeeTy.getTypePtr())) {
7163     if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
7164       if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
7165         PointeeTy = UnsignedIntTy;
7166       else
7167         if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
7168           PointeeTy = IntTy;
7169     }
7170   }
7171 }
7172 
7173 void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
7174                                         const FieldDecl *Field,
7175                                         QualType *NotEncodedT) const {
7176   // We follow the behavior of gcc, expanding structures which are
7177   // directly pointed to, and expanding embedded structures. Note that
7178   // these rules are sufficient to prevent recursive encoding of the
7179   // same type.
7180   getObjCEncodingForTypeImpl(T, S,
7181                              ObjCEncOptions()
7182                                  .setExpandPointedToStructures()
7183                                  .setExpandStructures()
7184                                  .setIsOutermostType(),
7185                              Field, NotEncodedT);
7186 }
7187 
7188 void ASTContext::getObjCEncodingForPropertyType(QualType T,
7189                                                 std::string& S) const {
7190   // Encode result type.
7191   // GCC has some special rules regarding encoding of properties which
7192   // closely resembles encoding of ivars.
7193   getObjCEncodingForTypeImpl(T, S,
7194                              ObjCEncOptions()
7195                                  .setExpandPointedToStructures()
7196                                  .setExpandStructures()
7197                                  .setIsOutermostType()
7198                                  .setEncodingProperty(),
7199                              /*Field=*/nullptr);
7200 }
7201 
7202 static char getObjCEncodingForPrimitiveType(const ASTContext *C,
7203                                             const BuiltinType *BT) {
7204     BuiltinType::Kind kind = BT->getKind();
7205     switch (kind) {
7206     case BuiltinType::Void:       return 'v';
7207     case BuiltinType::Bool:       return 'B';
7208     case BuiltinType::Char8:
7209     case BuiltinType::Char_U:
7210     case BuiltinType::UChar:      return 'C';
7211     case BuiltinType::Char16:
7212     case BuiltinType::UShort:     return 'S';
7213     case BuiltinType::Char32:
7214     case BuiltinType::UInt:       return 'I';
7215     case BuiltinType::ULong:
7216         return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
7217     case BuiltinType::UInt128:    return 'T';
7218     case BuiltinType::ULongLong:  return 'Q';
7219     case BuiltinType::Char_S:
7220     case BuiltinType::SChar:      return 'c';
7221     case BuiltinType::Short:      return 's';
7222     case BuiltinType::WChar_S:
7223     case BuiltinType::WChar_U:
7224     case BuiltinType::Int:        return 'i';
7225     case BuiltinType::Long:
7226       return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
7227     case BuiltinType::LongLong:   return 'q';
7228     case BuiltinType::Int128:     return 't';
7229     case BuiltinType::Float:      return 'f';
7230     case BuiltinType::Double:     return 'd';
7231     case BuiltinType::LongDouble: return 'D';
7232     case BuiltinType::NullPtr:    return '*'; // like char*
7233 
7234     case BuiltinType::BFloat16:
7235     case BuiltinType::Float16:
7236     case BuiltinType::Float128:
7237     case BuiltinType::Half:
7238     case BuiltinType::ShortAccum:
7239     case BuiltinType::Accum:
7240     case BuiltinType::LongAccum:
7241     case BuiltinType::UShortAccum:
7242     case BuiltinType::UAccum:
7243     case BuiltinType::ULongAccum:
7244     case BuiltinType::ShortFract:
7245     case BuiltinType::Fract:
7246     case BuiltinType::LongFract:
7247     case BuiltinType::UShortFract:
7248     case BuiltinType::UFract:
7249     case BuiltinType::ULongFract:
7250     case BuiltinType::SatShortAccum:
7251     case BuiltinType::SatAccum:
7252     case BuiltinType::SatLongAccum:
7253     case BuiltinType::SatUShortAccum:
7254     case BuiltinType::SatUAccum:
7255     case BuiltinType::SatULongAccum:
7256     case BuiltinType::SatShortFract:
7257     case BuiltinType::SatFract:
7258     case BuiltinType::SatLongFract:
7259     case BuiltinType::SatUShortFract:
7260     case BuiltinType::SatUFract:
7261     case BuiltinType::SatULongFract:
7262       // FIXME: potentially need @encodes for these!
7263       return ' ';
7264 
7265 #define SVE_TYPE(Name, Id, SingletonId) \
7266     case BuiltinType::Id:
7267 #include "clang/Basic/AArch64SVEACLETypes.def"
7268 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
7269 #include "clang/Basic/RISCVVTypes.def"
7270       {
7271         DiagnosticsEngine &Diags = C->getDiagnostics();
7272         unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
7273                                                 "cannot yet @encode type %0");
7274         Diags.Report(DiagID) << BT->getName(C->getPrintingPolicy());
7275         return ' ';
7276       }
7277 
7278     case BuiltinType::ObjCId:
7279     case BuiltinType::ObjCClass:
7280     case BuiltinType::ObjCSel:
7281       llvm_unreachable("@encoding ObjC primitive type");
7282 
7283     // OpenCL and placeholder types don't need @encodings.
7284 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7285     case BuiltinType::Id:
7286 #include "clang/Basic/OpenCLImageTypes.def"
7287 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
7288     case BuiltinType::Id:
7289 #include "clang/Basic/OpenCLExtensionTypes.def"
7290     case BuiltinType::OCLEvent:
7291     case BuiltinType::OCLClkEvent:
7292     case BuiltinType::OCLQueue:
7293     case BuiltinType::OCLReserveID:
7294     case BuiltinType::OCLSampler:
7295     case BuiltinType::Dependent:
7296 #define PPC_VECTOR_TYPE(Name, Id, Size) \
7297     case BuiltinType::Id:
7298 #include "clang/Basic/PPCTypes.def"
7299 #define BUILTIN_TYPE(KIND, ID)
7300 #define PLACEHOLDER_TYPE(KIND, ID) \
7301     case BuiltinType::KIND:
7302 #include "clang/AST/BuiltinTypes.def"
7303       llvm_unreachable("invalid builtin type for @encode");
7304     }
7305     llvm_unreachable("invalid BuiltinType::Kind value");
7306 }
7307 
7308 static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
7309   EnumDecl *Enum = ET->getDecl();
7310 
7311   // The encoding of an non-fixed enum type is always 'i', regardless of size.
7312   if (!Enum->isFixed())
7313     return 'i';
7314 
7315   // The encoding of a fixed enum type matches its fixed underlying type.
7316   const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
7317   return getObjCEncodingForPrimitiveType(C, BT);
7318 }
7319 
7320 static void EncodeBitField(const ASTContext *Ctx, std::string& S,
7321                            QualType T, const FieldDecl *FD) {
7322   assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
7323   S += 'b';
7324   // The NeXT runtime encodes bit fields as b followed by the number of bits.
7325   // The GNU runtime requires more information; bitfields are encoded as b,
7326   // then the offset (in bits) of the first element, then the type of the
7327   // bitfield, then the size in bits.  For example, in this structure:
7328   //
7329   // struct
7330   // {
7331   //    int integer;
7332   //    int flags:2;
7333   // };
7334   // On a 32-bit system, the encoding for flags would be b2 for the NeXT
7335   // runtime, but b32i2 for the GNU runtime.  The reason for this extra
7336   // information is not especially sensible, but we're stuck with it for
7337   // compatibility with GCC, although providing it breaks anything that
7338   // actually uses runtime introspection and wants to work on both runtimes...
7339   if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
7340     uint64_t Offset;
7341 
7342     if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
7343       Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), nullptr,
7344                                          IVD);
7345     } else {
7346       const RecordDecl *RD = FD->getParent();
7347       const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
7348       Offset = RL.getFieldOffset(FD->getFieldIndex());
7349     }
7350 
7351     S += llvm::utostr(Offset);
7352 
7353     if (const auto *ET = T->getAs<EnumType>())
7354       S += ObjCEncodingForEnumType(Ctx, ET);
7355     else {
7356       const auto *BT = T->castAs<BuiltinType>();
7357       S += getObjCEncodingForPrimitiveType(Ctx, BT);
7358     }
7359   }
7360   S += llvm::utostr(FD->getBitWidthValue(*Ctx));
7361 }
7362 
7363 // Helper function for determining whether the encoded type string would include
7364 // a template specialization type.
7365 static bool hasTemplateSpecializationInEncodedString(const Type *T,
7366                                                      bool VisitBasesAndFields) {
7367   T = T->getBaseElementTypeUnsafe();
7368 
7369   if (auto *PT = T->getAs<PointerType>())
7370     return hasTemplateSpecializationInEncodedString(
7371         PT->getPointeeType().getTypePtr(), false);
7372 
7373   auto *CXXRD = T->getAsCXXRecordDecl();
7374 
7375   if (!CXXRD)
7376     return false;
7377 
7378   if (isa<ClassTemplateSpecializationDecl>(CXXRD))
7379     return true;
7380 
7381   if (!CXXRD->hasDefinition() || !VisitBasesAndFields)
7382     return false;
7383 
7384   for (auto B : CXXRD->bases())
7385     if (hasTemplateSpecializationInEncodedString(B.getType().getTypePtr(),
7386                                                  true))
7387       return true;
7388 
7389   for (auto *FD : CXXRD->fields())
7390     if (hasTemplateSpecializationInEncodedString(FD->getType().getTypePtr(),
7391                                                  true))
7392       return true;
7393 
7394   return false;
7395 }
7396 
7397 // FIXME: Use SmallString for accumulating string.
7398 void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
7399                                             const ObjCEncOptions Options,
7400                                             const FieldDecl *FD,
7401                                             QualType *NotEncodedT) const {
7402   CanQualType CT = getCanonicalType(T);
7403   switch (CT->getTypeClass()) {
7404   case Type::Builtin:
7405   case Type::Enum:
7406     if (FD && FD->isBitField())
7407       return EncodeBitField(this, S, T, FD);
7408     if (const auto *BT = dyn_cast<BuiltinType>(CT))
7409       S += getObjCEncodingForPrimitiveType(this, BT);
7410     else
7411       S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
7412     return;
7413 
7414   case Type::Complex:
7415     S += 'j';
7416     getObjCEncodingForTypeImpl(T->castAs<ComplexType>()->getElementType(), S,
7417                                ObjCEncOptions(),
7418                                /*Field=*/nullptr);
7419     return;
7420 
7421   case Type::Atomic:
7422     S += 'A';
7423     getObjCEncodingForTypeImpl(T->castAs<AtomicType>()->getValueType(), S,
7424                                ObjCEncOptions(),
7425                                /*Field=*/nullptr);
7426     return;
7427 
7428   // encoding for pointer or reference types.
7429   case Type::Pointer:
7430   case Type::LValueReference:
7431   case Type::RValueReference: {
7432     QualType PointeeTy;
7433     if (isa<PointerType>(CT)) {
7434       const auto *PT = T->castAs<PointerType>();
7435       if (PT->isObjCSelType()) {
7436         S += ':';
7437         return;
7438       }
7439       PointeeTy = PT->getPointeeType();
7440     } else {
7441       PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
7442     }
7443 
7444     bool isReadOnly = false;
7445     // For historical/compatibility reasons, the read-only qualifier of the
7446     // pointee gets emitted _before_ the '^'.  The read-only qualifier of
7447     // the pointer itself gets ignored, _unless_ we are looking at a typedef!
7448     // Also, do not emit the 'r' for anything but the outermost type!
7449     if (isa<TypedefType>(T.getTypePtr())) {
7450       if (Options.IsOutermostType() && T.isConstQualified()) {
7451         isReadOnly = true;
7452         S += 'r';
7453       }
7454     } else if (Options.IsOutermostType()) {
7455       QualType P = PointeeTy;
7456       while (auto PT = P->getAs<PointerType>())
7457         P = PT->getPointeeType();
7458       if (P.isConstQualified()) {
7459         isReadOnly = true;
7460         S += 'r';
7461       }
7462     }
7463     if (isReadOnly) {
7464       // Another legacy compatibility encoding. Some ObjC qualifier and type
7465       // combinations need to be rearranged.
7466       // Rewrite "in const" from "nr" to "rn"
7467       if (StringRef(S).endswith("nr"))
7468         S.replace(S.end()-2, S.end(), "rn");
7469     }
7470 
7471     if (PointeeTy->isCharType()) {
7472       // char pointer types should be encoded as '*' unless it is a
7473       // type that has been typedef'd to 'BOOL'.
7474       if (!isTypeTypedefedAsBOOL(PointeeTy)) {
7475         S += '*';
7476         return;
7477       }
7478     } else if (const auto *RTy = PointeeTy->getAs<RecordType>()) {
7479       // GCC binary compat: Need to convert "struct objc_class *" to "#".
7480       if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
7481         S += '#';
7482         return;
7483       }
7484       // GCC binary compat: Need to convert "struct objc_object *" to "@".
7485       if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
7486         S += '@';
7487         return;
7488       }
7489       // If the encoded string for the class includes template names, just emit
7490       // "^v" for pointers to the class.
7491       if (getLangOpts().CPlusPlus &&
7492           (!getLangOpts().EncodeCXXClassTemplateSpec &&
7493            hasTemplateSpecializationInEncodedString(
7494                RTy, Options.ExpandPointedToStructures()))) {
7495         S += "^v";
7496         return;
7497       }
7498       // fall through...
7499     }
7500     S += '^';
7501     getLegacyIntegralTypeEncoding(PointeeTy);
7502 
7503     ObjCEncOptions NewOptions;
7504     if (Options.ExpandPointedToStructures())
7505       NewOptions.setExpandStructures();
7506     getObjCEncodingForTypeImpl(PointeeTy, S, NewOptions,
7507                                /*Field=*/nullptr, NotEncodedT);
7508     return;
7509   }
7510 
7511   case Type::ConstantArray:
7512   case Type::IncompleteArray:
7513   case Type::VariableArray: {
7514     const auto *AT = cast<ArrayType>(CT);
7515 
7516     if (isa<IncompleteArrayType>(AT) && !Options.IsStructField()) {
7517       // Incomplete arrays are encoded as a pointer to the array element.
7518       S += '^';
7519 
7520       getObjCEncodingForTypeImpl(
7521           AT->getElementType(), S,
7522           Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD);
7523     } else {
7524       S += '[';
7525 
7526       if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
7527         S += llvm::utostr(CAT->getSize().getZExtValue());
7528       else {
7529         //Variable length arrays are encoded as a regular array with 0 elements.
7530         assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
7531                "Unknown array type!");
7532         S += '0';
7533       }
7534 
7535       getObjCEncodingForTypeImpl(
7536           AT->getElementType(), S,
7537           Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD,
7538           NotEncodedT);
7539       S += ']';
7540     }
7541     return;
7542   }
7543 
7544   case Type::FunctionNoProto:
7545   case Type::FunctionProto:
7546     S += '?';
7547     return;
7548 
7549   case Type::Record: {
7550     RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
7551     S += RDecl->isUnion() ? '(' : '{';
7552     // Anonymous structures print as '?'
7553     if (const IdentifierInfo *II = RDecl->getIdentifier()) {
7554       S += II->getName();
7555       if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
7556         const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
7557         llvm::raw_string_ostream OS(S);
7558         printTemplateArgumentList(OS, TemplateArgs.asArray(),
7559                                   getPrintingPolicy());
7560       }
7561     } else {
7562       S += '?';
7563     }
7564     if (Options.ExpandStructures()) {
7565       S += '=';
7566       if (!RDecl->isUnion()) {
7567         getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
7568       } else {
7569         for (const auto *Field : RDecl->fields()) {
7570           if (FD) {
7571             S += '"';
7572             S += Field->getNameAsString();
7573             S += '"';
7574           }
7575 
7576           // Special case bit-fields.
7577           if (Field->isBitField()) {
7578             getObjCEncodingForTypeImpl(Field->getType(), S,
7579                                        ObjCEncOptions().setExpandStructures(),
7580                                        Field);
7581           } else {
7582             QualType qt = Field->getType();
7583             getLegacyIntegralTypeEncoding(qt);
7584             getObjCEncodingForTypeImpl(
7585                 qt, S,
7586                 ObjCEncOptions().setExpandStructures().setIsStructField(), FD,
7587                 NotEncodedT);
7588           }
7589         }
7590       }
7591     }
7592     S += RDecl->isUnion() ? ')' : '}';
7593     return;
7594   }
7595 
7596   case Type::BlockPointer: {
7597     const auto *BT = T->castAs<BlockPointerType>();
7598     S += "@?"; // Unlike a pointer-to-function, which is "^?".
7599     if (Options.EncodeBlockParameters()) {
7600       const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
7601 
7602       S += '<';
7603       // Block return type
7604       getObjCEncodingForTypeImpl(FT->getReturnType(), S,
7605                                  Options.forComponentType(), FD, NotEncodedT);
7606       // Block self
7607       S += "@?";
7608       // Block parameters
7609       if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) {
7610         for (const auto &I : FPT->param_types())
7611           getObjCEncodingForTypeImpl(I, S, Options.forComponentType(), FD,
7612                                      NotEncodedT);
7613       }
7614       S += '>';
7615     }
7616     return;
7617   }
7618 
7619   case Type::ObjCObject: {
7620     // hack to match legacy encoding of *id and *Class
7621     QualType Ty = getObjCObjectPointerType(CT);
7622     if (Ty->isObjCIdType()) {
7623       S += "{objc_object=}";
7624       return;
7625     }
7626     else if (Ty->isObjCClassType()) {
7627       S += "{objc_class=}";
7628       return;
7629     }
7630     // TODO: Double check to make sure this intentionally falls through.
7631     LLVM_FALLTHROUGH;
7632   }
7633 
7634   case Type::ObjCInterface: {
7635     // Ignore protocol qualifiers when mangling at this level.
7636     // @encode(class_name)
7637     ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
7638     S += '{';
7639     S += OI->getObjCRuntimeNameAsString();
7640     if (Options.ExpandStructures()) {
7641       S += '=';
7642       SmallVector<const ObjCIvarDecl*, 32> Ivars;
7643       DeepCollectObjCIvars(OI, true, Ivars);
7644       for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
7645         const FieldDecl *Field = Ivars[i];
7646         if (Field->isBitField())
7647           getObjCEncodingForTypeImpl(Field->getType(), S,
7648                                      ObjCEncOptions().setExpandStructures(),
7649                                      Field);
7650         else
7651           getObjCEncodingForTypeImpl(Field->getType(), S,
7652                                      ObjCEncOptions().setExpandStructures(), FD,
7653                                      NotEncodedT);
7654       }
7655     }
7656     S += '}';
7657     return;
7658   }
7659 
7660   case Type::ObjCObjectPointer: {
7661     const auto *OPT = T->castAs<ObjCObjectPointerType>();
7662     if (OPT->isObjCIdType()) {
7663       S += '@';
7664       return;
7665     }
7666 
7667     if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
7668       // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
7669       // Since this is a binary compatibility issue, need to consult with
7670       // runtime folks. Fortunately, this is a *very* obscure construct.
7671       S += '#';
7672       return;
7673     }
7674 
7675     if (OPT->isObjCQualifiedIdType()) {
7676       getObjCEncodingForTypeImpl(
7677           getObjCIdType(), S,
7678           Options.keepingOnly(ObjCEncOptions()
7679                                   .setExpandPointedToStructures()
7680                                   .setExpandStructures()),
7681           FD);
7682       if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) {
7683         // Note that we do extended encoding of protocol qualifer list
7684         // Only when doing ivar or property encoding.
7685         S += '"';
7686         for (const auto *I : OPT->quals()) {
7687           S += '<';
7688           S += I->getObjCRuntimeNameAsString();
7689           S += '>';
7690         }
7691         S += '"';
7692       }
7693       return;
7694     }
7695 
7696     S += '@';
7697     if (OPT->getInterfaceDecl() &&
7698         (FD || Options.EncodingProperty() || Options.EncodeClassNames())) {
7699       S += '"';
7700       S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
7701       for (const auto *I : OPT->quals()) {
7702         S += '<';
7703         S += I->getObjCRuntimeNameAsString();
7704         S += '>';
7705       }
7706       S += '"';
7707     }
7708     return;
7709   }
7710 
7711   // gcc just blithely ignores member pointers.
7712   // FIXME: we should do better than that.  'M' is available.
7713   case Type::MemberPointer:
7714   // This matches gcc's encoding, even though technically it is insufficient.
7715   //FIXME. We should do a better job than gcc.
7716   case Type::Vector:
7717   case Type::ExtVector:
7718   // Until we have a coherent encoding of these three types, issue warning.
7719     if (NotEncodedT)
7720       *NotEncodedT = T;
7721     return;
7722 
7723   case Type::ConstantMatrix:
7724     if (NotEncodedT)
7725       *NotEncodedT = T;
7726     return;
7727 
7728   // We could see an undeduced auto type here during error recovery.
7729   // Just ignore it.
7730   case Type::Auto:
7731   case Type::DeducedTemplateSpecialization:
7732     return;
7733 
7734   case Type::Pipe:
7735   case Type::ExtInt:
7736 #define ABSTRACT_TYPE(KIND, BASE)
7737 #define TYPE(KIND, BASE)
7738 #define DEPENDENT_TYPE(KIND, BASE) \
7739   case Type::KIND:
7740 #define NON_CANONICAL_TYPE(KIND, BASE) \
7741   case Type::KIND:
7742 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
7743   case Type::KIND:
7744 #include "clang/AST/TypeNodes.inc"
7745     llvm_unreachable("@encode for dependent type!");
7746   }
7747   llvm_unreachable("bad type kind!");
7748 }
7749 
7750 void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
7751                                                  std::string &S,
7752                                                  const FieldDecl *FD,
7753                                                  bool includeVBases,
7754                                                  QualType *NotEncodedT) const {
7755   assert(RDecl && "Expected non-null RecordDecl");
7756   assert(!RDecl->isUnion() && "Should not be called for unions");
7757   if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
7758     return;
7759 
7760   const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
7761   std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
7762   const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
7763 
7764   if (CXXRec) {
7765     for (const auto &BI : CXXRec->bases()) {
7766       if (!BI.isVirtual()) {
7767         CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
7768         if (base->isEmpty())
7769           continue;
7770         uint64_t offs = toBits(layout.getBaseClassOffset(base));
7771         FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
7772                                   std::make_pair(offs, base));
7773       }
7774     }
7775   }
7776 
7777   unsigned i = 0;
7778   for (FieldDecl *Field : RDecl->fields()) {
7779     if (!Field->isZeroLengthBitField(*this) && Field->isZeroSize(*this))
7780       continue;
7781     uint64_t offs = layout.getFieldOffset(i);
7782     FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
7783                               std::make_pair(offs, Field));
7784     ++i;
7785   }
7786 
7787   if (CXXRec && includeVBases) {
7788     for (const auto &BI : CXXRec->vbases()) {
7789       CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
7790       if (base->isEmpty())
7791         continue;
7792       uint64_t offs = toBits(layout.getVBaseClassOffset(base));
7793       if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
7794           FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
7795         FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
7796                                   std::make_pair(offs, base));
7797     }
7798   }
7799 
7800   CharUnits size;
7801   if (CXXRec) {
7802     size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
7803   } else {
7804     size = layout.getSize();
7805   }
7806 
7807 #ifndef NDEBUG
7808   uint64_t CurOffs = 0;
7809 #endif
7810   std::multimap<uint64_t, NamedDecl *>::iterator
7811     CurLayObj = FieldOrBaseOffsets.begin();
7812 
7813   if (CXXRec && CXXRec->isDynamicClass() &&
7814       (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
7815     if (FD) {
7816       S += "\"_vptr$";
7817       std::string recname = CXXRec->getNameAsString();
7818       if (recname.empty()) recname = "?";
7819       S += recname;
7820       S += '"';
7821     }
7822     S += "^^?";
7823 #ifndef NDEBUG
7824     CurOffs += getTypeSize(VoidPtrTy);
7825 #endif
7826   }
7827 
7828   if (!RDecl->hasFlexibleArrayMember()) {
7829     // Mark the end of the structure.
7830     uint64_t offs = toBits(size);
7831     FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
7832                               std::make_pair(offs, nullptr));
7833   }
7834 
7835   for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
7836 #ifndef NDEBUG
7837     assert(CurOffs <= CurLayObj->first);
7838     if (CurOffs < CurLayObj->first) {
7839       uint64_t padding = CurLayObj->first - CurOffs;
7840       // FIXME: There doesn't seem to be a way to indicate in the encoding that
7841       // packing/alignment of members is different that normal, in which case
7842       // the encoding will be out-of-sync with the real layout.
7843       // If the runtime switches to just consider the size of types without
7844       // taking into account alignment, we could make padding explicit in the
7845       // encoding (e.g. using arrays of chars). The encoding strings would be
7846       // longer then though.
7847       CurOffs += padding;
7848     }
7849 #endif
7850 
7851     NamedDecl *dcl = CurLayObj->second;
7852     if (!dcl)
7853       break; // reached end of structure.
7854 
7855     if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) {
7856       // We expand the bases without their virtual bases since those are going
7857       // in the initial structure. Note that this differs from gcc which
7858       // expands virtual bases each time one is encountered in the hierarchy,
7859       // making the encoding type bigger than it really is.
7860       getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
7861                                       NotEncodedT);
7862       assert(!base->isEmpty());
7863 #ifndef NDEBUG
7864       CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
7865 #endif
7866     } else {
7867       const auto *field = cast<FieldDecl>(dcl);
7868       if (FD) {
7869         S += '"';
7870         S += field->getNameAsString();
7871         S += '"';
7872       }
7873 
7874       if (field->isBitField()) {
7875         EncodeBitField(this, S, field->getType(), field);
7876 #ifndef NDEBUG
7877         CurOffs += field->getBitWidthValue(*this);
7878 #endif
7879       } else {
7880         QualType qt = field->getType();
7881         getLegacyIntegralTypeEncoding(qt);
7882         getObjCEncodingForTypeImpl(
7883             qt, S, ObjCEncOptions().setExpandStructures().setIsStructField(),
7884             FD, NotEncodedT);
7885 #ifndef NDEBUG
7886         CurOffs += getTypeSize(field->getType());
7887 #endif
7888       }
7889     }
7890   }
7891 }
7892 
7893 void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
7894                                                  std::string& S) const {
7895   if (QT & Decl::OBJC_TQ_In)
7896     S += 'n';
7897   if (QT & Decl::OBJC_TQ_Inout)
7898     S += 'N';
7899   if (QT & Decl::OBJC_TQ_Out)
7900     S += 'o';
7901   if (QT & Decl::OBJC_TQ_Bycopy)
7902     S += 'O';
7903   if (QT & Decl::OBJC_TQ_Byref)
7904     S += 'R';
7905   if (QT & Decl::OBJC_TQ_Oneway)
7906     S += 'V';
7907 }
7908 
7909 TypedefDecl *ASTContext::getObjCIdDecl() const {
7910   if (!ObjCIdDecl) {
7911     QualType T = getObjCObjectType(ObjCBuiltinIdTy, {}, {});
7912     T = getObjCObjectPointerType(T);
7913     ObjCIdDecl = buildImplicitTypedef(T, "id");
7914   }
7915   return ObjCIdDecl;
7916 }
7917 
7918 TypedefDecl *ASTContext::getObjCSelDecl() const {
7919   if (!ObjCSelDecl) {
7920     QualType T = getPointerType(ObjCBuiltinSelTy);
7921     ObjCSelDecl = buildImplicitTypedef(T, "SEL");
7922   }
7923   return ObjCSelDecl;
7924 }
7925 
7926 TypedefDecl *ASTContext::getObjCClassDecl() const {
7927   if (!ObjCClassDecl) {
7928     QualType T = getObjCObjectType(ObjCBuiltinClassTy, {}, {});
7929     T = getObjCObjectPointerType(T);
7930     ObjCClassDecl = buildImplicitTypedef(T, "Class");
7931   }
7932   return ObjCClassDecl;
7933 }
7934 
7935 ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
7936   if (!ObjCProtocolClassDecl) {
7937     ObjCProtocolClassDecl
7938       = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
7939                                   SourceLocation(),
7940                                   &Idents.get("Protocol"),
7941                                   /*typeParamList=*/nullptr,
7942                                   /*PrevDecl=*/nullptr,
7943                                   SourceLocation(), true);
7944   }
7945 
7946   return ObjCProtocolClassDecl;
7947 }
7948 
7949 //===----------------------------------------------------------------------===//
7950 // __builtin_va_list Construction Functions
7951 //===----------------------------------------------------------------------===//
7952 
7953 static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
7954                                                  StringRef Name) {
7955   // typedef char* __builtin[_ms]_va_list;
7956   QualType T = Context->getPointerType(Context->CharTy);
7957   return Context->buildImplicitTypedef(T, Name);
7958 }
7959 
7960 static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
7961   return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
7962 }
7963 
7964 static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
7965   return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
7966 }
7967 
7968 static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
7969   // typedef void* __builtin_va_list;
7970   QualType T = Context->getPointerType(Context->VoidTy);
7971   return Context->buildImplicitTypedef(T, "__builtin_va_list");
7972 }
7973 
7974 static TypedefDecl *
7975 CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
7976   // struct __va_list
7977   RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
7978   if (Context->getLangOpts().CPlusPlus) {
7979     // namespace std { struct __va_list {
7980     NamespaceDecl *NS;
7981     NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
7982                                Context->getTranslationUnitDecl(),
7983                                /*Inline*/ false, SourceLocation(),
7984                                SourceLocation(), &Context->Idents.get("std"),
7985                                /*PrevDecl*/ nullptr);
7986     NS->setImplicit();
7987     VaListTagDecl->setDeclContext(NS);
7988   }
7989 
7990   VaListTagDecl->startDefinition();
7991 
7992   const size_t NumFields = 5;
7993   QualType FieldTypes[NumFields];
7994   const char *FieldNames[NumFields];
7995 
7996   // void *__stack;
7997   FieldTypes[0] = Context->getPointerType(Context->VoidTy);
7998   FieldNames[0] = "__stack";
7999 
8000   // void *__gr_top;
8001   FieldTypes[1] = Context->getPointerType(Context->VoidTy);
8002   FieldNames[1] = "__gr_top";
8003 
8004   // void *__vr_top;
8005   FieldTypes[2] = Context->getPointerType(Context->VoidTy);
8006   FieldNames[2] = "__vr_top";
8007 
8008   // int __gr_offs;
8009   FieldTypes[3] = Context->IntTy;
8010   FieldNames[3] = "__gr_offs";
8011 
8012   // int __vr_offs;
8013   FieldTypes[4] = Context->IntTy;
8014   FieldNames[4] = "__vr_offs";
8015 
8016   // Create fields
8017   for (unsigned i = 0; i < NumFields; ++i) {
8018     FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
8019                                          VaListTagDecl,
8020                                          SourceLocation(),
8021                                          SourceLocation(),
8022                                          &Context->Idents.get(FieldNames[i]),
8023                                          FieldTypes[i], /*TInfo=*/nullptr,
8024                                          /*BitWidth=*/nullptr,
8025                                          /*Mutable=*/false,
8026                                          ICIS_NoInit);
8027     Field->setAccess(AS_public);
8028     VaListTagDecl->addDecl(Field);
8029   }
8030   VaListTagDecl->completeDefinition();
8031   Context->VaListTagDecl = VaListTagDecl;
8032   QualType VaListTagType = Context->getRecordType(VaListTagDecl);
8033 
8034   // } __builtin_va_list;
8035   return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
8036 }
8037 
8038 static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
8039   // typedef struct __va_list_tag {
8040   RecordDecl *VaListTagDecl;
8041 
8042   VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
8043   VaListTagDecl->startDefinition();
8044 
8045   const size_t NumFields = 5;
8046   QualType FieldTypes[NumFields];
8047   const char *FieldNames[NumFields];
8048 
8049   //   unsigned char gpr;
8050   FieldTypes[0] = Context->UnsignedCharTy;
8051   FieldNames[0] = "gpr";
8052 
8053   //   unsigned char fpr;
8054   FieldTypes[1] = Context->UnsignedCharTy;
8055   FieldNames[1] = "fpr";
8056 
8057   //   unsigned short reserved;
8058   FieldTypes[2] = Context->UnsignedShortTy;
8059   FieldNames[2] = "reserved";
8060 
8061   //   void* overflow_arg_area;
8062   FieldTypes[3] = Context->getPointerType(Context->VoidTy);
8063   FieldNames[3] = "overflow_arg_area";
8064 
8065   //   void* reg_save_area;
8066   FieldTypes[4] = Context->getPointerType(Context->VoidTy);
8067   FieldNames[4] = "reg_save_area";
8068 
8069   // Create fields
8070   for (unsigned i = 0; i < NumFields; ++i) {
8071     FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
8072                                          SourceLocation(),
8073                                          SourceLocation(),
8074                                          &Context->Idents.get(FieldNames[i]),
8075                                          FieldTypes[i], /*TInfo=*/nullptr,
8076                                          /*BitWidth=*/nullptr,
8077                                          /*Mutable=*/false,
8078                                          ICIS_NoInit);
8079     Field->setAccess(AS_public);
8080     VaListTagDecl->addDecl(Field);
8081   }
8082   VaListTagDecl->completeDefinition();
8083   Context->VaListTagDecl = VaListTagDecl;
8084   QualType VaListTagType = Context->getRecordType(VaListTagDecl);
8085 
8086   // } __va_list_tag;
8087   TypedefDecl *VaListTagTypedefDecl =
8088       Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
8089 
8090   QualType VaListTagTypedefType =
8091     Context->getTypedefType(VaListTagTypedefDecl);
8092 
8093   // typedef __va_list_tag __builtin_va_list[1];
8094   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
8095   QualType VaListTagArrayType
8096     = Context->getConstantArrayType(VaListTagTypedefType,
8097                                     Size, nullptr, ArrayType::Normal, 0);
8098   return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
8099 }
8100 
8101 static TypedefDecl *
8102 CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
8103   // struct __va_list_tag {
8104   RecordDecl *VaListTagDecl;
8105   VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
8106   VaListTagDecl->startDefinition();
8107 
8108   const size_t NumFields = 4;
8109   QualType FieldTypes[NumFields];
8110   const char *FieldNames[NumFields];
8111 
8112   //   unsigned gp_offset;
8113   FieldTypes[0] = Context->UnsignedIntTy;
8114   FieldNames[0] = "gp_offset";
8115 
8116   //   unsigned fp_offset;
8117   FieldTypes[1] = Context->UnsignedIntTy;
8118   FieldNames[1] = "fp_offset";
8119 
8120   //   void* overflow_arg_area;
8121   FieldTypes[2] = Context->getPointerType(Context->VoidTy);
8122   FieldNames[2] = "overflow_arg_area";
8123 
8124   //   void* reg_save_area;
8125   FieldTypes[3] = Context->getPointerType(Context->VoidTy);
8126   FieldNames[3] = "reg_save_area";
8127 
8128   // Create fields
8129   for (unsigned i = 0; i < NumFields; ++i) {
8130     FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
8131                                          VaListTagDecl,
8132                                          SourceLocation(),
8133                                          SourceLocation(),
8134                                          &Context->Idents.get(FieldNames[i]),
8135                                          FieldTypes[i], /*TInfo=*/nullptr,
8136                                          /*BitWidth=*/nullptr,
8137                                          /*Mutable=*/false,
8138                                          ICIS_NoInit);
8139     Field->setAccess(AS_public);
8140     VaListTagDecl->addDecl(Field);
8141   }
8142   VaListTagDecl->completeDefinition();
8143   Context->VaListTagDecl = VaListTagDecl;
8144   QualType VaListTagType = Context->getRecordType(VaListTagDecl);
8145 
8146   // };
8147 
8148   // typedef struct __va_list_tag __builtin_va_list[1];
8149   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
8150   QualType VaListTagArrayType = Context->getConstantArrayType(
8151       VaListTagType, Size, nullptr, ArrayType::Normal, 0);
8152   return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
8153 }
8154 
8155 static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
8156   // typedef int __builtin_va_list[4];
8157   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
8158   QualType IntArrayType = Context->getConstantArrayType(
8159       Context->IntTy, Size, nullptr, ArrayType::Normal, 0);
8160   return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
8161 }
8162 
8163 static TypedefDecl *
8164 CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
8165   // struct __va_list
8166   RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
8167   if (Context->getLangOpts().CPlusPlus) {
8168     // namespace std { struct __va_list {
8169     NamespaceDecl *NS;
8170     NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
8171                                Context->getTranslationUnitDecl(),
8172                                /*Inline*/false, SourceLocation(),
8173                                SourceLocation(), &Context->Idents.get("std"),
8174                                /*PrevDecl*/ nullptr);
8175     NS->setImplicit();
8176     VaListDecl->setDeclContext(NS);
8177   }
8178 
8179   VaListDecl->startDefinition();
8180 
8181   // void * __ap;
8182   FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
8183                                        VaListDecl,
8184                                        SourceLocation(),
8185                                        SourceLocation(),
8186                                        &Context->Idents.get("__ap"),
8187                                        Context->getPointerType(Context->VoidTy),
8188                                        /*TInfo=*/nullptr,
8189                                        /*BitWidth=*/nullptr,
8190                                        /*Mutable=*/false,
8191                                        ICIS_NoInit);
8192   Field->setAccess(AS_public);
8193   VaListDecl->addDecl(Field);
8194 
8195   // };
8196   VaListDecl->completeDefinition();
8197   Context->VaListTagDecl = VaListDecl;
8198 
8199   // typedef struct __va_list __builtin_va_list;
8200   QualType T = Context->getRecordType(VaListDecl);
8201   return Context->buildImplicitTypedef(T, "__builtin_va_list");
8202 }
8203 
8204 static TypedefDecl *
8205 CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
8206   // struct __va_list_tag {
8207   RecordDecl *VaListTagDecl;
8208   VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
8209   VaListTagDecl->startDefinition();
8210 
8211   const size_t NumFields = 4;
8212   QualType FieldTypes[NumFields];
8213   const char *FieldNames[NumFields];
8214 
8215   //   long __gpr;
8216   FieldTypes[0] = Context->LongTy;
8217   FieldNames[0] = "__gpr";
8218 
8219   //   long __fpr;
8220   FieldTypes[1] = Context->LongTy;
8221   FieldNames[1] = "__fpr";
8222 
8223   //   void *__overflow_arg_area;
8224   FieldTypes[2] = Context->getPointerType(Context->VoidTy);
8225   FieldNames[2] = "__overflow_arg_area";
8226 
8227   //   void *__reg_save_area;
8228   FieldTypes[3] = Context->getPointerType(Context->VoidTy);
8229   FieldNames[3] = "__reg_save_area";
8230 
8231   // Create fields
8232   for (unsigned i = 0; i < NumFields; ++i) {
8233     FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
8234                                          VaListTagDecl,
8235                                          SourceLocation(),
8236                                          SourceLocation(),
8237                                          &Context->Idents.get(FieldNames[i]),
8238                                          FieldTypes[i], /*TInfo=*/nullptr,
8239                                          /*BitWidth=*/nullptr,
8240                                          /*Mutable=*/false,
8241                                          ICIS_NoInit);
8242     Field->setAccess(AS_public);
8243     VaListTagDecl->addDecl(Field);
8244   }
8245   VaListTagDecl->completeDefinition();
8246   Context->VaListTagDecl = VaListTagDecl;
8247   QualType VaListTagType = Context->getRecordType(VaListTagDecl);
8248 
8249   // };
8250 
8251   // typedef __va_list_tag __builtin_va_list[1];
8252   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
8253   QualType VaListTagArrayType = Context->getConstantArrayType(
8254       VaListTagType, Size, nullptr, ArrayType::Normal, 0);
8255 
8256   return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
8257 }
8258 
8259 static TypedefDecl *CreateHexagonBuiltinVaListDecl(const ASTContext *Context) {
8260   // typedef struct __va_list_tag {
8261   RecordDecl *VaListTagDecl;
8262   VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
8263   VaListTagDecl->startDefinition();
8264 
8265   const size_t NumFields = 3;
8266   QualType FieldTypes[NumFields];
8267   const char *FieldNames[NumFields];
8268 
8269   //   void *CurrentSavedRegisterArea;
8270   FieldTypes[0] = Context->getPointerType(Context->VoidTy);
8271   FieldNames[0] = "__current_saved_reg_area_pointer";
8272 
8273   //   void *SavedRegAreaEnd;
8274   FieldTypes[1] = Context->getPointerType(Context->VoidTy);
8275   FieldNames[1] = "__saved_reg_area_end_pointer";
8276 
8277   //   void *OverflowArea;
8278   FieldTypes[2] = Context->getPointerType(Context->VoidTy);
8279   FieldNames[2] = "__overflow_area_pointer";
8280 
8281   // Create fields
8282   for (unsigned i = 0; i < NumFields; ++i) {
8283     FieldDecl *Field = FieldDecl::Create(
8284         const_cast<ASTContext &>(*Context), VaListTagDecl, SourceLocation(),
8285         SourceLocation(), &Context->Idents.get(FieldNames[i]), FieldTypes[i],
8286         /*TInfo=*/0,
8287         /*BitWidth=*/0,
8288         /*Mutable=*/false, ICIS_NoInit);
8289     Field->setAccess(AS_public);
8290     VaListTagDecl->addDecl(Field);
8291   }
8292   VaListTagDecl->completeDefinition();
8293   Context->VaListTagDecl = VaListTagDecl;
8294   QualType VaListTagType = Context->getRecordType(VaListTagDecl);
8295 
8296   // } __va_list_tag;
8297   TypedefDecl *VaListTagTypedefDecl =
8298       Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
8299 
8300   QualType VaListTagTypedefType = Context->getTypedefType(VaListTagTypedefDecl);
8301 
8302   // typedef __va_list_tag __builtin_va_list[1];
8303   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
8304   QualType VaListTagArrayType = Context->getConstantArrayType(
8305       VaListTagTypedefType, Size, nullptr, ArrayType::Normal, 0);
8306 
8307   return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
8308 }
8309 
8310 static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
8311                                      TargetInfo::BuiltinVaListKind Kind) {
8312   switch (Kind) {
8313   case TargetInfo::CharPtrBuiltinVaList:
8314     return CreateCharPtrBuiltinVaListDecl(Context);
8315   case TargetInfo::VoidPtrBuiltinVaList:
8316     return CreateVoidPtrBuiltinVaListDecl(Context);
8317   case TargetInfo::AArch64ABIBuiltinVaList:
8318     return CreateAArch64ABIBuiltinVaListDecl(Context);
8319   case TargetInfo::PowerABIBuiltinVaList:
8320     return CreatePowerABIBuiltinVaListDecl(Context);
8321   case TargetInfo::X86_64ABIBuiltinVaList:
8322     return CreateX86_64ABIBuiltinVaListDecl(Context);
8323   case TargetInfo::PNaClABIBuiltinVaList:
8324     return CreatePNaClABIBuiltinVaListDecl(Context);
8325   case TargetInfo::AAPCSABIBuiltinVaList:
8326     return CreateAAPCSABIBuiltinVaListDecl(Context);
8327   case TargetInfo::SystemZBuiltinVaList:
8328     return CreateSystemZBuiltinVaListDecl(Context);
8329   case TargetInfo::HexagonBuiltinVaList:
8330     return CreateHexagonBuiltinVaListDecl(Context);
8331   }
8332 
8333   llvm_unreachable("Unhandled __builtin_va_list type kind");
8334 }
8335 
8336 TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
8337   if (!BuiltinVaListDecl) {
8338     BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
8339     assert(BuiltinVaListDecl->isImplicit());
8340   }
8341 
8342   return BuiltinVaListDecl;
8343 }
8344 
8345 Decl *ASTContext::getVaListTagDecl() const {
8346   // Force the creation of VaListTagDecl by building the __builtin_va_list
8347   // declaration.
8348   if (!VaListTagDecl)
8349     (void)getBuiltinVaListDecl();
8350 
8351   return VaListTagDecl;
8352 }
8353 
8354 TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
8355   if (!BuiltinMSVaListDecl)
8356     BuiltinMSVaListDecl = CreateMSVaListDecl(this);
8357 
8358   return BuiltinMSVaListDecl;
8359 }
8360 
8361 bool ASTContext::canBuiltinBeRedeclared(const FunctionDecl *FD) const {
8362   return BuiltinInfo.canBeRedeclared(FD->getBuiltinID());
8363 }
8364 
8365 void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
8366   assert(ObjCConstantStringType.isNull() &&
8367          "'NSConstantString' type already set!");
8368 
8369   ObjCConstantStringType = getObjCInterfaceType(Decl);
8370 }
8371 
8372 /// Retrieve the template name that corresponds to a non-empty
8373 /// lookup.
8374 TemplateName
8375 ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
8376                                       UnresolvedSetIterator End) const {
8377   unsigned size = End - Begin;
8378   assert(size > 1 && "set is not overloaded!");
8379 
8380   void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
8381                           size * sizeof(FunctionTemplateDecl*));
8382   auto *OT = new (memory) OverloadedTemplateStorage(size);
8383 
8384   NamedDecl **Storage = OT->getStorage();
8385   for (UnresolvedSetIterator I = Begin; I != End; ++I) {
8386     NamedDecl *D = *I;
8387     assert(isa<FunctionTemplateDecl>(D) ||
8388            isa<UnresolvedUsingValueDecl>(D) ||
8389            (isa<UsingShadowDecl>(D) &&
8390             isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
8391     *Storage++ = D;
8392   }
8393 
8394   return TemplateName(OT);
8395 }
8396 
8397 /// Retrieve a template name representing an unqualified-id that has been
8398 /// assumed to name a template for ADL purposes.
8399 TemplateName ASTContext::getAssumedTemplateName(DeclarationName Name) const {
8400   auto *OT = new (*this) AssumedTemplateStorage(Name);
8401   return TemplateName(OT);
8402 }
8403 
8404 /// Retrieve the template name that represents a qualified
8405 /// template name such as \c std::vector.
8406 TemplateName
8407 ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
8408                                      bool TemplateKeyword,
8409                                      TemplateDecl *Template) const {
8410   assert(NNS && "Missing nested-name-specifier in qualified template name");
8411 
8412   // FIXME: Canonicalization?
8413   llvm::FoldingSetNodeID ID;
8414   QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
8415 
8416   void *InsertPos = nullptr;
8417   QualifiedTemplateName *QTN =
8418     QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
8419   if (!QTN) {
8420     QTN = new (*this, alignof(QualifiedTemplateName))
8421         QualifiedTemplateName(NNS, TemplateKeyword, Template);
8422     QualifiedTemplateNames.InsertNode(QTN, InsertPos);
8423   }
8424 
8425   return TemplateName(QTN);
8426 }
8427 
8428 /// Retrieve the template name that represents a dependent
8429 /// template name such as \c MetaFun::template apply.
8430 TemplateName
8431 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
8432                                      const IdentifierInfo *Name) const {
8433   assert((!NNS || NNS->isDependent()) &&
8434          "Nested name specifier must be dependent");
8435 
8436   llvm::FoldingSetNodeID ID;
8437   DependentTemplateName::Profile(ID, NNS, Name);
8438 
8439   void *InsertPos = nullptr;
8440   DependentTemplateName *QTN =
8441     DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
8442 
8443   if (QTN)
8444     return TemplateName(QTN);
8445 
8446   NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
8447   if (CanonNNS == NNS) {
8448     QTN = new (*this, alignof(DependentTemplateName))
8449         DependentTemplateName(NNS, Name);
8450   } else {
8451     TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
8452     QTN = new (*this, alignof(DependentTemplateName))
8453         DependentTemplateName(NNS, Name, Canon);
8454     DependentTemplateName *CheckQTN =
8455       DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
8456     assert(!CheckQTN && "Dependent type name canonicalization broken");
8457     (void)CheckQTN;
8458   }
8459 
8460   DependentTemplateNames.InsertNode(QTN, InsertPos);
8461   return TemplateName(QTN);
8462 }
8463 
8464 /// Retrieve the template name that represents a dependent
8465 /// template name such as \c MetaFun::template operator+.
8466 TemplateName
8467 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
8468                                      OverloadedOperatorKind Operator) const {
8469   assert((!NNS || NNS->isDependent()) &&
8470          "Nested name specifier must be dependent");
8471 
8472   llvm::FoldingSetNodeID ID;
8473   DependentTemplateName::Profile(ID, NNS, Operator);
8474 
8475   void *InsertPos = nullptr;
8476   DependentTemplateName *QTN
8477     = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
8478 
8479   if (QTN)
8480     return TemplateName(QTN);
8481 
8482   NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
8483   if (CanonNNS == NNS) {
8484     QTN = new (*this, alignof(DependentTemplateName))
8485         DependentTemplateName(NNS, Operator);
8486   } else {
8487     TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
8488     QTN = new (*this, alignof(DependentTemplateName))
8489         DependentTemplateName(NNS, Operator, Canon);
8490 
8491     DependentTemplateName *CheckQTN
8492       = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
8493     assert(!CheckQTN && "Dependent template name canonicalization broken");
8494     (void)CheckQTN;
8495   }
8496 
8497   DependentTemplateNames.InsertNode(QTN, InsertPos);
8498   return TemplateName(QTN);
8499 }
8500 
8501 TemplateName
8502 ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
8503                                          TemplateName replacement) const {
8504   llvm::FoldingSetNodeID ID;
8505   SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
8506 
8507   void *insertPos = nullptr;
8508   SubstTemplateTemplateParmStorage *subst
8509     = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
8510 
8511   if (!subst) {
8512     subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
8513     SubstTemplateTemplateParms.InsertNode(subst, insertPos);
8514   }
8515 
8516   return TemplateName(subst);
8517 }
8518 
8519 TemplateName
8520 ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
8521                                        const TemplateArgument &ArgPack) const {
8522   auto &Self = const_cast<ASTContext &>(*this);
8523   llvm::FoldingSetNodeID ID;
8524   SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
8525 
8526   void *InsertPos = nullptr;
8527   SubstTemplateTemplateParmPackStorage *Subst
8528     = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
8529 
8530   if (!Subst) {
8531     Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
8532                                                            ArgPack.pack_size(),
8533                                                          ArgPack.pack_begin());
8534     SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
8535   }
8536 
8537   return TemplateName(Subst);
8538 }
8539 
8540 /// getFromTargetType - Given one of the integer types provided by
8541 /// TargetInfo, produce the corresponding type. The unsigned @p Type
8542 /// is actually a value of type @c TargetInfo::IntType.
8543 CanQualType ASTContext::getFromTargetType(unsigned Type) const {
8544   switch (Type) {
8545   case TargetInfo::NoInt: return {};
8546   case TargetInfo::SignedChar: return SignedCharTy;
8547   case TargetInfo::UnsignedChar: return UnsignedCharTy;
8548   case TargetInfo::SignedShort: return ShortTy;
8549   case TargetInfo::UnsignedShort: return UnsignedShortTy;
8550   case TargetInfo::SignedInt: return IntTy;
8551   case TargetInfo::UnsignedInt: return UnsignedIntTy;
8552   case TargetInfo::SignedLong: return LongTy;
8553   case TargetInfo::UnsignedLong: return UnsignedLongTy;
8554   case TargetInfo::SignedLongLong: return LongLongTy;
8555   case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
8556   }
8557 
8558   llvm_unreachable("Unhandled TargetInfo::IntType value");
8559 }
8560 
8561 //===----------------------------------------------------------------------===//
8562 //                        Type Predicates.
8563 //===----------------------------------------------------------------------===//
8564 
8565 /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
8566 /// garbage collection attribute.
8567 ///
8568 Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
8569   if (getLangOpts().getGC() == LangOptions::NonGC)
8570     return Qualifiers::GCNone;
8571 
8572   assert(getLangOpts().ObjC);
8573   Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
8574 
8575   // Default behaviour under objective-C's gc is for ObjC pointers
8576   // (or pointers to them) be treated as though they were declared
8577   // as __strong.
8578   if (GCAttrs == Qualifiers::GCNone) {
8579     if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
8580       return Qualifiers::Strong;
8581     else if (Ty->isPointerType())
8582       return getObjCGCAttrKind(Ty->castAs<PointerType>()->getPointeeType());
8583   } else {
8584     // It's not valid to set GC attributes on anything that isn't a
8585     // pointer.
8586 #ifndef NDEBUG
8587     QualType CT = Ty->getCanonicalTypeInternal();
8588     while (const auto *AT = dyn_cast<ArrayType>(CT))
8589       CT = AT->getElementType();
8590     assert(CT->isAnyPointerType() || CT->isBlockPointerType());
8591 #endif
8592   }
8593   return GCAttrs;
8594 }
8595 
8596 //===----------------------------------------------------------------------===//
8597 //                        Type Compatibility Testing
8598 //===----------------------------------------------------------------------===//
8599 
8600 /// areCompatVectorTypes - Return true if the two specified vector types are
8601 /// compatible.
8602 static bool areCompatVectorTypes(const VectorType *LHS,
8603                                  const VectorType *RHS) {
8604   assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
8605   return LHS->getElementType() == RHS->getElementType() &&
8606          LHS->getNumElements() == RHS->getNumElements();
8607 }
8608 
8609 /// areCompatMatrixTypes - Return true if the two specified matrix types are
8610 /// compatible.
8611 static bool areCompatMatrixTypes(const ConstantMatrixType *LHS,
8612                                  const ConstantMatrixType *RHS) {
8613   assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
8614   return LHS->getElementType() == RHS->getElementType() &&
8615          LHS->getNumRows() == RHS->getNumRows() &&
8616          LHS->getNumColumns() == RHS->getNumColumns();
8617 }
8618 
8619 bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
8620                                           QualType SecondVec) {
8621   assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
8622   assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
8623 
8624   if (hasSameUnqualifiedType(FirstVec, SecondVec))
8625     return true;
8626 
8627   // Treat Neon vector types and most AltiVec vector types as if they are the
8628   // equivalent GCC vector types.
8629   const auto *First = FirstVec->castAs<VectorType>();
8630   const auto *Second = SecondVec->castAs<VectorType>();
8631   if (First->getNumElements() == Second->getNumElements() &&
8632       hasSameType(First->getElementType(), Second->getElementType()) &&
8633       First->getVectorKind() != VectorType::AltiVecPixel &&
8634       First->getVectorKind() != VectorType::AltiVecBool &&
8635       Second->getVectorKind() != VectorType::AltiVecPixel &&
8636       Second->getVectorKind() != VectorType::AltiVecBool &&
8637       First->getVectorKind() != VectorType::SveFixedLengthDataVector &&
8638       First->getVectorKind() != VectorType::SveFixedLengthPredicateVector &&
8639       Second->getVectorKind() != VectorType::SveFixedLengthDataVector &&
8640       Second->getVectorKind() != VectorType::SveFixedLengthPredicateVector)
8641     return true;
8642 
8643   return false;
8644 }
8645 
8646 bool ASTContext::areCompatibleSveTypes(QualType FirstType,
8647                                        QualType SecondType) {
8648   assert(((FirstType->isSizelessBuiltinType() && SecondType->isVectorType()) ||
8649           (FirstType->isVectorType() && SecondType->isSizelessBuiltinType())) &&
8650          "Expected SVE builtin type and vector type!");
8651 
8652   auto IsValidCast = [this](QualType FirstType, QualType SecondType) {
8653     if (const auto *BT = FirstType->getAs<BuiltinType>()) {
8654       if (const auto *VT = SecondType->getAs<VectorType>()) {
8655         // Predicates have the same representation as uint8 so we also have to
8656         // check the kind to make these types incompatible.
8657         if (VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector)
8658           return BT->getKind() == BuiltinType::SveBool;
8659         else if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector)
8660           return VT->getElementType().getCanonicalType() ==
8661                  FirstType->getSveEltType(*this);
8662         else if (VT->getVectorKind() == VectorType::GenericVector)
8663           return getTypeSize(SecondType) == getLangOpts().ArmSveVectorBits &&
8664                  hasSameType(VT->getElementType(),
8665                              getBuiltinVectorTypeInfo(BT).ElementType);
8666       }
8667     }
8668     return false;
8669   };
8670 
8671   return IsValidCast(FirstType, SecondType) ||
8672          IsValidCast(SecondType, FirstType);
8673 }
8674 
8675 bool ASTContext::areLaxCompatibleSveTypes(QualType FirstType,
8676                                           QualType SecondType) {
8677   assert(((FirstType->isSizelessBuiltinType() && SecondType->isVectorType()) ||
8678           (FirstType->isVectorType() && SecondType->isSizelessBuiltinType())) &&
8679          "Expected SVE builtin type and vector type!");
8680 
8681   auto IsLaxCompatible = [this](QualType FirstType, QualType SecondType) {
8682     if (!FirstType->getAs<BuiltinType>())
8683       return false;
8684 
8685     const auto *VecTy = SecondType->getAs<VectorType>();
8686     if (VecTy &&
8687         (VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector ||
8688          VecTy->getVectorKind() == VectorType::GenericVector)) {
8689       const LangOptions::LaxVectorConversionKind LVCKind =
8690           getLangOpts().getLaxVectorConversions();
8691 
8692       // If __ARM_FEATURE_SVE_BITS != N do not allow GNU vector lax conversion.
8693       // "Whenever __ARM_FEATURE_SVE_BITS==N, GNUT implicitly
8694       // converts to VLAT and VLAT implicitly converts to GNUT."
8695       // ACLE Spec Version 00bet6, 3.7.3.2. Behavior common to vectors and
8696       // predicates.
8697       if (VecTy->getVectorKind() == VectorType::GenericVector &&
8698           getTypeSize(SecondType) != getLangOpts().ArmSveVectorBits)
8699         return false;
8700 
8701       // If -flax-vector-conversions=all is specified, the types are
8702       // certainly compatible.
8703       if (LVCKind == LangOptions::LaxVectorConversionKind::All)
8704         return true;
8705 
8706       // If -flax-vector-conversions=integer is specified, the types are
8707       // compatible if the elements are integer types.
8708       if (LVCKind == LangOptions::LaxVectorConversionKind::Integer)
8709         return VecTy->getElementType().getCanonicalType()->isIntegerType() &&
8710                FirstType->getSveEltType(*this)->isIntegerType();
8711     }
8712 
8713     return false;
8714   };
8715 
8716   return IsLaxCompatible(FirstType, SecondType) ||
8717          IsLaxCompatible(SecondType, FirstType);
8718 }
8719 
8720 bool ASTContext::hasDirectOwnershipQualifier(QualType Ty) const {
8721   while (true) {
8722     // __strong id
8723     if (const AttributedType *Attr = dyn_cast<AttributedType>(Ty)) {
8724       if (Attr->getAttrKind() == attr::ObjCOwnership)
8725         return true;
8726 
8727       Ty = Attr->getModifiedType();
8728 
8729     // X *__strong (...)
8730     } else if (const ParenType *Paren = dyn_cast<ParenType>(Ty)) {
8731       Ty = Paren->getInnerType();
8732 
8733     // We do not want to look through typedefs, typeof(expr),
8734     // typeof(type), or any other way that the type is somehow
8735     // abstracted.
8736     } else {
8737       return false;
8738     }
8739   }
8740 }
8741 
8742 //===----------------------------------------------------------------------===//
8743 // ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
8744 //===----------------------------------------------------------------------===//
8745 
8746 /// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
8747 /// inheritance hierarchy of 'rProto'.
8748 bool
8749 ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
8750                                            ObjCProtocolDecl *rProto) const {
8751   if (declaresSameEntity(lProto, rProto))
8752     return true;
8753   for (auto *PI : rProto->protocols())
8754     if (ProtocolCompatibleWithProtocol(lProto, PI))
8755       return true;
8756   return false;
8757 }
8758 
8759 /// ObjCQualifiedClassTypesAreCompatible - compare  Class<pr,...> and
8760 /// Class<pr1, ...>.
8761 bool ASTContext::ObjCQualifiedClassTypesAreCompatible(
8762     const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs) {
8763   for (auto *lhsProto : lhs->quals()) {
8764     bool match = false;
8765     for (auto *rhsProto : rhs->quals()) {
8766       if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
8767         match = true;
8768         break;
8769       }
8770     }
8771     if (!match)
8772       return false;
8773   }
8774   return true;
8775 }
8776 
8777 /// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
8778 /// ObjCQualifiedIDType.
8779 bool ASTContext::ObjCQualifiedIdTypesAreCompatible(
8780     const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs,
8781     bool compare) {
8782   // Allow id<P..> and an 'id' in all cases.
8783   if (lhs->isObjCIdType() || rhs->isObjCIdType())
8784     return true;
8785 
8786   // Don't allow id<P..> to convert to Class or Class<P..> in either direction.
8787   if (lhs->isObjCClassType() || lhs->isObjCQualifiedClassType() ||
8788       rhs->isObjCClassType() || rhs->isObjCQualifiedClassType())
8789     return false;
8790 
8791   if (lhs->isObjCQualifiedIdType()) {
8792     if (rhs->qual_empty()) {
8793       // If the RHS is a unqualified interface pointer "NSString*",
8794       // make sure we check the class hierarchy.
8795       if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
8796         for (auto *I : lhs->quals()) {
8797           // when comparing an id<P> on lhs with a static type on rhs,
8798           // see if static class implements all of id's protocols, directly or
8799           // through its super class and categories.
8800           if (!rhsID->ClassImplementsProtocol(I, true))
8801             return false;
8802         }
8803       }
8804       // If there are no qualifiers and no interface, we have an 'id'.
8805       return true;
8806     }
8807     // Both the right and left sides have qualifiers.
8808     for (auto *lhsProto : lhs->quals()) {
8809       bool match = false;
8810 
8811       // when comparing an id<P> on lhs with a static type on rhs,
8812       // see if static class implements all of id's protocols, directly or
8813       // through its super class and categories.
8814       for (auto *rhsProto : rhs->quals()) {
8815         if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
8816             (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
8817           match = true;
8818           break;
8819         }
8820       }
8821       // If the RHS is a qualified interface pointer "NSString<P>*",
8822       // make sure we check the class hierarchy.
8823       if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
8824         for (auto *I : lhs->quals()) {
8825           // when comparing an id<P> on lhs with a static type on rhs,
8826           // see if static class implements all of id's protocols, directly or
8827           // through its super class and categories.
8828           if (rhsID->ClassImplementsProtocol(I, true)) {
8829             match = true;
8830             break;
8831           }
8832         }
8833       }
8834       if (!match)
8835         return false;
8836     }
8837 
8838     return true;
8839   }
8840 
8841   assert(rhs->isObjCQualifiedIdType() && "One of the LHS/RHS should be id<x>");
8842 
8843   if (lhs->getInterfaceType()) {
8844     // If both the right and left sides have qualifiers.
8845     for (auto *lhsProto : lhs->quals()) {
8846       bool match = false;
8847 
8848       // when comparing an id<P> on rhs with a static type on lhs,
8849       // see if static class implements all of id's protocols, directly or
8850       // through its super class and categories.
8851       // First, lhs protocols in the qualifier list must be found, direct
8852       // or indirect in rhs's qualifier list or it is a mismatch.
8853       for (auto *rhsProto : rhs->quals()) {
8854         if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
8855             (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
8856           match = true;
8857           break;
8858         }
8859       }
8860       if (!match)
8861         return false;
8862     }
8863 
8864     // Static class's protocols, or its super class or category protocols
8865     // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
8866     if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) {
8867       llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
8868       CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
8869       // This is rather dubious but matches gcc's behavior. If lhs has
8870       // no type qualifier and its class has no static protocol(s)
8871       // assume that it is mismatch.
8872       if (LHSInheritedProtocols.empty() && lhs->qual_empty())
8873         return false;
8874       for (auto *lhsProto : LHSInheritedProtocols) {
8875         bool match = false;
8876         for (auto *rhsProto : rhs->quals()) {
8877           if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
8878               (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
8879             match = true;
8880             break;
8881           }
8882         }
8883         if (!match)
8884           return false;
8885       }
8886     }
8887     return true;
8888   }
8889   return false;
8890 }
8891 
8892 /// canAssignObjCInterfaces - Return true if the two interface types are
8893 /// compatible for assignment from RHS to LHS.  This handles validation of any
8894 /// protocol qualifiers on the LHS or RHS.
8895 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
8896                                          const ObjCObjectPointerType *RHSOPT) {
8897   const ObjCObjectType* LHS = LHSOPT->getObjectType();
8898   const ObjCObjectType* RHS = RHSOPT->getObjectType();
8899 
8900   // If either type represents the built-in 'id' type, return true.
8901   if (LHS->isObjCUnqualifiedId() || RHS->isObjCUnqualifiedId())
8902     return true;
8903 
8904   // Function object that propagates a successful result or handles
8905   // __kindof types.
8906   auto finish = [&](bool succeeded) -> bool {
8907     if (succeeded)
8908       return true;
8909 
8910     if (!RHS->isKindOfType())
8911       return false;
8912 
8913     // Strip off __kindof and protocol qualifiers, then check whether
8914     // we can assign the other way.
8915     return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
8916                                    LHSOPT->stripObjCKindOfTypeAndQuals(*this));
8917   };
8918 
8919   // Casts from or to id<P> are allowed when the other side has compatible
8920   // protocols.
8921   if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
8922     return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false));
8923   }
8924 
8925   // Verify protocol compatibility for casts from Class<P1> to Class<P2>.
8926   if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
8927     return finish(ObjCQualifiedClassTypesAreCompatible(LHSOPT, RHSOPT));
8928   }
8929 
8930   // Casts from Class to Class<Foo>, or vice-versa, are allowed.
8931   if (LHS->isObjCClass() && RHS->isObjCClass()) {
8932     return true;
8933   }
8934 
8935   // If we have 2 user-defined types, fall into that path.
8936   if (LHS->getInterface() && RHS->getInterface()) {
8937     return finish(canAssignObjCInterfaces(LHS, RHS));
8938   }
8939 
8940   return false;
8941 }
8942 
8943 /// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
8944 /// for providing type-safety for objective-c pointers used to pass/return
8945 /// arguments in block literals. When passed as arguments, passing 'A*' where
8946 /// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
8947 /// not OK. For the return type, the opposite is not OK.
8948 bool ASTContext::canAssignObjCInterfacesInBlockPointer(
8949                                          const ObjCObjectPointerType *LHSOPT,
8950                                          const ObjCObjectPointerType *RHSOPT,
8951                                          bool BlockReturnType) {
8952 
8953   // Function object that propagates a successful result or handles
8954   // __kindof types.
8955   auto finish = [&](bool succeeded) -> bool {
8956     if (succeeded)
8957       return true;
8958 
8959     const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
8960     if (!Expected->isKindOfType())
8961       return false;
8962 
8963     // Strip off __kindof and protocol qualifiers, then check whether
8964     // we can assign the other way.
8965     return canAssignObjCInterfacesInBlockPointer(
8966              RHSOPT->stripObjCKindOfTypeAndQuals(*this),
8967              LHSOPT->stripObjCKindOfTypeAndQuals(*this),
8968              BlockReturnType);
8969   };
8970 
8971   if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
8972     return true;
8973 
8974   if (LHSOPT->isObjCBuiltinType()) {
8975     return finish(RHSOPT->isObjCBuiltinType() ||
8976                   RHSOPT->isObjCQualifiedIdType());
8977   }
8978 
8979   if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) {
8980     if (getLangOpts().CompatibilityQualifiedIdBlockParamTypeChecking)
8981       // Use for block parameters previous type checking for compatibility.
8982       return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false) ||
8983                     // Or corrected type checking as in non-compat mode.
8984                     (!BlockReturnType &&
8985                      ObjCQualifiedIdTypesAreCompatible(RHSOPT, LHSOPT, false)));
8986     else
8987       return finish(ObjCQualifiedIdTypesAreCompatible(
8988           (BlockReturnType ? LHSOPT : RHSOPT),
8989           (BlockReturnType ? RHSOPT : LHSOPT), false));
8990   }
8991 
8992   const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
8993   const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
8994   if (LHS && RHS)  { // We have 2 user-defined types.
8995     if (LHS != RHS) {
8996       if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
8997         return finish(BlockReturnType);
8998       if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
8999         return finish(!BlockReturnType);
9000     }
9001     else
9002       return true;
9003   }
9004   return false;
9005 }
9006 
9007 /// Comparison routine for Objective-C protocols to be used with
9008 /// llvm::array_pod_sort.
9009 static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
9010                                       ObjCProtocolDecl * const *rhs) {
9011   return (*lhs)->getName().compare((*rhs)->getName());
9012 }
9013 
9014 /// getIntersectionOfProtocols - This routine finds the intersection of set
9015 /// of protocols inherited from two distinct objective-c pointer objects with
9016 /// the given common base.
9017 /// It is used to build composite qualifier list of the composite type of
9018 /// the conditional expression involving two objective-c pointer objects.
9019 static
9020 void getIntersectionOfProtocols(ASTContext &Context,
9021                                 const ObjCInterfaceDecl *CommonBase,
9022                                 const ObjCObjectPointerType *LHSOPT,
9023                                 const ObjCObjectPointerType *RHSOPT,
9024       SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
9025 
9026   const ObjCObjectType* LHS = LHSOPT->getObjectType();
9027   const ObjCObjectType* RHS = RHSOPT->getObjectType();
9028   assert(LHS->getInterface() && "LHS must have an interface base");
9029   assert(RHS->getInterface() && "RHS must have an interface base");
9030 
9031   // Add all of the protocols for the LHS.
9032   llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
9033 
9034   // Start with the protocol qualifiers.
9035   for (auto proto : LHS->quals()) {
9036     Context.CollectInheritedProtocols(proto, LHSProtocolSet);
9037   }
9038 
9039   // Also add the protocols associated with the LHS interface.
9040   Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
9041 
9042   // Add all of the protocols for the RHS.
9043   llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
9044 
9045   // Start with the protocol qualifiers.
9046   for (auto proto : RHS->quals()) {
9047     Context.CollectInheritedProtocols(proto, RHSProtocolSet);
9048   }
9049 
9050   // Also add the protocols associated with the RHS interface.
9051   Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
9052 
9053   // Compute the intersection of the collected protocol sets.
9054   for (auto proto : LHSProtocolSet) {
9055     if (RHSProtocolSet.count(proto))
9056       IntersectionSet.push_back(proto);
9057   }
9058 
9059   // Compute the set of protocols that is implied by either the common type or
9060   // the protocols within the intersection.
9061   llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
9062   Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
9063 
9064   // Remove any implied protocols from the list of inherited protocols.
9065   if (!ImpliedProtocols.empty()) {
9066     IntersectionSet.erase(
9067       std::remove_if(IntersectionSet.begin(),
9068                      IntersectionSet.end(),
9069                      [&](ObjCProtocolDecl *proto) -> bool {
9070                        return ImpliedProtocols.count(proto) > 0;
9071                      }),
9072       IntersectionSet.end());
9073   }
9074 
9075   // Sort the remaining protocols by name.
9076   llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
9077                        compareObjCProtocolsByName);
9078 }
9079 
9080 /// Determine whether the first type is a subtype of the second.
9081 static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
9082                                      QualType rhs) {
9083   // Common case: two object pointers.
9084   const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
9085   const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
9086   if (lhsOPT && rhsOPT)
9087     return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
9088 
9089   // Two block pointers.
9090   const auto *lhsBlock = lhs->getAs<BlockPointerType>();
9091   const auto *rhsBlock = rhs->getAs<BlockPointerType>();
9092   if (lhsBlock && rhsBlock)
9093     return ctx.typesAreBlockPointerCompatible(lhs, rhs);
9094 
9095   // If either is an unqualified 'id' and the other is a block, it's
9096   // acceptable.
9097   if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
9098       (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
9099     return true;
9100 
9101   return false;
9102 }
9103 
9104 // Check that the given Objective-C type argument lists are equivalent.
9105 static bool sameObjCTypeArgs(ASTContext &ctx,
9106                              const ObjCInterfaceDecl *iface,
9107                              ArrayRef<QualType> lhsArgs,
9108                              ArrayRef<QualType> rhsArgs,
9109                              bool stripKindOf) {
9110   if (lhsArgs.size() != rhsArgs.size())
9111     return false;
9112 
9113   ObjCTypeParamList *typeParams = iface->getTypeParamList();
9114   for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
9115     if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
9116       continue;
9117 
9118     switch (typeParams->begin()[i]->getVariance()) {
9119     case ObjCTypeParamVariance::Invariant:
9120       if (!stripKindOf ||
9121           !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
9122                            rhsArgs[i].stripObjCKindOfType(ctx))) {
9123         return false;
9124       }
9125       break;
9126 
9127     case ObjCTypeParamVariance::Covariant:
9128       if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
9129         return false;
9130       break;
9131 
9132     case ObjCTypeParamVariance::Contravariant:
9133       if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
9134         return false;
9135       break;
9136     }
9137   }
9138 
9139   return true;
9140 }
9141 
9142 QualType ASTContext::areCommonBaseCompatible(
9143            const ObjCObjectPointerType *Lptr,
9144            const ObjCObjectPointerType *Rptr) {
9145   const ObjCObjectType *LHS = Lptr->getObjectType();
9146   const ObjCObjectType *RHS = Rptr->getObjectType();
9147   const ObjCInterfaceDecl* LDecl = LHS->getInterface();
9148   const ObjCInterfaceDecl* RDecl = RHS->getInterface();
9149 
9150   if (!LDecl || !RDecl)
9151     return {};
9152 
9153   // When either LHS or RHS is a kindof type, we should return a kindof type.
9154   // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
9155   // kindof(A).
9156   bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
9157 
9158   // Follow the left-hand side up the class hierarchy until we either hit a
9159   // root or find the RHS. Record the ancestors in case we don't find it.
9160   llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
9161     LHSAncestors;
9162   while (true) {
9163     // Record this ancestor. We'll need this if the common type isn't in the
9164     // path from the LHS to the root.
9165     LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
9166 
9167     if (declaresSameEntity(LHS->getInterface(), RDecl)) {
9168       // Get the type arguments.
9169       ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
9170       bool anyChanges = false;
9171       if (LHS->isSpecialized() && RHS->isSpecialized()) {
9172         // Both have type arguments, compare them.
9173         if (!sameObjCTypeArgs(*this, LHS->getInterface(),
9174                               LHS->getTypeArgs(), RHS->getTypeArgs(),
9175                               /*stripKindOf=*/true))
9176           return {};
9177       } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
9178         // If only one has type arguments, the result will not have type
9179         // arguments.
9180         LHSTypeArgs = {};
9181         anyChanges = true;
9182       }
9183 
9184       // Compute the intersection of protocols.
9185       SmallVector<ObjCProtocolDecl *, 8> Protocols;
9186       getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
9187                                  Protocols);
9188       if (!Protocols.empty())
9189         anyChanges = true;
9190 
9191       // If anything in the LHS will have changed, build a new result type.
9192       // If we need to return a kindof type but LHS is not a kindof type, we
9193       // build a new result type.
9194       if (anyChanges || LHS->isKindOfType() != anyKindOf) {
9195         QualType Result = getObjCInterfaceType(LHS->getInterface());
9196         Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
9197                                    anyKindOf || LHS->isKindOfType());
9198         return getObjCObjectPointerType(Result);
9199       }
9200 
9201       return getObjCObjectPointerType(QualType(LHS, 0));
9202     }
9203 
9204     // Find the superclass.
9205     QualType LHSSuperType = LHS->getSuperClassType();
9206     if (LHSSuperType.isNull())
9207       break;
9208 
9209     LHS = LHSSuperType->castAs<ObjCObjectType>();
9210   }
9211 
9212   // We didn't find anything by following the LHS to its root; now check
9213   // the RHS against the cached set of ancestors.
9214   while (true) {
9215     auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
9216     if (KnownLHS != LHSAncestors.end()) {
9217       LHS = KnownLHS->second;
9218 
9219       // Get the type arguments.
9220       ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
9221       bool anyChanges = false;
9222       if (LHS->isSpecialized() && RHS->isSpecialized()) {
9223         // Both have type arguments, compare them.
9224         if (!sameObjCTypeArgs(*this, LHS->getInterface(),
9225                               LHS->getTypeArgs(), RHS->getTypeArgs(),
9226                               /*stripKindOf=*/true))
9227           return {};
9228       } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
9229         // If only one has type arguments, the result will not have type
9230         // arguments.
9231         RHSTypeArgs = {};
9232         anyChanges = true;
9233       }
9234 
9235       // Compute the intersection of protocols.
9236       SmallVector<ObjCProtocolDecl *, 8> Protocols;
9237       getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
9238                                  Protocols);
9239       if (!Protocols.empty())
9240         anyChanges = true;
9241 
9242       // If we need to return a kindof type but RHS is not a kindof type, we
9243       // build a new result type.
9244       if (anyChanges || RHS->isKindOfType() != anyKindOf) {
9245         QualType Result = getObjCInterfaceType(RHS->getInterface());
9246         Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
9247                                    anyKindOf || RHS->isKindOfType());
9248         return getObjCObjectPointerType(Result);
9249       }
9250 
9251       return getObjCObjectPointerType(QualType(RHS, 0));
9252     }
9253 
9254     // Find the superclass of the RHS.
9255     QualType RHSSuperType = RHS->getSuperClassType();
9256     if (RHSSuperType.isNull())
9257       break;
9258 
9259     RHS = RHSSuperType->castAs<ObjCObjectType>();
9260   }
9261 
9262   return {};
9263 }
9264 
9265 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
9266                                          const ObjCObjectType *RHS) {
9267   assert(LHS->getInterface() && "LHS is not an interface type");
9268   assert(RHS->getInterface() && "RHS is not an interface type");
9269 
9270   // Verify that the base decls are compatible: the RHS must be a subclass of
9271   // the LHS.
9272   ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
9273   bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
9274   if (!IsSuperClass)
9275     return false;
9276 
9277   // If the LHS has protocol qualifiers, determine whether all of them are
9278   // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
9279   // LHS).
9280   if (LHS->getNumProtocols() > 0) {
9281     // OK if conversion of LHS to SuperClass results in narrowing of types
9282     // ; i.e., SuperClass may implement at least one of the protocols
9283     // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
9284     // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
9285     llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
9286     CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
9287     // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
9288     // qualifiers.
9289     for (auto *RHSPI : RHS->quals())
9290       CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
9291     // If there is no protocols associated with RHS, it is not a match.
9292     if (SuperClassInheritedProtocols.empty())
9293       return false;
9294 
9295     for (const auto *LHSProto : LHS->quals()) {
9296       bool SuperImplementsProtocol = false;
9297       for (auto *SuperClassProto : SuperClassInheritedProtocols)
9298         if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
9299           SuperImplementsProtocol = true;
9300           break;
9301         }
9302       if (!SuperImplementsProtocol)
9303         return false;
9304     }
9305   }
9306 
9307   // If the LHS is specialized, we may need to check type arguments.
9308   if (LHS->isSpecialized()) {
9309     // Follow the superclass chain until we've matched the LHS class in the
9310     // hierarchy. This substitutes type arguments through.
9311     const ObjCObjectType *RHSSuper = RHS;
9312     while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
9313       RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
9314 
9315     // If the RHS is specializd, compare type arguments.
9316     if (RHSSuper->isSpecialized() &&
9317         !sameObjCTypeArgs(*this, LHS->getInterface(),
9318                           LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
9319                           /*stripKindOf=*/true)) {
9320       return false;
9321     }
9322   }
9323 
9324   return true;
9325 }
9326 
9327 bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
9328   // get the "pointed to" types
9329   const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
9330   const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
9331 
9332   if (!LHSOPT || !RHSOPT)
9333     return false;
9334 
9335   return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
9336          canAssignObjCInterfaces(RHSOPT, LHSOPT);
9337 }
9338 
9339 bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
9340   return canAssignObjCInterfaces(
9341       getObjCObjectPointerType(To)->castAs<ObjCObjectPointerType>(),
9342       getObjCObjectPointerType(From)->castAs<ObjCObjectPointerType>());
9343 }
9344 
9345 /// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
9346 /// both shall have the identically qualified version of a compatible type.
9347 /// C99 6.2.7p1: Two types have compatible types if their types are the
9348 /// same. See 6.7.[2,3,5] for additional rules.
9349 bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
9350                                     bool CompareUnqualified) {
9351   if (getLangOpts().CPlusPlus)
9352     return hasSameType(LHS, RHS);
9353 
9354   return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
9355 }
9356 
9357 bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
9358   return typesAreCompatible(LHS, RHS);
9359 }
9360 
9361 bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
9362   return !mergeTypes(LHS, RHS, true).isNull();
9363 }
9364 
9365 /// mergeTransparentUnionType - if T is a transparent union type and a member
9366 /// of T is compatible with SubType, return the merged type, else return
9367 /// QualType()
9368 QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
9369                                                bool OfBlockPointer,
9370                                                bool Unqualified) {
9371   if (const RecordType *UT = T->getAsUnionType()) {
9372     RecordDecl *UD = UT->getDecl();
9373     if (UD->hasAttr<TransparentUnionAttr>()) {
9374       for (const auto *I : UD->fields()) {
9375         QualType ET = I->getType().getUnqualifiedType();
9376         QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
9377         if (!MT.isNull())
9378           return MT;
9379       }
9380     }
9381   }
9382 
9383   return {};
9384 }
9385 
9386 /// mergeFunctionParameterTypes - merge two types which appear as function
9387 /// parameter types
9388 QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
9389                                                  bool OfBlockPointer,
9390                                                  bool Unqualified) {
9391   // GNU extension: two types are compatible if they appear as a function
9392   // argument, one of the types is a transparent union type and the other
9393   // type is compatible with a union member
9394   QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
9395                                               Unqualified);
9396   if (!lmerge.isNull())
9397     return lmerge;
9398 
9399   QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
9400                                               Unqualified);
9401   if (!rmerge.isNull())
9402     return rmerge;
9403 
9404   return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
9405 }
9406 
9407 QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
9408                                         bool OfBlockPointer, bool Unqualified,
9409                                         bool AllowCXX) {
9410   const auto *lbase = lhs->castAs<FunctionType>();
9411   const auto *rbase = rhs->castAs<FunctionType>();
9412   const auto *lproto = dyn_cast<FunctionProtoType>(lbase);
9413   const auto *rproto = dyn_cast<FunctionProtoType>(rbase);
9414   bool allLTypes = true;
9415   bool allRTypes = true;
9416 
9417   // Check return type
9418   QualType retType;
9419   if (OfBlockPointer) {
9420     QualType RHS = rbase->getReturnType();
9421     QualType LHS = lbase->getReturnType();
9422     bool UnqualifiedResult = Unqualified;
9423     if (!UnqualifiedResult)
9424       UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
9425     retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
9426   }
9427   else
9428     retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
9429                          Unqualified);
9430   if (retType.isNull())
9431     return {};
9432 
9433   if (Unqualified)
9434     retType = retType.getUnqualifiedType();
9435 
9436   CanQualType LRetType = getCanonicalType(lbase->getReturnType());
9437   CanQualType RRetType = getCanonicalType(rbase->getReturnType());
9438   if (Unqualified) {
9439     LRetType = LRetType.getUnqualifiedType();
9440     RRetType = RRetType.getUnqualifiedType();
9441   }
9442 
9443   if (getCanonicalType(retType) != LRetType)
9444     allLTypes = false;
9445   if (getCanonicalType(retType) != RRetType)
9446     allRTypes = false;
9447 
9448   // FIXME: double check this
9449   // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
9450   //                           rbase->getRegParmAttr() != 0 &&
9451   //                           lbase->getRegParmAttr() != rbase->getRegParmAttr()?
9452   FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
9453   FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
9454 
9455   // Compatible functions must have compatible calling conventions
9456   if (lbaseInfo.getCC() != rbaseInfo.getCC())
9457     return {};
9458 
9459   // Regparm is part of the calling convention.
9460   if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
9461     return {};
9462   if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
9463     return {};
9464 
9465   if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
9466     return {};
9467   if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
9468     return {};
9469   if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
9470     return {};
9471 
9472   // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
9473   bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
9474 
9475   if (lbaseInfo.getNoReturn() != NoReturn)
9476     allLTypes = false;
9477   if (rbaseInfo.getNoReturn() != NoReturn)
9478     allRTypes = false;
9479 
9480   FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
9481 
9482   if (lproto && rproto) { // two C99 style function prototypes
9483     assert((AllowCXX ||
9484             (!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec())) &&
9485            "C++ shouldn't be here");
9486     // Compatible functions must have the same number of parameters
9487     if (lproto->getNumParams() != rproto->getNumParams())
9488       return {};
9489 
9490     // Variadic and non-variadic functions aren't compatible
9491     if (lproto->isVariadic() != rproto->isVariadic())
9492       return {};
9493 
9494     if (lproto->getMethodQuals() != rproto->getMethodQuals())
9495       return {};
9496 
9497     SmallVector<FunctionProtoType::ExtParameterInfo, 4> newParamInfos;
9498     bool canUseLeft, canUseRight;
9499     if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight,
9500                                newParamInfos))
9501       return {};
9502 
9503     if (!canUseLeft)
9504       allLTypes = false;
9505     if (!canUseRight)
9506       allRTypes = false;
9507 
9508     // Check parameter type compatibility
9509     SmallVector<QualType, 10> types;
9510     for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
9511       QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
9512       QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
9513       QualType paramType = mergeFunctionParameterTypes(
9514           lParamType, rParamType, OfBlockPointer, Unqualified);
9515       if (paramType.isNull())
9516         return {};
9517 
9518       if (Unqualified)
9519         paramType = paramType.getUnqualifiedType();
9520 
9521       types.push_back(paramType);
9522       if (Unqualified) {
9523         lParamType = lParamType.getUnqualifiedType();
9524         rParamType = rParamType.getUnqualifiedType();
9525       }
9526 
9527       if (getCanonicalType(paramType) != getCanonicalType(lParamType))
9528         allLTypes = false;
9529       if (getCanonicalType(paramType) != getCanonicalType(rParamType))
9530         allRTypes = false;
9531     }
9532 
9533     if (allLTypes) return lhs;
9534     if (allRTypes) return rhs;
9535 
9536     FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
9537     EPI.ExtInfo = einfo;
9538     EPI.ExtParameterInfos =
9539         newParamInfos.empty() ? nullptr : newParamInfos.data();
9540     return getFunctionType(retType, types, EPI);
9541   }
9542 
9543   if (lproto) allRTypes = false;
9544   if (rproto) allLTypes = false;
9545 
9546   const FunctionProtoType *proto = lproto ? lproto : rproto;
9547   if (proto) {
9548     assert((AllowCXX || !proto->hasExceptionSpec()) && "C++ shouldn't be here");
9549     if (proto->isVariadic())
9550       return {};
9551     // Check that the types are compatible with the types that
9552     // would result from default argument promotions (C99 6.7.5.3p15).
9553     // The only types actually affected are promotable integer
9554     // types and floats, which would be passed as a different
9555     // type depending on whether the prototype is visible.
9556     for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
9557       QualType paramTy = proto->getParamType(i);
9558 
9559       // Look at the converted type of enum types, since that is the type used
9560       // to pass enum values.
9561       if (const auto *Enum = paramTy->getAs<EnumType>()) {
9562         paramTy = Enum->getDecl()->getIntegerType();
9563         if (paramTy.isNull())
9564           return {};
9565       }
9566 
9567       if (paramTy->isPromotableIntegerType() ||
9568           getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
9569         return {};
9570     }
9571 
9572     if (allLTypes) return lhs;
9573     if (allRTypes) return rhs;
9574 
9575     FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
9576     EPI.ExtInfo = einfo;
9577     return getFunctionType(retType, proto->getParamTypes(), EPI);
9578   }
9579 
9580   if (allLTypes) return lhs;
9581   if (allRTypes) return rhs;
9582   return getFunctionNoProtoType(retType, einfo);
9583 }
9584 
9585 /// Given that we have an enum type and a non-enum type, try to merge them.
9586 static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
9587                                      QualType other, bool isBlockReturnType) {
9588   // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
9589   // a signed integer type, or an unsigned integer type.
9590   // Compatibility is based on the underlying type, not the promotion
9591   // type.
9592   QualType underlyingType = ET->getDecl()->getIntegerType();
9593   if (underlyingType.isNull())
9594     return {};
9595   if (Context.hasSameType(underlyingType, other))
9596     return other;
9597 
9598   // In block return types, we're more permissive and accept any
9599   // integral type of the same size.
9600   if (isBlockReturnType && other->isIntegerType() &&
9601       Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
9602     return other;
9603 
9604   return {};
9605 }
9606 
9607 QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
9608                                 bool OfBlockPointer,
9609                                 bool Unqualified, bool BlockReturnType) {
9610   // C++ [expr]: If an expression initially has the type "reference to T", the
9611   // type is adjusted to "T" prior to any further analysis, the expression
9612   // designates the object or function denoted by the reference, and the
9613   // expression is an lvalue unless the reference is an rvalue reference and
9614   // the expression is a function call (possibly inside parentheses).
9615   if (LHS->getAs<ReferenceType>() || RHS->getAs<ReferenceType>())
9616     return {};
9617 
9618   if (Unqualified) {
9619     LHS = LHS.getUnqualifiedType();
9620     RHS = RHS.getUnqualifiedType();
9621   }
9622 
9623   QualType LHSCan = getCanonicalType(LHS),
9624            RHSCan = getCanonicalType(RHS);
9625 
9626   // If two types are identical, they are compatible.
9627   if (LHSCan == RHSCan)
9628     return LHS;
9629 
9630   // If the qualifiers are different, the types aren't compatible... mostly.
9631   Qualifiers LQuals = LHSCan.getLocalQualifiers();
9632   Qualifiers RQuals = RHSCan.getLocalQualifiers();
9633   if (LQuals != RQuals) {
9634     // If any of these qualifiers are different, we have a type
9635     // mismatch.
9636     if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
9637         LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
9638         LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
9639         LQuals.hasUnaligned() != RQuals.hasUnaligned())
9640       return {};
9641 
9642     // Exactly one GC qualifier difference is allowed: __strong is
9643     // okay if the other type has no GC qualifier but is an Objective
9644     // C object pointer (i.e. implicitly strong by default).  We fix
9645     // this by pretending that the unqualified type was actually
9646     // qualified __strong.
9647     Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
9648     Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
9649     assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
9650 
9651     if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
9652       return {};
9653 
9654     if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
9655       return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
9656     }
9657     if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
9658       return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
9659     }
9660     return {};
9661   }
9662 
9663   // Okay, qualifiers are equal.
9664 
9665   Type::TypeClass LHSClass = LHSCan->getTypeClass();
9666   Type::TypeClass RHSClass = RHSCan->getTypeClass();
9667 
9668   // We want to consider the two function types to be the same for these
9669   // comparisons, just force one to the other.
9670   if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
9671   if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
9672 
9673   // Same as above for arrays
9674   if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
9675     LHSClass = Type::ConstantArray;
9676   if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
9677     RHSClass = Type::ConstantArray;
9678 
9679   // ObjCInterfaces are just specialized ObjCObjects.
9680   if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
9681   if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
9682 
9683   // Canonicalize ExtVector -> Vector.
9684   if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
9685   if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
9686 
9687   // If the canonical type classes don't match.
9688   if (LHSClass != RHSClass) {
9689     // Note that we only have special rules for turning block enum
9690     // returns into block int returns, not vice-versa.
9691     if (const auto *ETy = LHS->getAs<EnumType>()) {
9692       return mergeEnumWithInteger(*this, ETy, RHS, false);
9693     }
9694     if (const EnumType* ETy = RHS->getAs<EnumType>()) {
9695       return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
9696     }
9697     // allow block pointer type to match an 'id' type.
9698     if (OfBlockPointer && !BlockReturnType) {
9699        if (LHS->isObjCIdType() && RHS->isBlockPointerType())
9700          return LHS;
9701       if (RHS->isObjCIdType() && LHS->isBlockPointerType())
9702         return RHS;
9703     }
9704 
9705     return {};
9706   }
9707 
9708   // The canonical type classes match.
9709   switch (LHSClass) {
9710 #define TYPE(Class, Base)
9711 #define ABSTRACT_TYPE(Class, Base)
9712 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
9713 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
9714 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
9715 #include "clang/AST/TypeNodes.inc"
9716     llvm_unreachable("Non-canonical and dependent types shouldn't get here");
9717 
9718   case Type::Auto:
9719   case Type::DeducedTemplateSpecialization:
9720   case Type::LValueReference:
9721   case Type::RValueReference:
9722   case Type::MemberPointer:
9723     llvm_unreachable("C++ should never be in mergeTypes");
9724 
9725   case Type::ObjCInterface:
9726   case Type::IncompleteArray:
9727   case Type::VariableArray:
9728   case Type::FunctionProto:
9729   case Type::ExtVector:
9730     llvm_unreachable("Types are eliminated above");
9731 
9732   case Type::Pointer:
9733   {
9734     // Merge two pointer types, while trying to preserve typedef info
9735     QualType LHSPointee = LHS->castAs<PointerType>()->getPointeeType();
9736     QualType RHSPointee = RHS->castAs<PointerType>()->getPointeeType();
9737     if (Unqualified) {
9738       LHSPointee = LHSPointee.getUnqualifiedType();
9739       RHSPointee = RHSPointee.getUnqualifiedType();
9740     }
9741     QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
9742                                      Unqualified);
9743     if (ResultType.isNull())
9744       return {};
9745     if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
9746       return LHS;
9747     if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
9748       return RHS;
9749     return getPointerType(ResultType);
9750   }
9751   case Type::BlockPointer:
9752   {
9753     // Merge two block pointer types, while trying to preserve typedef info
9754     QualType LHSPointee = LHS->castAs<BlockPointerType>()->getPointeeType();
9755     QualType RHSPointee = RHS->castAs<BlockPointerType>()->getPointeeType();
9756     if (Unqualified) {
9757       LHSPointee = LHSPointee.getUnqualifiedType();
9758       RHSPointee = RHSPointee.getUnqualifiedType();
9759     }
9760     if (getLangOpts().OpenCL) {
9761       Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
9762       Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
9763       // Blocks can't be an expression in a ternary operator (OpenCL v2.0
9764       // 6.12.5) thus the following check is asymmetric.
9765       if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual))
9766         return {};
9767       LHSPteeQual.removeAddressSpace();
9768       RHSPteeQual.removeAddressSpace();
9769       LHSPointee =
9770           QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
9771       RHSPointee =
9772           QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
9773     }
9774     QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
9775                                      Unqualified);
9776     if (ResultType.isNull())
9777       return {};
9778     if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
9779       return LHS;
9780     if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
9781       return RHS;
9782     return getBlockPointerType(ResultType);
9783   }
9784   case Type::Atomic:
9785   {
9786     // Merge two pointer types, while trying to preserve typedef info
9787     QualType LHSValue = LHS->castAs<AtomicType>()->getValueType();
9788     QualType RHSValue = RHS->castAs<AtomicType>()->getValueType();
9789     if (Unqualified) {
9790       LHSValue = LHSValue.getUnqualifiedType();
9791       RHSValue = RHSValue.getUnqualifiedType();
9792     }
9793     QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
9794                                      Unqualified);
9795     if (ResultType.isNull())
9796       return {};
9797     if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
9798       return LHS;
9799     if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
9800       return RHS;
9801     return getAtomicType(ResultType);
9802   }
9803   case Type::ConstantArray:
9804   {
9805     const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
9806     const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
9807     if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
9808       return {};
9809 
9810     QualType LHSElem = getAsArrayType(LHS)->getElementType();
9811     QualType RHSElem = getAsArrayType(RHS)->getElementType();
9812     if (Unqualified) {
9813       LHSElem = LHSElem.getUnqualifiedType();
9814       RHSElem = RHSElem.getUnqualifiedType();
9815     }
9816 
9817     QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
9818     if (ResultType.isNull())
9819       return {};
9820 
9821     const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
9822     const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
9823 
9824     // If either side is a variable array, and both are complete, check whether
9825     // the current dimension is definite.
9826     if (LVAT || RVAT) {
9827       auto SizeFetch = [this](const VariableArrayType* VAT,
9828           const ConstantArrayType* CAT)
9829           -> std::pair<bool,llvm::APInt> {
9830         if (VAT) {
9831           Optional<llvm::APSInt> TheInt;
9832           Expr *E = VAT->getSizeExpr();
9833           if (E && (TheInt = E->getIntegerConstantExpr(*this)))
9834             return std::make_pair(true, *TheInt);
9835           return std::make_pair(false, llvm::APSInt());
9836         }
9837         if (CAT)
9838           return std::make_pair(true, CAT->getSize());
9839         return std::make_pair(false, llvm::APInt());
9840       };
9841 
9842       bool HaveLSize, HaveRSize;
9843       llvm::APInt LSize, RSize;
9844       std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT);
9845       std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT);
9846       if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize))
9847         return {}; // Definite, but unequal, array dimension
9848     }
9849 
9850     if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
9851       return LHS;
9852     if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
9853       return RHS;
9854     if (LCAT)
9855       return getConstantArrayType(ResultType, LCAT->getSize(),
9856                                   LCAT->getSizeExpr(),
9857                                   ArrayType::ArraySizeModifier(), 0);
9858     if (RCAT)
9859       return getConstantArrayType(ResultType, RCAT->getSize(),
9860                                   RCAT->getSizeExpr(),
9861                                   ArrayType::ArraySizeModifier(), 0);
9862     if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
9863       return LHS;
9864     if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
9865       return RHS;
9866     if (LVAT) {
9867       // FIXME: This isn't correct! But tricky to implement because
9868       // the array's size has to be the size of LHS, but the type
9869       // has to be different.
9870       return LHS;
9871     }
9872     if (RVAT) {
9873       // FIXME: This isn't correct! But tricky to implement because
9874       // the array's size has to be the size of RHS, but the type
9875       // has to be different.
9876       return RHS;
9877     }
9878     if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
9879     if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
9880     return getIncompleteArrayType(ResultType,
9881                                   ArrayType::ArraySizeModifier(), 0);
9882   }
9883   case Type::FunctionNoProto:
9884     return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
9885   case Type::Record:
9886   case Type::Enum:
9887     return {};
9888   case Type::Builtin:
9889     // Only exactly equal builtin types are compatible, which is tested above.
9890     return {};
9891   case Type::Complex:
9892     // Distinct complex types are incompatible.
9893     return {};
9894   case Type::Vector:
9895     // FIXME: The merged type should be an ExtVector!
9896     if (areCompatVectorTypes(LHSCan->castAs<VectorType>(),
9897                              RHSCan->castAs<VectorType>()))
9898       return LHS;
9899     return {};
9900   case Type::ConstantMatrix:
9901     if (areCompatMatrixTypes(LHSCan->castAs<ConstantMatrixType>(),
9902                              RHSCan->castAs<ConstantMatrixType>()))
9903       return LHS;
9904     return {};
9905   case Type::ObjCObject: {
9906     // Check if the types are assignment compatible.
9907     // FIXME: This should be type compatibility, e.g. whether
9908     // "LHS x; RHS x;" at global scope is legal.
9909     if (canAssignObjCInterfaces(LHS->castAs<ObjCObjectType>(),
9910                                 RHS->castAs<ObjCObjectType>()))
9911       return LHS;
9912     return {};
9913   }
9914   case Type::ObjCObjectPointer:
9915     if (OfBlockPointer) {
9916       if (canAssignObjCInterfacesInBlockPointer(
9917               LHS->castAs<ObjCObjectPointerType>(),
9918               RHS->castAs<ObjCObjectPointerType>(), BlockReturnType))
9919         return LHS;
9920       return {};
9921     }
9922     if (canAssignObjCInterfaces(LHS->castAs<ObjCObjectPointerType>(),
9923                                 RHS->castAs<ObjCObjectPointerType>()))
9924       return LHS;
9925     return {};
9926   case Type::Pipe:
9927     assert(LHS != RHS &&
9928            "Equivalent pipe types should have already been handled!");
9929     return {};
9930   case Type::ExtInt: {
9931     // Merge two ext-int types, while trying to preserve typedef info.
9932     bool LHSUnsigned  = LHS->castAs<ExtIntType>()->isUnsigned();
9933     bool RHSUnsigned = RHS->castAs<ExtIntType>()->isUnsigned();
9934     unsigned LHSBits = LHS->castAs<ExtIntType>()->getNumBits();
9935     unsigned RHSBits = RHS->castAs<ExtIntType>()->getNumBits();
9936 
9937     // Like unsigned/int, shouldn't have a type if they dont match.
9938     if (LHSUnsigned != RHSUnsigned)
9939       return {};
9940 
9941     if (LHSBits != RHSBits)
9942       return {};
9943     return LHS;
9944   }
9945   }
9946 
9947   llvm_unreachable("Invalid Type::Class!");
9948 }
9949 
9950 bool ASTContext::mergeExtParameterInfo(
9951     const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
9952     bool &CanUseFirst, bool &CanUseSecond,
9953     SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos) {
9954   assert(NewParamInfos.empty() && "param info list not empty");
9955   CanUseFirst = CanUseSecond = true;
9956   bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
9957   bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
9958 
9959   // Fast path: if the first type doesn't have ext parameter infos,
9960   // we match if and only if the second type also doesn't have them.
9961   if (!FirstHasInfo && !SecondHasInfo)
9962     return true;
9963 
9964   bool NeedParamInfo = false;
9965   size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
9966                           : SecondFnType->getExtParameterInfos().size();
9967 
9968   for (size_t I = 0; I < E; ++I) {
9969     FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
9970     if (FirstHasInfo)
9971       FirstParam = FirstFnType->getExtParameterInfo(I);
9972     if (SecondHasInfo)
9973       SecondParam = SecondFnType->getExtParameterInfo(I);
9974 
9975     // Cannot merge unless everything except the noescape flag matches.
9976     if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false))
9977       return false;
9978 
9979     bool FirstNoEscape = FirstParam.isNoEscape();
9980     bool SecondNoEscape = SecondParam.isNoEscape();
9981     bool IsNoEscape = FirstNoEscape && SecondNoEscape;
9982     NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape));
9983     if (NewParamInfos.back().getOpaqueValue())
9984       NeedParamInfo = true;
9985     if (FirstNoEscape != IsNoEscape)
9986       CanUseFirst = false;
9987     if (SecondNoEscape != IsNoEscape)
9988       CanUseSecond = false;
9989   }
9990 
9991   if (!NeedParamInfo)
9992     NewParamInfos.clear();
9993 
9994   return true;
9995 }
9996 
9997 void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) {
9998   ObjCLayouts[CD] = nullptr;
9999 }
10000 
10001 /// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
10002 /// 'RHS' attributes and returns the merged version; including for function
10003 /// return types.
10004 QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
10005   QualType LHSCan = getCanonicalType(LHS),
10006   RHSCan = getCanonicalType(RHS);
10007   // If two types are identical, they are compatible.
10008   if (LHSCan == RHSCan)
10009     return LHS;
10010   if (RHSCan->isFunctionType()) {
10011     if (!LHSCan->isFunctionType())
10012       return {};
10013     QualType OldReturnType =
10014         cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
10015     QualType NewReturnType =
10016         cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
10017     QualType ResReturnType =
10018       mergeObjCGCQualifiers(NewReturnType, OldReturnType);
10019     if (ResReturnType.isNull())
10020       return {};
10021     if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
10022       // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
10023       // In either case, use OldReturnType to build the new function type.
10024       const auto *F = LHS->castAs<FunctionType>();
10025       if (const auto *FPT = cast<FunctionProtoType>(F)) {
10026         FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10027         EPI.ExtInfo = getFunctionExtInfo(LHS);
10028         QualType ResultType =
10029             getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
10030         return ResultType;
10031       }
10032     }
10033     return {};
10034   }
10035 
10036   // If the qualifiers are different, the types can still be merged.
10037   Qualifiers LQuals = LHSCan.getLocalQualifiers();
10038   Qualifiers RQuals = RHSCan.getLocalQualifiers();
10039   if (LQuals != RQuals) {
10040     // If any of these qualifiers are different, we have a type mismatch.
10041     if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
10042         LQuals.getAddressSpace() != RQuals.getAddressSpace())
10043       return {};
10044 
10045     // Exactly one GC qualifier difference is allowed: __strong is
10046     // okay if the other type has no GC qualifier but is an Objective
10047     // C object pointer (i.e. implicitly strong by default).  We fix
10048     // this by pretending that the unqualified type was actually
10049     // qualified __strong.
10050     Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
10051     Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
10052     assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
10053 
10054     if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
10055       return {};
10056 
10057     if (GC_L == Qualifiers::Strong)
10058       return LHS;
10059     if (GC_R == Qualifiers::Strong)
10060       return RHS;
10061     return {};
10062   }
10063 
10064   if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
10065     QualType LHSBaseQT = LHS->castAs<ObjCObjectPointerType>()->getPointeeType();
10066     QualType RHSBaseQT = RHS->castAs<ObjCObjectPointerType>()->getPointeeType();
10067     QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
10068     if (ResQT == LHSBaseQT)
10069       return LHS;
10070     if (ResQT == RHSBaseQT)
10071       return RHS;
10072   }
10073   return {};
10074 }
10075 
10076 //===----------------------------------------------------------------------===//
10077 //                         Integer Predicates
10078 //===----------------------------------------------------------------------===//
10079 
10080 unsigned ASTContext::getIntWidth(QualType T) const {
10081   if (const auto *ET = T->getAs<EnumType>())
10082     T = ET->getDecl()->getIntegerType();
10083   if (T->isBooleanType())
10084     return 1;
10085   if(const auto *EIT = T->getAs<ExtIntType>())
10086     return EIT->getNumBits();
10087   // For builtin types, just use the standard type sizing method
10088   return (unsigned)getTypeSize(T);
10089 }
10090 
10091 QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
10092   assert((T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) &&
10093          "Unexpected type");
10094 
10095   // Turn <4 x signed int> -> <4 x unsigned int>
10096   if (const auto *VTy = T->getAs<VectorType>())
10097     return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
10098                          VTy->getNumElements(), VTy->getVectorKind());
10099 
10100   // For enums, we return the unsigned version of the base type.
10101   if (const auto *ETy = T->getAs<EnumType>())
10102     T = ETy->getDecl()->getIntegerType();
10103 
10104   switch (T->castAs<BuiltinType>()->getKind()) {
10105   case BuiltinType::Char_S:
10106   case BuiltinType::SChar:
10107     return UnsignedCharTy;
10108   case BuiltinType::Short:
10109     return UnsignedShortTy;
10110   case BuiltinType::Int:
10111     return UnsignedIntTy;
10112   case BuiltinType::Long:
10113     return UnsignedLongTy;
10114   case BuiltinType::LongLong:
10115     return UnsignedLongLongTy;
10116   case BuiltinType::Int128:
10117     return UnsignedInt128Ty;
10118   // wchar_t is special. It is either signed or not, but when it's signed,
10119   // there's no matching "unsigned wchar_t". Therefore we return the unsigned
10120   // version of it's underlying type instead.
10121   case BuiltinType::WChar_S:
10122     return getUnsignedWCharType();
10123 
10124   case BuiltinType::ShortAccum:
10125     return UnsignedShortAccumTy;
10126   case BuiltinType::Accum:
10127     return UnsignedAccumTy;
10128   case BuiltinType::LongAccum:
10129     return UnsignedLongAccumTy;
10130   case BuiltinType::SatShortAccum:
10131     return SatUnsignedShortAccumTy;
10132   case BuiltinType::SatAccum:
10133     return SatUnsignedAccumTy;
10134   case BuiltinType::SatLongAccum:
10135     return SatUnsignedLongAccumTy;
10136   case BuiltinType::ShortFract:
10137     return UnsignedShortFractTy;
10138   case BuiltinType::Fract:
10139     return UnsignedFractTy;
10140   case BuiltinType::LongFract:
10141     return UnsignedLongFractTy;
10142   case BuiltinType::SatShortFract:
10143     return SatUnsignedShortFractTy;
10144   case BuiltinType::SatFract:
10145     return SatUnsignedFractTy;
10146   case BuiltinType::SatLongFract:
10147     return SatUnsignedLongFractTy;
10148   default:
10149     llvm_unreachable("Unexpected signed integer or fixed point type");
10150   }
10151 }
10152 
10153 ASTMutationListener::~ASTMutationListener() = default;
10154 
10155 void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
10156                                             QualType ReturnType) {}
10157 
10158 //===----------------------------------------------------------------------===//
10159 //                          Builtin Type Computation
10160 //===----------------------------------------------------------------------===//
10161 
10162 /// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
10163 /// pointer over the consumed characters.  This returns the resultant type.  If
10164 /// AllowTypeModifiers is false then modifier like * are not parsed, just basic
10165 /// types.  This allows "v2i*" to be parsed as a pointer to a v2i instead of
10166 /// a vector of "i*".
10167 ///
10168 /// RequiresICE is filled in on return to indicate whether the value is required
10169 /// to be an Integer Constant Expression.
10170 static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
10171                                   ASTContext::GetBuiltinTypeError &Error,
10172                                   bool &RequiresICE,
10173                                   bool AllowTypeModifiers) {
10174   // Modifiers.
10175   int HowLong = 0;
10176   bool Signed = false, Unsigned = false;
10177   RequiresICE = false;
10178 
10179   // Read the prefixed modifiers first.
10180   bool Done = false;
10181   #ifndef NDEBUG
10182   bool IsSpecial = false;
10183   #endif
10184   while (!Done) {
10185     switch (*Str++) {
10186     default: Done = true; --Str; break;
10187     case 'I':
10188       RequiresICE = true;
10189       break;
10190     case 'S':
10191       assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
10192       assert(!Signed && "Can't use 'S' modifier multiple times!");
10193       Signed = true;
10194       break;
10195     case 'U':
10196       assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
10197       assert(!Unsigned && "Can't use 'U' modifier multiple times!");
10198       Unsigned = true;
10199       break;
10200     case 'L':
10201       assert(!IsSpecial && "Can't use 'L' with 'W', 'N', 'Z' or 'O' modifiers");
10202       assert(HowLong <= 2 && "Can't have LLLL modifier");
10203       ++HowLong;
10204       break;
10205     case 'N':
10206       // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
10207       assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
10208       assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
10209       #ifndef NDEBUG
10210       IsSpecial = true;
10211       #endif
10212       if (Context.getTargetInfo().getLongWidth() == 32)
10213         ++HowLong;
10214       break;
10215     case 'W':
10216       // This modifier represents int64 type.
10217       assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
10218       assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
10219       #ifndef NDEBUG
10220       IsSpecial = true;
10221       #endif
10222       switch (Context.getTargetInfo().getInt64Type()) {
10223       default:
10224         llvm_unreachable("Unexpected integer type");
10225       case TargetInfo::SignedLong:
10226         HowLong = 1;
10227         break;
10228       case TargetInfo::SignedLongLong:
10229         HowLong = 2;
10230         break;
10231       }
10232       break;
10233     case 'Z':
10234       // This modifier represents int32 type.
10235       assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
10236       assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!");
10237       #ifndef NDEBUG
10238       IsSpecial = true;
10239       #endif
10240       switch (Context.getTargetInfo().getIntTypeByWidth(32, true)) {
10241       default:
10242         llvm_unreachable("Unexpected integer type");
10243       case TargetInfo::SignedInt:
10244         HowLong = 0;
10245         break;
10246       case TargetInfo::SignedLong:
10247         HowLong = 1;
10248         break;
10249       case TargetInfo::SignedLongLong:
10250         HowLong = 2;
10251         break;
10252       }
10253       break;
10254     case 'O':
10255       assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
10256       assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!");
10257       #ifndef NDEBUG
10258       IsSpecial = true;
10259       #endif
10260       if (Context.getLangOpts().OpenCL)
10261         HowLong = 1;
10262       else
10263         HowLong = 2;
10264       break;
10265     }
10266   }
10267 
10268   QualType Type;
10269 
10270   // Read the base type.
10271   switch (*Str++) {
10272   default: llvm_unreachable("Unknown builtin type letter!");
10273   case 'y':
10274     assert(HowLong == 0 && !Signed && !Unsigned &&
10275            "Bad modifiers used with 'y'!");
10276     Type = Context.BFloat16Ty;
10277     break;
10278   case 'v':
10279     assert(HowLong == 0 && !Signed && !Unsigned &&
10280            "Bad modifiers used with 'v'!");
10281     Type = Context.VoidTy;
10282     break;
10283   case 'h':
10284     assert(HowLong == 0 && !Signed && !Unsigned &&
10285            "Bad modifiers used with 'h'!");
10286     Type = Context.HalfTy;
10287     break;
10288   case 'f':
10289     assert(HowLong == 0 && !Signed && !Unsigned &&
10290            "Bad modifiers used with 'f'!");
10291     Type = Context.FloatTy;
10292     break;
10293   case 'd':
10294     assert(HowLong < 3 && !Signed && !Unsigned &&
10295            "Bad modifiers used with 'd'!");
10296     if (HowLong == 1)
10297       Type = Context.LongDoubleTy;
10298     else if (HowLong == 2)
10299       Type = Context.Float128Ty;
10300     else
10301       Type = Context.DoubleTy;
10302     break;
10303   case 's':
10304     assert(HowLong == 0 && "Bad modifiers used with 's'!");
10305     if (Unsigned)
10306       Type = Context.UnsignedShortTy;
10307     else
10308       Type = Context.ShortTy;
10309     break;
10310   case 'i':
10311     if (HowLong == 3)
10312       Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
10313     else if (HowLong == 2)
10314       Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
10315     else if (HowLong == 1)
10316       Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
10317     else
10318       Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
10319     break;
10320   case 'c':
10321     assert(HowLong == 0 && "Bad modifiers used with 'c'!");
10322     if (Signed)
10323       Type = Context.SignedCharTy;
10324     else if (Unsigned)
10325       Type = Context.UnsignedCharTy;
10326     else
10327       Type = Context.CharTy;
10328     break;
10329   case 'b': // boolean
10330     assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
10331     Type = Context.BoolTy;
10332     break;
10333   case 'z':  // size_t.
10334     assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
10335     Type = Context.getSizeType();
10336     break;
10337   case 'w':  // wchar_t.
10338     assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
10339     Type = Context.getWideCharType();
10340     break;
10341   case 'F':
10342     Type = Context.getCFConstantStringType();
10343     break;
10344   case 'G':
10345     Type = Context.getObjCIdType();
10346     break;
10347   case 'H':
10348     Type = Context.getObjCSelType();
10349     break;
10350   case 'M':
10351     Type = Context.getObjCSuperType();
10352     break;
10353   case 'a':
10354     Type = Context.getBuiltinVaListType();
10355     assert(!Type.isNull() && "builtin va list type not initialized!");
10356     break;
10357   case 'A':
10358     // This is a "reference" to a va_list; however, what exactly
10359     // this means depends on how va_list is defined. There are two
10360     // different kinds of va_list: ones passed by value, and ones
10361     // passed by reference.  An example of a by-value va_list is
10362     // x86, where va_list is a char*. An example of by-ref va_list
10363     // is x86-64, where va_list is a __va_list_tag[1]. For x86,
10364     // we want this argument to be a char*&; for x86-64, we want
10365     // it to be a __va_list_tag*.
10366     Type = Context.getBuiltinVaListType();
10367     assert(!Type.isNull() && "builtin va list type not initialized!");
10368     if (Type->isArrayType())
10369       Type = Context.getArrayDecayedType(Type);
10370     else
10371       Type = Context.getLValueReferenceType(Type);
10372     break;
10373   case 'q': {
10374     char *End;
10375     unsigned NumElements = strtoul(Str, &End, 10);
10376     assert(End != Str && "Missing vector size");
10377     Str = End;
10378 
10379     QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
10380                                              RequiresICE, false);
10381     assert(!RequiresICE && "Can't require vector ICE");
10382 
10383     Type = Context.getScalableVectorType(ElementType, NumElements);
10384     break;
10385   }
10386   case 'V': {
10387     char *End;
10388     unsigned NumElements = strtoul(Str, &End, 10);
10389     assert(End != Str && "Missing vector size");
10390     Str = End;
10391 
10392     QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
10393                                              RequiresICE, false);
10394     assert(!RequiresICE && "Can't require vector ICE");
10395 
10396     // TODO: No way to make AltiVec vectors in builtins yet.
10397     Type = Context.getVectorType(ElementType, NumElements,
10398                                  VectorType::GenericVector);
10399     break;
10400   }
10401   case 'E': {
10402     char *End;
10403 
10404     unsigned NumElements = strtoul(Str, &End, 10);
10405     assert(End != Str && "Missing vector size");
10406 
10407     Str = End;
10408 
10409     QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
10410                                              false);
10411     Type = Context.getExtVectorType(ElementType, NumElements);
10412     break;
10413   }
10414   case 'X': {
10415     QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
10416                                              false);
10417     assert(!RequiresICE && "Can't require complex ICE");
10418     Type = Context.getComplexType(ElementType);
10419     break;
10420   }
10421   case 'Y':
10422     Type = Context.getPointerDiffType();
10423     break;
10424   case 'P':
10425     Type = Context.getFILEType();
10426     if (Type.isNull()) {
10427       Error = ASTContext::GE_Missing_stdio;
10428       return {};
10429     }
10430     break;
10431   case 'J':
10432     if (Signed)
10433       Type = Context.getsigjmp_bufType();
10434     else
10435       Type = Context.getjmp_bufType();
10436 
10437     if (Type.isNull()) {
10438       Error = ASTContext::GE_Missing_setjmp;
10439       return {};
10440     }
10441     break;
10442   case 'K':
10443     assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
10444     Type = Context.getucontext_tType();
10445 
10446     if (Type.isNull()) {
10447       Error = ASTContext::GE_Missing_ucontext;
10448       return {};
10449     }
10450     break;
10451   case 'p':
10452     Type = Context.getProcessIDType();
10453     break;
10454   }
10455 
10456   // If there are modifiers and if we're allowed to parse them, go for it.
10457   Done = !AllowTypeModifiers;
10458   while (!Done) {
10459     switch (char c = *Str++) {
10460     default: Done = true; --Str; break;
10461     case '*':
10462     case '&': {
10463       // Both pointers and references can have their pointee types
10464       // qualified with an address space.
10465       char *End;
10466       unsigned AddrSpace = strtoul(Str, &End, 10);
10467       if (End != Str) {
10468         // Note AddrSpace == 0 is not the same as an unspecified address space.
10469         Type = Context.getAddrSpaceQualType(
10470           Type,
10471           Context.getLangASForBuiltinAddressSpace(AddrSpace));
10472         Str = End;
10473       }
10474       if (c == '*')
10475         Type = Context.getPointerType(Type);
10476       else
10477         Type = Context.getLValueReferenceType(Type);
10478       break;
10479     }
10480     // FIXME: There's no way to have a built-in with an rvalue ref arg.
10481     case 'C':
10482       Type = Type.withConst();
10483       break;
10484     case 'D':
10485       Type = Context.getVolatileType(Type);
10486       break;
10487     case 'R':
10488       Type = Type.withRestrict();
10489       break;
10490     }
10491   }
10492 
10493   assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
10494          "Integer constant 'I' type must be an integer");
10495 
10496   return Type;
10497 }
10498 
10499 // On some targets such as PowerPC, some of the builtins are defined with custom
10500 // type decriptors for target-dependent types. These descriptors are decoded in
10501 // other functions, but it may be useful to be able to fall back to default
10502 // descriptor decoding to define builtins mixing target-dependent and target-
10503 // independent types. This function allows decoding one type descriptor with
10504 // default decoding.
10505 QualType ASTContext::DecodeTypeStr(const char *&Str, const ASTContext &Context,
10506                                    GetBuiltinTypeError &Error, bool &RequireICE,
10507                                    bool AllowTypeModifiers) const {
10508   return DecodeTypeFromStr(Str, Context, Error, RequireICE, AllowTypeModifiers);
10509 }
10510 
10511 /// GetBuiltinType - Return the type for the specified builtin.
10512 QualType ASTContext::GetBuiltinType(unsigned Id,
10513                                     GetBuiltinTypeError &Error,
10514                                     unsigned *IntegerConstantArgs) const {
10515   const char *TypeStr = BuiltinInfo.getTypeString(Id);
10516   if (TypeStr[0] == '\0') {
10517     Error = GE_Missing_type;
10518     return {};
10519   }
10520 
10521   SmallVector<QualType, 8> ArgTypes;
10522 
10523   bool RequiresICE = false;
10524   Error = GE_None;
10525   QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
10526                                        RequiresICE, true);
10527   if (Error != GE_None)
10528     return {};
10529 
10530   assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
10531 
10532   while (TypeStr[0] && TypeStr[0] != '.') {
10533     QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
10534     if (Error != GE_None)
10535       return {};
10536 
10537     // If this argument is required to be an IntegerConstantExpression and the
10538     // caller cares, fill in the bitmask we return.
10539     if (RequiresICE && IntegerConstantArgs)
10540       *IntegerConstantArgs |= 1 << ArgTypes.size();
10541 
10542     // Do array -> pointer decay.  The builtin should use the decayed type.
10543     if (Ty->isArrayType())
10544       Ty = getArrayDecayedType(Ty);
10545 
10546     ArgTypes.push_back(Ty);
10547   }
10548 
10549   if (Id == Builtin::BI__GetExceptionInfo)
10550     return {};
10551 
10552   assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
10553          "'.' should only occur at end of builtin type list!");
10554 
10555   bool Variadic = (TypeStr[0] == '.');
10556 
10557   FunctionType::ExtInfo EI(getDefaultCallingConvention(
10558       Variadic, /*IsCXXMethod=*/false, /*IsBuiltin=*/true));
10559   if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
10560 
10561 
10562   // We really shouldn't be making a no-proto type here.
10563   if (ArgTypes.empty() && Variadic && !getLangOpts().CPlusPlus)
10564     return getFunctionNoProtoType(ResType, EI);
10565 
10566   FunctionProtoType::ExtProtoInfo EPI;
10567   EPI.ExtInfo = EI;
10568   EPI.Variadic = Variadic;
10569   if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id))
10570     EPI.ExceptionSpec.Type =
10571         getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
10572 
10573   return getFunctionType(ResType, ArgTypes, EPI);
10574 }
10575 
10576 static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
10577                                              const FunctionDecl *FD) {
10578   if (!FD->isExternallyVisible())
10579     return GVA_Internal;
10580 
10581   // Non-user-provided functions get emitted as weak definitions with every
10582   // use, no matter whether they've been explicitly instantiated etc.
10583   if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
10584     if (!MD->isUserProvided())
10585       return GVA_DiscardableODR;
10586 
10587   GVALinkage External;
10588   switch (FD->getTemplateSpecializationKind()) {
10589   case TSK_Undeclared:
10590   case TSK_ExplicitSpecialization:
10591     External = GVA_StrongExternal;
10592     break;
10593 
10594   case TSK_ExplicitInstantiationDefinition:
10595     return GVA_StrongODR;
10596 
10597   // C++11 [temp.explicit]p10:
10598   //   [ Note: The intent is that an inline function that is the subject of
10599   //   an explicit instantiation declaration will still be implicitly
10600   //   instantiated when used so that the body can be considered for
10601   //   inlining, but that no out-of-line copy of the inline function would be
10602   //   generated in the translation unit. -- end note ]
10603   case TSK_ExplicitInstantiationDeclaration:
10604     return GVA_AvailableExternally;
10605 
10606   case TSK_ImplicitInstantiation:
10607     External = GVA_DiscardableODR;
10608     break;
10609   }
10610 
10611   if (!FD->isInlined())
10612     return External;
10613 
10614   if ((!Context.getLangOpts().CPlusPlus &&
10615        !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
10616        !FD->hasAttr<DLLExportAttr>()) ||
10617       FD->hasAttr<GNUInlineAttr>()) {
10618     // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
10619 
10620     // GNU or C99 inline semantics. Determine whether this symbol should be
10621     // externally visible.
10622     if (FD->isInlineDefinitionExternallyVisible())
10623       return External;
10624 
10625     // C99 inline semantics, where the symbol is not externally visible.
10626     return GVA_AvailableExternally;
10627   }
10628 
10629   // Functions specified with extern and inline in -fms-compatibility mode
10630   // forcibly get emitted.  While the body of the function cannot be later
10631   // replaced, the function definition cannot be discarded.
10632   if (FD->isMSExternInline())
10633     return GVA_StrongODR;
10634 
10635   return GVA_DiscardableODR;
10636 }
10637 
10638 static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context,
10639                                                 const Decl *D, GVALinkage L) {
10640   // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
10641   // dllexport/dllimport on inline functions.
10642   if (D->hasAttr<DLLImportAttr>()) {
10643     if (L == GVA_DiscardableODR || L == GVA_StrongODR)
10644       return GVA_AvailableExternally;
10645   } else if (D->hasAttr<DLLExportAttr>()) {
10646     if (L == GVA_DiscardableODR)
10647       return GVA_StrongODR;
10648   } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice) {
10649     // Device-side functions with __global__ attribute must always be
10650     // visible externally so they can be launched from host.
10651     if (D->hasAttr<CUDAGlobalAttr>() &&
10652         (L == GVA_DiscardableODR || L == GVA_Internal))
10653       return GVA_StrongODR;
10654     // Single source offloading languages like CUDA/HIP need to be able to
10655     // access static device variables from host code of the same compilation
10656     // unit. This is done by externalizing the static variable with a shared
10657     // name between the host and device compilation which is the same for the
10658     // same compilation unit whereas different among different compilation
10659     // units.
10660     if (Context.shouldExternalizeStaticVar(D))
10661       return GVA_StrongExternal;
10662   }
10663   return L;
10664 }
10665 
10666 /// Adjust the GVALinkage for a declaration based on what an external AST source
10667 /// knows about whether there can be other definitions of this declaration.
10668 static GVALinkage
10669 adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D,
10670                                           GVALinkage L) {
10671   ExternalASTSource *Source = Ctx.getExternalSource();
10672   if (!Source)
10673     return L;
10674 
10675   switch (Source->hasExternalDefinitions(D)) {
10676   case ExternalASTSource::EK_Never:
10677     // Other translation units rely on us to provide the definition.
10678     if (L == GVA_DiscardableODR)
10679       return GVA_StrongODR;
10680     break;
10681 
10682   case ExternalASTSource::EK_Always:
10683     return GVA_AvailableExternally;
10684 
10685   case ExternalASTSource::EK_ReplyHazy:
10686     break;
10687   }
10688   return L;
10689 }
10690 
10691 GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
10692   return adjustGVALinkageForExternalDefinitionKind(*this, FD,
10693            adjustGVALinkageForAttributes(*this, FD,
10694              basicGVALinkageForFunction(*this, FD)));
10695 }
10696 
10697 static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
10698                                              const VarDecl *VD) {
10699   if (!VD->isExternallyVisible())
10700     return GVA_Internal;
10701 
10702   if (VD->isStaticLocal()) {
10703     const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
10704     while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
10705       LexicalContext = LexicalContext->getLexicalParent();
10706 
10707     // ObjC Blocks can create local variables that don't have a FunctionDecl
10708     // LexicalContext.
10709     if (!LexicalContext)
10710       return GVA_DiscardableODR;
10711 
10712     // Otherwise, let the static local variable inherit its linkage from the
10713     // nearest enclosing function.
10714     auto StaticLocalLinkage =
10715         Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
10716 
10717     // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
10718     // be emitted in any object with references to the symbol for the object it
10719     // contains, whether inline or out-of-line."
10720     // Similar behavior is observed with MSVC. An alternative ABI could use
10721     // StrongODR/AvailableExternally to match the function, but none are
10722     // known/supported currently.
10723     if (StaticLocalLinkage == GVA_StrongODR ||
10724         StaticLocalLinkage == GVA_AvailableExternally)
10725       return GVA_DiscardableODR;
10726     return StaticLocalLinkage;
10727   }
10728 
10729   // MSVC treats in-class initialized static data members as definitions.
10730   // By giving them non-strong linkage, out-of-line definitions won't
10731   // cause link errors.
10732   if (Context.isMSStaticDataMemberInlineDefinition(VD))
10733     return GVA_DiscardableODR;
10734 
10735   // Most non-template variables have strong linkage; inline variables are
10736   // linkonce_odr or (occasionally, for compatibility) weak_odr.
10737   GVALinkage StrongLinkage;
10738   switch (Context.getInlineVariableDefinitionKind(VD)) {
10739   case ASTContext::InlineVariableDefinitionKind::None:
10740     StrongLinkage = GVA_StrongExternal;
10741     break;
10742   case ASTContext::InlineVariableDefinitionKind::Weak:
10743   case ASTContext::InlineVariableDefinitionKind::WeakUnknown:
10744     StrongLinkage = GVA_DiscardableODR;
10745     break;
10746   case ASTContext::InlineVariableDefinitionKind::Strong:
10747     StrongLinkage = GVA_StrongODR;
10748     break;
10749   }
10750 
10751   switch (VD->getTemplateSpecializationKind()) {
10752   case TSK_Undeclared:
10753     return StrongLinkage;
10754 
10755   case TSK_ExplicitSpecialization:
10756     return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
10757                    VD->isStaticDataMember()
10758                ? GVA_StrongODR
10759                : StrongLinkage;
10760 
10761   case TSK_ExplicitInstantiationDefinition:
10762     return GVA_StrongODR;
10763 
10764   case TSK_ExplicitInstantiationDeclaration:
10765     return GVA_AvailableExternally;
10766 
10767   case TSK_ImplicitInstantiation:
10768     return GVA_DiscardableODR;
10769   }
10770 
10771   llvm_unreachable("Invalid Linkage!");
10772 }
10773 
10774 GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
10775   return adjustGVALinkageForExternalDefinitionKind(*this, VD,
10776            adjustGVALinkageForAttributes(*this, VD,
10777              basicGVALinkageForVariable(*this, VD)));
10778 }
10779 
10780 bool ASTContext::DeclMustBeEmitted(const Decl *D) {
10781   if (const auto *VD = dyn_cast<VarDecl>(D)) {
10782     if (!VD->isFileVarDecl())
10783       return false;
10784     // Global named register variables (GNU extension) are never emitted.
10785     if (VD->getStorageClass() == SC_Register)
10786       return false;
10787     if (VD->getDescribedVarTemplate() ||
10788         isa<VarTemplatePartialSpecializationDecl>(VD))
10789       return false;
10790   } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
10791     // We never need to emit an uninstantiated function template.
10792     if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
10793       return false;
10794   } else if (isa<PragmaCommentDecl>(D))
10795     return true;
10796   else if (isa<PragmaDetectMismatchDecl>(D))
10797     return true;
10798   else if (isa<OMPRequiresDecl>(D))
10799     return true;
10800   else if (isa<OMPThreadPrivateDecl>(D))
10801     return !D->getDeclContext()->isDependentContext();
10802   else if (isa<OMPAllocateDecl>(D))
10803     return !D->getDeclContext()->isDependentContext();
10804   else if (isa<OMPDeclareReductionDecl>(D) || isa<OMPDeclareMapperDecl>(D))
10805     return !D->getDeclContext()->isDependentContext();
10806   else if (isa<ImportDecl>(D))
10807     return true;
10808   else
10809     return false;
10810 
10811   // If this is a member of a class template, we do not need to emit it.
10812   if (D->getDeclContext()->isDependentContext())
10813     return false;
10814 
10815   // Weak references don't produce any output by themselves.
10816   if (D->hasAttr<WeakRefAttr>())
10817     return false;
10818 
10819   // Aliases and used decls are required.
10820   if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
10821     return true;
10822 
10823   if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
10824     // Forward declarations aren't required.
10825     if (!FD->doesThisDeclarationHaveABody())
10826       return FD->doesDeclarationForceExternallyVisibleDefinition();
10827 
10828     // Constructors and destructors are required.
10829     if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
10830       return true;
10831 
10832     // The key function for a class is required.  This rule only comes
10833     // into play when inline functions can be key functions, though.
10834     if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
10835       if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
10836         const CXXRecordDecl *RD = MD->getParent();
10837         if (MD->isOutOfLine() && RD->isDynamicClass()) {
10838           const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
10839           if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
10840             return true;
10841         }
10842       }
10843     }
10844 
10845     GVALinkage Linkage = GetGVALinkageForFunction(FD);
10846 
10847     // static, static inline, always_inline, and extern inline functions can
10848     // always be deferred.  Normal inline functions can be deferred in C99/C++.
10849     // Implicit template instantiations can also be deferred in C++.
10850     return !isDiscardableGVALinkage(Linkage);
10851   }
10852 
10853   const auto *VD = cast<VarDecl>(D);
10854   assert(VD->isFileVarDecl() && "Expected file scoped var");
10855 
10856   // If the decl is marked as `declare target to`, it should be emitted for the
10857   // host and for the device.
10858   if (LangOpts.OpenMP &&
10859       OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
10860     return true;
10861 
10862   if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
10863       !isMSStaticDataMemberInlineDefinition(VD))
10864     return false;
10865 
10866   // Variables that can be needed in other TUs are required.
10867   auto Linkage = GetGVALinkageForVariable(VD);
10868   if (!isDiscardableGVALinkage(Linkage))
10869     return true;
10870 
10871   // We never need to emit a variable that is available in another TU.
10872   if (Linkage == GVA_AvailableExternally)
10873     return false;
10874 
10875   // Variables that have destruction with side-effects are required.
10876   if (VD->needsDestruction(*this))
10877     return true;
10878 
10879   // Variables that have initialization with side-effects are required.
10880   if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
10881       // We can get a value-dependent initializer during error recovery.
10882       (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
10883     return true;
10884 
10885   // Likewise, variables with tuple-like bindings are required if their
10886   // bindings have side-effects.
10887   if (const auto *DD = dyn_cast<DecompositionDecl>(VD))
10888     for (const auto *BD : DD->bindings())
10889       if (const auto *BindingVD = BD->getHoldingVar())
10890         if (DeclMustBeEmitted(BindingVD))
10891           return true;
10892 
10893   return false;
10894 }
10895 
10896 void ASTContext::forEachMultiversionedFunctionVersion(
10897     const FunctionDecl *FD,
10898     llvm::function_ref<void(FunctionDecl *)> Pred) const {
10899   assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
10900   llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
10901   FD = FD->getMostRecentDecl();
10902   // FIXME: The order of traversal here matters and depends on the order of
10903   // lookup results, which happens to be (mostly) oldest-to-newest, but we
10904   // shouldn't rely on that.
10905   for (auto *CurDecl :
10906        FD->getDeclContext()->getRedeclContext()->lookup(FD->getDeclName())) {
10907     FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl();
10908     if (CurFD && hasSameType(CurFD->getType(), FD->getType()) &&
10909         std::end(SeenDecls) == llvm::find(SeenDecls, CurFD)) {
10910       SeenDecls.insert(CurFD);
10911       Pred(CurFD);
10912     }
10913   }
10914 }
10915 
10916 CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
10917                                                     bool IsCXXMethod,
10918                                                     bool IsBuiltin) const {
10919   // Pass through to the C++ ABI object
10920   if (IsCXXMethod)
10921     return ABI->getDefaultMethodCallConv(IsVariadic);
10922 
10923   // Builtins ignore user-specified default calling convention and remain the
10924   // Target's default calling convention.
10925   if (!IsBuiltin) {
10926     switch (LangOpts.getDefaultCallingConv()) {
10927     case LangOptions::DCC_None:
10928       break;
10929     case LangOptions::DCC_CDecl:
10930       return CC_C;
10931     case LangOptions::DCC_FastCall:
10932       if (getTargetInfo().hasFeature("sse2") && !IsVariadic)
10933         return CC_X86FastCall;
10934       break;
10935     case LangOptions::DCC_StdCall:
10936       if (!IsVariadic)
10937         return CC_X86StdCall;
10938       break;
10939     case LangOptions::DCC_VectorCall:
10940       // __vectorcall cannot be applied to variadic functions.
10941       if (!IsVariadic)
10942         return CC_X86VectorCall;
10943       break;
10944     case LangOptions::DCC_RegCall:
10945       // __regcall cannot be applied to variadic functions.
10946       if (!IsVariadic)
10947         return CC_X86RegCall;
10948       break;
10949     }
10950   }
10951   return Target->getDefaultCallingConv();
10952 }
10953 
10954 bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
10955   // Pass through to the C++ ABI object
10956   return ABI->isNearlyEmpty(RD);
10957 }
10958 
10959 VTableContextBase *ASTContext::getVTableContext() {
10960   if (!VTContext.get()) {
10961     auto ABI = Target->getCXXABI();
10962     if (ABI.isMicrosoft())
10963       VTContext.reset(new MicrosoftVTableContext(*this));
10964     else {
10965       auto ComponentLayout = getLangOpts().RelativeCXXABIVTables
10966                                  ? ItaniumVTableContext::Relative
10967                                  : ItaniumVTableContext::Pointer;
10968       VTContext.reset(new ItaniumVTableContext(*this, ComponentLayout));
10969     }
10970   }
10971   return VTContext.get();
10972 }
10973 
10974 MangleContext *ASTContext::createMangleContext(const TargetInfo *T) {
10975   if (!T)
10976     T = Target;
10977   switch (T->getCXXABI().getKind()) {
10978   case TargetCXXABI::AppleARM64:
10979   case TargetCXXABI::Fuchsia:
10980   case TargetCXXABI::GenericAArch64:
10981   case TargetCXXABI::GenericItanium:
10982   case TargetCXXABI::GenericARM:
10983   case TargetCXXABI::GenericMIPS:
10984   case TargetCXXABI::iOS:
10985   case TargetCXXABI::WebAssembly:
10986   case TargetCXXABI::WatchOS:
10987   case TargetCXXABI::XL:
10988     return ItaniumMangleContext::create(*this, getDiagnostics());
10989   case TargetCXXABI::Microsoft:
10990     return MicrosoftMangleContext::create(*this, getDiagnostics());
10991   }
10992   llvm_unreachable("Unsupported ABI");
10993 }
10994 
10995 CXXABI::~CXXABI() = default;
10996 
10997 size_t ASTContext::getSideTableAllocatedMemory() const {
10998   return ASTRecordLayouts.getMemorySize() +
10999          llvm::capacity_in_bytes(ObjCLayouts) +
11000          llvm::capacity_in_bytes(KeyFunctions) +
11001          llvm::capacity_in_bytes(ObjCImpls) +
11002          llvm::capacity_in_bytes(BlockVarCopyInits) +
11003          llvm::capacity_in_bytes(DeclAttrs) +
11004          llvm::capacity_in_bytes(TemplateOrInstantiation) +
11005          llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
11006          llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
11007          llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
11008          llvm::capacity_in_bytes(OverriddenMethods) +
11009          llvm::capacity_in_bytes(Types) +
11010          llvm::capacity_in_bytes(VariableArrayTypes);
11011 }
11012 
11013 /// getIntTypeForBitwidth -
11014 /// sets integer QualTy according to specified details:
11015 /// bitwidth, signed/unsigned.
11016 /// Returns empty type if there is no appropriate target types.
11017 QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
11018                                            unsigned Signed) const {
11019   TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
11020   CanQualType QualTy = getFromTargetType(Ty);
11021   if (!QualTy && DestWidth == 128)
11022     return Signed ? Int128Ty : UnsignedInt128Ty;
11023   return QualTy;
11024 }
11025 
11026 /// getRealTypeForBitwidth -
11027 /// sets floating point QualTy according to specified bitwidth.
11028 /// Returns empty type if there is no appropriate target types.
11029 QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth,
11030                                             bool ExplicitIEEE) const {
11031   TargetInfo::RealType Ty =
11032       getTargetInfo().getRealTypeByWidth(DestWidth, ExplicitIEEE);
11033   switch (Ty) {
11034   case TargetInfo::Float:
11035     return FloatTy;
11036   case TargetInfo::Double:
11037     return DoubleTy;
11038   case TargetInfo::LongDouble:
11039     return LongDoubleTy;
11040   case TargetInfo::Float128:
11041     return Float128Ty;
11042   case TargetInfo::NoFloat:
11043     return {};
11044   }
11045 
11046   llvm_unreachable("Unhandled TargetInfo::RealType value");
11047 }
11048 
11049 void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
11050   if (Number > 1)
11051     MangleNumbers[ND] = Number;
11052 }
11053 
11054 unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
11055   auto I = MangleNumbers.find(ND);
11056   return I != MangleNumbers.end() ? I->second : 1;
11057 }
11058 
11059 void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
11060   if (Number > 1)
11061     StaticLocalNumbers[VD] = Number;
11062 }
11063 
11064 unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
11065   auto I = StaticLocalNumbers.find(VD);
11066   return I != StaticLocalNumbers.end() ? I->second : 1;
11067 }
11068 
11069 MangleNumberingContext &
11070 ASTContext::getManglingNumberContext(const DeclContext *DC) {
11071   assert(LangOpts.CPlusPlus);  // We don't need mangling numbers for plain C.
11072   std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
11073   if (!MCtx)
11074     MCtx = createMangleNumberingContext();
11075   return *MCtx;
11076 }
11077 
11078 MangleNumberingContext &
11079 ASTContext::getManglingNumberContext(NeedExtraManglingDecl_t, const Decl *D) {
11080   assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
11081   std::unique_ptr<MangleNumberingContext> &MCtx =
11082       ExtraMangleNumberingContexts[D];
11083   if (!MCtx)
11084     MCtx = createMangleNumberingContext();
11085   return *MCtx;
11086 }
11087 
11088 std::unique_ptr<MangleNumberingContext>
11089 ASTContext::createMangleNumberingContext() const {
11090   return ABI->createMangleNumberingContext();
11091 }
11092 
11093 const CXXConstructorDecl *
11094 ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
11095   return ABI->getCopyConstructorForExceptionObject(
11096       cast<CXXRecordDecl>(RD->getFirstDecl()));
11097 }
11098 
11099 void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
11100                                                       CXXConstructorDecl *CD) {
11101   return ABI->addCopyConstructorForExceptionObject(
11102       cast<CXXRecordDecl>(RD->getFirstDecl()),
11103       cast<CXXConstructorDecl>(CD->getFirstDecl()));
11104 }
11105 
11106 void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
11107                                                  TypedefNameDecl *DD) {
11108   return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
11109 }
11110 
11111 TypedefNameDecl *
11112 ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
11113   return ABI->getTypedefNameForUnnamedTagDecl(TD);
11114 }
11115 
11116 void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
11117                                                 DeclaratorDecl *DD) {
11118   return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
11119 }
11120 
11121 DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
11122   return ABI->getDeclaratorForUnnamedTagDecl(TD);
11123 }
11124 
11125 void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
11126   ParamIndices[D] = index;
11127 }
11128 
11129 unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
11130   ParameterIndexTable::const_iterator I = ParamIndices.find(D);
11131   assert(I != ParamIndices.end() &&
11132          "ParmIndices lacks entry set by ParmVarDecl");
11133   return I->second;
11134 }
11135 
11136 QualType ASTContext::getStringLiteralArrayType(QualType EltTy,
11137                                                unsigned Length) const {
11138   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
11139   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
11140     EltTy = EltTy.withConst();
11141 
11142   EltTy = adjustStringLiteralBaseType(EltTy);
11143 
11144   // Get an array type for the string, according to C99 6.4.5. This includes
11145   // the null terminator character.
11146   return getConstantArrayType(EltTy, llvm::APInt(32, Length + 1), nullptr,
11147                               ArrayType::Normal, /*IndexTypeQuals*/ 0);
11148 }
11149 
11150 StringLiteral *
11151 ASTContext::getPredefinedStringLiteralFromCache(StringRef Key) const {
11152   StringLiteral *&Result = StringLiteralCache[Key];
11153   if (!Result)
11154     Result = StringLiteral::Create(
11155         *this, Key, StringLiteral::Ascii,
11156         /*Pascal*/ false, getStringLiteralArrayType(CharTy, Key.size()),
11157         SourceLocation());
11158   return Result;
11159 }
11160 
11161 MSGuidDecl *
11162 ASTContext::getMSGuidDecl(MSGuidDecl::Parts Parts) const {
11163   assert(MSGuidTagDecl && "building MS GUID without MS extensions?");
11164 
11165   llvm::FoldingSetNodeID ID;
11166   MSGuidDecl::Profile(ID, Parts);
11167 
11168   void *InsertPos;
11169   if (MSGuidDecl *Existing = MSGuidDecls.FindNodeOrInsertPos(ID, InsertPos))
11170     return Existing;
11171 
11172   QualType GUIDType = getMSGuidType().withConst();
11173   MSGuidDecl *New = MSGuidDecl::Create(*this, GUIDType, Parts);
11174   MSGuidDecls.InsertNode(New, InsertPos);
11175   return New;
11176 }
11177 
11178 TemplateParamObjectDecl *
11179 ASTContext::getTemplateParamObjectDecl(QualType T, const APValue &V) const {
11180   assert(T->isRecordType() && "template param object of unexpected type");
11181 
11182   // C++ [temp.param]p8:
11183   //   [...] a static storage duration object of type 'const T' [...]
11184   T.addConst();
11185 
11186   llvm::FoldingSetNodeID ID;
11187   TemplateParamObjectDecl::Profile(ID, T, V);
11188 
11189   void *InsertPos;
11190   if (TemplateParamObjectDecl *Existing =
11191           TemplateParamObjectDecls.FindNodeOrInsertPos(ID, InsertPos))
11192     return Existing;
11193 
11194   TemplateParamObjectDecl *New = TemplateParamObjectDecl::Create(*this, T, V);
11195   TemplateParamObjectDecls.InsertNode(New, InsertPos);
11196   return New;
11197 }
11198 
11199 bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
11200   const llvm::Triple &T = getTargetInfo().getTriple();
11201   if (!T.isOSDarwin())
11202     return false;
11203 
11204   if (!(T.isiOS() && T.isOSVersionLT(7)) &&
11205       !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
11206     return false;
11207 
11208   QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
11209   CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
11210   uint64_t Size = sizeChars.getQuantity();
11211   CharUnits alignChars = getTypeAlignInChars(AtomicTy);
11212   unsigned Align = alignChars.getQuantity();
11213   unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
11214   return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
11215 }
11216 
11217 bool
11218 ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
11219                                 const ObjCMethodDecl *MethodImpl) {
11220   // No point trying to match an unavailable/deprecated mothod.
11221   if (MethodDecl->hasAttr<UnavailableAttr>()
11222       || MethodDecl->hasAttr<DeprecatedAttr>())
11223     return false;
11224   if (MethodDecl->getObjCDeclQualifier() !=
11225       MethodImpl->getObjCDeclQualifier())
11226     return false;
11227   if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
11228     return false;
11229 
11230   if (MethodDecl->param_size() != MethodImpl->param_size())
11231     return false;
11232 
11233   for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
11234        IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
11235        EF = MethodDecl->param_end();
11236        IM != EM && IF != EF; ++IM, ++IF) {
11237     const ParmVarDecl *DeclVar = (*IF);
11238     const ParmVarDecl *ImplVar = (*IM);
11239     if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
11240       return false;
11241     if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
11242       return false;
11243   }
11244 
11245   return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
11246 }
11247 
11248 uint64_t ASTContext::getTargetNullPointerValue(QualType QT) const {
11249   LangAS AS;
11250   if (QT->getUnqualifiedDesugaredType()->isNullPtrType())
11251     AS = LangAS::Default;
11252   else
11253     AS = QT->getPointeeType().getAddressSpace();
11254 
11255   return getTargetInfo().getNullPointerValue(AS);
11256 }
11257 
11258 unsigned ASTContext::getTargetAddressSpace(LangAS AS) const {
11259   if (isTargetAddressSpace(AS))
11260     return toTargetAddressSpace(AS);
11261   else
11262     return (*AddrSpaceMap)[(unsigned)AS];
11263 }
11264 
11265 QualType ASTContext::getCorrespondingSaturatedType(QualType Ty) const {
11266   assert(Ty->isFixedPointType());
11267 
11268   if (Ty->isSaturatedFixedPointType()) return Ty;
11269 
11270   switch (Ty->castAs<BuiltinType>()->getKind()) {
11271     default:
11272       llvm_unreachable("Not a fixed point type!");
11273     case BuiltinType::ShortAccum:
11274       return SatShortAccumTy;
11275     case BuiltinType::Accum:
11276       return SatAccumTy;
11277     case BuiltinType::LongAccum:
11278       return SatLongAccumTy;
11279     case BuiltinType::UShortAccum:
11280       return SatUnsignedShortAccumTy;
11281     case BuiltinType::UAccum:
11282       return SatUnsignedAccumTy;
11283     case BuiltinType::ULongAccum:
11284       return SatUnsignedLongAccumTy;
11285     case BuiltinType::ShortFract:
11286       return SatShortFractTy;
11287     case BuiltinType::Fract:
11288       return SatFractTy;
11289     case BuiltinType::LongFract:
11290       return SatLongFractTy;
11291     case BuiltinType::UShortFract:
11292       return SatUnsignedShortFractTy;
11293     case BuiltinType::UFract:
11294       return SatUnsignedFractTy;
11295     case BuiltinType::ULongFract:
11296       return SatUnsignedLongFractTy;
11297   }
11298 }
11299 
11300 LangAS ASTContext::getLangASForBuiltinAddressSpace(unsigned AS) const {
11301   if (LangOpts.OpenCL)
11302     return getTargetInfo().getOpenCLBuiltinAddressSpace(AS);
11303 
11304   if (LangOpts.CUDA)
11305     return getTargetInfo().getCUDABuiltinAddressSpace(AS);
11306 
11307   return getLangASFromTargetAS(AS);
11308 }
11309 
11310 // Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
11311 // doesn't include ASTContext.h
11312 template
11313 clang::LazyGenerationalUpdatePtr<
11314     const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
11315 clang::LazyGenerationalUpdatePtr<
11316     const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
11317         const clang::ASTContext &Ctx, Decl *Value);
11318 
11319 unsigned char ASTContext::getFixedPointScale(QualType Ty) const {
11320   assert(Ty->isFixedPointType());
11321 
11322   const TargetInfo &Target = getTargetInfo();
11323   switch (Ty->castAs<BuiltinType>()->getKind()) {
11324     default:
11325       llvm_unreachable("Not a fixed point type!");
11326     case BuiltinType::ShortAccum:
11327     case BuiltinType::SatShortAccum:
11328       return Target.getShortAccumScale();
11329     case BuiltinType::Accum:
11330     case BuiltinType::SatAccum:
11331       return Target.getAccumScale();
11332     case BuiltinType::LongAccum:
11333     case BuiltinType::SatLongAccum:
11334       return Target.getLongAccumScale();
11335     case BuiltinType::UShortAccum:
11336     case BuiltinType::SatUShortAccum:
11337       return Target.getUnsignedShortAccumScale();
11338     case BuiltinType::UAccum:
11339     case BuiltinType::SatUAccum:
11340       return Target.getUnsignedAccumScale();
11341     case BuiltinType::ULongAccum:
11342     case BuiltinType::SatULongAccum:
11343       return Target.getUnsignedLongAccumScale();
11344     case BuiltinType::ShortFract:
11345     case BuiltinType::SatShortFract:
11346       return Target.getShortFractScale();
11347     case BuiltinType::Fract:
11348     case BuiltinType::SatFract:
11349       return Target.getFractScale();
11350     case BuiltinType::LongFract:
11351     case BuiltinType::SatLongFract:
11352       return Target.getLongFractScale();
11353     case BuiltinType::UShortFract:
11354     case BuiltinType::SatUShortFract:
11355       return Target.getUnsignedShortFractScale();
11356     case BuiltinType::UFract:
11357     case BuiltinType::SatUFract:
11358       return Target.getUnsignedFractScale();
11359     case BuiltinType::ULongFract:
11360     case BuiltinType::SatULongFract:
11361       return Target.getUnsignedLongFractScale();
11362   }
11363 }
11364 
11365 unsigned char ASTContext::getFixedPointIBits(QualType Ty) const {
11366   assert(Ty->isFixedPointType());
11367 
11368   const TargetInfo &Target = getTargetInfo();
11369   switch (Ty->castAs<BuiltinType>()->getKind()) {
11370     default:
11371       llvm_unreachable("Not a fixed point type!");
11372     case BuiltinType::ShortAccum:
11373     case BuiltinType::SatShortAccum:
11374       return Target.getShortAccumIBits();
11375     case BuiltinType::Accum:
11376     case BuiltinType::SatAccum:
11377       return Target.getAccumIBits();
11378     case BuiltinType::LongAccum:
11379     case BuiltinType::SatLongAccum:
11380       return Target.getLongAccumIBits();
11381     case BuiltinType::UShortAccum:
11382     case BuiltinType::SatUShortAccum:
11383       return Target.getUnsignedShortAccumIBits();
11384     case BuiltinType::UAccum:
11385     case BuiltinType::SatUAccum:
11386       return Target.getUnsignedAccumIBits();
11387     case BuiltinType::ULongAccum:
11388     case BuiltinType::SatULongAccum:
11389       return Target.getUnsignedLongAccumIBits();
11390     case BuiltinType::ShortFract:
11391     case BuiltinType::SatShortFract:
11392     case BuiltinType::Fract:
11393     case BuiltinType::SatFract:
11394     case BuiltinType::LongFract:
11395     case BuiltinType::SatLongFract:
11396     case BuiltinType::UShortFract:
11397     case BuiltinType::SatUShortFract:
11398     case BuiltinType::UFract:
11399     case BuiltinType::SatUFract:
11400     case BuiltinType::ULongFract:
11401     case BuiltinType::SatULongFract:
11402       return 0;
11403   }
11404 }
11405 
11406 llvm::FixedPointSemantics
11407 ASTContext::getFixedPointSemantics(QualType Ty) const {
11408   assert((Ty->isFixedPointType() || Ty->isIntegerType()) &&
11409          "Can only get the fixed point semantics for a "
11410          "fixed point or integer type.");
11411   if (Ty->isIntegerType())
11412     return llvm::FixedPointSemantics::GetIntegerSemantics(
11413         getIntWidth(Ty), Ty->isSignedIntegerType());
11414 
11415   bool isSigned = Ty->isSignedFixedPointType();
11416   return llvm::FixedPointSemantics(
11417       static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned,
11418       Ty->isSaturatedFixedPointType(),
11419       !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding());
11420 }
11421 
11422 llvm::APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const {
11423   assert(Ty->isFixedPointType());
11424   return llvm::APFixedPoint::getMax(getFixedPointSemantics(Ty));
11425 }
11426 
11427 llvm::APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const {
11428   assert(Ty->isFixedPointType());
11429   return llvm::APFixedPoint::getMin(getFixedPointSemantics(Ty));
11430 }
11431 
11432 QualType ASTContext::getCorrespondingSignedFixedPointType(QualType Ty) const {
11433   assert(Ty->isUnsignedFixedPointType() &&
11434          "Expected unsigned fixed point type");
11435 
11436   switch (Ty->castAs<BuiltinType>()->getKind()) {
11437   case BuiltinType::UShortAccum:
11438     return ShortAccumTy;
11439   case BuiltinType::UAccum:
11440     return AccumTy;
11441   case BuiltinType::ULongAccum:
11442     return LongAccumTy;
11443   case BuiltinType::SatUShortAccum:
11444     return SatShortAccumTy;
11445   case BuiltinType::SatUAccum:
11446     return SatAccumTy;
11447   case BuiltinType::SatULongAccum:
11448     return SatLongAccumTy;
11449   case BuiltinType::UShortFract:
11450     return ShortFractTy;
11451   case BuiltinType::UFract:
11452     return FractTy;
11453   case BuiltinType::ULongFract:
11454     return LongFractTy;
11455   case BuiltinType::SatUShortFract:
11456     return SatShortFractTy;
11457   case BuiltinType::SatUFract:
11458     return SatFractTy;
11459   case BuiltinType::SatULongFract:
11460     return SatLongFractTy;
11461   default:
11462     llvm_unreachable("Unexpected unsigned fixed point type");
11463   }
11464 }
11465 
11466 ParsedTargetAttr
11467 ASTContext::filterFunctionTargetAttrs(const TargetAttr *TD) const {
11468   assert(TD != nullptr);
11469   ParsedTargetAttr ParsedAttr = TD->parse();
11470 
11471   ParsedAttr.Features.erase(
11472       llvm::remove_if(ParsedAttr.Features,
11473                       [&](const std::string &Feat) {
11474                         return !Target->isValidFeatureName(
11475                             StringRef{Feat}.substr(1));
11476                       }),
11477       ParsedAttr.Features.end());
11478   return ParsedAttr;
11479 }
11480 
11481 void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
11482                                        const FunctionDecl *FD) const {
11483   if (FD)
11484     getFunctionFeatureMap(FeatureMap, GlobalDecl().getWithDecl(FD));
11485   else
11486     Target->initFeatureMap(FeatureMap, getDiagnostics(),
11487                            Target->getTargetOpts().CPU,
11488                            Target->getTargetOpts().Features);
11489 }
11490 
11491 // Fills in the supplied string map with the set of target features for the
11492 // passed in function.
11493 void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
11494                                        GlobalDecl GD) const {
11495   StringRef TargetCPU = Target->getTargetOpts().CPU;
11496   const FunctionDecl *FD = GD.getDecl()->getAsFunction();
11497   if (const auto *TD = FD->getAttr<TargetAttr>()) {
11498     ParsedTargetAttr ParsedAttr = filterFunctionTargetAttrs(TD);
11499 
11500     // Make a copy of the features as passed on the command line into the
11501     // beginning of the additional features from the function to override.
11502     ParsedAttr.Features.insert(
11503         ParsedAttr.Features.begin(),
11504         Target->getTargetOpts().FeaturesAsWritten.begin(),
11505         Target->getTargetOpts().FeaturesAsWritten.end());
11506 
11507     if (ParsedAttr.Architecture != "" &&
11508         Target->isValidCPUName(ParsedAttr.Architecture))
11509       TargetCPU = ParsedAttr.Architecture;
11510 
11511     // Now populate the feature map, first with the TargetCPU which is either
11512     // the default or a new one from the target attribute string. Then we'll use
11513     // the passed in features (FeaturesAsWritten) along with the new ones from
11514     // the attribute.
11515     Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU,
11516                            ParsedAttr.Features);
11517   } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) {
11518     llvm::SmallVector<StringRef, 32> FeaturesTmp;
11519     Target->getCPUSpecificCPUDispatchFeatures(
11520         SD->getCPUName(GD.getMultiVersionIndex())->getName(), FeaturesTmp);
11521     std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end());
11522     Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
11523   } else {
11524     FeatureMap = Target->getTargetOpts().FeatureMap;
11525   }
11526 }
11527 
11528 OMPTraitInfo &ASTContext::getNewOMPTraitInfo() {
11529   OMPTraitInfoVector.emplace_back(new OMPTraitInfo());
11530   return *OMPTraitInfoVector.back();
11531 }
11532 
11533 const StreamingDiagnostic &clang::
11534 operator<<(const StreamingDiagnostic &DB,
11535            const ASTContext::SectionInfo &Section) {
11536   if (Section.Decl)
11537     return DB << Section.Decl;
11538   return DB << "a prior #pragma section";
11539 }
11540 
11541 bool ASTContext::mayExternalizeStaticVar(const Decl *D) const {
11542   bool IsStaticVar =
11543       isa<VarDecl>(D) && cast<VarDecl>(D)->getStorageClass() == SC_Static;
11544   bool IsExplicitDeviceVar = (D->hasAttr<CUDADeviceAttr>() &&
11545                               !D->getAttr<CUDADeviceAttr>()->isImplicit()) ||
11546                              (D->hasAttr<CUDAConstantAttr>() &&
11547                               !D->getAttr<CUDAConstantAttr>()->isImplicit());
11548   // CUDA/HIP: static managed variables need to be externalized since it is
11549   // a declaration in IR, therefore cannot have internal linkage.
11550   return IsStaticVar &&
11551          (D->hasAttr<HIPManagedAttr>() || IsExplicitDeviceVar);
11552 }
11553 
11554 bool ASTContext::shouldExternalizeStaticVar(const Decl *D) const {
11555   return mayExternalizeStaticVar(D) &&
11556          (D->hasAttr<HIPManagedAttr>() ||
11557           CUDAStaticDeviceVarReferencedByHost.count(cast<VarDecl>(D)));
11558 }
11559 
11560 StringRef ASTContext::getCUIDHash() const {
11561   if (!CUIDHash.empty())
11562     return CUIDHash;
11563   if (LangOpts.CUID.empty())
11564     return StringRef();
11565   CUIDHash = llvm::utohexstr(llvm::MD5Hash(LangOpts.CUID), /*LowerCase=*/true);
11566   return CUIDHash;
11567 }
11568