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