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