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,
105   Float16Rank,
106   HalfRank,
107   FloatRank,
108   DoubleRank,
109   LongDoubleRank,
110   Float128Rank,
111   Ibm128Rank
112 };
113 
114 /// \returns location that is relevant when searching for Doc comments related
115 /// to \p D.
116 static SourceLocation getDeclLocForCommentSearch(const Decl *D,
117                                                  SourceManager &SourceMgr) {
118   assert(D);
119 
120   // User can not attach documentation to implicit declarations.
121   if (D->isImplicit())
122     return {};
123 
124   // User can not attach documentation to implicit instantiations.
125   if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
126     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
127       return {};
128   }
129 
130   if (const auto *VD = dyn_cast<VarDecl>(D)) {
131     if (VD->isStaticDataMember() &&
132         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
133       return {};
134   }
135 
136   if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) {
137     if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
138       return {};
139   }
140 
141   if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
142     TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
143     if (TSK == TSK_ImplicitInstantiation ||
144         TSK == TSK_Undeclared)
145       return {};
146   }
147 
148   if (const auto *ED = dyn_cast<EnumDecl>(D)) {
149     if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
150       return {};
151   }
152   if (const auto *TD = dyn_cast<TagDecl>(D)) {
153     // When tag declaration (but not definition!) is part of the
154     // decl-specifier-seq of some other declaration, it doesn't get comment
155     if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
156       return {};
157   }
158   // TODO: handle comments for function parameters properly.
159   if (isa<ParmVarDecl>(D))
160     return {};
161 
162   // TODO: we could look up template parameter documentation in the template
163   // documentation.
164   if (isa<TemplateTypeParmDecl>(D) ||
165       isa<NonTypeTemplateParmDecl>(D) ||
166       isa<TemplateTemplateParmDecl>(D))
167     return {};
168 
169   // Find declaration location.
170   // For Objective-C declarations we generally don't expect to have multiple
171   // declarators, thus use declaration starting location as the "declaration
172   // location".
173   // For all other declarations multiple declarators are used quite frequently,
174   // so we use the location of the identifier as the "declaration location".
175   if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
176       isa<ObjCPropertyDecl>(D) ||
177       isa<RedeclarableTemplateDecl>(D) ||
178       isa<ClassTemplateSpecializationDecl>(D) ||
179       // Allow association with Y across {} in `typedef struct X {} Y`.
180       isa<TypedefDecl>(D))
181     return D->getBeginLoc();
182 
183   const SourceLocation DeclLoc = D->getLocation();
184   if (DeclLoc.isMacroID()) {
185     if (isa<TypedefDecl>(D)) {
186       // If location of the typedef name is in a macro, it is because being
187       // declared via a macro. Try using declaration's starting location as
188       // the "declaration location".
189       return D->getBeginLoc();
190     }
191 
192     if (const auto *TD = dyn_cast<TagDecl>(D)) {
193       // If location of the tag decl is inside a macro, but the spelling of
194       // the tag name comes from a macro argument, it looks like a special
195       // macro like NS_ENUM is being used to define the tag decl.  In that
196       // case, adjust the source location to the expansion loc so that we can
197       // attach the comment to the tag decl.
198       if (SourceMgr.isMacroArgExpansion(DeclLoc) && TD->isCompleteDefinition())
199         return SourceMgr.getExpansionLoc(DeclLoc);
200     }
201   }
202 
203   return DeclLoc;
204 }
205 
206 RawComment *ASTContext::getRawCommentForDeclNoCacheImpl(
207     const Decl *D, const SourceLocation RepresentativeLocForDecl,
208     const std::map<unsigned, RawComment *> &CommentsInTheFile) const {
209   // If the declaration doesn't map directly to a location in a file, we
210   // can't find the comment.
211   if (RepresentativeLocForDecl.isInvalid() ||
212       !RepresentativeLocForDecl.isFileID())
213     return nullptr;
214 
215   // If there are no comments anywhere, we won't find anything.
216   if (CommentsInTheFile.empty())
217     return nullptr;
218 
219   // Decompose the location for the declaration and find the beginning of the
220   // file buffer.
221   const std::pair<FileID, unsigned> DeclLocDecomp =
222       SourceMgr.getDecomposedLoc(RepresentativeLocForDecl);
223 
224   // Slow path.
225   auto OffsetCommentBehindDecl =
226       CommentsInTheFile.lower_bound(DeclLocDecomp.second);
227 
228   // First check whether we have a trailing comment.
229   if (OffsetCommentBehindDecl != CommentsInTheFile.end()) {
230     RawComment *CommentBehindDecl = OffsetCommentBehindDecl->second;
231     if ((CommentBehindDecl->isDocumentation() ||
232          LangOpts.CommentOpts.ParseAllComments) &&
233         CommentBehindDecl->isTrailingComment() &&
234         (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
235          isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
236 
237       // Check that Doxygen trailing comment comes after the declaration, starts
238       // on the same line and in the same file as the declaration.
239       if (SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second) ==
240           Comments.getCommentBeginLine(CommentBehindDecl, DeclLocDecomp.first,
241                                        OffsetCommentBehindDecl->first)) {
242         return CommentBehindDecl;
243       }
244     }
245   }
246 
247   // The comment just after the declaration was not a trailing comment.
248   // Let's look at the previous comment.
249   if (OffsetCommentBehindDecl == CommentsInTheFile.begin())
250     return nullptr;
251 
252   auto OffsetCommentBeforeDecl = --OffsetCommentBehindDecl;
253   RawComment *CommentBeforeDecl = OffsetCommentBeforeDecl->second;
254 
255   // Check that we actually have a non-member Doxygen comment.
256   if (!(CommentBeforeDecl->isDocumentation() ||
257         LangOpts.CommentOpts.ParseAllComments) ||
258       CommentBeforeDecl->isTrailingComment())
259     return nullptr;
260 
261   // Decompose the end of the comment.
262   const unsigned CommentEndOffset =
263       Comments.getCommentEndOffset(CommentBeforeDecl);
264 
265   // Get the corresponding buffer.
266   bool Invalid = false;
267   const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
268                                                &Invalid).data();
269   if (Invalid)
270     return nullptr;
271 
272   // Extract text between the comment and declaration.
273   StringRef Text(Buffer + CommentEndOffset,
274                  DeclLocDecomp.second - CommentEndOffset);
275 
276   // There should be no other declarations or preprocessor directives between
277   // comment and declaration.
278   if (Text.find_first_of(";{}#@") != StringRef::npos)
279     return nullptr;
280 
281   return CommentBeforeDecl;
282 }
283 
284 RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
285   const SourceLocation DeclLoc = getDeclLocForCommentSearch(D, SourceMgr);
286 
287   // If the declaration doesn't map directly to a location in a file, we
288   // can't find the comment.
289   if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
290     return nullptr;
291 
292   if (ExternalSource && !CommentsLoaded) {
293     ExternalSource->ReadComments();
294     CommentsLoaded = true;
295   }
296 
297   if (Comments.empty())
298     return nullptr;
299 
300   const FileID File = SourceMgr.getDecomposedLoc(DeclLoc).first;
301   const auto CommentsInThisFile = Comments.getCommentsInFile(File);
302   if (!CommentsInThisFile || CommentsInThisFile->empty())
303     return nullptr;
304 
305   return getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile);
306 }
307 
308 void ASTContext::addComment(const RawComment &RC) {
309   assert(LangOpts.RetainCommentsFromSystemHeaders ||
310          !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin()));
311   Comments.addComment(RC, LangOpts.CommentOpts, BumpAlloc);
312 }
313 
314 /// If we have a 'templated' declaration for a template, adjust 'D' to
315 /// refer to the actual template.
316 /// If we have an implicit instantiation, adjust 'D' to refer to template.
317 static const Decl &adjustDeclToTemplate(const Decl &D) {
318   if (const auto *FD = dyn_cast<FunctionDecl>(&D)) {
319     // Is this function declaration part of a function template?
320     if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
321       return *FTD;
322 
323     // Nothing to do if function is not an implicit instantiation.
324     if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
325       return D;
326 
327     // Function is an implicit instantiation of a function template?
328     if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
329       return *FTD;
330 
331     // Function is instantiated from a member definition of a class template?
332     if (const FunctionDecl *MemberDecl =
333             FD->getInstantiatedFromMemberFunction())
334       return *MemberDecl;
335 
336     return D;
337   }
338   if (const auto *VD = dyn_cast<VarDecl>(&D)) {
339     // Static data member is instantiated from a member definition of a class
340     // template?
341     if (VD->isStaticDataMember())
342       if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
343         return *MemberDecl;
344 
345     return D;
346   }
347   if (const auto *CRD = dyn_cast<CXXRecordDecl>(&D)) {
348     // Is this class declaration part of a class template?
349     if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
350       return *CTD;
351 
352     // Class is an implicit instantiation of a class template or partial
353     // specialization?
354     if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
355       if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
356         return D;
357       llvm::PointerUnion<ClassTemplateDecl *,
358                          ClassTemplatePartialSpecializationDecl *>
359           PU = CTSD->getSpecializedTemplateOrPartial();
360       return PU.is<ClassTemplateDecl *>()
361                  ? *static_cast<const Decl *>(PU.get<ClassTemplateDecl *>())
362                  : *static_cast<const Decl *>(
363                        PU.get<ClassTemplatePartialSpecializationDecl *>());
364     }
365 
366     // Class is instantiated from a member definition of a class template?
367     if (const MemberSpecializationInfo *Info =
368             CRD->getMemberSpecializationInfo())
369       return *Info->getInstantiatedFrom();
370 
371     return D;
372   }
373   if (const auto *ED = dyn_cast<EnumDecl>(&D)) {
374     // Enum is instantiated from a member definition of a class template?
375     if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
376       return *MemberDecl;
377 
378     return D;
379   }
380   // FIXME: Adjust alias templates?
381   return D;
382 }
383 
384 const RawComment *ASTContext::getRawCommentForAnyRedecl(
385                                                 const Decl *D,
386                                                 const Decl **OriginalDecl) const {
387   if (!D) {
388     if (OriginalDecl)
389       OriginalDecl = nullptr;
390     return nullptr;
391   }
392 
393   D = &adjustDeclToTemplate(*D);
394 
395   // Any comment directly attached to D?
396   {
397     auto DeclComment = DeclRawComments.find(D);
398     if (DeclComment != DeclRawComments.end()) {
399       if (OriginalDecl)
400         *OriginalDecl = D;
401       return DeclComment->second;
402     }
403   }
404 
405   // Any comment attached to any redeclaration of D?
406   const Decl *CanonicalD = D->getCanonicalDecl();
407   if (!CanonicalD)
408     return nullptr;
409 
410   {
411     auto RedeclComment = RedeclChainComments.find(CanonicalD);
412     if (RedeclComment != RedeclChainComments.end()) {
413       if (OriginalDecl)
414         *OriginalDecl = RedeclComment->second;
415       auto CommentAtRedecl = DeclRawComments.find(RedeclComment->second);
416       assert(CommentAtRedecl != DeclRawComments.end() &&
417              "This decl is supposed to have comment attached.");
418       return CommentAtRedecl->second;
419     }
420   }
421 
422   // Any redeclarations of D that we haven't checked for comments yet?
423   // We can't use DenseMap::iterator directly since it'd get invalid.
424   auto LastCheckedRedecl = [this, CanonicalD]() -> const Decl * {
425     auto LookupRes = CommentlessRedeclChains.find(CanonicalD);
426     if (LookupRes != CommentlessRedeclChains.end())
427       return LookupRes->second;
428     return nullptr;
429   }();
430 
431   for (const auto Redecl : D->redecls()) {
432     assert(Redecl);
433     // Skip all redeclarations that have been checked previously.
434     if (LastCheckedRedecl) {
435       if (LastCheckedRedecl == Redecl) {
436         LastCheckedRedecl = nullptr;
437       }
438       continue;
439     }
440     const RawComment *RedeclComment = getRawCommentForDeclNoCache(Redecl);
441     if (RedeclComment) {
442       cacheRawCommentForDecl(*Redecl, *RedeclComment);
443       if (OriginalDecl)
444         *OriginalDecl = Redecl;
445       return RedeclComment;
446     }
447     CommentlessRedeclChains[CanonicalD] = Redecl;
448   }
449 
450   if (OriginalDecl)
451     *OriginalDecl = nullptr;
452   return nullptr;
453 }
454 
455 void ASTContext::cacheRawCommentForDecl(const Decl &OriginalD,
456                                         const RawComment &Comment) const {
457   assert(Comment.isDocumentation() || LangOpts.CommentOpts.ParseAllComments);
458   DeclRawComments.try_emplace(&OriginalD, &Comment);
459   const Decl *const CanonicalDecl = OriginalD.getCanonicalDecl();
460   RedeclChainComments.try_emplace(CanonicalDecl, &OriginalD);
461   CommentlessRedeclChains.erase(CanonicalDecl);
462 }
463 
464 static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
465                    SmallVectorImpl<const NamedDecl *> &Redeclared) {
466   const DeclContext *DC = ObjCMethod->getDeclContext();
467   if (const auto *IMD = dyn_cast<ObjCImplDecl>(DC)) {
468     const ObjCInterfaceDecl *ID = IMD->getClassInterface();
469     if (!ID)
470       return;
471     // Add redeclared method here.
472     for (const auto *Ext : ID->known_extensions()) {
473       if (ObjCMethodDecl *RedeclaredMethod =
474             Ext->getMethod(ObjCMethod->getSelector(),
475                                   ObjCMethod->isInstanceMethod()))
476         Redeclared.push_back(RedeclaredMethod);
477     }
478   }
479 }
480 
481 void ASTContext::attachCommentsToJustParsedDecls(ArrayRef<Decl *> Decls,
482                                                  const Preprocessor *PP) {
483   if (Comments.empty() || Decls.empty())
484     return;
485 
486   FileID File;
487   for (Decl *D : Decls) {
488     SourceLocation Loc = D->getLocation();
489     if (Loc.isValid()) {
490       // See if there are any new comments that are not attached to a decl.
491       // The location doesn't have to be precise - we care only about the file.
492       File = SourceMgr.getDecomposedLoc(Loc).first;
493       break;
494     }
495   }
496 
497   if (File.isInvalid())
498     return;
499 
500   auto CommentsInThisFile = Comments.getCommentsInFile(File);
501   if (!CommentsInThisFile || CommentsInThisFile->empty() ||
502       CommentsInThisFile->rbegin()->second->isAttached())
503     return;
504 
505   // There is at least one comment not attached to a decl.
506   // Maybe it should be attached to one of Decls?
507   //
508   // Note that this way we pick up not only comments that precede the
509   // declaration, but also comments that *follow* the declaration -- thanks to
510   // the lookahead in the lexer: we've consumed the semicolon and looked
511   // ahead through comments.
512 
513   for (const Decl *D : Decls) {
514     assert(D);
515     if (D->isInvalidDecl())
516       continue;
517 
518     D = &adjustDeclToTemplate(*D);
519 
520     const SourceLocation DeclLoc = getDeclLocForCommentSearch(D, SourceMgr);
521 
522     if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
523       continue;
524 
525     if (DeclRawComments.count(D) > 0)
526       continue;
527 
528     if (RawComment *const DocComment =
529             getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile)) {
530       cacheRawCommentForDecl(*D, *DocComment);
531       comments::FullComment *FC = DocComment->parse(*this, PP, D);
532       ParsedComments[D->getCanonicalDecl()] = FC;
533     }
534   }
535 }
536 
537 comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
538                                                     const Decl *D) const {
539   auto *ThisDeclInfo = new (*this) comments::DeclInfo;
540   ThisDeclInfo->CommentDecl = D;
541   ThisDeclInfo->IsFilled = false;
542   ThisDeclInfo->fill();
543   ThisDeclInfo->CommentDecl = FC->getDecl();
544   if (!ThisDeclInfo->TemplateParameters)
545     ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
546   comments::FullComment *CFC =
547     new (*this) comments::FullComment(FC->getBlocks(),
548                                       ThisDeclInfo);
549   return CFC;
550 }
551 
552 comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
553   const RawComment *RC = getRawCommentForDeclNoCache(D);
554   return RC ? RC->parse(*this, nullptr, D) : nullptr;
555 }
556 
557 comments::FullComment *ASTContext::getCommentForDecl(
558                                               const Decl *D,
559                                               const Preprocessor *PP) const {
560   if (!D || D->isInvalidDecl())
561     return nullptr;
562   D = &adjustDeclToTemplate(*D);
563 
564   const Decl *Canonical = D->getCanonicalDecl();
565   llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
566       ParsedComments.find(Canonical);
567 
568   if (Pos != ParsedComments.end()) {
569     if (Canonical != D) {
570       comments::FullComment *FC = Pos->second;
571       comments::FullComment *CFC = cloneFullComment(FC, D);
572       return CFC;
573     }
574     return Pos->second;
575   }
576 
577   const Decl *OriginalDecl = nullptr;
578 
579   const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
580   if (!RC) {
581     if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
582       SmallVector<const NamedDecl*, 8> Overridden;
583       const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
584       if (OMD && OMD->isPropertyAccessor())
585         if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
586           if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
587             return cloneFullComment(FC, D);
588       if (OMD)
589         addRedeclaredMethods(OMD, Overridden);
590       getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
591       for (unsigned i = 0, e = Overridden.size(); i < e; i++)
592         if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
593           return cloneFullComment(FC, D);
594     }
595     else if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
596       // Attach any tag type's documentation to its typedef if latter
597       // does not have one of its own.
598       QualType QT = TD->getUnderlyingType();
599       if (const auto *TT = QT->getAs<TagType>())
600         if (const Decl *TD = TT->getDecl())
601           if (comments::FullComment *FC = getCommentForDecl(TD, PP))
602             return cloneFullComment(FC, D);
603     }
604     else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
605       while (IC->getSuperClass()) {
606         IC = IC->getSuperClass();
607         if (comments::FullComment *FC = getCommentForDecl(IC, PP))
608           return cloneFullComment(FC, D);
609       }
610     }
611     else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(D)) {
612       if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
613         if (comments::FullComment *FC = getCommentForDecl(IC, PP))
614           return cloneFullComment(FC, D);
615     }
616     else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
617       if (!(RD = RD->getDefinition()))
618         return nullptr;
619       // Check non-virtual bases.
620       for (const auto &I : RD->bases()) {
621         if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
622           continue;
623         QualType Ty = I.getType();
624         if (Ty.isNull())
625           continue;
626         if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
627           if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
628             continue;
629 
630           if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
631             return cloneFullComment(FC, D);
632         }
633       }
634       // Check virtual bases.
635       for (const auto &I : RD->vbases()) {
636         if (I.getAccessSpecifier() != AS_public)
637           continue;
638         QualType Ty = I.getType();
639         if (Ty.isNull())
640           continue;
641         if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
642           if (!(VirtualBase= VirtualBase->getDefinition()))
643             continue;
644           if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
645             return cloneFullComment(FC, D);
646         }
647       }
648     }
649     return nullptr;
650   }
651 
652   // If the RawComment was attached to other redeclaration of this Decl, we
653   // should parse the comment in context of that other Decl.  This is important
654   // because comments can contain references to parameter names which can be
655   // different across redeclarations.
656   if (D != OriginalDecl && OriginalDecl)
657     return getCommentForDecl(OriginalDecl, PP);
658 
659   comments::FullComment *FC = RC->parse(*this, PP, D);
660   ParsedComments[Canonical] = FC;
661   return FC;
662 }
663 
664 void
665 ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
666                                                    const ASTContext &C,
667                                                TemplateTemplateParmDecl *Parm) {
668   ID.AddInteger(Parm->getDepth());
669   ID.AddInteger(Parm->getPosition());
670   ID.AddBoolean(Parm->isParameterPack());
671 
672   TemplateParameterList *Params = Parm->getTemplateParameters();
673   ID.AddInteger(Params->size());
674   for (TemplateParameterList::const_iterator P = Params->begin(),
675                                           PEnd = Params->end();
676        P != PEnd; ++P) {
677     if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
678       ID.AddInteger(0);
679       ID.AddBoolean(TTP->isParameterPack());
680       const TypeConstraint *TC = TTP->getTypeConstraint();
681       ID.AddBoolean(TC != nullptr);
682       if (TC)
683         TC->getImmediatelyDeclaredConstraint()->Profile(ID, C,
684                                                         /*Canonical=*/true);
685       if (TTP->isExpandedParameterPack()) {
686         ID.AddBoolean(true);
687         ID.AddInteger(TTP->getNumExpansionParameters());
688       } else
689         ID.AddBoolean(false);
690       continue;
691     }
692 
693     if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
694       ID.AddInteger(1);
695       ID.AddBoolean(NTTP->isParameterPack());
696       ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
697       if (NTTP->isExpandedParameterPack()) {
698         ID.AddBoolean(true);
699         ID.AddInteger(NTTP->getNumExpansionTypes());
700         for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
701           QualType T = NTTP->getExpansionType(I);
702           ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
703         }
704       } else
705         ID.AddBoolean(false);
706       continue;
707     }
708 
709     auto *TTP = cast<TemplateTemplateParmDecl>(*P);
710     ID.AddInteger(2);
711     Profile(ID, C, TTP);
712   }
713   Expr *RequiresClause = Parm->getTemplateParameters()->getRequiresClause();
714   ID.AddBoolean(RequiresClause != nullptr);
715   if (RequiresClause)
716     RequiresClause->Profile(ID, C, /*Canonical=*/true);
717 }
718 
719 static Expr *
720 canonicalizeImmediatelyDeclaredConstraint(const ASTContext &C, Expr *IDC,
721                                           QualType ConstrainedType) {
722   // This is a bit ugly - we need to form a new immediately-declared
723   // constraint that references the new parameter; this would ideally
724   // require semantic analysis (e.g. template<C T> struct S {}; - the
725   // converted arguments of C<T> could be an argument pack if C is
726   // declared as template<typename... T> concept C = ...).
727   // We don't have semantic analysis here so we dig deep into the
728   // ready-made constraint expr and change the thing manually.
729   ConceptSpecializationExpr *CSE;
730   if (const auto *Fold = dyn_cast<CXXFoldExpr>(IDC))
731     CSE = cast<ConceptSpecializationExpr>(Fold->getLHS());
732   else
733     CSE = cast<ConceptSpecializationExpr>(IDC);
734   ArrayRef<TemplateArgument> OldConverted = CSE->getTemplateArguments();
735   SmallVector<TemplateArgument, 3> NewConverted;
736   NewConverted.reserve(OldConverted.size());
737   if (OldConverted.front().getKind() == TemplateArgument::Pack) {
738     // The case:
739     // template<typename... T> concept C = true;
740     // template<C<int> T> struct S; -> constraint is C<{T, int}>
741     NewConverted.push_back(ConstrainedType);
742     llvm::append_range(NewConverted,
743                        OldConverted.front().pack_elements().drop_front(1));
744     TemplateArgument NewPack(NewConverted);
745 
746     NewConverted.clear();
747     NewConverted.push_back(NewPack);
748     assert(OldConverted.size() == 1 &&
749            "Template parameter pack should be the last parameter");
750   } else {
751     assert(OldConverted.front().getKind() == TemplateArgument::Type &&
752            "Unexpected first argument kind for immediately-declared "
753            "constraint");
754     NewConverted.push_back(ConstrainedType);
755     llvm::append_range(NewConverted, OldConverted.drop_front(1));
756   }
757   Expr *NewIDC = ConceptSpecializationExpr::Create(
758       C, CSE->getNamedConcept(), NewConverted, nullptr,
759       CSE->isInstantiationDependent(), CSE->containsUnexpandedParameterPack());
760 
761   if (auto *OrigFold = dyn_cast<CXXFoldExpr>(IDC))
762     NewIDC = new (C) CXXFoldExpr(
763         OrigFold->getType(), /*Callee*/nullptr, SourceLocation(), NewIDC,
764         BinaryOperatorKind::BO_LAnd, SourceLocation(), /*RHS=*/nullptr,
765         SourceLocation(), /*NumExpansions=*/None);
766   return NewIDC;
767 }
768 
769 TemplateTemplateParmDecl *
770 ASTContext::getCanonicalTemplateTemplateParmDecl(
771                                           TemplateTemplateParmDecl *TTP) const {
772   // Check if we already have a canonical template template parameter.
773   llvm::FoldingSetNodeID ID;
774   CanonicalTemplateTemplateParm::Profile(ID, *this, TTP);
775   void *InsertPos = nullptr;
776   CanonicalTemplateTemplateParm *Canonical
777     = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
778   if (Canonical)
779     return Canonical->getParam();
780 
781   // Build a canonical template parameter list.
782   TemplateParameterList *Params = TTP->getTemplateParameters();
783   SmallVector<NamedDecl *, 4> CanonParams;
784   CanonParams.reserve(Params->size());
785   for (TemplateParameterList::const_iterator P = Params->begin(),
786                                           PEnd = Params->end();
787        P != PEnd; ++P) {
788     if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
789       TemplateTypeParmDecl *NewTTP = TemplateTypeParmDecl::Create(*this,
790           getTranslationUnitDecl(), SourceLocation(), SourceLocation(),
791           TTP->getDepth(), TTP->getIndex(), nullptr, false,
792           TTP->isParameterPack(), TTP->hasTypeConstraint(),
793           TTP->isExpandedParameterPack() ?
794           llvm::Optional<unsigned>(TTP->getNumExpansionParameters()) : None);
795       if (const auto *TC = TTP->getTypeConstraint()) {
796         QualType ParamAsArgument(NewTTP->getTypeForDecl(), 0);
797         Expr *NewIDC = canonicalizeImmediatelyDeclaredConstraint(
798                 *this, TC->getImmediatelyDeclaredConstraint(),
799                 ParamAsArgument);
800         TemplateArgumentListInfo CanonArgsAsWritten;
801         if (auto *Args = TC->getTemplateArgsAsWritten())
802           for (const auto &ArgLoc : Args->arguments())
803             CanonArgsAsWritten.addArgument(
804                 TemplateArgumentLoc(ArgLoc.getArgument(),
805                                     TemplateArgumentLocInfo()));
806         NewTTP->setTypeConstraint(
807             NestedNameSpecifierLoc(),
808             DeclarationNameInfo(TC->getNamedConcept()->getDeclName(),
809                                 SourceLocation()), /*FoundDecl=*/nullptr,
810             // Actually canonicalizing a TemplateArgumentLoc is difficult so we
811             // simply omit the ArgsAsWritten
812             TC->getNamedConcept(), /*ArgsAsWritten=*/nullptr, NewIDC);
813       }
814       CanonParams.push_back(NewTTP);
815     } else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
816       QualType T = getCanonicalType(NTTP->getType());
817       TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
818       NonTypeTemplateParmDecl *Param;
819       if (NTTP->isExpandedParameterPack()) {
820         SmallVector<QualType, 2> ExpandedTypes;
821         SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
822         for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
823           ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
824           ExpandedTInfos.push_back(
825                                 getTrivialTypeSourceInfo(ExpandedTypes.back()));
826         }
827 
828         Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
829                                                 SourceLocation(),
830                                                 SourceLocation(),
831                                                 NTTP->getDepth(),
832                                                 NTTP->getPosition(), nullptr,
833                                                 T,
834                                                 TInfo,
835                                                 ExpandedTypes,
836                                                 ExpandedTInfos);
837       } else {
838         Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
839                                                 SourceLocation(),
840                                                 SourceLocation(),
841                                                 NTTP->getDepth(),
842                                                 NTTP->getPosition(), nullptr,
843                                                 T,
844                                                 NTTP->isParameterPack(),
845                                                 TInfo);
846       }
847       if (AutoType *AT = T->getContainedAutoType()) {
848         if (AT->isConstrained()) {
849           Param->setPlaceholderTypeConstraint(
850               canonicalizeImmediatelyDeclaredConstraint(
851                   *this, NTTP->getPlaceholderTypeConstraint(), T));
852         }
853       }
854       CanonParams.push_back(Param);
855 
856     } else
857       CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
858                                            cast<TemplateTemplateParmDecl>(*P)));
859   }
860 
861   Expr *CanonRequiresClause = nullptr;
862   if (Expr *RequiresClause = TTP->getTemplateParameters()->getRequiresClause())
863     CanonRequiresClause = RequiresClause;
864 
865   TemplateTemplateParmDecl *CanonTTP
866     = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
867                                        SourceLocation(), TTP->getDepth(),
868                                        TTP->getPosition(),
869                                        TTP->isParameterPack(),
870                                        nullptr,
871                          TemplateParameterList::Create(*this, SourceLocation(),
872                                                        SourceLocation(),
873                                                        CanonParams,
874                                                        SourceLocation(),
875                                                        CanonRequiresClause));
876 
877   // Get the new insert position for the node we care about.
878   Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
879   assert(!Canonical && "Shouldn't be in the map!");
880   (void)Canonical;
881 
882   // Create the canonical template template parameter entry.
883   Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
884   CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
885   return CanonTTP;
886 }
887 
888 TargetCXXABI::Kind ASTContext::getCXXABIKind() const {
889   auto Kind = getTargetInfo().getCXXABI().getKind();
890   return getLangOpts().CXXABI.getValueOr(Kind);
891 }
892 
893 CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
894   if (!LangOpts.CPlusPlus) return nullptr;
895 
896   switch (getCXXABIKind()) {
897   case TargetCXXABI::AppleARM64:
898   case TargetCXXABI::Fuchsia:
899   case TargetCXXABI::GenericARM: // Same as Itanium at this level
900   case TargetCXXABI::iOS:
901   case TargetCXXABI::WatchOS:
902   case TargetCXXABI::GenericAArch64:
903   case TargetCXXABI::GenericMIPS:
904   case TargetCXXABI::GenericItanium:
905   case TargetCXXABI::WebAssembly:
906   case TargetCXXABI::XL:
907     return CreateItaniumCXXABI(*this);
908   case TargetCXXABI::Microsoft:
909     return CreateMicrosoftCXXABI(*this);
910   }
911   llvm_unreachable("Invalid CXXABI type!");
912 }
913 
914 interp::Context &ASTContext::getInterpContext() {
915   if (!InterpContext) {
916     InterpContext.reset(new interp::Context(*this));
917   }
918   return *InterpContext.get();
919 }
920 
921 ParentMapContext &ASTContext::getParentMapContext() {
922   if (!ParentMapCtx)
923     ParentMapCtx.reset(new ParentMapContext(*this));
924   return *ParentMapCtx.get();
925 }
926 
927 static const LangASMap *getAddressSpaceMap(const TargetInfo &T,
928                                            const LangOptions &LOpts) {
929   if (LOpts.FakeAddressSpaceMap) {
930     // The fake address space map must have a distinct entry for each
931     // language-specific address space.
932     static const unsigned FakeAddrSpaceMap[] = {
933         0,  // Default
934         1,  // opencl_global
935         3,  // opencl_local
936         2,  // opencl_constant
937         0,  // opencl_private
938         4,  // opencl_generic
939         5,  // opencl_global_device
940         6,  // opencl_global_host
941         7,  // cuda_device
942         8,  // cuda_constant
943         9,  // cuda_shared
944         1,  // sycl_global
945         5,  // sycl_global_device
946         6,  // sycl_global_host
947         3,  // sycl_local
948         0,  // sycl_private
949         10, // ptr32_sptr
950         11, // ptr32_uptr
951         12  // ptr64
952     };
953     return &FakeAddrSpaceMap;
954   } else {
955     return &T.getAddressSpaceMap();
956   }
957 }
958 
959 static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
960                                           const LangOptions &LangOpts) {
961   switch (LangOpts.getAddressSpaceMapMangling()) {
962   case LangOptions::ASMM_Target:
963     return TI.useAddressSpaceMapMangling();
964   case LangOptions::ASMM_On:
965     return true;
966   case LangOptions::ASMM_Off:
967     return false;
968   }
969   llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
970 }
971 
972 ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
973                        IdentifierTable &idents, SelectorTable &sels,
974                        Builtin::Context &builtins, TranslationUnitKind TUKind)
975     : ConstantArrayTypes(this_(), ConstantArrayTypesLog2InitSize),
976       FunctionProtoTypes(this_(), FunctionProtoTypesLog2InitSize),
977       TemplateSpecializationTypes(this_()),
978       DependentTemplateSpecializationTypes(this_()), AutoTypes(this_()),
979       SubstTemplateTemplateParmPacks(this_()),
980       CanonTemplateTemplateParms(this_()), SourceMgr(SM), LangOpts(LOpts),
981       NoSanitizeL(new NoSanitizeList(LangOpts.NoSanitizeFiles, SM)),
982       XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
983                                         LangOpts.XRayNeverInstrumentFiles,
984                                         LangOpts.XRayAttrListFiles, SM)),
985       ProfList(new ProfileList(LangOpts.ProfileListFiles, SM)),
986       PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
987       BuiltinInfo(builtins), TUKind(TUKind), DeclarationNames(*this),
988       Comments(SM), CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
989       CompCategories(this_()), LastSDM(nullptr, 0) {
990   addTranslationUnitDecl();
991 }
992 
993 void ASTContext::cleanup() {
994   // Release the DenseMaps associated with DeclContext objects.
995   // FIXME: Is this the ideal solution?
996   ReleaseDeclContextMaps();
997 
998   // Call all of the deallocation functions on all of their targets.
999   for (auto &Pair : Deallocations)
1000     (Pair.first)(Pair.second);
1001   Deallocations.clear();
1002 
1003   // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
1004   // because they can contain DenseMaps.
1005   for (llvm::DenseMap<const ObjCContainerDecl*,
1006        const ASTRecordLayout*>::iterator
1007        I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
1008     // Increment in loop to prevent using deallocated memory.
1009     if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
1010       R->Destroy(*this);
1011   ObjCLayouts.clear();
1012 
1013   for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
1014        I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
1015     // Increment in loop to prevent using deallocated memory.
1016     if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
1017       R->Destroy(*this);
1018   }
1019   ASTRecordLayouts.clear();
1020 
1021   for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
1022                                                     AEnd = DeclAttrs.end();
1023        A != AEnd; ++A)
1024     A->second->~AttrVec();
1025   DeclAttrs.clear();
1026 
1027   for (const auto &Value : ModuleInitializers)
1028     Value.second->~PerModuleInitializers();
1029   ModuleInitializers.clear();
1030 }
1031 
1032 ASTContext::~ASTContext() { cleanup(); }
1033 
1034 void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) {
1035   TraversalScope = TopLevelDecls;
1036   getParentMapContext().clear();
1037 }
1038 
1039 void ASTContext::AddDeallocation(void (*Callback)(void *), void *Data) const {
1040   Deallocations.push_back({Callback, Data});
1041 }
1042 
1043 void
1044 ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
1045   ExternalSource = std::move(Source);
1046 }
1047 
1048 void ASTContext::PrintStats() const {
1049   llvm::errs() << "\n*** AST Context Stats:\n";
1050   llvm::errs() << "  " << Types.size() << " types total.\n";
1051 
1052   unsigned counts[] = {
1053 #define TYPE(Name, Parent) 0,
1054 #define ABSTRACT_TYPE(Name, Parent)
1055 #include "clang/AST/TypeNodes.inc"
1056     0 // Extra
1057   };
1058 
1059   for (unsigned i = 0, e = Types.size(); i != e; ++i) {
1060     Type *T = Types[i];
1061     counts[(unsigned)T->getTypeClass()]++;
1062   }
1063 
1064   unsigned Idx = 0;
1065   unsigned TotalBytes = 0;
1066 #define TYPE(Name, Parent)                                              \
1067   if (counts[Idx])                                                      \
1068     llvm::errs() << "    " << counts[Idx] << " " << #Name               \
1069                  << " types, " << sizeof(Name##Type) << " each "        \
1070                  << "(" << counts[Idx] * sizeof(Name##Type)             \
1071                  << " bytes)\n";                                        \
1072   TotalBytes += counts[Idx] * sizeof(Name##Type);                       \
1073   ++Idx;
1074 #define ABSTRACT_TYPE(Name, Parent)
1075 #include "clang/AST/TypeNodes.inc"
1076 
1077   llvm::errs() << "Total bytes = " << TotalBytes << "\n";
1078 
1079   // Implicit special member functions.
1080   llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
1081                << NumImplicitDefaultConstructors
1082                << " implicit default constructors created\n";
1083   llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
1084                << NumImplicitCopyConstructors
1085                << " implicit copy constructors created\n";
1086   if (getLangOpts().CPlusPlus)
1087     llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
1088                  << NumImplicitMoveConstructors
1089                  << " implicit move constructors created\n";
1090   llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
1091                << NumImplicitCopyAssignmentOperators
1092                << " implicit copy assignment operators created\n";
1093   if (getLangOpts().CPlusPlus)
1094     llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
1095                  << NumImplicitMoveAssignmentOperators
1096                  << " implicit move assignment operators created\n";
1097   llvm::errs() << NumImplicitDestructorsDeclared << "/"
1098                << NumImplicitDestructors
1099                << " implicit destructors created\n";
1100 
1101   if (ExternalSource) {
1102     llvm::errs() << "\n";
1103     ExternalSource->PrintStats();
1104   }
1105 
1106   BumpAlloc.PrintStats();
1107 }
1108 
1109 void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
1110                                            bool NotifyListeners) {
1111   if (NotifyListeners)
1112     if (auto *Listener = getASTMutationListener())
1113       Listener->RedefinedHiddenDefinition(ND, M);
1114 
1115   MergedDefModules[cast<NamedDecl>(ND->getCanonicalDecl())].push_back(M);
1116 }
1117 
1118 void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
1119   auto It = MergedDefModules.find(cast<NamedDecl>(ND->getCanonicalDecl()));
1120   if (It == MergedDefModules.end())
1121     return;
1122 
1123   auto &Merged = It->second;
1124   llvm::DenseSet<Module*> Found;
1125   for (Module *&M : Merged)
1126     if (!Found.insert(M).second)
1127       M = nullptr;
1128   llvm::erase_value(Merged, nullptr);
1129 }
1130 
1131 ArrayRef<Module *>
1132 ASTContext::getModulesWithMergedDefinition(const NamedDecl *Def) {
1133   auto MergedIt =
1134       MergedDefModules.find(cast<NamedDecl>(Def->getCanonicalDecl()));
1135   if (MergedIt == MergedDefModules.end())
1136     return None;
1137   return MergedIt->second;
1138 }
1139 
1140 void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
1141   if (LazyInitializers.empty())
1142     return;
1143 
1144   auto *Source = Ctx.getExternalSource();
1145   assert(Source && "lazy initializers but no external source");
1146 
1147   auto LazyInits = std::move(LazyInitializers);
1148   LazyInitializers.clear();
1149 
1150   for (auto ID : LazyInits)
1151     Initializers.push_back(Source->GetExternalDecl(ID));
1152 
1153   assert(LazyInitializers.empty() &&
1154          "GetExternalDecl for lazy module initializer added more inits");
1155 }
1156 
1157 void ASTContext::addModuleInitializer(Module *M, Decl *D) {
1158   // One special case: if we add a module initializer that imports another
1159   // module, and that module's only initializer is an ImportDecl, simplify.
1160   if (const auto *ID = dyn_cast<ImportDecl>(D)) {
1161     auto It = ModuleInitializers.find(ID->getImportedModule());
1162 
1163     // Maybe the ImportDecl does nothing at all. (Common case.)
1164     if (It == ModuleInitializers.end())
1165       return;
1166 
1167     // Maybe the ImportDecl only imports another ImportDecl.
1168     auto &Imported = *It->second;
1169     if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
1170       Imported.resolve(*this);
1171       auto *OnlyDecl = Imported.Initializers.front();
1172       if (isa<ImportDecl>(OnlyDecl))
1173         D = OnlyDecl;
1174     }
1175   }
1176 
1177   auto *&Inits = ModuleInitializers[M];
1178   if (!Inits)
1179     Inits = new (*this) PerModuleInitializers;
1180   Inits->Initializers.push_back(D);
1181 }
1182 
1183 void ASTContext::addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs) {
1184   auto *&Inits = ModuleInitializers[M];
1185   if (!Inits)
1186     Inits = new (*this) PerModuleInitializers;
1187   Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
1188                                  IDs.begin(), IDs.end());
1189 }
1190 
1191 ArrayRef<Decl *> ASTContext::getModuleInitializers(Module *M) {
1192   auto It = ModuleInitializers.find(M);
1193   if (It == ModuleInitializers.end())
1194     return None;
1195 
1196   auto *Inits = It->second;
1197   Inits->resolve(*this);
1198   return Inits->Initializers;
1199 }
1200 
1201 ExternCContextDecl *ASTContext::getExternCContextDecl() const {
1202   if (!ExternCContext)
1203     ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
1204 
1205   return ExternCContext;
1206 }
1207 
1208 BuiltinTemplateDecl *
1209 ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
1210                                      const IdentifierInfo *II) const {
1211   auto *BuiltinTemplate =
1212       BuiltinTemplateDecl::Create(*this, getTranslationUnitDecl(), II, BTK);
1213   BuiltinTemplate->setImplicit();
1214   getTranslationUnitDecl()->addDecl(BuiltinTemplate);
1215 
1216   return BuiltinTemplate;
1217 }
1218 
1219 BuiltinTemplateDecl *
1220 ASTContext::getMakeIntegerSeqDecl() const {
1221   if (!MakeIntegerSeqDecl)
1222     MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq,
1223                                                   getMakeIntegerSeqName());
1224   return MakeIntegerSeqDecl;
1225 }
1226 
1227 BuiltinTemplateDecl *
1228 ASTContext::getTypePackElementDecl() const {
1229   if (!TypePackElementDecl)
1230     TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element,
1231                                                    getTypePackElementName());
1232   return TypePackElementDecl;
1233 }
1234 
1235 RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
1236                                             RecordDecl::TagKind TK) const {
1237   SourceLocation Loc;
1238   RecordDecl *NewDecl;
1239   if (getLangOpts().CPlusPlus)
1240     NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1241                                     Loc, &Idents.get(Name));
1242   else
1243     NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1244                                  &Idents.get(Name));
1245   NewDecl->setImplicit();
1246   NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1247       const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
1248   return NewDecl;
1249 }
1250 
1251 TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
1252                                               StringRef Name) const {
1253   TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
1254   TypedefDecl *NewDecl = TypedefDecl::Create(
1255       const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1256       SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1257   NewDecl->setImplicit();
1258   return NewDecl;
1259 }
1260 
1261 TypedefDecl *ASTContext::getInt128Decl() const {
1262   if (!Int128Decl)
1263     Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
1264   return Int128Decl;
1265 }
1266 
1267 TypedefDecl *ASTContext::getUInt128Decl() const {
1268   if (!UInt128Decl)
1269     UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
1270   return UInt128Decl;
1271 }
1272 
1273 void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
1274   auto *Ty = new (*this, TypeAlignment) BuiltinType(K);
1275   R = CanQualType::CreateUnsafe(QualType(Ty, 0));
1276   Types.push_back(Ty);
1277 }
1278 
1279 void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
1280                                   const TargetInfo *AuxTarget) {
1281   assert((!this->Target || this->Target == &Target) &&
1282          "Incorrect target reinitialization");
1283   assert(VoidTy.isNull() && "Context reinitialized?");
1284 
1285   this->Target = &Target;
1286   this->AuxTarget = AuxTarget;
1287 
1288   ABI.reset(createCXXABI(Target));
1289   AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
1290   AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
1291 
1292   // C99 6.2.5p19.
1293   InitBuiltinType(VoidTy,              BuiltinType::Void);
1294 
1295   // C99 6.2.5p2.
1296   InitBuiltinType(BoolTy,              BuiltinType::Bool);
1297   // C99 6.2.5p3.
1298   if (LangOpts.CharIsSigned)
1299     InitBuiltinType(CharTy,            BuiltinType::Char_S);
1300   else
1301     InitBuiltinType(CharTy,            BuiltinType::Char_U);
1302   // C99 6.2.5p4.
1303   InitBuiltinType(SignedCharTy,        BuiltinType::SChar);
1304   InitBuiltinType(ShortTy,             BuiltinType::Short);
1305   InitBuiltinType(IntTy,               BuiltinType::Int);
1306   InitBuiltinType(LongTy,              BuiltinType::Long);
1307   InitBuiltinType(LongLongTy,          BuiltinType::LongLong);
1308 
1309   // C99 6.2.5p6.
1310   InitBuiltinType(UnsignedCharTy,      BuiltinType::UChar);
1311   InitBuiltinType(UnsignedShortTy,     BuiltinType::UShort);
1312   InitBuiltinType(UnsignedIntTy,       BuiltinType::UInt);
1313   InitBuiltinType(UnsignedLongTy,      BuiltinType::ULong);
1314   InitBuiltinType(UnsignedLongLongTy,  BuiltinType::ULongLong);
1315 
1316   // C99 6.2.5p10.
1317   InitBuiltinType(FloatTy,             BuiltinType::Float);
1318   InitBuiltinType(DoubleTy,            BuiltinType::Double);
1319   InitBuiltinType(LongDoubleTy,        BuiltinType::LongDouble);
1320 
1321   // GNU extension, __float128 for IEEE quadruple precision
1322   InitBuiltinType(Float128Ty,          BuiltinType::Float128);
1323 
1324   // __ibm128 for IBM extended precision
1325   InitBuiltinType(Ibm128Ty, BuiltinType::Ibm128);
1326 
1327   // C11 extension ISO/IEC TS 18661-3
1328   InitBuiltinType(Float16Ty,           BuiltinType::Float16);
1329 
1330   // ISO/IEC JTC1 SC22 WG14 N1169 Extension
1331   InitBuiltinType(ShortAccumTy,            BuiltinType::ShortAccum);
1332   InitBuiltinType(AccumTy,                 BuiltinType::Accum);
1333   InitBuiltinType(LongAccumTy,             BuiltinType::LongAccum);
1334   InitBuiltinType(UnsignedShortAccumTy,    BuiltinType::UShortAccum);
1335   InitBuiltinType(UnsignedAccumTy,         BuiltinType::UAccum);
1336   InitBuiltinType(UnsignedLongAccumTy,     BuiltinType::ULongAccum);
1337   InitBuiltinType(ShortFractTy,            BuiltinType::ShortFract);
1338   InitBuiltinType(FractTy,                 BuiltinType::Fract);
1339   InitBuiltinType(LongFractTy,             BuiltinType::LongFract);
1340   InitBuiltinType(UnsignedShortFractTy,    BuiltinType::UShortFract);
1341   InitBuiltinType(UnsignedFractTy,         BuiltinType::UFract);
1342   InitBuiltinType(UnsignedLongFractTy,     BuiltinType::ULongFract);
1343   InitBuiltinType(SatShortAccumTy,         BuiltinType::SatShortAccum);
1344   InitBuiltinType(SatAccumTy,              BuiltinType::SatAccum);
1345   InitBuiltinType(SatLongAccumTy,          BuiltinType::SatLongAccum);
1346   InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum);
1347   InitBuiltinType(SatUnsignedAccumTy,      BuiltinType::SatUAccum);
1348   InitBuiltinType(SatUnsignedLongAccumTy,  BuiltinType::SatULongAccum);
1349   InitBuiltinType(SatShortFractTy,         BuiltinType::SatShortFract);
1350   InitBuiltinType(SatFractTy,              BuiltinType::SatFract);
1351   InitBuiltinType(SatLongFractTy,          BuiltinType::SatLongFract);
1352   InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract);
1353   InitBuiltinType(SatUnsignedFractTy,      BuiltinType::SatUFract);
1354   InitBuiltinType(SatUnsignedLongFractTy,  BuiltinType::SatULongFract);
1355 
1356   // GNU extension, 128-bit integers.
1357   InitBuiltinType(Int128Ty,            BuiltinType::Int128);
1358   InitBuiltinType(UnsignedInt128Ty,    BuiltinType::UInt128);
1359 
1360   // C++ 3.9.1p5
1361   if (TargetInfo::isTypeSigned(Target.getWCharType()))
1362     InitBuiltinType(WCharTy,           BuiltinType::WChar_S);
1363   else  // -fshort-wchar makes wchar_t be unsigned.
1364     InitBuiltinType(WCharTy,           BuiltinType::WChar_U);
1365   if (LangOpts.CPlusPlus && LangOpts.WChar)
1366     WideCharTy = WCharTy;
1367   else {
1368     // C99 (or C++ using -fno-wchar).
1369     WideCharTy = getFromTargetType(Target.getWCharType());
1370   }
1371 
1372   WIntTy = getFromTargetType(Target.getWIntType());
1373 
1374   // C++20 (proposed)
1375   InitBuiltinType(Char8Ty,              BuiltinType::Char8);
1376 
1377   if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1378     InitBuiltinType(Char16Ty,           BuiltinType::Char16);
1379   else // C99
1380     Char16Ty = getFromTargetType(Target.getChar16Type());
1381 
1382   if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1383     InitBuiltinType(Char32Ty,           BuiltinType::Char32);
1384   else // C99
1385     Char32Ty = getFromTargetType(Target.getChar32Type());
1386 
1387   // Placeholder type for type-dependent expressions whose type is
1388   // completely unknown. No code should ever check a type against
1389   // DependentTy and users should never see it; however, it is here to
1390   // help diagnose failures to properly check for type-dependent
1391   // expressions.
1392   InitBuiltinType(DependentTy,         BuiltinType::Dependent);
1393 
1394   // Placeholder type for functions.
1395   InitBuiltinType(OverloadTy,          BuiltinType::Overload);
1396 
1397   // Placeholder type for bound members.
1398   InitBuiltinType(BoundMemberTy,       BuiltinType::BoundMember);
1399 
1400   // Placeholder type for pseudo-objects.
1401   InitBuiltinType(PseudoObjectTy,      BuiltinType::PseudoObject);
1402 
1403   // "any" type; useful for debugger-like clients.
1404   InitBuiltinType(UnknownAnyTy,        BuiltinType::UnknownAny);
1405 
1406   // Placeholder type for unbridged ARC casts.
1407   InitBuiltinType(ARCUnbridgedCastTy,  BuiltinType::ARCUnbridgedCast);
1408 
1409   // Placeholder type for builtin functions.
1410   InitBuiltinType(BuiltinFnTy,  BuiltinType::BuiltinFn);
1411 
1412   // Placeholder type for OMP array sections.
1413   if (LangOpts.OpenMP) {
1414     InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
1415     InitBuiltinType(OMPArrayShapingTy, BuiltinType::OMPArrayShaping);
1416     InitBuiltinType(OMPIteratorTy, BuiltinType::OMPIterator);
1417   }
1418   if (LangOpts.MatrixTypes)
1419     InitBuiltinType(IncompleteMatrixIdxTy, BuiltinType::IncompleteMatrixIdx);
1420 
1421   // Builtin types for 'id', 'Class', and 'SEL'.
1422   InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1423   InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
1424   InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
1425 
1426   if (LangOpts.OpenCL) {
1427 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1428     InitBuiltinType(SingletonId, BuiltinType::Id);
1429 #include "clang/Basic/OpenCLImageTypes.def"
1430 
1431     InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
1432     InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
1433     InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1434     InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
1435     InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
1436 
1437 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1438     InitBuiltinType(Id##Ty, BuiltinType::Id);
1439 #include "clang/Basic/OpenCLExtensionTypes.def"
1440   }
1441 
1442   if (Target.hasAArch64SVETypes()) {
1443 #define SVE_TYPE(Name, Id, SingletonId) \
1444     InitBuiltinType(SingletonId, BuiltinType::Id);
1445 #include "clang/Basic/AArch64SVEACLETypes.def"
1446   }
1447 
1448   if (Target.getTriple().isPPC64()) {
1449 #define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \
1450       InitBuiltinType(Id##Ty, BuiltinType::Id);
1451 #include "clang/Basic/PPCTypes.def"
1452 #define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \
1453     InitBuiltinType(Id##Ty, BuiltinType::Id);
1454 #include "clang/Basic/PPCTypes.def"
1455   }
1456 
1457   if (Target.hasRISCVVTypes()) {
1458 #define RVV_TYPE(Name, Id, SingletonId)                                        \
1459   InitBuiltinType(SingletonId, BuiltinType::Id);
1460 #include "clang/Basic/RISCVVTypes.def"
1461   }
1462 
1463   // Builtin type for __objc_yes and __objc_no
1464   ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1465                        SignedCharTy : BoolTy);
1466 
1467   ObjCConstantStringType = QualType();
1468 
1469   ObjCSuperType = QualType();
1470 
1471   // void * type
1472   if (LangOpts.OpenCLGenericAddressSpace) {
1473     auto Q = VoidTy.getQualifiers();
1474     Q.setAddressSpace(LangAS::opencl_generic);
1475     VoidPtrTy = getPointerType(getCanonicalType(
1476         getQualifiedType(VoidTy.getUnqualifiedType(), Q)));
1477   } else {
1478     VoidPtrTy = getPointerType(VoidTy);
1479   }
1480 
1481   // nullptr type (C++0x 2.14.7)
1482   InitBuiltinType(NullPtrTy,           BuiltinType::NullPtr);
1483 
1484   // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1485   InitBuiltinType(HalfTy, BuiltinType::Half);
1486 
1487   InitBuiltinType(BFloat16Ty, BuiltinType::BFloat16);
1488 
1489   // Builtin type used to help define __builtin_va_list.
1490   VaListTagDecl = nullptr;
1491 
1492   // MSVC predeclares struct _GUID, and we need it to create MSGuidDecls.
1493   if (LangOpts.MicrosoftExt || LangOpts.Borland) {
1494     MSGuidTagDecl = buildImplicitRecord("_GUID");
1495     getTranslationUnitDecl()->addDecl(MSGuidTagDecl);
1496   }
1497 }
1498 
1499 DiagnosticsEngine &ASTContext::getDiagnostics() const {
1500   return SourceMgr.getDiagnostics();
1501 }
1502 
1503 AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1504   AttrVec *&Result = DeclAttrs[D];
1505   if (!Result) {
1506     void *Mem = Allocate(sizeof(AttrVec));
1507     Result = new (Mem) AttrVec;
1508   }
1509 
1510   return *Result;
1511 }
1512 
1513 /// Erase the attributes corresponding to the given declaration.
1514 void ASTContext::eraseDeclAttrs(const Decl *D) {
1515   llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1516   if (Pos != DeclAttrs.end()) {
1517     Pos->second->~AttrVec();
1518     DeclAttrs.erase(Pos);
1519   }
1520 }
1521 
1522 // FIXME: Remove ?
1523 MemberSpecializationInfo *
1524 ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
1525   assert(Var->isStaticDataMember() && "Not a static data member");
1526   return getTemplateOrSpecializationInfo(Var)
1527       .dyn_cast<MemberSpecializationInfo *>();
1528 }
1529 
1530 ASTContext::TemplateOrSpecializationInfo
1531 ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1532   llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1533       TemplateOrInstantiation.find(Var);
1534   if (Pos == TemplateOrInstantiation.end())
1535     return {};
1536 
1537   return Pos->second;
1538 }
1539 
1540 void
1541 ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
1542                                                 TemplateSpecializationKind TSK,
1543                                           SourceLocation PointOfInstantiation) {
1544   assert(Inst->isStaticDataMember() && "Not a static data member");
1545   assert(Tmpl->isStaticDataMember() && "Not a static data member");
1546   setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1547                                             Tmpl, TSK, PointOfInstantiation));
1548 }
1549 
1550 void
1551 ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1552                                             TemplateOrSpecializationInfo TSI) {
1553   assert(!TemplateOrInstantiation[Inst] &&
1554          "Already noted what the variable was instantiated from");
1555   TemplateOrInstantiation[Inst] = TSI;
1556 }
1557 
1558 NamedDecl *
1559 ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) {
1560   auto Pos = InstantiatedFromUsingDecl.find(UUD);
1561   if (Pos == InstantiatedFromUsingDecl.end())
1562     return nullptr;
1563 
1564   return Pos->second;
1565 }
1566 
1567 void
1568 ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) {
1569   assert((isa<UsingDecl>(Pattern) ||
1570           isa<UnresolvedUsingValueDecl>(Pattern) ||
1571           isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1572          "pattern decl is not a using decl");
1573   assert((isa<UsingDecl>(Inst) ||
1574           isa<UnresolvedUsingValueDecl>(Inst) ||
1575           isa<UnresolvedUsingTypenameDecl>(Inst)) &&
1576          "instantiation did not produce a using decl");
1577   assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1578   InstantiatedFromUsingDecl[Inst] = Pattern;
1579 }
1580 
1581 UsingEnumDecl *
1582 ASTContext::getInstantiatedFromUsingEnumDecl(UsingEnumDecl *UUD) {
1583   auto Pos = InstantiatedFromUsingEnumDecl.find(UUD);
1584   if (Pos == InstantiatedFromUsingEnumDecl.end())
1585     return nullptr;
1586 
1587   return Pos->second;
1588 }
1589 
1590 void ASTContext::setInstantiatedFromUsingEnumDecl(UsingEnumDecl *Inst,
1591                                                   UsingEnumDecl *Pattern) {
1592   assert(!InstantiatedFromUsingEnumDecl[Inst] && "pattern already exists");
1593   InstantiatedFromUsingEnumDecl[Inst] = Pattern;
1594 }
1595 
1596 UsingShadowDecl *
1597 ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1598   llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1599     = InstantiatedFromUsingShadowDecl.find(Inst);
1600   if (Pos == InstantiatedFromUsingShadowDecl.end())
1601     return nullptr;
1602 
1603   return Pos->second;
1604 }
1605 
1606 void
1607 ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1608                                                UsingShadowDecl *Pattern) {
1609   assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1610   InstantiatedFromUsingShadowDecl[Inst] = Pattern;
1611 }
1612 
1613 FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1614   llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1615     = InstantiatedFromUnnamedFieldDecl.find(Field);
1616   if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1617     return nullptr;
1618 
1619   return Pos->second;
1620 }
1621 
1622 void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1623                                                      FieldDecl *Tmpl) {
1624   assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1625   assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1626   assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1627          "Already noted what unnamed field was instantiated from");
1628 
1629   InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1630 }
1631 
1632 ASTContext::overridden_cxx_method_iterator
1633 ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1634   return overridden_methods(Method).begin();
1635 }
1636 
1637 ASTContext::overridden_cxx_method_iterator
1638 ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1639   return overridden_methods(Method).end();
1640 }
1641 
1642 unsigned
1643 ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1644   auto Range = overridden_methods(Method);
1645   return Range.end() - Range.begin();
1646 }
1647 
1648 ASTContext::overridden_method_range
1649 ASTContext::overridden_methods(const CXXMethodDecl *Method) const {
1650   llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1651       OverriddenMethods.find(Method->getCanonicalDecl());
1652   if (Pos == OverriddenMethods.end())
1653     return overridden_method_range(nullptr, nullptr);
1654   return overridden_method_range(Pos->second.begin(), Pos->second.end());
1655 }
1656 
1657 void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1658                                      const CXXMethodDecl *Overridden) {
1659   assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
1660   OverriddenMethods[Method].push_back(Overridden);
1661 }
1662 
1663 void ASTContext::getOverriddenMethods(
1664                       const NamedDecl *D,
1665                       SmallVectorImpl<const NamedDecl *> &Overridden) const {
1666   assert(D);
1667 
1668   if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
1669     Overridden.append(overridden_methods_begin(CXXMethod),
1670                       overridden_methods_end(CXXMethod));
1671     return;
1672   }
1673 
1674   const auto *Method = dyn_cast<ObjCMethodDecl>(D);
1675   if (!Method)
1676     return;
1677 
1678   SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1679   Method->getOverriddenMethods(OverDecls);
1680   Overridden.append(OverDecls.begin(), OverDecls.end());
1681 }
1682 
1683 void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1684   assert(!Import->getNextLocalImport() &&
1685          "Import declaration already in the chain");
1686   assert(!Import->isFromASTFile() && "Non-local import declaration");
1687   if (!FirstLocalImport) {
1688     FirstLocalImport = Import;
1689     LastLocalImport = Import;
1690     return;
1691   }
1692 
1693   LastLocalImport->setNextLocalImport(Import);
1694   LastLocalImport = Import;
1695 }
1696 
1697 //===----------------------------------------------------------------------===//
1698 //                         Type Sizing and Analysis
1699 //===----------------------------------------------------------------------===//
1700 
1701 /// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1702 /// scalar floating point type.
1703 const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
1704   switch (T->castAs<BuiltinType>()->getKind()) {
1705   default:
1706     llvm_unreachable("Not a floating point type!");
1707   case BuiltinType::BFloat16:
1708     return Target->getBFloat16Format();
1709   case BuiltinType::Float16:
1710   case BuiltinType::Half:
1711     return Target->getHalfFormat();
1712   case BuiltinType::Float:      return Target->getFloatFormat();
1713   case BuiltinType::Double:     return Target->getDoubleFormat();
1714   case BuiltinType::Ibm128:
1715     return Target->getIbm128Format();
1716   case BuiltinType::LongDouble:
1717     if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice)
1718       return AuxTarget->getLongDoubleFormat();
1719     return Target->getLongDoubleFormat();
1720   case BuiltinType::Float128:
1721     if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice)
1722       return AuxTarget->getFloat128Format();
1723     return Target->getFloat128Format();
1724   }
1725 }
1726 
1727 CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
1728   unsigned Align = Target->getCharWidth();
1729 
1730   bool UseAlignAttrOnly = false;
1731   if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1732     Align = AlignFromAttr;
1733 
1734     // __attribute__((aligned)) can increase or decrease alignment
1735     // *except* on a struct or struct member, where it only increases
1736     // alignment unless 'packed' is also specified.
1737     //
1738     // It is an error for alignas to decrease alignment, so we can
1739     // ignore that possibility;  Sema should diagnose it.
1740     if (isa<FieldDecl>(D)) {
1741       UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1742         cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1743     } else {
1744       UseAlignAttrOnly = true;
1745     }
1746   }
1747   else if (isa<FieldDecl>(D))
1748       UseAlignAttrOnly =
1749         D->hasAttr<PackedAttr>() ||
1750         cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1751 
1752   // If we're using the align attribute only, just ignore everything
1753   // else about the declaration and its type.
1754   if (UseAlignAttrOnly) {
1755     // do nothing
1756   } else if (const auto *VD = dyn_cast<ValueDecl>(D)) {
1757     QualType T = VD->getType();
1758     if (const auto *RT = T->getAs<ReferenceType>()) {
1759       if (ForAlignof)
1760         T = RT->getPointeeType();
1761       else
1762         T = getPointerType(RT->getPointeeType());
1763     }
1764     QualType BaseT = getBaseElementType(T);
1765     if (T->isFunctionType())
1766       Align = getTypeInfoImpl(T.getTypePtr()).Align;
1767     else if (!BaseT->isIncompleteType()) {
1768       // Adjust alignments of declarations with array type by the
1769       // large-array alignment on the target.
1770       if (const ArrayType *arrayType = getAsArrayType(T)) {
1771         unsigned MinWidth = Target->getLargeArrayMinWidth();
1772         if (!ForAlignof && MinWidth) {
1773           if (isa<VariableArrayType>(arrayType))
1774             Align = std::max(Align, Target->getLargeArrayAlign());
1775           else if (isa<ConstantArrayType>(arrayType) &&
1776                    MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1777             Align = std::max(Align, Target->getLargeArrayAlign());
1778         }
1779       }
1780       Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
1781       if (BaseT.getQualifiers().hasUnaligned())
1782         Align = Target->getCharWidth();
1783       if (const auto *VD = dyn_cast<VarDecl>(D)) {
1784         if (VD->hasGlobalStorage() && !ForAlignof) {
1785           uint64_t TypeSize = getTypeSize(T.getTypePtr());
1786           Align = std::max(Align, getTargetInfo().getMinGlobalAlign(TypeSize));
1787         }
1788       }
1789     }
1790 
1791     // Fields can be subject to extra alignment constraints, like if
1792     // the field is packed, the struct is packed, or the struct has a
1793     // a max-field-alignment constraint (#pragma pack).  So calculate
1794     // the actual alignment of the field within the struct, and then
1795     // (as we're expected to) constrain that by the alignment of the type.
1796     if (const auto *Field = dyn_cast<FieldDecl>(VD)) {
1797       const RecordDecl *Parent = Field->getParent();
1798       // We can only produce a sensible answer if the record is valid.
1799       if (!Parent->isInvalidDecl()) {
1800         const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
1801 
1802         // Start with the record's overall alignment.
1803         unsigned FieldAlign = toBits(Layout.getAlignment());
1804 
1805         // Use the GCD of that and the offset within the record.
1806         uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1807         if (Offset > 0) {
1808           // Alignment is always a power of 2, so the GCD will be a power of 2,
1809           // which means we get to do this crazy thing instead of Euclid's.
1810           uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1811           if (LowBitOfOffset < FieldAlign)
1812             FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1813         }
1814 
1815         Align = std::min(Align, FieldAlign);
1816       }
1817     }
1818   }
1819 
1820   // Some targets have hard limitation on the maximum requestable alignment in
1821   // aligned attribute for static variables.
1822   const unsigned MaxAlignedAttr = getTargetInfo().getMaxAlignedAttribute();
1823   const auto *VD = dyn_cast<VarDecl>(D);
1824   if (MaxAlignedAttr && VD && VD->getStorageClass() == SC_Static)
1825     Align = std::min(Align, MaxAlignedAttr);
1826 
1827   return toCharUnitsFromBits(Align);
1828 }
1829 
1830 CharUnits ASTContext::getExnObjectAlignment() const {
1831   return toCharUnitsFromBits(Target->getExnObjectAlignment());
1832 }
1833 
1834 // getTypeInfoDataSizeInChars - Return the size of a type, in
1835 // chars. If the type is a record, its data size is returned.  This is
1836 // the size of the memcpy that's performed when assigning this type
1837 // using a trivial copy/move assignment operator.
1838 TypeInfoChars ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1839   TypeInfoChars Info = getTypeInfoInChars(T);
1840 
1841   // In C++, objects can sometimes be allocated into the tail padding
1842   // of a base-class subobject.  We decide whether that's possible
1843   // during class layout, so here we can just trust the layout results.
1844   if (getLangOpts().CPlusPlus) {
1845     if (const auto *RT = T->getAs<RecordType>()) {
1846       const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1847       Info.Width = layout.getDataSize();
1848     }
1849   }
1850 
1851   return Info;
1852 }
1853 
1854 /// getConstantArrayInfoInChars - Performing the computation in CharUnits
1855 /// instead of in bits prevents overflowing the uint64_t for some large arrays.
1856 TypeInfoChars
1857 static getConstantArrayInfoInChars(const ASTContext &Context,
1858                                    const ConstantArrayType *CAT) {
1859   TypeInfoChars EltInfo = Context.getTypeInfoInChars(CAT->getElementType());
1860   uint64_t Size = CAT->getSize().getZExtValue();
1861   assert((Size == 0 || static_cast<uint64_t>(EltInfo.Width.getQuantity()) <=
1862               (uint64_t)(-1)/Size) &&
1863          "Overflow in array type char size evaluation");
1864   uint64_t Width = EltInfo.Width.getQuantity() * Size;
1865   unsigned Align = EltInfo.Align.getQuantity();
1866   if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1867       Context.getTargetInfo().getPointerWidth(0) == 64)
1868     Width = llvm::alignTo(Width, Align);
1869   return TypeInfoChars(CharUnits::fromQuantity(Width),
1870                        CharUnits::fromQuantity(Align),
1871                        EltInfo.AlignRequirement);
1872 }
1873 
1874 TypeInfoChars ASTContext::getTypeInfoInChars(const Type *T) const {
1875   if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
1876     return getConstantArrayInfoInChars(*this, CAT);
1877   TypeInfo Info = getTypeInfo(T);
1878   return TypeInfoChars(toCharUnitsFromBits(Info.Width),
1879                        toCharUnitsFromBits(Info.Align), Info.AlignRequirement);
1880 }
1881 
1882 TypeInfoChars ASTContext::getTypeInfoInChars(QualType T) const {
1883   return getTypeInfoInChars(T.getTypePtr());
1884 }
1885 
1886 bool ASTContext::isAlignmentRequired(const Type *T) const {
1887   return getTypeInfo(T).AlignRequirement != AlignRequirementKind::None;
1888 }
1889 
1890 bool ASTContext::isAlignmentRequired(QualType T) const {
1891   return isAlignmentRequired(T.getTypePtr());
1892 }
1893 
1894 unsigned ASTContext::getTypeAlignIfKnown(QualType T,
1895                                          bool NeedsPreferredAlignment) const {
1896   // An alignment on a typedef overrides anything else.
1897   if (const auto *TT = T->getAs<TypedefType>())
1898     if (unsigned Align = TT->getDecl()->getMaxAlignment())
1899       return Align;
1900 
1901   // If we have an (array of) complete type, we're done.
1902   T = getBaseElementType(T);
1903   if (!T->isIncompleteType())
1904     return NeedsPreferredAlignment ? getPreferredTypeAlign(T) : getTypeAlign(T);
1905 
1906   // If we had an array type, its element type might be a typedef
1907   // type with an alignment attribute.
1908   if (const auto *TT = T->getAs<TypedefType>())
1909     if (unsigned Align = TT->getDecl()->getMaxAlignment())
1910       return Align;
1911 
1912   // Otherwise, see if the declaration of the type had an attribute.
1913   if (const auto *TT = T->getAs<TagType>())
1914     return TT->getDecl()->getMaxAlignment();
1915 
1916   return 0;
1917 }
1918 
1919 TypeInfo ASTContext::getTypeInfo(const Type *T) const {
1920   TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1921   if (I != MemoizedTypeInfo.end())
1922     return I->second;
1923 
1924   // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1925   TypeInfo TI = getTypeInfoImpl(T);
1926   MemoizedTypeInfo[T] = TI;
1927   return TI;
1928 }
1929 
1930 /// getTypeInfoImpl - Return the size of the specified type, in bits.  This
1931 /// method does not work on incomplete types.
1932 ///
1933 /// FIXME: Pointers into different addr spaces could have different sizes and
1934 /// alignment requirements: getPointerInfo should take an AddrSpace, this
1935 /// should take a QualType, &c.
1936 TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1937   uint64_t Width = 0;
1938   unsigned Align = 8;
1939   AlignRequirementKind AlignRequirement = AlignRequirementKind::None;
1940   unsigned AS = 0;
1941   switch (T->getTypeClass()) {
1942 #define TYPE(Class, Base)
1943 #define ABSTRACT_TYPE(Class, Base)
1944 #define NON_CANONICAL_TYPE(Class, Base)
1945 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1946 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)                       \
1947   case Type::Class:                                                            \
1948   assert(!T->isDependentType() && "should not see dependent types here");      \
1949   return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
1950 #include "clang/AST/TypeNodes.inc"
1951     llvm_unreachable("Should not see dependent types");
1952 
1953   case Type::FunctionNoProto:
1954   case Type::FunctionProto:
1955     // GCC extension: alignof(function) = 32 bits
1956     Width = 0;
1957     Align = 32;
1958     break;
1959 
1960   case Type::IncompleteArray:
1961   case Type::VariableArray:
1962   case Type::ConstantArray: {
1963     // Model non-constant sized arrays as size zero, but track the alignment.
1964     uint64_t Size = 0;
1965     if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
1966       Size = CAT->getSize().getZExtValue();
1967 
1968     TypeInfo EltInfo = getTypeInfo(cast<ArrayType>(T)->getElementType());
1969     assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
1970            "Overflow in array type bit size evaluation");
1971     Width = EltInfo.Width * Size;
1972     Align = EltInfo.Align;
1973     AlignRequirement = EltInfo.AlignRequirement;
1974     if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1975         getTargetInfo().getPointerWidth(0) == 64)
1976       Width = llvm::alignTo(Width, Align);
1977     break;
1978   }
1979 
1980   case Type::ExtVector:
1981   case Type::Vector: {
1982     const auto *VT = cast<VectorType>(T);
1983     TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1984     Width = VT->isExtVectorBoolType() ? VT->getNumElements()
1985                                       : EltInfo.Width * VT->getNumElements();
1986     // Enforce at least byte alignment.
1987     Align = std::max<unsigned>(8, Width);
1988 
1989     // If the alignment is not a power of 2, round up to the next power of 2.
1990     // This happens for non-power-of-2 length vectors.
1991     if (Align & (Align-1)) {
1992       Align = llvm::NextPowerOf2(Align);
1993       Width = llvm::alignTo(Width, Align);
1994     }
1995     // Adjust the alignment based on the target max.
1996     uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1997     if (TargetVectorAlign && TargetVectorAlign < Align)
1998       Align = TargetVectorAlign;
1999     if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector)
2000       // Adjust the alignment for fixed-length SVE vectors. This is important
2001       // for non-power-of-2 vector lengths.
2002       Align = 128;
2003     else if (VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector)
2004       // Adjust the alignment for fixed-length SVE predicates.
2005       Align = 16;
2006     break;
2007   }
2008 
2009   case Type::ConstantMatrix: {
2010     const auto *MT = cast<ConstantMatrixType>(T);
2011     TypeInfo ElementInfo = getTypeInfo(MT->getElementType());
2012     // The internal layout of a matrix value is implementation defined.
2013     // Initially be ABI compatible with arrays with respect to alignment and
2014     // size.
2015     Width = ElementInfo.Width * MT->getNumRows() * MT->getNumColumns();
2016     Align = ElementInfo.Align;
2017     break;
2018   }
2019 
2020   case Type::Builtin:
2021     switch (cast<BuiltinType>(T)->getKind()) {
2022     default: llvm_unreachable("Unknown builtin type!");
2023     case BuiltinType::Void:
2024       // GCC extension: alignof(void) = 8 bits.
2025       Width = 0;
2026       Align = 8;
2027       break;
2028     case BuiltinType::Bool:
2029       Width = Target->getBoolWidth();
2030       Align = Target->getBoolAlign();
2031       break;
2032     case BuiltinType::Char_S:
2033     case BuiltinType::Char_U:
2034     case BuiltinType::UChar:
2035     case BuiltinType::SChar:
2036     case BuiltinType::Char8:
2037       Width = Target->getCharWidth();
2038       Align = Target->getCharAlign();
2039       break;
2040     case BuiltinType::WChar_S:
2041     case BuiltinType::WChar_U:
2042       Width = Target->getWCharWidth();
2043       Align = Target->getWCharAlign();
2044       break;
2045     case BuiltinType::Char16:
2046       Width = Target->getChar16Width();
2047       Align = Target->getChar16Align();
2048       break;
2049     case BuiltinType::Char32:
2050       Width = Target->getChar32Width();
2051       Align = Target->getChar32Align();
2052       break;
2053     case BuiltinType::UShort:
2054     case BuiltinType::Short:
2055       Width = Target->getShortWidth();
2056       Align = Target->getShortAlign();
2057       break;
2058     case BuiltinType::UInt:
2059     case BuiltinType::Int:
2060       Width = Target->getIntWidth();
2061       Align = Target->getIntAlign();
2062       break;
2063     case BuiltinType::ULong:
2064     case BuiltinType::Long:
2065       Width = Target->getLongWidth();
2066       Align = Target->getLongAlign();
2067       break;
2068     case BuiltinType::ULongLong:
2069     case BuiltinType::LongLong:
2070       Width = Target->getLongLongWidth();
2071       Align = Target->getLongLongAlign();
2072       break;
2073     case BuiltinType::Int128:
2074     case BuiltinType::UInt128:
2075       Width = 128;
2076       Align = 128; // int128_t is 128-bit aligned on all targets.
2077       break;
2078     case BuiltinType::ShortAccum:
2079     case BuiltinType::UShortAccum:
2080     case BuiltinType::SatShortAccum:
2081     case BuiltinType::SatUShortAccum:
2082       Width = Target->getShortAccumWidth();
2083       Align = Target->getShortAccumAlign();
2084       break;
2085     case BuiltinType::Accum:
2086     case BuiltinType::UAccum:
2087     case BuiltinType::SatAccum:
2088     case BuiltinType::SatUAccum:
2089       Width = Target->getAccumWidth();
2090       Align = Target->getAccumAlign();
2091       break;
2092     case BuiltinType::LongAccum:
2093     case BuiltinType::ULongAccum:
2094     case BuiltinType::SatLongAccum:
2095     case BuiltinType::SatULongAccum:
2096       Width = Target->getLongAccumWidth();
2097       Align = Target->getLongAccumAlign();
2098       break;
2099     case BuiltinType::ShortFract:
2100     case BuiltinType::UShortFract:
2101     case BuiltinType::SatShortFract:
2102     case BuiltinType::SatUShortFract:
2103       Width = Target->getShortFractWidth();
2104       Align = Target->getShortFractAlign();
2105       break;
2106     case BuiltinType::Fract:
2107     case BuiltinType::UFract:
2108     case BuiltinType::SatFract:
2109     case BuiltinType::SatUFract:
2110       Width = Target->getFractWidth();
2111       Align = Target->getFractAlign();
2112       break;
2113     case BuiltinType::LongFract:
2114     case BuiltinType::ULongFract:
2115     case BuiltinType::SatLongFract:
2116     case BuiltinType::SatULongFract:
2117       Width = Target->getLongFractWidth();
2118       Align = Target->getLongFractAlign();
2119       break;
2120     case BuiltinType::BFloat16:
2121       Width = Target->getBFloat16Width();
2122       Align = Target->getBFloat16Align();
2123       break;
2124     case BuiltinType::Float16:
2125     case BuiltinType::Half:
2126       if (Target->hasFloat16Type() || !getLangOpts().OpenMP ||
2127           !getLangOpts().OpenMPIsDevice) {
2128         Width = Target->getHalfWidth();
2129         Align = Target->getHalfAlign();
2130       } else {
2131         assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
2132                "Expected OpenMP device compilation.");
2133         Width = AuxTarget->getHalfWidth();
2134         Align = AuxTarget->getHalfAlign();
2135       }
2136       break;
2137     case BuiltinType::Float:
2138       Width = Target->getFloatWidth();
2139       Align = Target->getFloatAlign();
2140       break;
2141     case BuiltinType::Double:
2142       Width = Target->getDoubleWidth();
2143       Align = Target->getDoubleAlign();
2144       break;
2145     case BuiltinType::Ibm128:
2146       Width = Target->getIbm128Width();
2147       Align = Target->getIbm128Align();
2148       break;
2149     case BuiltinType::LongDouble:
2150       if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
2151           (Target->getLongDoubleWidth() != AuxTarget->getLongDoubleWidth() ||
2152            Target->getLongDoubleAlign() != AuxTarget->getLongDoubleAlign())) {
2153         Width = AuxTarget->getLongDoubleWidth();
2154         Align = AuxTarget->getLongDoubleAlign();
2155       } else {
2156         Width = Target->getLongDoubleWidth();
2157         Align = Target->getLongDoubleAlign();
2158       }
2159       break;
2160     case BuiltinType::Float128:
2161       if (Target->hasFloat128Type() || !getLangOpts().OpenMP ||
2162           !getLangOpts().OpenMPIsDevice) {
2163         Width = Target->getFloat128Width();
2164         Align = Target->getFloat128Align();
2165       } else {
2166         assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
2167                "Expected OpenMP device compilation.");
2168         Width = AuxTarget->getFloat128Width();
2169         Align = AuxTarget->getFloat128Align();
2170       }
2171       break;
2172     case BuiltinType::NullPtr:
2173       Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
2174       Align = Target->getPointerAlign(0); //   == sizeof(void*)
2175       break;
2176     case BuiltinType::ObjCId:
2177     case BuiltinType::ObjCClass:
2178     case BuiltinType::ObjCSel:
2179       Width = Target->getPointerWidth(0);
2180       Align = Target->getPointerAlign(0);
2181       break;
2182     case BuiltinType::OCLSampler:
2183     case BuiltinType::OCLEvent:
2184     case BuiltinType::OCLClkEvent:
2185     case BuiltinType::OCLQueue:
2186     case BuiltinType::OCLReserveID:
2187 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2188     case BuiltinType::Id:
2189 #include "clang/Basic/OpenCLImageTypes.def"
2190 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2191   case BuiltinType::Id:
2192 #include "clang/Basic/OpenCLExtensionTypes.def"
2193       AS = getTargetAddressSpace(
2194           Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T)));
2195       Width = Target->getPointerWidth(AS);
2196       Align = Target->getPointerAlign(AS);
2197       break;
2198     // The SVE types are effectively target-specific.  The length of an
2199     // SVE_VECTOR_TYPE is only known at runtime, but it is always a multiple
2200     // of 128 bits.  There is one predicate bit for each vector byte, so the
2201     // length of an SVE_PREDICATE_TYPE is always a multiple of 16 bits.
2202     //
2203     // Because the length is only known at runtime, we use a dummy value
2204     // of 0 for the static length.  The alignment values are those defined
2205     // by the Procedure Call Standard for the Arm Architecture.
2206 #define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId, NumEls, ElBits,    \
2207                         IsSigned, IsFP, IsBF)                                  \
2208   case BuiltinType::Id:                                                        \
2209     Width = 0;                                                                 \
2210     Align = 128;                                                               \
2211     break;
2212 #define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId, NumEls)         \
2213   case BuiltinType::Id:                                                        \
2214     Width = 0;                                                                 \
2215     Align = 16;                                                                \
2216     break;
2217 #include "clang/Basic/AArch64SVEACLETypes.def"
2218 #define PPC_VECTOR_TYPE(Name, Id, Size)                                        \
2219   case BuiltinType::Id:                                                        \
2220     Width = Size;                                                              \
2221     Align = Size;                                                              \
2222     break;
2223 #include "clang/Basic/PPCTypes.def"
2224 #define RVV_VECTOR_TYPE(Name, Id, SingletonId, ElKind, ElBits, NF, IsSigned,   \
2225                         IsFP)                                                  \
2226   case BuiltinType::Id:                                                        \
2227     Width = 0;                                                                 \
2228     Align = ElBits;                                                            \
2229     break;
2230 #define RVV_PREDICATE_TYPE(Name, Id, SingletonId, ElKind)                      \
2231   case BuiltinType::Id:                                                        \
2232     Width = 0;                                                                 \
2233     Align = 8;                                                                 \
2234     break;
2235 #include "clang/Basic/RISCVVTypes.def"
2236     }
2237     break;
2238   case Type::ObjCObjectPointer:
2239     Width = Target->getPointerWidth(0);
2240     Align = Target->getPointerAlign(0);
2241     break;
2242   case Type::BlockPointer:
2243     AS = getTargetAddressSpace(cast<BlockPointerType>(T)->getPointeeType());
2244     Width = Target->getPointerWidth(AS);
2245     Align = Target->getPointerAlign(AS);
2246     break;
2247   case Type::LValueReference:
2248   case Type::RValueReference:
2249     // alignof and sizeof should never enter this code path here, so we go
2250     // the pointer route.
2251     AS = getTargetAddressSpace(cast<ReferenceType>(T)->getPointeeType());
2252     Width = Target->getPointerWidth(AS);
2253     Align = Target->getPointerAlign(AS);
2254     break;
2255   case Type::Pointer:
2256     AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
2257     Width = Target->getPointerWidth(AS);
2258     Align = Target->getPointerAlign(AS);
2259     break;
2260   case Type::MemberPointer: {
2261     const auto *MPT = cast<MemberPointerType>(T);
2262     CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT);
2263     Width = MPI.Width;
2264     Align = MPI.Align;
2265     break;
2266   }
2267   case Type::Complex: {
2268     // Complex types have the same alignment as their elements, but twice the
2269     // size.
2270     TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
2271     Width = EltInfo.Width * 2;
2272     Align = EltInfo.Align;
2273     break;
2274   }
2275   case Type::ObjCObject:
2276     return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
2277   case Type::Adjusted:
2278   case Type::Decayed:
2279     return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
2280   case Type::ObjCInterface: {
2281     const auto *ObjCI = cast<ObjCInterfaceType>(T);
2282     if (ObjCI->getDecl()->isInvalidDecl()) {
2283       Width = 8;
2284       Align = 8;
2285       break;
2286     }
2287     const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2288     Width = toBits(Layout.getSize());
2289     Align = toBits(Layout.getAlignment());
2290     break;
2291   }
2292   case Type::BitInt: {
2293     const auto *EIT = cast<BitIntType>(T);
2294     Align =
2295         std::min(static_cast<unsigned>(std::max(
2296                      getCharWidth(), llvm::PowerOf2Ceil(EIT->getNumBits()))),
2297                  Target->getLongLongAlign());
2298     Width = llvm::alignTo(EIT->getNumBits(), Align);
2299     break;
2300   }
2301   case Type::Record:
2302   case Type::Enum: {
2303     const auto *TT = cast<TagType>(T);
2304 
2305     if (TT->getDecl()->isInvalidDecl()) {
2306       Width = 8;
2307       Align = 8;
2308       break;
2309     }
2310 
2311     if (const auto *ET = dyn_cast<EnumType>(TT)) {
2312       const EnumDecl *ED = ET->getDecl();
2313       TypeInfo Info =
2314           getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
2315       if (unsigned AttrAlign = ED->getMaxAlignment()) {
2316         Info.Align = AttrAlign;
2317         Info.AlignRequirement = AlignRequirementKind::RequiredByEnum;
2318       }
2319       return Info;
2320     }
2321 
2322     const auto *RT = cast<RecordType>(TT);
2323     const RecordDecl *RD = RT->getDecl();
2324     const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2325     Width = toBits(Layout.getSize());
2326     Align = toBits(Layout.getAlignment());
2327     AlignRequirement = RD->hasAttr<AlignedAttr>()
2328                            ? AlignRequirementKind::RequiredByRecord
2329                            : AlignRequirementKind::None;
2330     break;
2331   }
2332 
2333   case Type::SubstTemplateTypeParm:
2334     return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
2335                        getReplacementType().getTypePtr());
2336 
2337   case Type::Auto:
2338   case Type::DeducedTemplateSpecialization: {
2339     const auto *A = cast<DeducedType>(T);
2340     assert(!A->getDeducedType().isNull() &&
2341            "cannot request the size of an undeduced or dependent auto type");
2342     return getTypeInfo(A->getDeducedType().getTypePtr());
2343   }
2344 
2345   case Type::Paren:
2346     return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
2347 
2348   case Type::MacroQualified:
2349     return getTypeInfo(
2350         cast<MacroQualifiedType>(T)->getUnderlyingType().getTypePtr());
2351 
2352   case Type::ObjCTypeParam:
2353     return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
2354 
2355   case Type::Using:
2356     return getTypeInfo(cast<UsingType>(T)->desugar().getTypePtr());
2357 
2358   case Type::Typedef: {
2359     const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
2360     TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
2361     // If the typedef has an aligned attribute on it, it overrides any computed
2362     // alignment we have.  This violates the GCC documentation (which says that
2363     // attribute(aligned) can only round up) but matches its implementation.
2364     if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
2365       Align = AttrAlign;
2366       AlignRequirement = AlignRequirementKind::RequiredByTypedef;
2367     } else {
2368       Align = Info.Align;
2369       AlignRequirement = Info.AlignRequirement;
2370     }
2371     Width = Info.Width;
2372     break;
2373   }
2374 
2375   case Type::Elaborated:
2376     return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
2377 
2378   case Type::Attributed:
2379     return getTypeInfo(
2380                   cast<AttributedType>(T)->getEquivalentType().getTypePtr());
2381 
2382   case Type::BTFTagAttributed:
2383     return getTypeInfo(
2384         cast<BTFTagAttributedType>(T)->getWrappedType().getTypePtr());
2385 
2386   case Type::Atomic: {
2387     // Start with the base type information.
2388     TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
2389     Width = Info.Width;
2390     Align = Info.Align;
2391 
2392     if (!Width) {
2393       // An otherwise zero-sized type should still generate an
2394       // atomic operation.
2395       Width = Target->getCharWidth();
2396       assert(Align);
2397     } else if (Width <= Target->getMaxAtomicPromoteWidth()) {
2398       // If the size of the type doesn't exceed the platform's max
2399       // atomic promotion width, make the size and alignment more
2400       // favorable to atomic operations:
2401 
2402       // Round the size up to a power of 2.
2403       if (!llvm::isPowerOf2_64(Width))
2404         Width = llvm::NextPowerOf2(Width);
2405 
2406       // Set the alignment equal to the size.
2407       Align = static_cast<unsigned>(Width);
2408     }
2409   }
2410   break;
2411 
2412   case Type::Pipe:
2413     Width = Target->getPointerWidth(getTargetAddressSpace(LangAS::opencl_global));
2414     Align = Target->getPointerAlign(getTargetAddressSpace(LangAS::opencl_global));
2415     break;
2416   }
2417 
2418   assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
2419   return TypeInfo(Width, Align, AlignRequirement);
2420 }
2421 
2422 unsigned ASTContext::getTypeUnadjustedAlign(const Type *T) const {
2423   UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T);
2424   if (I != MemoizedUnadjustedAlign.end())
2425     return I->second;
2426 
2427   unsigned UnadjustedAlign;
2428   if (const auto *RT = T->getAs<RecordType>()) {
2429     const RecordDecl *RD = RT->getDecl();
2430     const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2431     UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2432   } else if (const auto *ObjCI = T->getAs<ObjCInterfaceType>()) {
2433     const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2434     UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2435   } else {
2436     UnadjustedAlign = getTypeAlign(T->getUnqualifiedDesugaredType());
2437   }
2438 
2439   MemoizedUnadjustedAlign[T] = UnadjustedAlign;
2440   return UnadjustedAlign;
2441 }
2442 
2443 unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
2444   unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
2445   return SimdAlign;
2446 }
2447 
2448 /// toCharUnitsFromBits - Convert a size in bits to a size in characters.
2449 CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
2450   return CharUnits::fromQuantity(BitSize / getCharWidth());
2451 }
2452 
2453 /// toBits - Convert a size in characters to a size in characters.
2454 int64_t ASTContext::toBits(CharUnits CharSize) const {
2455   return CharSize.getQuantity() * getCharWidth();
2456 }
2457 
2458 /// getTypeSizeInChars - Return the size of the specified type, in characters.
2459 /// This method does not work on incomplete types.
2460 CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
2461   return getTypeInfoInChars(T).Width;
2462 }
2463 CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
2464   return getTypeInfoInChars(T).Width;
2465 }
2466 
2467 /// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
2468 /// characters. This method does not work on incomplete types.
2469 CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
2470   return toCharUnitsFromBits(getTypeAlign(T));
2471 }
2472 CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
2473   return toCharUnitsFromBits(getTypeAlign(T));
2474 }
2475 
2476 /// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a
2477 /// type, in characters, before alignment adustments. This method does
2478 /// not work on incomplete types.
2479 CharUnits ASTContext::getTypeUnadjustedAlignInChars(QualType T) const {
2480   return toCharUnitsFromBits(getTypeUnadjustedAlign(T));
2481 }
2482 CharUnits ASTContext::getTypeUnadjustedAlignInChars(const Type *T) const {
2483   return toCharUnitsFromBits(getTypeUnadjustedAlign(T));
2484 }
2485 
2486 /// getPreferredTypeAlign - Return the "preferred" alignment of the specified
2487 /// type for the current target in bits.  This can be different than the ABI
2488 /// alignment in cases where it is beneficial for performance or backwards
2489 /// compatibility preserving to overalign a data type. (Note: despite the name,
2490 /// the preferred alignment is ABI-impacting, and not an optimization.)
2491 unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
2492   TypeInfo TI = getTypeInfo(T);
2493   unsigned ABIAlign = TI.Align;
2494 
2495   T = T->getBaseElementTypeUnsafe();
2496 
2497   // The preferred alignment of member pointers is that of a pointer.
2498   if (T->isMemberPointerType())
2499     return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
2500 
2501   if (!Target->allowsLargerPreferedTypeAlignment())
2502     return ABIAlign;
2503 
2504   if (const auto *RT = T->getAs<RecordType>()) {
2505     const RecordDecl *RD = RT->getDecl();
2506 
2507     // When used as part of a typedef, or together with a 'packed' attribute,
2508     // the 'aligned' attribute can be used to decrease alignment. Note that the
2509     // 'packed' case is already taken into consideration when computing the
2510     // alignment, we only need to handle the typedef case here.
2511     if (TI.AlignRequirement == AlignRequirementKind::RequiredByTypedef ||
2512         RD->isInvalidDecl())
2513       return ABIAlign;
2514 
2515     unsigned PreferredAlign = static_cast<unsigned>(
2516         toBits(getASTRecordLayout(RD).PreferredAlignment));
2517     assert(PreferredAlign >= ABIAlign &&
2518            "PreferredAlign should be at least as large as ABIAlign.");
2519     return PreferredAlign;
2520   }
2521 
2522   // Double (and, for targets supporting AIX `power` alignment, long double) and
2523   // long long should be naturally aligned (despite requiring less alignment) if
2524   // possible.
2525   if (const auto *CT = T->getAs<ComplexType>())
2526     T = CT->getElementType().getTypePtr();
2527   if (const auto *ET = T->getAs<EnumType>())
2528     T = ET->getDecl()->getIntegerType().getTypePtr();
2529   if (T->isSpecificBuiltinType(BuiltinType::Double) ||
2530       T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2531       T->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2532       (T->isSpecificBuiltinType(BuiltinType::LongDouble) &&
2533        Target->defaultsToAIXPowerAlignment()))
2534     // Don't increase the alignment if an alignment attribute was specified on a
2535     // typedef declaration.
2536     if (!TI.isAlignRequired())
2537       return std::max(ABIAlign, (unsigned)getTypeSize(T));
2538 
2539   return ABIAlign;
2540 }
2541 
2542 /// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2543 /// for __attribute__((aligned)) on this target, to be used if no alignment
2544 /// value is specified.
2545 unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const {
2546   return getTargetInfo().getDefaultAlignForAttributeAligned();
2547 }
2548 
2549 /// getAlignOfGlobalVar - Return the alignment in bits that should be given
2550 /// to a global variable of the specified type.
2551 unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
2552   uint64_t TypeSize = getTypeSize(T.getTypePtr());
2553   return std::max(getPreferredTypeAlign(T),
2554                   getTargetInfo().getMinGlobalAlign(TypeSize));
2555 }
2556 
2557 /// getAlignOfGlobalVarInChars - Return the alignment in characters that
2558 /// should be given to a global variable of the specified type.
2559 CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
2560   return toCharUnitsFromBits(getAlignOfGlobalVar(T));
2561 }
2562 
2563 CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
2564   CharUnits Offset = CharUnits::Zero();
2565   const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2566   while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2567     Offset += Layout->getBaseClassOffset(Base);
2568     Layout = &getASTRecordLayout(Base);
2569   }
2570   return Offset;
2571 }
2572 
2573 CharUnits ASTContext::getMemberPointerPathAdjustment(const APValue &MP) const {
2574   const ValueDecl *MPD = MP.getMemberPointerDecl();
2575   CharUnits ThisAdjustment = CharUnits::Zero();
2576   ArrayRef<const CXXRecordDecl*> Path = MP.getMemberPointerPath();
2577   bool DerivedMember = MP.isMemberPointerToDerivedMember();
2578   const CXXRecordDecl *RD = cast<CXXRecordDecl>(MPD->getDeclContext());
2579   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
2580     const CXXRecordDecl *Base = RD;
2581     const CXXRecordDecl *Derived = Path[I];
2582     if (DerivedMember)
2583       std::swap(Base, Derived);
2584     ThisAdjustment += getASTRecordLayout(Derived).getBaseClassOffset(Base);
2585     RD = Path[I];
2586   }
2587   if (DerivedMember)
2588     ThisAdjustment = -ThisAdjustment;
2589   return ThisAdjustment;
2590 }
2591 
2592 /// DeepCollectObjCIvars -
2593 /// This routine first collects all declared, but not synthesized, ivars in
2594 /// super class and then collects all ivars, including those synthesized for
2595 /// current class. This routine is used for implementation of current class
2596 /// when all ivars, declared and synthesized are known.
2597 void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
2598                                       bool leafClass,
2599                             SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
2600   if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2601     DeepCollectObjCIvars(SuperClass, false, Ivars);
2602   if (!leafClass) {
2603     llvm::append_range(Ivars, OI->ivars());
2604   } else {
2605     auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
2606     for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
2607          Iv= Iv->getNextIvar())
2608       Ivars.push_back(Iv);
2609   }
2610 }
2611 
2612 /// CollectInheritedProtocols - Collect all protocols in current class and
2613 /// those inherited by it.
2614 void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
2615                           llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
2616   if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
2617     // We can use protocol_iterator here instead of
2618     // all_referenced_protocol_iterator since we are walking all categories.
2619     for (auto *Proto : OI->all_referenced_protocols()) {
2620       CollectInheritedProtocols(Proto, Protocols);
2621     }
2622 
2623     // Categories of this Interface.
2624     for (const auto *Cat : OI->visible_categories())
2625       CollectInheritedProtocols(Cat, Protocols);
2626 
2627     if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2628       while (SD) {
2629         CollectInheritedProtocols(SD, Protocols);
2630         SD = SD->getSuperClass();
2631       }
2632   } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
2633     for (auto *Proto : OC->protocols()) {
2634       CollectInheritedProtocols(Proto, Protocols);
2635     }
2636   } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
2637     // Insert the protocol.
2638     if (!Protocols.insert(
2639           const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2640       return;
2641 
2642     for (auto *Proto : OP->protocols())
2643       CollectInheritedProtocols(Proto, Protocols);
2644   }
2645 }
2646 
2647 static bool unionHasUniqueObjectRepresentations(const ASTContext &Context,
2648                                                 const RecordDecl *RD) {
2649   assert(RD->isUnion() && "Must be union type");
2650   CharUnits UnionSize = Context.getTypeSizeInChars(RD->getTypeForDecl());
2651 
2652   for (const auto *Field : RD->fields()) {
2653     if (!Context.hasUniqueObjectRepresentations(Field->getType()))
2654       return false;
2655     CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType());
2656     if (FieldSize != UnionSize)
2657       return false;
2658   }
2659   return !RD->field_empty();
2660 }
2661 
2662 static int64_t getSubobjectOffset(const FieldDecl *Field,
2663                                   const ASTContext &Context,
2664                                   const clang::ASTRecordLayout & /*Layout*/) {
2665   return Context.getFieldOffset(Field);
2666 }
2667 
2668 static int64_t getSubobjectOffset(const CXXRecordDecl *RD,
2669                                   const ASTContext &Context,
2670                                   const clang::ASTRecordLayout &Layout) {
2671   return Context.toBits(Layout.getBaseClassOffset(RD));
2672 }
2673 
2674 static llvm::Optional<int64_t>
2675 structHasUniqueObjectRepresentations(const ASTContext &Context,
2676                                      const RecordDecl *RD);
2677 
2678 static llvm::Optional<int64_t>
2679 getSubobjectSizeInBits(const FieldDecl *Field, const ASTContext &Context) {
2680   if (Field->getType()->isRecordType()) {
2681     const RecordDecl *RD = Field->getType()->getAsRecordDecl();
2682     if (!RD->isUnion())
2683       return structHasUniqueObjectRepresentations(Context, RD);
2684   }
2685   if (!Field->getType()->isReferenceType() &&
2686       !Context.hasUniqueObjectRepresentations(Field->getType()))
2687     return llvm::None;
2688 
2689   int64_t FieldSizeInBits =
2690       Context.toBits(Context.getTypeSizeInChars(Field->getType()));
2691   if (Field->isBitField()) {
2692     int64_t BitfieldSize = Field->getBitWidthValue(Context);
2693     if (BitfieldSize > FieldSizeInBits)
2694       return llvm::None;
2695     FieldSizeInBits = BitfieldSize;
2696   }
2697   return FieldSizeInBits;
2698 }
2699 
2700 static llvm::Optional<int64_t>
2701 getSubobjectSizeInBits(const CXXRecordDecl *RD, const ASTContext &Context) {
2702   return structHasUniqueObjectRepresentations(Context, RD);
2703 }
2704 
2705 template <typename RangeT>
2706 static llvm::Optional<int64_t> structSubobjectsHaveUniqueObjectRepresentations(
2707     const RangeT &Subobjects, int64_t CurOffsetInBits,
2708     const ASTContext &Context, const clang::ASTRecordLayout &Layout) {
2709   for (const auto *Subobject : Subobjects) {
2710     llvm::Optional<int64_t> SizeInBits =
2711         getSubobjectSizeInBits(Subobject, Context);
2712     if (!SizeInBits)
2713       return llvm::None;
2714     if (*SizeInBits != 0) {
2715       int64_t Offset = getSubobjectOffset(Subobject, Context, Layout);
2716       if (Offset != CurOffsetInBits)
2717         return llvm::None;
2718       CurOffsetInBits += *SizeInBits;
2719     }
2720   }
2721   return CurOffsetInBits;
2722 }
2723 
2724 static llvm::Optional<int64_t>
2725 structHasUniqueObjectRepresentations(const ASTContext &Context,
2726                                      const RecordDecl *RD) {
2727   assert(!RD->isUnion() && "Must be struct/class type");
2728   const auto &Layout = Context.getASTRecordLayout(RD);
2729 
2730   int64_t CurOffsetInBits = 0;
2731   if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) {
2732     if (ClassDecl->isDynamicClass())
2733       return llvm::None;
2734 
2735     SmallVector<CXXRecordDecl *, 4> Bases;
2736     for (const auto &Base : ClassDecl->bases()) {
2737       // Empty types can be inherited from, and non-empty types can potentially
2738       // have tail padding, so just make sure there isn't an error.
2739       Bases.emplace_back(Base.getType()->getAsCXXRecordDecl());
2740     }
2741 
2742     llvm::sort(Bases, [&](const CXXRecordDecl *L, const CXXRecordDecl *R) {
2743       return Layout.getBaseClassOffset(L) < Layout.getBaseClassOffset(R);
2744     });
2745 
2746     llvm::Optional<int64_t> OffsetAfterBases =
2747         structSubobjectsHaveUniqueObjectRepresentations(Bases, CurOffsetInBits,
2748                                                         Context, Layout);
2749     if (!OffsetAfterBases)
2750       return llvm::None;
2751     CurOffsetInBits = *OffsetAfterBases;
2752   }
2753 
2754   llvm::Optional<int64_t> OffsetAfterFields =
2755       structSubobjectsHaveUniqueObjectRepresentations(
2756           RD->fields(), CurOffsetInBits, Context, Layout);
2757   if (!OffsetAfterFields)
2758     return llvm::None;
2759   CurOffsetInBits = *OffsetAfterFields;
2760 
2761   return CurOffsetInBits;
2762 }
2763 
2764 bool ASTContext::hasUniqueObjectRepresentations(QualType Ty) const {
2765   // C++17 [meta.unary.prop]:
2766   //   The predicate condition for a template specialization
2767   //   has_unique_object_representations<T> shall be
2768   //   satisfied if and only if:
2769   //     (9.1) - T is trivially copyable, and
2770   //     (9.2) - any two objects of type T with the same value have the same
2771   //     object representation, where two objects
2772   //   of array or non-union class type are considered to have the same value
2773   //   if their respective sequences of
2774   //   direct subobjects have the same values, and two objects of union type
2775   //   are considered to have the same
2776   //   value if they have the same active member and the corresponding members
2777   //   have the same value.
2778   //   The set of scalar types for which this condition holds is
2779   //   implementation-defined. [ Note: If a type has padding
2780   //   bits, the condition does not hold; otherwise, the condition holds true
2781   //   for unsigned integral types. -- end note ]
2782   assert(!Ty.isNull() && "Null QualType sent to unique object rep check");
2783 
2784   // Arrays are unique only if their element type is unique.
2785   if (Ty->isArrayType())
2786     return hasUniqueObjectRepresentations(getBaseElementType(Ty));
2787 
2788   // (9.1) - T is trivially copyable...
2789   if (!Ty.isTriviallyCopyableType(*this))
2790     return false;
2791 
2792   // All integrals and enums are unique.
2793   if (Ty->isIntegralOrEnumerationType())
2794     return true;
2795 
2796   // All other pointers are unique.
2797   if (Ty->isPointerType())
2798     return true;
2799 
2800   if (Ty->isMemberPointerType()) {
2801     const auto *MPT = Ty->getAs<MemberPointerType>();
2802     return !ABI->getMemberPointerInfo(MPT).HasPadding;
2803   }
2804 
2805   if (Ty->isRecordType()) {
2806     const RecordDecl *Record = Ty->castAs<RecordType>()->getDecl();
2807 
2808     if (Record->isInvalidDecl())
2809       return false;
2810 
2811     if (Record->isUnion())
2812       return unionHasUniqueObjectRepresentations(*this, Record);
2813 
2814     Optional<int64_t> StructSize =
2815         structHasUniqueObjectRepresentations(*this, Record);
2816 
2817     return StructSize &&
2818            StructSize.getValue() == static_cast<int64_t>(getTypeSize(Ty));
2819   }
2820 
2821   // FIXME: More cases to handle here (list by rsmith):
2822   // vectors (careful about, eg, vector of 3 foo)
2823   // _Complex int and friends
2824   // _Atomic T
2825   // Obj-C block pointers
2826   // Obj-C object pointers
2827   // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t,
2828   // clk_event_t, queue_t, reserve_id_t)
2829   // There're also Obj-C class types and the Obj-C selector type, but I think it
2830   // makes sense for those to return false here.
2831 
2832   return false;
2833 }
2834 
2835 unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
2836   unsigned count = 0;
2837   // Count ivars declared in class extension.
2838   for (const auto *Ext : OI->known_extensions())
2839     count += Ext->ivar_size();
2840 
2841   // Count ivar defined in this class's implementation.  This
2842   // includes synthesized ivars.
2843   if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
2844     count += ImplDecl->ivar_size();
2845 
2846   return count;
2847 }
2848 
2849 bool ASTContext::isSentinelNullExpr(const Expr *E) {
2850   if (!E)
2851     return false;
2852 
2853   // nullptr_t is always treated as null.
2854   if (E->getType()->isNullPtrType()) return true;
2855 
2856   if (E->getType()->isAnyPointerType() &&
2857       E->IgnoreParenCasts()->isNullPointerConstant(*this,
2858                                                 Expr::NPC_ValueDependentIsNull))
2859     return true;
2860 
2861   // Unfortunately, __null has type 'int'.
2862   if (isa<GNUNullExpr>(E)) return true;
2863 
2864   return false;
2865 }
2866 
2867 /// Get the implementation of ObjCInterfaceDecl, or nullptr if none
2868 /// exists.
2869 ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
2870   llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2871     I = ObjCImpls.find(D);
2872   if (I != ObjCImpls.end())
2873     return cast<ObjCImplementationDecl>(I->second);
2874   return nullptr;
2875 }
2876 
2877 /// Get the implementation of ObjCCategoryDecl, or nullptr if none
2878 /// exists.
2879 ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
2880   llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2881     I = ObjCImpls.find(D);
2882   if (I != ObjCImpls.end())
2883     return cast<ObjCCategoryImplDecl>(I->second);
2884   return nullptr;
2885 }
2886 
2887 /// Set the implementation of ObjCInterfaceDecl.
2888 void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2889                            ObjCImplementationDecl *ImplD) {
2890   assert(IFaceD && ImplD && "Passed null params");
2891   ObjCImpls[IFaceD] = ImplD;
2892 }
2893 
2894 /// Set the implementation of ObjCCategoryDecl.
2895 void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
2896                            ObjCCategoryImplDecl *ImplD) {
2897   assert(CatD && ImplD && "Passed null params");
2898   ObjCImpls[CatD] = ImplD;
2899 }
2900 
2901 const ObjCMethodDecl *
2902 ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const {
2903   return ObjCMethodRedecls.lookup(MD);
2904 }
2905 
2906 void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2907                                             const ObjCMethodDecl *Redecl) {
2908   assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
2909   ObjCMethodRedecls[MD] = Redecl;
2910 }
2911 
2912 const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
2913                                               const NamedDecl *ND) const {
2914   if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
2915     return ID;
2916   if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
2917     return CD->getClassInterface();
2918   if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
2919     return IMD->getClassInterface();
2920 
2921   return nullptr;
2922 }
2923 
2924 /// Get the copy initialization expression of VarDecl, or nullptr if
2925 /// none exists.
2926 BlockVarCopyInit ASTContext::getBlockVarCopyInit(const VarDecl *VD) const {
2927   assert(VD && "Passed null params");
2928   assert(VD->hasAttr<BlocksAttr>() &&
2929          "getBlockVarCopyInits - not __block var");
2930   auto I = BlockVarCopyInits.find(VD);
2931   if (I != BlockVarCopyInits.end())
2932     return I->second;
2933   return {nullptr, false};
2934 }
2935 
2936 /// Set the copy initialization expression of a block var decl.
2937 void ASTContext::setBlockVarCopyInit(const VarDecl*VD, Expr *CopyExpr,
2938                                      bool CanThrow) {
2939   assert(VD && CopyExpr && "Passed null params");
2940   assert(VD->hasAttr<BlocksAttr>() &&
2941          "setBlockVarCopyInits - not __block var");
2942   BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow);
2943 }
2944 
2945 TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
2946                                                  unsigned DataSize) const {
2947   if (!DataSize)
2948     DataSize = TypeLoc::getFullDataSizeForType(T);
2949   else
2950     assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
2951            "incorrect data size provided to CreateTypeSourceInfo!");
2952 
2953   auto *TInfo =
2954     (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2955   new (TInfo) TypeSourceInfo(T);
2956   return TInfo;
2957 }
2958 
2959 TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
2960                                                      SourceLocation L) const {
2961   TypeSourceInfo *DI = CreateTypeSourceInfo(T);
2962   DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
2963   return DI;
2964 }
2965 
2966 const ASTRecordLayout &
2967 ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
2968   return getObjCLayout(D, nullptr);
2969 }
2970 
2971 const ASTRecordLayout &
2972 ASTContext::getASTObjCImplementationLayout(
2973                                         const ObjCImplementationDecl *D) const {
2974   return getObjCLayout(D->getClassInterface(), D);
2975 }
2976 
2977 //===----------------------------------------------------------------------===//
2978 //                   Type creation/memoization methods
2979 //===----------------------------------------------------------------------===//
2980 
2981 QualType
2982 ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2983   unsigned fastQuals = quals.getFastQualifiers();
2984   quals.removeFastQualifiers();
2985 
2986   // Check if we've already instantiated this type.
2987   llvm::FoldingSetNodeID ID;
2988   ExtQuals::Profile(ID, baseType, quals);
2989   void *insertPos = nullptr;
2990   if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2991     assert(eq->getQualifiers() == quals);
2992     return QualType(eq, fastQuals);
2993   }
2994 
2995   // If the base type is not canonical, make the appropriate canonical type.
2996   QualType canon;
2997   if (!baseType->isCanonicalUnqualified()) {
2998     SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
2999     canonSplit.Quals.addConsistentQualifiers(quals);
3000     canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
3001 
3002     // Re-find the insert position.
3003     (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
3004   }
3005 
3006   auto *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
3007   ExtQualNodes.InsertNode(eq, insertPos);
3008   return QualType(eq, fastQuals);
3009 }
3010 
3011 QualType ASTContext::getAddrSpaceQualType(QualType T,
3012                                           LangAS AddressSpace) const {
3013   QualType CanT = getCanonicalType(T);
3014   if (CanT.getAddressSpace() == AddressSpace)
3015     return T;
3016 
3017   // If we are composing extended qualifiers together, merge together
3018   // into one ExtQuals node.
3019   QualifierCollector Quals;
3020   const Type *TypeNode = Quals.strip(T);
3021 
3022   // If this type already has an address space specified, it cannot get
3023   // another one.
3024   assert(!Quals.hasAddressSpace() &&
3025          "Type cannot be in multiple addr spaces!");
3026   Quals.addAddressSpace(AddressSpace);
3027 
3028   return getExtQualType(TypeNode, Quals);
3029 }
3030 
3031 QualType ASTContext::removeAddrSpaceQualType(QualType T) const {
3032   // If the type is not qualified with an address space, just return it
3033   // immediately.
3034   if (!T.hasAddressSpace())
3035     return T;
3036 
3037   // If we are composing extended qualifiers together, merge together
3038   // into one ExtQuals node.
3039   QualifierCollector Quals;
3040   const Type *TypeNode;
3041 
3042   while (T.hasAddressSpace()) {
3043     TypeNode = Quals.strip(T);
3044 
3045     // If the type no longer has an address space after stripping qualifiers,
3046     // jump out.
3047     if (!QualType(TypeNode, 0).hasAddressSpace())
3048       break;
3049 
3050     // There might be sugar in the way. Strip it and try again.
3051     T = T.getSingleStepDesugaredType(*this);
3052   }
3053 
3054   Quals.removeAddressSpace();
3055 
3056   // Removal of the address space can mean there are no longer any
3057   // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
3058   // or required.
3059   if (Quals.hasNonFastQualifiers())
3060     return getExtQualType(TypeNode, Quals);
3061   else
3062     return QualType(TypeNode, Quals.getFastQualifiers());
3063 }
3064 
3065 QualType ASTContext::getObjCGCQualType(QualType T,
3066                                        Qualifiers::GC GCAttr) const {
3067   QualType CanT = getCanonicalType(T);
3068   if (CanT.getObjCGCAttr() == GCAttr)
3069     return T;
3070 
3071   if (const auto *ptr = T->getAs<PointerType>()) {
3072     QualType Pointee = ptr->getPointeeType();
3073     if (Pointee->isAnyPointerType()) {
3074       QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
3075       return getPointerType(ResultType);
3076     }
3077   }
3078 
3079   // If we are composing extended qualifiers together, merge together
3080   // into one ExtQuals node.
3081   QualifierCollector Quals;
3082   const Type *TypeNode = Quals.strip(T);
3083 
3084   // If this type already has an ObjCGC specified, it cannot get
3085   // another one.
3086   assert(!Quals.hasObjCGCAttr() &&
3087          "Type cannot have multiple ObjCGCs!");
3088   Quals.addObjCGCAttr(GCAttr);
3089 
3090   return getExtQualType(TypeNode, Quals);
3091 }
3092 
3093 QualType ASTContext::removePtrSizeAddrSpace(QualType T) const {
3094   if (const PointerType *Ptr = T->getAs<PointerType>()) {
3095     QualType Pointee = Ptr->getPointeeType();
3096     if (isPtrSizeAddressSpace(Pointee.getAddressSpace())) {
3097       return getPointerType(removeAddrSpaceQualType(Pointee));
3098     }
3099   }
3100   return T;
3101 }
3102 
3103 const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
3104                                                    FunctionType::ExtInfo Info) {
3105   if (T->getExtInfo() == Info)
3106     return T;
3107 
3108   QualType Result;
3109   if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
3110     Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
3111   } else {
3112     const auto *FPT = cast<FunctionProtoType>(T);
3113     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
3114     EPI.ExtInfo = Info;
3115     Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
3116   }
3117 
3118   return cast<FunctionType>(Result.getTypePtr());
3119 }
3120 
3121 void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
3122                                                  QualType ResultType) {
3123   FD = FD->getMostRecentDecl();
3124   while (true) {
3125     const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
3126     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
3127     FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
3128     if (FunctionDecl *Next = FD->getPreviousDecl())
3129       FD = Next;
3130     else
3131       break;
3132   }
3133   if (ASTMutationListener *L = getASTMutationListener())
3134     L->DeducedReturnType(FD, ResultType);
3135 }
3136 
3137 /// Get a function type and produce the equivalent function type with the
3138 /// specified exception specification. Type sugar that can be present on a
3139 /// declaration of a function with an exception specification is permitted
3140 /// and preserved. Other type sugar (for instance, typedefs) is not.
3141 QualType ASTContext::getFunctionTypeWithExceptionSpec(
3142     QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) {
3143   // Might have some parens.
3144   if (const auto *PT = dyn_cast<ParenType>(Orig))
3145     return getParenType(
3146         getFunctionTypeWithExceptionSpec(PT->getInnerType(), ESI));
3147 
3148   // Might be wrapped in a macro qualified type.
3149   if (const auto *MQT = dyn_cast<MacroQualifiedType>(Orig))
3150     return getMacroQualifiedType(
3151         getFunctionTypeWithExceptionSpec(MQT->getUnderlyingType(), ESI),
3152         MQT->getMacroIdentifier());
3153 
3154   // Might have a calling-convention attribute.
3155   if (const auto *AT = dyn_cast<AttributedType>(Orig))
3156     return getAttributedType(
3157         AT->getAttrKind(),
3158         getFunctionTypeWithExceptionSpec(AT->getModifiedType(), ESI),
3159         getFunctionTypeWithExceptionSpec(AT->getEquivalentType(), ESI));
3160 
3161   // Anything else must be a function type. Rebuild it with the new exception
3162   // specification.
3163   const auto *Proto = Orig->castAs<FunctionProtoType>();
3164   return getFunctionType(
3165       Proto->getReturnType(), Proto->getParamTypes(),
3166       Proto->getExtProtoInfo().withExceptionSpec(ESI));
3167 }
3168 
3169 bool ASTContext::hasSameFunctionTypeIgnoringExceptionSpec(QualType T,
3170                                                           QualType U) {
3171   return hasSameType(T, U) ||
3172          (getLangOpts().CPlusPlus17 &&
3173           hasSameType(getFunctionTypeWithExceptionSpec(T, EST_None),
3174                       getFunctionTypeWithExceptionSpec(U, EST_None)));
3175 }
3176 
3177 QualType ASTContext::getFunctionTypeWithoutPtrSizes(QualType T) {
3178   if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3179     QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3180     SmallVector<QualType, 16> Args(Proto->param_types());
3181     for (unsigned i = 0, n = Args.size(); i != n; ++i)
3182       Args[i] = removePtrSizeAddrSpace(Args[i]);
3183     return getFunctionType(RetTy, Args, Proto->getExtProtoInfo());
3184   }
3185 
3186   if (const FunctionNoProtoType *Proto = T->getAs<FunctionNoProtoType>()) {
3187     QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3188     return getFunctionNoProtoType(RetTy, Proto->getExtInfo());
3189   }
3190 
3191   return T;
3192 }
3193 
3194 bool ASTContext::hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U) {
3195   return hasSameType(T, U) ||
3196          hasSameType(getFunctionTypeWithoutPtrSizes(T),
3197                      getFunctionTypeWithoutPtrSizes(U));
3198 }
3199 
3200 void ASTContext::adjustExceptionSpec(
3201     FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
3202     bool AsWritten) {
3203   // Update the type.
3204   QualType Updated =
3205       getFunctionTypeWithExceptionSpec(FD->getType(), ESI);
3206   FD->setType(Updated);
3207 
3208   if (!AsWritten)
3209     return;
3210 
3211   // Update the type in the type source information too.
3212   if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
3213     // If the type and the type-as-written differ, we may need to update
3214     // the type-as-written too.
3215     if (TSInfo->getType() != FD->getType())
3216       Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI);
3217 
3218     // FIXME: When we get proper type location information for exceptions,
3219     // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
3220     // up the TypeSourceInfo;
3221     assert(TypeLoc::getFullDataSizeForType(Updated) ==
3222                TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
3223            "TypeLoc size mismatch from updating exception specification");
3224     TSInfo->overrideType(Updated);
3225   }
3226 }
3227 
3228 /// getComplexType - Return the uniqued reference to the type for a complex
3229 /// number with the specified element type.
3230 QualType ASTContext::getComplexType(QualType T) const {
3231   // Unique pointers, to guarantee there is only one pointer of a particular
3232   // structure.
3233   llvm::FoldingSetNodeID ID;
3234   ComplexType::Profile(ID, T);
3235 
3236   void *InsertPos = nullptr;
3237   if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
3238     return QualType(CT, 0);
3239 
3240   // If the pointee type isn't canonical, this won't be a canonical type either,
3241   // so fill in the canonical type field.
3242   QualType Canonical;
3243   if (!T.isCanonical()) {
3244     Canonical = getComplexType(getCanonicalType(T));
3245 
3246     // Get the new insert position for the node we care about.
3247     ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
3248     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3249   }
3250   auto *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
3251   Types.push_back(New);
3252   ComplexTypes.InsertNode(New, InsertPos);
3253   return QualType(New, 0);
3254 }
3255 
3256 /// getPointerType - Return the uniqued reference to the type for a pointer to
3257 /// the specified type.
3258 QualType ASTContext::getPointerType(QualType T) const {
3259   // Unique pointers, to guarantee there is only one pointer of a particular
3260   // structure.
3261   llvm::FoldingSetNodeID ID;
3262   PointerType::Profile(ID, T);
3263 
3264   void *InsertPos = nullptr;
3265   if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3266     return QualType(PT, 0);
3267 
3268   // If the pointee type isn't canonical, this won't be a canonical type either,
3269   // so fill in the canonical type field.
3270   QualType Canonical;
3271   if (!T.isCanonical()) {
3272     Canonical = getPointerType(getCanonicalType(T));
3273 
3274     // Get the new insert position for the node we care about.
3275     PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3276     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3277   }
3278   auto *New = new (*this, TypeAlignment) PointerType(T, Canonical);
3279   Types.push_back(New);
3280   PointerTypes.InsertNode(New, InsertPos);
3281   return QualType(New, 0);
3282 }
3283 
3284 QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
3285   llvm::FoldingSetNodeID ID;
3286   AdjustedType::Profile(ID, Orig, New);
3287   void *InsertPos = nullptr;
3288   AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3289   if (AT)
3290     return QualType(AT, 0);
3291 
3292   QualType Canonical = getCanonicalType(New);
3293 
3294   // Get the new insert position for the node we care about.
3295   AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3296   assert(!AT && "Shouldn't be in the map!");
3297 
3298   AT = new (*this, TypeAlignment)
3299       AdjustedType(Type::Adjusted, Orig, New, Canonical);
3300   Types.push_back(AT);
3301   AdjustedTypes.InsertNode(AT, InsertPos);
3302   return QualType(AT, 0);
3303 }
3304 
3305 QualType ASTContext::getDecayedType(QualType T) const {
3306   assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
3307 
3308   QualType Decayed;
3309 
3310   // C99 6.7.5.3p7:
3311   //   A declaration of a parameter as "array of type" shall be
3312   //   adjusted to "qualified pointer to type", where the type
3313   //   qualifiers (if any) are those specified within the [ and ] of
3314   //   the array type derivation.
3315   if (T->isArrayType())
3316     Decayed = getArrayDecayedType(T);
3317 
3318   // C99 6.7.5.3p8:
3319   //   A declaration of a parameter as "function returning type"
3320   //   shall be adjusted to "pointer to function returning type", as
3321   //   in 6.3.2.1.
3322   if (T->isFunctionType())
3323     Decayed = getPointerType(T);
3324 
3325   llvm::FoldingSetNodeID ID;
3326   AdjustedType::Profile(ID, T, Decayed);
3327   void *InsertPos = nullptr;
3328   AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3329   if (AT)
3330     return QualType(AT, 0);
3331 
3332   QualType Canonical = getCanonicalType(Decayed);
3333 
3334   // Get the new insert position for the node we care about.
3335   AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3336   assert(!AT && "Shouldn't be in the map!");
3337 
3338   AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
3339   Types.push_back(AT);
3340   AdjustedTypes.InsertNode(AT, InsertPos);
3341   return QualType(AT, 0);
3342 }
3343 
3344 /// getBlockPointerType - Return the uniqued reference to the type for
3345 /// a pointer to the specified block.
3346 QualType ASTContext::getBlockPointerType(QualType T) const {
3347   assert(T->isFunctionType() && "block of function types only");
3348   // Unique pointers, to guarantee there is only one block of a particular
3349   // structure.
3350   llvm::FoldingSetNodeID ID;
3351   BlockPointerType::Profile(ID, T);
3352 
3353   void *InsertPos = nullptr;
3354   if (BlockPointerType *PT =
3355         BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3356     return QualType(PT, 0);
3357 
3358   // If the block pointee type isn't canonical, this won't be a canonical
3359   // type either so fill in the canonical type field.
3360   QualType Canonical;
3361   if (!T.isCanonical()) {
3362     Canonical = getBlockPointerType(getCanonicalType(T));
3363 
3364     // Get the new insert position for the node we care about.
3365     BlockPointerType *NewIP =
3366       BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3367     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3368   }
3369   auto *New = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
3370   Types.push_back(New);
3371   BlockPointerTypes.InsertNode(New, InsertPos);
3372   return QualType(New, 0);
3373 }
3374 
3375 /// getLValueReferenceType - Return the uniqued reference to the type for an
3376 /// lvalue reference to the specified type.
3377 QualType
3378 ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
3379   assert((!T->isPlaceholderType() ||
3380           T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
3381          "Unresolved placeholder type");
3382 
3383   // Unique pointers, to guarantee there is only one pointer of a particular
3384   // structure.
3385   llvm::FoldingSetNodeID ID;
3386   ReferenceType::Profile(ID, T, SpelledAsLValue);
3387 
3388   void *InsertPos = nullptr;
3389   if (LValueReferenceType *RT =
3390         LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
3391     return QualType(RT, 0);
3392 
3393   const auto *InnerRef = T->getAs<ReferenceType>();
3394 
3395   // If the referencee type isn't canonical, this won't be a canonical type
3396   // either, so fill in the canonical type field.
3397   QualType Canonical;
3398   if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
3399     QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
3400     Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
3401 
3402     // Get the new insert position for the node we care about.
3403     LValueReferenceType *NewIP =
3404       LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
3405     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3406   }
3407 
3408   auto *New = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
3409                                                              SpelledAsLValue);
3410   Types.push_back(New);
3411   LValueReferenceTypes.InsertNode(New, InsertPos);
3412 
3413   return QualType(New, 0);
3414 }
3415 
3416 /// getRValueReferenceType - Return the uniqued reference to the type for an
3417 /// rvalue reference to the specified type.
3418 QualType ASTContext::getRValueReferenceType(QualType T) const {
3419   assert((!T->isPlaceholderType() ||
3420           T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
3421          "Unresolved placeholder type");
3422 
3423   // Unique pointers, to guarantee there is only one pointer of a particular
3424   // structure.
3425   llvm::FoldingSetNodeID ID;
3426   ReferenceType::Profile(ID, T, false);
3427 
3428   void *InsertPos = nullptr;
3429   if (RValueReferenceType *RT =
3430         RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
3431     return QualType(RT, 0);
3432 
3433   const auto *InnerRef = T->getAs<ReferenceType>();
3434 
3435   // If the referencee type isn't canonical, this won't be a canonical type
3436   // either, so fill in the canonical type field.
3437   QualType Canonical;
3438   if (InnerRef || !T.isCanonical()) {
3439     QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
3440     Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
3441 
3442     // Get the new insert position for the node we care about.
3443     RValueReferenceType *NewIP =
3444       RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
3445     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3446   }
3447 
3448   auto *New = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
3449   Types.push_back(New);
3450   RValueReferenceTypes.InsertNode(New, InsertPos);
3451   return QualType(New, 0);
3452 }
3453 
3454 /// getMemberPointerType - Return the uniqued reference to the type for a
3455 /// member pointer to the specified type, in the specified class.
3456 QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
3457   // Unique pointers, to guarantee there is only one pointer of a particular
3458   // structure.
3459   llvm::FoldingSetNodeID ID;
3460   MemberPointerType::Profile(ID, T, Cls);
3461 
3462   void *InsertPos = nullptr;
3463   if (MemberPointerType *PT =
3464       MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3465     return QualType(PT, 0);
3466 
3467   // If the pointee or class type isn't canonical, this won't be a canonical
3468   // type either, so fill in the canonical type field.
3469   QualType Canonical;
3470   if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
3471     Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
3472 
3473     // Get the new insert position for the node we care about.
3474     MemberPointerType *NewIP =
3475       MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3476     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3477   }
3478   auto *New = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
3479   Types.push_back(New);
3480   MemberPointerTypes.InsertNode(New, InsertPos);
3481   return QualType(New, 0);
3482 }
3483 
3484 /// getConstantArrayType - Return the unique reference to the type for an
3485 /// array of the specified element type.
3486 QualType ASTContext::getConstantArrayType(QualType EltTy,
3487                                           const llvm::APInt &ArySizeIn,
3488                                           const Expr *SizeExpr,
3489                                           ArrayType::ArraySizeModifier ASM,
3490                                           unsigned IndexTypeQuals) const {
3491   assert((EltTy->isDependentType() ||
3492           EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
3493          "Constant array of VLAs is illegal!");
3494 
3495   // We only need the size as part of the type if it's instantiation-dependent.
3496   if (SizeExpr && !SizeExpr->isInstantiationDependent())
3497     SizeExpr = nullptr;
3498 
3499   // Convert the array size into a canonical width matching the pointer size for
3500   // the target.
3501   llvm::APInt ArySize(ArySizeIn);
3502   ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
3503 
3504   llvm::FoldingSetNodeID ID;
3505   ConstantArrayType::Profile(ID, *this, EltTy, ArySize, SizeExpr, ASM,
3506                              IndexTypeQuals);
3507 
3508   void *InsertPos = nullptr;
3509   if (ConstantArrayType *ATP =
3510       ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
3511     return QualType(ATP, 0);
3512 
3513   // If the element type isn't canonical or has qualifiers, or the array bound
3514   // is instantiation-dependent, this won't be a canonical type either, so fill
3515   // in the canonical type field.
3516   QualType Canon;
3517   if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers() || SizeExpr) {
3518     SplitQualType canonSplit = getCanonicalType(EltTy).split();
3519     Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize, nullptr,
3520                                  ASM, IndexTypeQuals);
3521     Canon = getQualifiedType(Canon, canonSplit.Quals);
3522 
3523     // Get the new insert position for the node we care about.
3524     ConstantArrayType *NewIP =
3525       ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
3526     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3527   }
3528 
3529   void *Mem = Allocate(
3530       ConstantArrayType::totalSizeToAlloc<const Expr *>(SizeExpr ? 1 : 0),
3531       TypeAlignment);
3532   auto *New = new (Mem)
3533     ConstantArrayType(EltTy, Canon, ArySize, SizeExpr, ASM, IndexTypeQuals);
3534   ConstantArrayTypes.InsertNode(New, InsertPos);
3535   Types.push_back(New);
3536   return QualType(New, 0);
3537 }
3538 
3539 /// getVariableArrayDecayedType - Turns the given type, which may be
3540 /// variably-modified, into the corresponding type with all the known
3541 /// sizes replaced with [*].
3542 QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
3543   // Vastly most common case.
3544   if (!type->isVariablyModifiedType()) return type;
3545 
3546   QualType result;
3547 
3548   SplitQualType split = type.getSplitDesugaredType();
3549   const Type *ty = split.Ty;
3550   switch (ty->getTypeClass()) {
3551 #define TYPE(Class, Base)
3552 #define ABSTRACT_TYPE(Class, Base)
3553 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3554 #include "clang/AST/TypeNodes.inc"
3555     llvm_unreachable("didn't desugar past all non-canonical types?");
3556 
3557   // These types should never be variably-modified.
3558   case Type::Builtin:
3559   case Type::Complex:
3560   case Type::Vector:
3561   case Type::DependentVector:
3562   case Type::ExtVector:
3563   case Type::DependentSizedExtVector:
3564   case Type::ConstantMatrix:
3565   case Type::DependentSizedMatrix:
3566   case Type::DependentAddressSpace:
3567   case Type::ObjCObject:
3568   case Type::ObjCInterface:
3569   case Type::ObjCObjectPointer:
3570   case Type::Record:
3571   case Type::Enum:
3572   case Type::UnresolvedUsing:
3573   case Type::TypeOfExpr:
3574   case Type::TypeOf:
3575   case Type::Decltype:
3576   case Type::UnaryTransform:
3577   case Type::DependentName:
3578   case Type::InjectedClassName:
3579   case Type::TemplateSpecialization:
3580   case Type::DependentTemplateSpecialization:
3581   case Type::TemplateTypeParm:
3582   case Type::SubstTemplateTypeParmPack:
3583   case Type::Auto:
3584   case Type::DeducedTemplateSpecialization:
3585   case Type::PackExpansion:
3586   case Type::BitInt:
3587   case Type::DependentBitInt:
3588     llvm_unreachable("type should never be variably-modified");
3589 
3590   // These types can be variably-modified but should never need to
3591   // further decay.
3592   case Type::FunctionNoProto:
3593   case Type::FunctionProto:
3594   case Type::BlockPointer:
3595   case Type::MemberPointer:
3596   case Type::Pipe:
3597     return type;
3598 
3599   // These types can be variably-modified.  All these modifications
3600   // preserve structure except as noted by comments.
3601   // TODO: if we ever care about optimizing VLAs, there are no-op
3602   // optimizations available here.
3603   case Type::Pointer:
3604     result = getPointerType(getVariableArrayDecayedType(
3605                               cast<PointerType>(ty)->getPointeeType()));
3606     break;
3607 
3608   case Type::LValueReference: {
3609     const auto *lv = cast<LValueReferenceType>(ty);
3610     result = getLValueReferenceType(
3611                  getVariableArrayDecayedType(lv->getPointeeType()),
3612                                     lv->isSpelledAsLValue());
3613     break;
3614   }
3615 
3616   case Type::RValueReference: {
3617     const auto *lv = cast<RValueReferenceType>(ty);
3618     result = getRValueReferenceType(
3619                  getVariableArrayDecayedType(lv->getPointeeType()));
3620     break;
3621   }
3622 
3623   case Type::Atomic: {
3624     const auto *at = cast<AtomicType>(ty);
3625     result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
3626     break;
3627   }
3628 
3629   case Type::ConstantArray: {
3630     const auto *cat = cast<ConstantArrayType>(ty);
3631     result = getConstantArrayType(
3632                  getVariableArrayDecayedType(cat->getElementType()),
3633                                   cat->getSize(),
3634                                   cat->getSizeExpr(),
3635                                   cat->getSizeModifier(),
3636                                   cat->getIndexTypeCVRQualifiers());
3637     break;
3638   }
3639 
3640   case Type::DependentSizedArray: {
3641     const auto *dat = cast<DependentSizedArrayType>(ty);
3642     result = getDependentSizedArrayType(
3643                  getVariableArrayDecayedType(dat->getElementType()),
3644                                         dat->getSizeExpr(),
3645                                         dat->getSizeModifier(),
3646                                         dat->getIndexTypeCVRQualifiers(),
3647                                         dat->getBracketsRange());
3648     break;
3649   }
3650 
3651   // Turn incomplete types into [*] types.
3652   case Type::IncompleteArray: {
3653     const auto *iat = cast<IncompleteArrayType>(ty);
3654     result = getVariableArrayType(
3655                  getVariableArrayDecayedType(iat->getElementType()),
3656                                   /*size*/ nullptr,
3657                                   ArrayType::Normal,
3658                                   iat->getIndexTypeCVRQualifiers(),
3659                                   SourceRange());
3660     break;
3661   }
3662 
3663   // Turn VLA types into [*] types.
3664   case Type::VariableArray: {
3665     const auto *vat = cast<VariableArrayType>(ty);
3666     result = getVariableArrayType(
3667                  getVariableArrayDecayedType(vat->getElementType()),
3668                                   /*size*/ nullptr,
3669                                   ArrayType::Star,
3670                                   vat->getIndexTypeCVRQualifiers(),
3671                                   vat->getBracketsRange());
3672     break;
3673   }
3674   }
3675 
3676   // Apply the top-level qualifiers from the original.
3677   return getQualifiedType(result, split.Quals);
3678 }
3679 
3680 /// getVariableArrayType - Returns a non-unique reference to the type for a
3681 /// variable array of the specified element type.
3682 QualType ASTContext::getVariableArrayType(QualType EltTy,
3683                                           Expr *NumElts,
3684                                           ArrayType::ArraySizeModifier ASM,
3685                                           unsigned IndexTypeQuals,
3686                                           SourceRange Brackets) const {
3687   // Since we don't unique expressions, it isn't possible to unique VLA's
3688   // that have an expression provided for their size.
3689   QualType Canon;
3690 
3691   // Be sure to pull qualifiers off the element type.
3692   if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
3693     SplitQualType canonSplit = getCanonicalType(EltTy).split();
3694     Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
3695                                  IndexTypeQuals, Brackets);
3696     Canon = getQualifiedType(Canon, canonSplit.Quals);
3697   }
3698 
3699   auto *New = new (*this, TypeAlignment)
3700     VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
3701 
3702   VariableArrayTypes.push_back(New);
3703   Types.push_back(New);
3704   return QualType(New, 0);
3705 }
3706 
3707 /// getDependentSizedArrayType - Returns a non-unique reference to
3708 /// the type for a dependently-sized array of the specified element
3709 /// type.
3710 QualType ASTContext::getDependentSizedArrayType(QualType elementType,
3711                                                 Expr *numElements,
3712                                                 ArrayType::ArraySizeModifier ASM,
3713                                                 unsigned elementTypeQuals,
3714                                                 SourceRange brackets) const {
3715   assert((!numElements || numElements->isTypeDependent() ||
3716           numElements->isValueDependent()) &&
3717          "Size must be type- or value-dependent!");
3718 
3719   // Dependently-sized array types that do not have a specified number
3720   // of elements will have their sizes deduced from a dependent
3721   // initializer.  We do no canonicalization here at all, which is okay
3722   // because they can't be used in most locations.
3723   if (!numElements) {
3724     auto *newType
3725       = new (*this, TypeAlignment)
3726           DependentSizedArrayType(*this, elementType, QualType(),
3727                                   numElements, ASM, elementTypeQuals,
3728                                   brackets);
3729     Types.push_back(newType);
3730     return QualType(newType, 0);
3731   }
3732 
3733   // Otherwise, we actually build a new type every time, but we
3734   // also build a canonical type.
3735 
3736   SplitQualType canonElementType = getCanonicalType(elementType).split();
3737 
3738   void *insertPos = nullptr;
3739   llvm::FoldingSetNodeID ID;
3740   DependentSizedArrayType::Profile(ID, *this,
3741                                    QualType(canonElementType.Ty, 0),
3742                                    ASM, elementTypeQuals, numElements);
3743 
3744   // Look for an existing type with these properties.
3745   DependentSizedArrayType *canonTy =
3746     DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
3747 
3748   // If we don't have one, build one.
3749   if (!canonTy) {
3750     canonTy = new (*this, TypeAlignment)
3751       DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
3752                               QualType(), numElements, ASM, elementTypeQuals,
3753                               brackets);
3754     DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
3755     Types.push_back(canonTy);
3756   }
3757 
3758   // Apply qualifiers from the element type to the array.
3759   QualType canon = getQualifiedType(QualType(canonTy,0),
3760                                     canonElementType.Quals);
3761 
3762   // If we didn't need extra canonicalization for the element type or the size
3763   // expression, then just use that as our result.
3764   if (QualType(canonElementType.Ty, 0) == elementType &&
3765       canonTy->getSizeExpr() == numElements)
3766     return canon;
3767 
3768   // Otherwise, we need to build a type which follows the spelling
3769   // of the element type.
3770   auto *sugaredType
3771     = new (*this, TypeAlignment)
3772         DependentSizedArrayType(*this, elementType, canon, numElements,
3773                                 ASM, elementTypeQuals, brackets);
3774   Types.push_back(sugaredType);
3775   return QualType(sugaredType, 0);
3776 }
3777 
3778 QualType ASTContext::getIncompleteArrayType(QualType elementType,
3779                                             ArrayType::ArraySizeModifier ASM,
3780                                             unsigned elementTypeQuals) const {
3781   llvm::FoldingSetNodeID ID;
3782   IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
3783 
3784   void *insertPos = nullptr;
3785   if (IncompleteArrayType *iat =
3786        IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
3787     return QualType(iat, 0);
3788 
3789   // If the element type isn't canonical, this won't be a canonical type
3790   // either, so fill in the canonical type field.  We also have to pull
3791   // qualifiers off the element type.
3792   QualType canon;
3793 
3794   if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
3795     SplitQualType canonSplit = getCanonicalType(elementType).split();
3796     canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
3797                                    ASM, elementTypeQuals);
3798     canon = getQualifiedType(canon, canonSplit.Quals);
3799 
3800     // Get the new insert position for the node we care about.
3801     IncompleteArrayType *existing =
3802       IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
3803     assert(!existing && "Shouldn't be in the map!"); (void) existing;
3804   }
3805 
3806   auto *newType = new (*this, TypeAlignment)
3807     IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
3808 
3809   IncompleteArrayTypes.InsertNode(newType, insertPos);
3810   Types.push_back(newType);
3811   return QualType(newType, 0);
3812 }
3813 
3814 ASTContext::BuiltinVectorTypeInfo
3815 ASTContext::getBuiltinVectorTypeInfo(const BuiltinType *Ty) const {
3816 #define SVE_INT_ELTTY(BITS, ELTS, SIGNED, NUMVECTORS)                          \
3817   {getIntTypeForBitwidth(BITS, SIGNED), llvm::ElementCount::getScalable(ELTS), \
3818    NUMVECTORS};
3819 
3820 #define SVE_ELTTY(ELTTY, ELTS, NUMVECTORS)                                     \
3821   {ELTTY, llvm::ElementCount::getScalable(ELTS), NUMVECTORS};
3822 
3823   switch (Ty->getKind()) {
3824   default:
3825     llvm_unreachable("Unsupported builtin vector type");
3826   case BuiltinType::SveInt8:
3827     return SVE_INT_ELTTY(8, 16, true, 1);
3828   case BuiltinType::SveUint8:
3829     return SVE_INT_ELTTY(8, 16, false, 1);
3830   case BuiltinType::SveInt8x2:
3831     return SVE_INT_ELTTY(8, 16, true, 2);
3832   case BuiltinType::SveUint8x2:
3833     return SVE_INT_ELTTY(8, 16, false, 2);
3834   case BuiltinType::SveInt8x3:
3835     return SVE_INT_ELTTY(8, 16, true, 3);
3836   case BuiltinType::SveUint8x3:
3837     return SVE_INT_ELTTY(8, 16, false, 3);
3838   case BuiltinType::SveInt8x4:
3839     return SVE_INT_ELTTY(8, 16, true, 4);
3840   case BuiltinType::SveUint8x4:
3841     return SVE_INT_ELTTY(8, 16, false, 4);
3842   case BuiltinType::SveInt16:
3843     return SVE_INT_ELTTY(16, 8, true, 1);
3844   case BuiltinType::SveUint16:
3845     return SVE_INT_ELTTY(16, 8, false, 1);
3846   case BuiltinType::SveInt16x2:
3847     return SVE_INT_ELTTY(16, 8, true, 2);
3848   case BuiltinType::SveUint16x2:
3849     return SVE_INT_ELTTY(16, 8, false, 2);
3850   case BuiltinType::SveInt16x3:
3851     return SVE_INT_ELTTY(16, 8, true, 3);
3852   case BuiltinType::SveUint16x3:
3853     return SVE_INT_ELTTY(16, 8, false, 3);
3854   case BuiltinType::SveInt16x4:
3855     return SVE_INT_ELTTY(16, 8, true, 4);
3856   case BuiltinType::SveUint16x4:
3857     return SVE_INT_ELTTY(16, 8, false, 4);
3858   case BuiltinType::SveInt32:
3859     return SVE_INT_ELTTY(32, 4, true, 1);
3860   case BuiltinType::SveUint32:
3861     return SVE_INT_ELTTY(32, 4, false, 1);
3862   case BuiltinType::SveInt32x2:
3863     return SVE_INT_ELTTY(32, 4, true, 2);
3864   case BuiltinType::SveUint32x2:
3865     return SVE_INT_ELTTY(32, 4, false, 2);
3866   case BuiltinType::SveInt32x3:
3867     return SVE_INT_ELTTY(32, 4, true, 3);
3868   case BuiltinType::SveUint32x3:
3869     return SVE_INT_ELTTY(32, 4, false, 3);
3870   case BuiltinType::SveInt32x4:
3871     return SVE_INT_ELTTY(32, 4, true, 4);
3872   case BuiltinType::SveUint32x4:
3873     return SVE_INT_ELTTY(32, 4, false, 4);
3874   case BuiltinType::SveInt64:
3875     return SVE_INT_ELTTY(64, 2, true, 1);
3876   case BuiltinType::SveUint64:
3877     return SVE_INT_ELTTY(64, 2, false, 1);
3878   case BuiltinType::SveInt64x2:
3879     return SVE_INT_ELTTY(64, 2, true, 2);
3880   case BuiltinType::SveUint64x2:
3881     return SVE_INT_ELTTY(64, 2, false, 2);
3882   case BuiltinType::SveInt64x3:
3883     return SVE_INT_ELTTY(64, 2, true, 3);
3884   case BuiltinType::SveUint64x3:
3885     return SVE_INT_ELTTY(64, 2, false, 3);
3886   case BuiltinType::SveInt64x4:
3887     return SVE_INT_ELTTY(64, 2, true, 4);
3888   case BuiltinType::SveUint64x4:
3889     return SVE_INT_ELTTY(64, 2, false, 4);
3890   case BuiltinType::SveBool:
3891     return SVE_ELTTY(BoolTy, 16, 1);
3892   case BuiltinType::SveFloat16:
3893     return SVE_ELTTY(HalfTy, 8, 1);
3894   case BuiltinType::SveFloat16x2:
3895     return SVE_ELTTY(HalfTy, 8, 2);
3896   case BuiltinType::SveFloat16x3:
3897     return SVE_ELTTY(HalfTy, 8, 3);
3898   case BuiltinType::SveFloat16x4:
3899     return SVE_ELTTY(HalfTy, 8, 4);
3900   case BuiltinType::SveFloat32:
3901     return SVE_ELTTY(FloatTy, 4, 1);
3902   case BuiltinType::SveFloat32x2:
3903     return SVE_ELTTY(FloatTy, 4, 2);
3904   case BuiltinType::SveFloat32x3:
3905     return SVE_ELTTY(FloatTy, 4, 3);
3906   case BuiltinType::SveFloat32x4:
3907     return SVE_ELTTY(FloatTy, 4, 4);
3908   case BuiltinType::SveFloat64:
3909     return SVE_ELTTY(DoubleTy, 2, 1);
3910   case BuiltinType::SveFloat64x2:
3911     return SVE_ELTTY(DoubleTy, 2, 2);
3912   case BuiltinType::SveFloat64x3:
3913     return SVE_ELTTY(DoubleTy, 2, 3);
3914   case BuiltinType::SveFloat64x4:
3915     return SVE_ELTTY(DoubleTy, 2, 4);
3916   case BuiltinType::SveBFloat16:
3917     return SVE_ELTTY(BFloat16Ty, 8, 1);
3918   case BuiltinType::SveBFloat16x2:
3919     return SVE_ELTTY(BFloat16Ty, 8, 2);
3920   case BuiltinType::SveBFloat16x3:
3921     return SVE_ELTTY(BFloat16Ty, 8, 3);
3922   case BuiltinType::SveBFloat16x4:
3923     return SVE_ELTTY(BFloat16Ty, 8, 4);
3924 #define RVV_VECTOR_TYPE_INT(Name, Id, SingletonId, NumEls, ElBits, NF,         \
3925                             IsSigned)                                          \
3926   case BuiltinType::Id:                                                        \
3927     return {getIntTypeForBitwidth(ElBits, IsSigned),                           \
3928             llvm::ElementCount::getScalable(NumEls), NF};
3929 #define RVV_VECTOR_TYPE_FLOAT(Name, Id, SingletonId, NumEls, ElBits, NF)       \
3930   case BuiltinType::Id:                                                        \
3931     return {ElBits == 16 ? Float16Ty : (ElBits == 32 ? FloatTy : DoubleTy),    \
3932             llvm::ElementCount::getScalable(NumEls), NF};
3933 #define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls)                      \
3934   case BuiltinType::Id:                                                        \
3935     return {BoolTy, llvm::ElementCount::getScalable(NumEls), 1};
3936 #include "clang/Basic/RISCVVTypes.def"
3937   }
3938 }
3939 
3940 /// getScalableVectorType - Return the unique reference to a scalable vector
3941 /// type of the specified element type and size. VectorType must be a built-in
3942 /// type.
3943 QualType ASTContext::getScalableVectorType(QualType EltTy,
3944                                            unsigned NumElts) const {
3945   if (Target->hasAArch64SVETypes()) {
3946     uint64_t EltTySize = getTypeSize(EltTy);
3947 #define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId, NumEls, ElBits,    \
3948                         IsSigned, IsFP, IsBF)                                  \
3949   if (!EltTy->isBooleanType() &&                                               \
3950       ((EltTy->hasIntegerRepresentation() &&                                   \
3951         EltTy->hasSignedIntegerRepresentation() == IsSigned) ||                \
3952        (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() &&      \
3953         IsFP && !IsBF) ||                                                      \
3954        (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() &&       \
3955         IsBF && !IsFP)) &&                                                     \
3956       EltTySize == ElBits && NumElts == NumEls) {                              \
3957     return SingletonId;                                                        \
3958   }
3959 #define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId, NumEls)         \
3960   if (EltTy->isBooleanType() && NumElts == NumEls)                             \
3961     return SingletonId;
3962 #include "clang/Basic/AArch64SVEACLETypes.def"
3963   } else if (Target->hasRISCVVTypes()) {
3964     uint64_t EltTySize = getTypeSize(EltTy);
3965 #define RVV_VECTOR_TYPE(Name, Id, SingletonId, NumEls, ElBits, NF, IsSigned,   \
3966                         IsFP)                                                  \
3967     if (!EltTy->isBooleanType() &&                                             \
3968         ((EltTy->hasIntegerRepresentation() &&                                 \
3969           EltTy->hasSignedIntegerRepresentation() == IsSigned) ||              \
3970          (EltTy->hasFloatingRepresentation() && IsFP)) &&                      \
3971         EltTySize == ElBits && NumElts == NumEls)                              \
3972       return SingletonId;
3973 #define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls)                      \
3974     if (EltTy->isBooleanType() && NumElts == NumEls)                           \
3975       return SingletonId;
3976 #include "clang/Basic/RISCVVTypes.def"
3977   }
3978   return QualType();
3979 }
3980 
3981 /// getVectorType - Return the unique reference to a vector type of
3982 /// the specified element type and size. VectorType must be a built-in type.
3983 QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
3984                                    VectorType::VectorKind VecKind) const {
3985   assert(vecType->isBuiltinType());
3986 
3987   // Check if we've already instantiated a vector of this type.
3988   llvm::FoldingSetNodeID ID;
3989   VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
3990 
3991   void *InsertPos = nullptr;
3992   if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3993     return QualType(VTP, 0);
3994 
3995   // If the element type isn't canonical, this won't be a canonical type either,
3996   // so fill in the canonical type field.
3997   QualType Canonical;
3998   if (!vecType.isCanonical()) {
3999     Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
4000 
4001     // Get the new insert position for the node we care about.
4002     VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4003     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4004   }
4005   auto *New = new (*this, TypeAlignment)
4006     VectorType(vecType, NumElts, Canonical, VecKind);
4007   VectorTypes.InsertNode(New, InsertPos);
4008   Types.push_back(New);
4009   return QualType(New, 0);
4010 }
4011 
4012 QualType
4013 ASTContext::getDependentVectorType(QualType VecType, Expr *SizeExpr,
4014                                    SourceLocation AttrLoc,
4015                                    VectorType::VectorKind VecKind) const {
4016   llvm::FoldingSetNodeID ID;
4017   DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr,
4018                                VecKind);
4019   void *InsertPos = nullptr;
4020   DependentVectorType *Canon =
4021       DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4022   DependentVectorType *New;
4023 
4024   if (Canon) {
4025     New = new (*this, TypeAlignment) DependentVectorType(
4026         *this, VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind);
4027   } else {
4028     QualType CanonVecTy = getCanonicalType(VecType);
4029     if (CanonVecTy == VecType) {
4030       New = new (*this, TypeAlignment) DependentVectorType(
4031           *this, VecType, QualType(), SizeExpr, AttrLoc, VecKind);
4032 
4033       DependentVectorType *CanonCheck =
4034           DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4035       assert(!CanonCheck &&
4036              "Dependent-sized vector_size canonical type broken");
4037       (void)CanonCheck;
4038       DependentVectorTypes.InsertNode(New, InsertPos);
4039     } else {
4040       QualType CanonTy = getDependentVectorType(CanonVecTy, SizeExpr,
4041                                                 SourceLocation(), VecKind);
4042       New = new (*this, TypeAlignment) DependentVectorType(
4043           *this, VecType, CanonTy, SizeExpr, AttrLoc, VecKind);
4044     }
4045   }
4046 
4047   Types.push_back(New);
4048   return QualType(New, 0);
4049 }
4050 
4051 /// getExtVectorType - Return the unique reference to an extended vector type of
4052 /// the specified element type and size. VectorType must be a built-in type.
4053 QualType
4054 ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
4055   assert(vecType->isBuiltinType() || vecType->isDependentType());
4056 
4057   // Check if we've already instantiated a vector of this type.
4058   llvm::FoldingSetNodeID ID;
4059   VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
4060                       VectorType::GenericVector);
4061   void *InsertPos = nullptr;
4062   if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
4063     return QualType(VTP, 0);
4064 
4065   // If the element type isn't canonical, this won't be a canonical type either,
4066   // so fill in the canonical type field.
4067   QualType Canonical;
4068   if (!vecType.isCanonical()) {
4069     Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
4070 
4071     // Get the new insert position for the node we care about.
4072     VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4073     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4074   }
4075   auto *New = new (*this, TypeAlignment)
4076     ExtVectorType(vecType, NumElts, Canonical);
4077   VectorTypes.InsertNode(New, InsertPos);
4078   Types.push_back(New);
4079   return QualType(New, 0);
4080 }
4081 
4082 QualType
4083 ASTContext::getDependentSizedExtVectorType(QualType vecType,
4084                                            Expr *SizeExpr,
4085                                            SourceLocation AttrLoc) const {
4086   llvm::FoldingSetNodeID ID;
4087   DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
4088                                        SizeExpr);
4089 
4090   void *InsertPos = nullptr;
4091   DependentSizedExtVectorType *Canon
4092     = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4093   DependentSizedExtVectorType *New;
4094   if (Canon) {
4095     // We already have a canonical version of this array type; use it as
4096     // the canonical type for a newly-built type.
4097     New = new (*this, TypeAlignment)
4098       DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
4099                                   SizeExpr, AttrLoc);
4100   } else {
4101     QualType CanonVecTy = getCanonicalType(vecType);
4102     if (CanonVecTy == vecType) {
4103       New = new (*this, TypeAlignment)
4104         DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
4105                                     AttrLoc);
4106 
4107       DependentSizedExtVectorType *CanonCheck
4108         = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4109       assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
4110       (void)CanonCheck;
4111       DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
4112     } else {
4113       QualType CanonExtTy = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
4114                                                            SourceLocation());
4115       New = new (*this, TypeAlignment) DependentSizedExtVectorType(
4116           *this, vecType, CanonExtTy, SizeExpr, AttrLoc);
4117     }
4118   }
4119 
4120   Types.push_back(New);
4121   return QualType(New, 0);
4122 }
4123 
4124 QualType ASTContext::getConstantMatrixType(QualType ElementTy, unsigned NumRows,
4125                                            unsigned NumColumns) const {
4126   llvm::FoldingSetNodeID ID;
4127   ConstantMatrixType::Profile(ID, ElementTy, NumRows, NumColumns,
4128                               Type::ConstantMatrix);
4129 
4130   assert(MatrixType::isValidElementType(ElementTy) &&
4131          "need a valid element type");
4132   assert(ConstantMatrixType::isDimensionValid(NumRows) &&
4133          ConstantMatrixType::isDimensionValid(NumColumns) &&
4134          "need valid matrix dimensions");
4135   void *InsertPos = nullptr;
4136   if (ConstantMatrixType *MTP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos))
4137     return QualType(MTP, 0);
4138 
4139   QualType Canonical;
4140   if (!ElementTy.isCanonical()) {
4141     Canonical =
4142         getConstantMatrixType(getCanonicalType(ElementTy), NumRows, NumColumns);
4143 
4144     ConstantMatrixType *NewIP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4145     assert(!NewIP && "Matrix type shouldn't already exist in the map");
4146     (void)NewIP;
4147   }
4148 
4149   auto *New = new (*this, TypeAlignment)
4150       ConstantMatrixType(ElementTy, NumRows, NumColumns, Canonical);
4151   MatrixTypes.InsertNode(New, InsertPos);
4152   Types.push_back(New);
4153   return QualType(New, 0);
4154 }
4155 
4156 QualType ASTContext::getDependentSizedMatrixType(QualType ElementTy,
4157                                                  Expr *RowExpr,
4158                                                  Expr *ColumnExpr,
4159                                                  SourceLocation AttrLoc) const {
4160   QualType CanonElementTy = getCanonicalType(ElementTy);
4161   llvm::FoldingSetNodeID ID;
4162   DependentSizedMatrixType::Profile(ID, *this, CanonElementTy, RowExpr,
4163                                     ColumnExpr);
4164 
4165   void *InsertPos = nullptr;
4166   DependentSizedMatrixType *Canon =
4167       DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4168 
4169   if (!Canon) {
4170     Canon = new (*this, TypeAlignment) DependentSizedMatrixType(
4171         *this, CanonElementTy, QualType(), RowExpr, ColumnExpr, AttrLoc);
4172 #ifndef NDEBUG
4173     DependentSizedMatrixType *CanonCheck =
4174         DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4175     assert(!CanonCheck && "Dependent-sized matrix canonical type broken");
4176 #endif
4177     DependentSizedMatrixTypes.InsertNode(Canon, InsertPos);
4178     Types.push_back(Canon);
4179   }
4180 
4181   // Already have a canonical version of the matrix type
4182   //
4183   // If it exactly matches the requested type, use it directly.
4184   if (Canon->getElementType() == ElementTy && Canon->getRowExpr() == RowExpr &&
4185       Canon->getRowExpr() == ColumnExpr)
4186     return QualType(Canon, 0);
4187 
4188   // Use Canon as the canonical type for newly-built type.
4189   DependentSizedMatrixType *New = new (*this, TypeAlignment)
4190       DependentSizedMatrixType(*this, ElementTy, QualType(Canon, 0), RowExpr,
4191                                ColumnExpr, AttrLoc);
4192   Types.push_back(New);
4193   return QualType(New, 0);
4194 }
4195 
4196 QualType ASTContext::getDependentAddressSpaceType(QualType PointeeType,
4197                                                   Expr *AddrSpaceExpr,
4198                                                   SourceLocation AttrLoc) const {
4199   assert(AddrSpaceExpr->isInstantiationDependent());
4200 
4201   QualType canonPointeeType = getCanonicalType(PointeeType);
4202 
4203   void *insertPos = nullptr;
4204   llvm::FoldingSetNodeID ID;
4205   DependentAddressSpaceType::Profile(ID, *this, canonPointeeType,
4206                                      AddrSpaceExpr);
4207 
4208   DependentAddressSpaceType *canonTy =
4209     DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos);
4210 
4211   if (!canonTy) {
4212     canonTy = new (*this, TypeAlignment)
4213       DependentAddressSpaceType(*this, canonPointeeType,
4214                                 QualType(), AddrSpaceExpr, AttrLoc);
4215     DependentAddressSpaceTypes.InsertNode(canonTy, insertPos);
4216     Types.push_back(canonTy);
4217   }
4218 
4219   if (canonPointeeType == PointeeType &&
4220       canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
4221     return QualType(canonTy, 0);
4222 
4223   auto *sugaredType
4224     = new (*this, TypeAlignment)
4225         DependentAddressSpaceType(*this, PointeeType, QualType(canonTy, 0),
4226                                   AddrSpaceExpr, AttrLoc);
4227   Types.push_back(sugaredType);
4228   return QualType(sugaredType, 0);
4229 }
4230 
4231 /// Determine whether \p T is canonical as the result type of a function.
4232 static bool isCanonicalResultType(QualType T) {
4233   return T.isCanonical() &&
4234          (T.getObjCLifetime() == Qualifiers::OCL_None ||
4235           T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
4236 }
4237 
4238 /// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
4239 QualType
4240 ASTContext::getFunctionNoProtoType(QualType ResultTy,
4241                                    const FunctionType::ExtInfo &Info) const {
4242   // Unique functions, to guarantee there is only one function of a particular
4243   // structure.
4244   llvm::FoldingSetNodeID ID;
4245   FunctionNoProtoType::Profile(ID, ResultTy, Info);
4246 
4247   void *InsertPos = nullptr;
4248   if (FunctionNoProtoType *FT =
4249         FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
4250     return QualType(FT, 0);
4251 
4252   QualType Canonical;
4253   if (!isCanonicalResultType(ResultTy)) {
4254     Canonical =
4255       getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info);
4256 
4257     // Get the new insert position for the node we care about.
4258     FunctionNoProtoType *NewIP =
4259       FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
4260     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4261   }
4262 
4263   auto *New = new (*this, TypeAlignment)
4264     FunctionNoProtoType(ResultTy, Canonical, Info);
4265   Types.push_back(New);
4266   FunctionNoProtoTypes.InsertNode(New, InsertPos);
4267   return QualType(New, 0);
4268 }
4269 
4270 CanQualType
4271 ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
4272   CanQualType CanResultType = getCanonicalType(ResultType);
4273 
4274   // Canonical result types do not have ARC lifetime qualifiers.
4275   if (CanResultType.getQualifiers().hasObjCLifetime()) {
4276     Qualifiers Qs = CanResultType.getQualifiers();
4277     Qs.removeObjCLifetime();
4278     return CanQualType::CreateUnsafe(
4279              getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
4280   }
4281 
4282   return CanResultType;
4283 }
4284 
4285 static bool isCanonicalExceptionSpecification(
4286     const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
4287   if (ESI.Type == EST_None)
4288     return true;
4289   if (!NoexceptInType)
4290     return false;
4291 
4292   // C++17 onwards: exception specification is part of the type, as a simple
4293   // boolean "can this function type throw".
4294   if (ESI.Type == EST_BasicNoexcept)
4295     return true;
4296 
4297   // A noexcept(expr) specification is (possibly) canonical if expr is
4298   // value-dependent.
4299   if (ESI.Type == EST_DependentNoexcept)
4300     return true;
4301 
4302   // A dynamic exception specification is canonical if it only contains pack
4303   // expansions (so we can't tell whether it's non-throwing) and all its
4304   // contained types are canonical.
4305   if (ESI.Type == EST_Dynamic) {
4306     bool AnyPackExpansions = false;
4307     for (QualType ET : ESI.Exceptions) {
4308       if (!ET.isCanonical())
4309         return false;
4310       if (ET->getAs<PackExpansionType>())
4311         AnyPackExpansions = true;
4312     }
4313     return AnyPackExpansions;
4314   }
4315 
4316   return false;
4317 }
4318 
4319 QualType ASTContext::getFunctionTypeInternal(
4320     QualType ResultTy, ArrayRef<QualType> ArgArray,
4321     const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
4322   size_t NumArgs = ArgArray.size();
4323 
4324   // Unique functions, to guarantee there is only one function of a particular
4325   // structure.
4326   llvm::FoldingSetNodeID ID;
4327   FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
4328                              *this, true);
4329 
4330   QualType Canonical;
4331   bool Unique = false;
4332 
4333   void *InsertPos = nullptr;
4334   if (FunctionProtoType *FPT =
4335         FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
4336     QualType Existing = QualType(FPT, 0);
4337 
4338     // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
4339     // it so long as our exception specification doesn't contain a dependent
4340     // noexcept expression, or we're just looking for a canonical type.
4341     // Otherwise, we're going to need to create a type
4342     // sugar node to hold the concrete expression.
4343     if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) ||
4344         EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
4345       return Existing;
4346 
4347     // We need a new type sugar node for this one, to hold the new noexcept
4348     // expression. We do no canonicalization here, but that's OK since we don't
4349     // expect to see the same noexcept expression much more than once.
4350     Canonical = getCanonicalType(Existing);
4351     Unique = true;
4352   }
4353 
4354   bool NoexceptInType = getLangOpts().CPlusPlus17;
4355   bool IsCanonicalExceptionSpec =
4356       isCanonicalExceptionSpecification(EPI.ExceptionSpec, NoexceptInType);
4357 
4358   // Determine whether the type being created is already canonical or not.
4359   bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
4360                      isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
4361   for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
4362     if (!ArgArray[i].isCanonicalAsParam())
4363       isCanonical = false;
4364 
4365   if (OnlyWantCanonical)
4366     assert(isCanonical &&
4367            "given non-canonical parameters constructing canonical type");
4368 
4369   // If this type isn't canonical, get the canonical version of it if we don't
4370   // already have it. The exception spec is only partially part of the
4371   // canonical type, and only in C++17 onwards.
4372   if (!isCanonical && Canonical.isNull()) {
4373     SmallVector<QualType, 16> CanonicalArgs;
4374     CanonicalArgs.reserve(NumArgs);
4375     for (unsigned i = 0; i != NumArgs; ++i)
4376       CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
4377 
4378     llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
4379     FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
4380     CanonicalEPI.HasTrailingReturn = false;
4381 
4382     if (IsCanonicalExceptionSpec) {
4383       // Exception spec is already OK.
4384     } else if (NoexceptInType) {
4385       switch (EPI.ExceptionSpec.Type) {
4386       case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated:
4387         // We don't know yet. It shouldn't matter what we pick here; no-one
4388         // should ever look at this.
4389         LLVM_FALLTHROUGH;
4390       case EST_None: case EST_MSAny: case EST_NoexceptFalse:
4391         CanonicalEPI.ExceptionSpec.Type = EST_None;
4392         break;
4393 
4394         // A dynamic exception specification is almost always "not noexcept",
4395         // with the exception that a pack expansion might expand to no types.
4396       case EST_Dynamic: {
4397         bool AnyPacks = false;
4398         for (QualType ET : EPI.ExceptionSpec.Exceptions) {
4399           if (ET->getAs<PackExpansionType>())
4400             AnyPacks = true;
4401           ExceptionTypeStorage.push_back(getCanonicalType(ET));
4402         }
4403         if (!AnyPacks)
4404           CanonicalEPI.ExceptionSpec.Type = EST_None;
4405         else {
4406           CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
4407           CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
4408         }
4409         break;
4410       }
4411 
4412       case EST_DynamicNone:
4413       case EST_BasicNoexcept:
4414       case EST_NoexceptTrue:
4415       case EST_NoThrow:
4416         CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
4417         break;
4418 
4419       case EST_DependentNoexcept:
4420         llvm_unreachable("dependent noexcept is already canonical");
4421       }
4422     } else {
4423       CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
4424     }
4425 
4426     // Adjust the canonical function result type.
4427     CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
4428     Canonical =
4429         getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
4430 
4431     // Get the new insert position for the node we care about.
4432     FunctionProtoType *NewIP =
4433       FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
4434     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4435   }
4436 
4437   // Compute the needed size to hold this FunctionProtoType and the
4438   // various trailing objects.
4439   auto ESH = FunctionProtoType::getExceptionSpecSize(
4440       EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size());
4441   size_t Size = FunctionProtoType::totalSizeToAlloc<
4442       QualType, SourceLocation, FunctionType::FunctionTypeExtraBitfields,
4443       FunctionType::ExceptionType, Expr *, FunctionDecl *,
4444       FunctionProtoType::ExtParameterInfo, Qualifiers>(
4445       NumArgs, EPI.Variadic,
4446       FunctionProtoType::hasExtraBitfields(EPI.ExceptionSpec.Type),
4447       ESH.NumExceptionType, ESH.NumExprPtr, ESH.NumFunctionDeclPtr,
4448       EPI.ExtParameterInfos ? NumArgs : 0,
4449       EPI.TypeQuals.hasNonFastQualifiers() ? 1 : 0);
4450 
4451   auto *FTP = (FunctionProtoType *)Allocate(Size, TypeAlignment);
4452   FunctionProtoType::ExtProtoInfo newEPI = EPI;
4453   new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
4454   Types.push_back(FTP);
4455   if (!Unique)
4456     FunctionProtoTypes.InsertNode(FTP, InsertPos);
4457   return QualType(FTP, 0);
4458 }
4459 
4460 QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
4461   llvm::FoldingSetNodeID ID;
4462   PipeType::Profile(ID, T, ReadOnly);
4463 
4464   void *InsertPos = nullptr;
4465   if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
4466     return QualType(PT, 0);
4467 
4468   // If the pipe element type isn't canonical, this won't be a canonical type
4469   // either, so fill in the canonical type field.
4470   QualType Canonical;
4471   if (!T.isCanonical()) {
4472     Canonical = getPipeType(getCanonicalType(T), ReadOnly);
4473 
4474     // Get the new insert position for the node we care about.
4475     PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
4476     assert(!NewIP && "Shouldn't be in the map!");
4477     (void)NewIP;
4478   }
4479   auto *New = new (*this, TypeAlignment) PipeType(T, Canonical, ReadOnly);
4480   Types.push_back(New);
4481   PipeTypes.InsertNode(New, InsertPos);
4482   return QualType(New, 0);
4483 }
4484 
4485 QualType ASTContext::adjustStringLiteralBaseType(QualType Ty) const {
4486   // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
4487   return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant)
4488                          : Ty;
4489 }
4490 
4491 QualType ASTContext::getReadPipeType(QualType T) const {
4492   return getPipeType(T, true);
4493 }
4494 
4495 QualType ASTContext::getWritePipeType(QualType T) const {
4496   return getPipeType(T, false);
4497 }
4498 
4499 QualType ASTContext::getBitIntType(bool IsUnsigned, unsigned NumBits) const {
4500   llvm::FoldingSetNodeID ID;
4501   BitIntType::Profile(ID, IsUnsigned, NumBits);
4502 
4503   void *InsertPos = nullptr;
4504   if (BitIntType *EIT = BitIntTypes.FindNodeOrInsertPos(ID, InsertPos))
4505     return QualType(EIT, 0);
4506 
4507   auto *New = new (*this, TypeAlignment) BitIntType(IsUnsigned, NumBits);
4508   BitIntTypes.InsertNode(New, InsertPos);
4509   Types.push_back(New);
4510   return QualType(New, 0);
4511 }
4512 
4513 QualType ASTContext::getDependentBitIntType(bool IsUnsigned,
4514                                             Expr *NumBitsExpr) const {
4515   assert(NumBitsExpr->isInstantiationDependent() && "Only good for dependent");
4516   llvm::FoldingSetNodeID ID;
4517   DependentBitIntType::Profile(ID, *this, IsUnsigned, NumBitsExpr);
4518 
4519   void *InsertPos = nullptr;
4520   if (DependentBitIntType *Existing =
4521           DependentBitIntTypes.FindNodeOrInsertPos(ID, InsertPos))
4522     return QualType(Existing, 0);
4523 
4524   auto *New = new (*this, TypeAlignment)
4525       DependentBitIntType(*this, IsUnsigned, NumBitsExpr);
4526   DependentBitIntTypes.InsertNode(New, InsertPos);
4527 
4528   Types.push_back(New);
4529   return QualType(New, 0);
4530 }
4531 
4532 #ifndef NDEBUG
4533 static bool NeedsInjectedClassNameType(const RecordDecl *D) {
4534   if (!isa<CXXRecordDecl>(D)) return false;
4535   const auto *RD = cast<CXXRecordDecl>(D);
4536   if (isa<ClassTemplatePartialSpecializationDecl>(RD))
4537     return true;
4538   if (RD->getDescribedClassTemplate() &&
4539       !isa<ClassTemplateSpecializationDecl>(RD))
4540     return true;
4541   return false;
4542 }
4543 #endif
4544 
4545 /// getInjectedClassNameType - Return the unique reference to the
4546 /// injected class name type for the specified templated declaration.
4547 QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
4548                                               QualType TST) const {
4549   assert(NeedsInjectedClassNameType(Decl));
4550   if (Decl->TypeForDecl) {
4551     assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
4552   } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
4553     assert(PrevDecl->TypeForDecl && "previous declaration has no type");
4554     Decl->TypeForDecl = PrevDecl->TypeForDecl;
4555     assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
4556   } else {
4557     Type *newType =
4558       new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
4559     Decl->TypeForDecl = newType;
4560     Types.push_back(newType);
4561   }
4562   return QualType(Decl->TypeForDecl, 0);
4563 }
4564 
4565 /// getTypeDeclType - Return the unique reference to the type for the
4566 /// specified type declaration.
4567 QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
4568   assert(Decl && "Passed null for Decl param");
4569   assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
4570 
4571   if (const auto *Typedef = dyn_cast<TypedefNameDecl>(Decl))
4572     return getTypedefType(Typedef);
4573 
4574   assert(!isa<TemplateTypeParmDecl>(Decl) &&
4575          "Template type parameter types are always available.");
4576 
4577   if (const auto *Record = dyn_cast<RecordDecl>(Decl)) {
4578     assert(Record->isFirstDecl() && "struct/union has previous declaration");
4579     assert(!NeedsInjectedClassNameType(Record));
4580     return getRecordType(Record);
4581   } else if (const auto *Enum = dyn_cast<EnumDecl>(Decl)) {
4582     assert(Enum->isFirstDecl() && "enum has previous declaration");
4583     return getEnumType(Enum);
4584   } else if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
4585     return getUnresolvedUsingType(Using);
4586   } else
4587     llvm_unreachable("TypeDecl without a type?");
4588 
4589   return QualType(Decl->TypeForDecl, 0);
4590 }
4591 
4592 /// getTypedefType - Return the unique reference to the type for the
4593 /// specified typedef name decl.
4594 QualType ASTContext::getTypedefType(const TypedefNameDecl *Decl,
4595                                     QualType Underlying) const {
4596   if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
4597 
4598   if (Underlying.isNull())
4599     Underlying = Decl->getUnderlyingType();
4600   QualType Canonical = getCanonicalType(Underlying);
4601   auto *newType = new (*this, TypeAlignment)
4602       TypedefType(Type::Typedef, Decl, Underlying, Canonical);
4603   Decl->TypeForDecl = newType;
4604   Types.push_back(newType);
4605   return QualType(newType, 0);
4606 }
4607 
4608 QualType ASTContext::getUsingType(const UsingShadowDecl *Found,
4609                                   QualType Underlying) const {
4610   llvm::FoldingSetNodeID ID;
4611   UsingType::Profile(ID, Found);
4612 
4613   void *InsertPos = nullptr;
4614   UsingType *T = UsingTypes.FindNodeOrInsertPos(ID, InsertPos);
4615   if (T)
4616     return QualType(T, 0);
4617 
4618   assert(!Underlying.hasLocalQualifiers());
4619   assert(Underlying == getTypeDeclType(cast<TypeDecl>(Found->getTargetDecl())));
4620   QualType Canon = Underlying.getCanonicalType();
4621 
4622   UsingType *NewType =
4623       new (*this, TypeAlignment) UsingType(Found, Underlying, Canon);
4624   Types.push_back(NewType);
4625   UsingTypes.InsertNode(NewType, InsertPos);
4626   return QualType(NewType, 0);
4627 }
4628 
4629 QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
4630   if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
4631 
4632   if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
4633     if (PrevDecl->TypeForDecl)
4634       return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
4635 
4636   auto *newType = new (*this, TypeAlignment) RecordType(Decl);
4637   Decl->TypeForDecl = newType;
4638   Types.push_back(newType);
4639   return QualType(newType, 0);
4640 }
4641 
4642 QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
4643   if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
4644 
4645   if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
4646     if (PrevDecl->TypeForDecl)
4647       return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
4648 
4649   auto *newType = new (*this, TypeAlignment) EnumType(Decl);
4650   Decl->TypeForDecl = newType;
4651   Types.push_back(newType);
4652   return QualType(newType, 0);
4653 }
4654 
4655 QualType ASTContext::getUnresolvedUsingType(
4656     const UnresolvedUsingTypenameDecl *Decl) const {
4657   if (Decl->TypeForDecl)
4658     return QualType(Decl->TypeForDecl, 0);
4659 
4660   if (const UnresolvedUsingTypenameDecl *CanonicalDecl =
4661           Decl->getCanonicalDecl())
4662     if (CanonicalDecl->TypeForDecl)
4663       return QualType(Decl->TypeForDecl = CanonicalDecl->TypeForDecl, 0);
4664 
4665   Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Decl);
4666   Decl->TypeForDecl = newType;
4667   Types.push_back(newType);
4668   return QualType(newType, 0);
4669 }
4670 
4671 QualType ASTContext::getAttributedType(attr::Kind attrKind,
4672                                        QualType modifiedType,
4673                                        QualType equivalentType) {
4674   llvm::FoldingSetNodeID id;
4675   AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
4676 
4677   void *insertPos = nullptr;
4678   AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
4679   if (type) return QualType(type, 0);
4680 
4681   QualType canon = getCanonicalType(equivalentType);
4682   type = new (*this, TypeAlignment)
4683       AttributedType(canon, attrKind, modifiedType, equivalentType);
4684 
4685   Types.push_back(type);
4686   AttributedTypes.InsertNode(type, insertPos);
4687 
4688   return QualType(type, 0);
4689 }
4690 
4691 QualType ASTContext::getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr,
4692                                              QualType Wrapped) {
4693   llvm::FoldingSetNodeID ID;
4694   BTFTagAttributedType::Profile(ID, Wrapped, BTFAttr);
4695 
4696   void *InsertPos = nullptr;
4697   BTFTagAttributedType *Ty =
4698       BTFTagAttributedTypes.FindNodeOrInsertPos(ID, InsertPos);
4699   if (Ty)
4700     return QualType(Ty, 0);
4701 
4702   QualType Canon = getCanonicalType(Wrapped);
4703   Ty = new (*this, TypeAlignment) BTFTagAttributedType(Canon, Wrapped, BTFAttr);
4704 
4705   Types.push_back(Ty);
4706   BTFTagAttributedTypes.InsertNode(Ty, InsertPos);
4707 
4708   return QualType(Ty, 0);
4709 }
4710 
4711 /// Retrieve a substitution-result type.
4712 QualType
4713 ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
4714                                          QualType Replacement) const {
4715   assert(Replacement.isCanonical()
4716          && "replacement types must always be canonical");
4717 
4718   llvm::FoldingSetNodeID ID;
4719   SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
4720   void *InsertPos = nullptr;
4721   SubstTemplateTypeParmType *SubstParm
4722     = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4723 
4724   if (!SubstParm) {
4725     SubstParm = new (*this, TypeAlignment)
4726       SubstTemplateTypeParmType(Parm, Replacement);
4727     Types.push_back(SubstParm);
4728     SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
4729   }
4730 
4731   return QualType(SubstParm, 0);
4732 }
4733 
4734 /// Retrieve a
4735 QualType ASTContext::getSubstTemplateTypeParmPackType(
4736                                           const TemplateTypeParmType *Parm,
4737                                               const TemplateArgument &ArgPack) {
4738 #ifndef NDEBUG
4739   for (const auto &P : ArgPack.pack_elements()) {
4740     assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
4741     assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
4742   }
4743 #endif
4744 
4745   llvm::FoldingSetNodeID ID;
4746   SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
4747   void *InsertPos = nullptr;
4748   if (SubstTemplateTypeParmPackType *SubstParm
4749         = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
4750     return QualType(SubstParm, 0);
4751 
4752   QualType Canon;
4753   if (!Parm->isCanonicalUnqualified()) {
4754     Canon = getCanonicalType(QualType(Parm, 0));
4755     Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
4756                                              ArgPack);
4757     SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
4758   }
4759 
4760   auto *SubstParm
4761     = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
4762                                                                ArgPack);
4763   Types.push_back(SubstParm);
4764   SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos);
4765   return QualType(SubstParm, 0);
4766 }
4767 
4768 /// Retrieve the template type parameter type for a template
4769 /// parameter or parameter pack with the given depth, index, and (optionally)
4770 /// name.
4771 QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
4772                                              bool ParameterPack,
4773                                              TemplateTypeParmDecl *TTPDecl) const {
4774   llvm::FoldingSetNodeID ID;
4775   TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
4776   void *InsertPos = nullptr;
4777   TemplateTypeParmType *TypeParm
4778     = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4779 
4780   if (TypeParm)
4781     return QualType(TypeParm, 0);
4782 
4783   if (TTPDecl) {
4784     QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
4785     TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
4786 
4787     TemplateTypeParmType *TypeCheck
4788       = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4789     assert(!TypeCheck && "Template type parameter canonical type broken");
4790     (void)TypeCheck;
4791   } else
4792     TypeParm = new (*this, TypeAlignment)
4793       TemplateTypeParmType(Depth, Index, ParameterPack);
4794 
4795   Types.push_back(TypeParm);
4796   TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
4797 
4798   return QualType(TypeParm, 0);
4799 }
4800 
4801 TypeSourceInfo *
4802 ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
4803                                               SourceLocation NameLoc,
4804                                         const TemplateArgumentListInfo &Args,
4805                                               QualType Underlying) const {
4806   assert(!Name.getAsDependentTemplateName() &&
4807          "No dependent template names here!");
4808   QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
4809 
4810   TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
4811   TemplateSpecializationTypeLoc TL =
4812       DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
4813   TL.setTemplateKeywordLoc(SourceLocation());
4814   TL.setTemplateNameLoc(NameLoc);
4815   TL.setLAngleLoc(Args.getLAngleLoc());
4816   TL.setRAngleLoc(Args.getRAngleLoc());
4817   for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
4818     TL.setArgLocInfo(i, Args[i].getLocInfo());
4819   return DI;
4820 }
4821 
4822 QualType
4823 ASTContext::getTemplateSpecializationType(TemplateName Template,
4824                                           const TemplateArgumentListInfo &Args,
4825                                           QualType Underlying) const {
4826   assert(!Template.getAsDependentTemplateName() &&
4827          "No dependent template names here!");
4828 
4829   SmallVector<TemplateArgument, 4> ArgVec;
4830   ArgVec.reserve(Args.size());
4831   for (const TemplateArgumentLoc &Arg : Args.arguments())
4832     ArgVec.push_back(Arg.getArgument());
4833 
4834   return getTemplateSpecializationType(Template, ArgVec, Underlying);
4835 }
4836 
4837 #ifndef NDEBUG
4838 static bool hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) {
4839   for (const TemplateArgument &Arg : Args)
4840     if (Arg.isPackExpansion())
4841       return true;
4842 
4843   return true;
4844 }
4845 #endif
4846 
4847 QualType
4848 ASTContext::getTemplateSpecializationType(TemplateName Template,
4849                                           ArrayRef<TemplateArgument> Args,
4850                                           QualType Underlying) const {
4851   assert(!Template.getAsDependentTemplateName() &&
4852          "No dependent template names here!");
4853   // Look through qualified template names.
4854   if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
4855     Template = TemplateName(QTN->getTemplateDecl());
4856 
4857   bool IsTypeAlias =
4858     Template.getAsTemplateDecl() &&
4859     isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
4860   QualType CanonType;
4861   if (!Underlying.isNull())
4862     CanonType = getCanonicalType(Underlying);
4863   else {
4864     // We can get here with an alias template when the specialization contains
4865     // a pack expansion that does not match up with a parameter pack.
4866     assert((!IsTypeAlias || hasAnyPackExpansions(Args)) &&
4867            "Caller must compute aliased type");
4868     IsTypeAlias = false;
4869     CanonType = getCanonicalTemplateSpecializationType(Template, Args);
4870   }
4871 
4872   // Allocate the (non-canonical) template specialization type, but don't
4873   // try to unique it: these types typically have location information that
4874   // we don't unique and don't want to lose.
4875   void *Mem = Allocate(sizeof(TemplateSpecializationType) +
4876                        sizeof(TemplateArgument) * Args.size() +
4877                        (IsTypeAlias? sizeof(QualType) : 0),
4878                        TypeAlignment);
4879   auto *Spec
4880     = new (Mem) TemplateSpecializationType(Template, Args, CanonType,
4881                                          IsTypeAlias ? Underlying : QualType());
4882 
4883   Types.push_back(Spec);
4884   return QualType(Spec, 0);
4885 }
4886 
4887 static bool
4888 getCanonicalTemplateArguments(const ASTContext &C,
4889                               ArrayRef<TemplateArgument> OrigArgs,
4890                               SmallVectorImpl<TemplateArgument> &CanonArgs) {
4891   bool AnyNonCanonArgs = false;
4892   unsigned NumArgs = OrigArgs.size();
4893   CanonArgs.resize(NumArgs);
4894   for (unsigned I = 0; I != NumArgs; ++I) {
4895     const TemplateArgument &OrigArg = OrigArgs[I];
4896     TemplateArgument &CanonArg = CanonArgs[I];
4897     CanonArg = C.getCanonicalTemplateArgument(OrigArg);
4898     if (!CanonArg.structurallyEquals(OrigArg))
4899       AnyNonCanonArgs = true;
4900   }
4901   return AnyNonCanonArgs;
4902 }
4903 
4904 QualType ASTContext::getCanonicalTemplateSpecializationType(
4905     TemplateName Template, ArrayRef<TemplateArgument> Args) const {
4906   assert(!Template.getAsDependentTemplateName() &&
4907          "No dependent template names here!");
4908 
4909   // Look through qualified template names.
4910   if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
4911     Template = TemplateName(QTN->getTemplateDecl());
4912 
4913   // Build the canonical template specialization type.
4914   TemplateName CanonTemplate = getCanonicalTemplateName(Template);
4915   SmallVector<TemplateArgument, 4> CanonArgs;
4916   ::getCanonicalTemplateArguments(*this, Args, CanonArgs);
4917 
4918   // Determine whether this canonical template specialization type already
4919   // exists.
4920   llvm::FoldingSetNodeID ID;
4921   TemplateSpecializationType::Profile(ID, CanonTemplate,
4922                                       CanonArgs, *this);
4923 
4924   void *InsertPos = nullptr;
4925   TemplateSpecializationType *Spec
4926     = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
4927 
4928   if (!Spec) {
4929     // Allocate a new canonical template specialization type.
4930     void *Mem = Allocate((sizeof(TemplateSpecializationType) +
4931                           sizeof(TemplateArgument) * CanonArgs.size()),
4932                          TypeAlignment);
4933     Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
4934                                                 CanonArgs,
4935                                                 QualType(), QualType());
4936     Types.push_back(Spec);
4937     TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
4938   }
4939 
4940   assert(Spec->isDependentType() &&
4941          "Non-dependent template-id type must have a canonical type");
4942   return QualType(Spec, 0);
4943 }
4944 
4945 QualType ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
4946                                        NestedNameSpecifier *NNS,
4947                                        QualType NamedType,
4948                                        TagDecl *OwnedTagDecl) const {
4949   llvm::FoldingSetNodeID ID;
4950   ElaboratedType::Profile(ID, Keyword, NNS, NamedType, OwnedTagDecl);
4951 
4952   void *InsertPos = nullptr;
4953   ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
4954   if (T)
4955     return QualType(T, 0);
4956 
4957   QualType Canon = NamedType;
4958   if (!Canon.isCanonical()) {
4959     Canon = getCanonicalType(NamedType);
4960     ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
4961     assert(!CheckT && "Elaborated canonical type broken");
4962     (void)CheckT;
4963   }
4964 
4965   void *Mem = Allocate(ElaboratedType::totalSizeToAlloc<TagDecl *>(!!OwnedTagDecl),
4966                        TypeAlignment);
4967   T = new (Mem) ElaboratedType(Keyword, NNS, NamedType, Canon, OwnedTagDecl);
4968 
4969   Types.push_back(T);
4970   ElaboratedTypes.InsertNode(T, InsertPos);
4971   return QualType(T, 0);
4972 }
4973 
4974 QualType
4975 ASTContext::getParenType(QualType InnerType) const {
4976   llvm::FoldingSetNodeID ID;
4977   ParenType::Profile(ID, InnerType);
4978 
4979   void *InsertPos = nullptr;
4980   ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
4981   if (T)
4982     return QualType(T, 0);
4983 
4984   QualType Canon = InnerType;
4985   if (!Canon.isCanonical()) {
4986     Canon = getCanonicalType(InnerType);
4987     ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
4988     assert(!CheckT && "Paren canonical type broken");
4989     (void)CheckT;
4990   }
4991 
4992   T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
4993   Types.push_back(T);
4994   ParenTypes.InsertNode(T, InsertPos);
4995   return QualType(T, 0);
4996 }
4997 
4998 QualType
4999 ASTContext::getMacroQualifiedType(QualType UnderlyingTy,
5000                                   const IdentifierInfo *MacroII) const {
5001   QualType Canon = UnderlyingTy;
5002   if (!Canon.isCanonical())
5003     Canon = getCanonicalType(UnderlyingTy);
5004 
5005   auto *newType = new (*this, TypeAlignment)
5006       MacroQualifiedType(UnderlyingTy, Canon, MacroII);
5007   Types.push_back(newType);
5008   return QualType(newType, 0);
5009 }
5010 
5011 QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
5012                                           NestedNameSpecifier *NNS,
5013                                           const IdentifierInfo *Name,
5014                                           QualType Canon) const {
5015   if (Canon.isNull()) {
5016     NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5017     if (CanonNNS != NNS)
5018       Canon = getDependentNameType(Keyword, CanonNNS, Name);
5019   }
5020 
5021   llvm::FoldingSetNodeID ID;
5022   DependentNameType::Profile(ID, Keyword, NNS, Name);
5023 
5024   void *InsertPos = nullptr;
5025   DependentNameType *T
5026     = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
5027   if (T)
5028     return QualType(T, 0);
5029 
5030   T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
5031   Types.push_back(T);
5032   DependentNameTypes.InsertNode(T, InsertPos);
5033   return QualType(T, 0);
5034 }
5035 
5036 QualType
5037 ASTContext::getDependentTemplateSpecializationType(
5038                                  ElaboratedTypeKeyword Keyword,
5039                                  NestedNameSpecifier *NNS,
5040                                  const IdentifierInfo *Name,
5041                                  const TemplateArgumentListInfo &Args) const {
5042   // TODO: avoid this copy
5043   SmallVector<TemplateArgument, 16> ArgCopy;
5044   for (unsigned I = 0, E = Args.size(); I != E; ++I)
5045     ArgCopy.push_back(Args[I].getArgument());
5046   return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy);
5047 }
5048 
5049 QualType
5050 ASTContext::getDependentTemplateSpecializationType(
5051                                  ElaboratedTypeKeyword Keyword,
5052                                  NestedNameSpecifier *NNS,
5053                                  const IdentifierInfo *Name,
5054                                  ArrayRef<TemplateArgument> Args) const {
5055   assert((!NNS || NNS->isDependent()) &&
5056          "nested-name-specifier must be dependent");
5057 
5058   llvm::FoldingSetNodeID ID;
5059   DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
5060                                                Name, Args);
5061 
5062   void *InsertPos = nullptr;
5063   DependentTemplateSpecializationType *T
5064     = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
5065   if (T)
5066     return QualType(T, 0);
5067 
5068   NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5069 
5070   ElaboratedTypeKeyword CanonKeyword = Keyword;
5071   if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
5072 
5073   SmallVector<TemplateArgument, 16> CanonArgs;
5074   bool AnyNonCanonArgs =
5075       ::getCanonicalTemplateArguments(*this, Args, CanonArgs);
5076 
5077   QualType Canon;
5078   if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
5079     Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
5080                                                    Name,
5081                                                    CanonArgs);
5082 
5083     // Find the insert position again.
5084     DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
5085   }
5086 
5087   void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
5088                         sizeof(TemplateArgument) * Args.size()),
5089                        TypeAlignment);
5090   T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
5091                                                     Name, Args, Canon);
5092   Types.push_back(T);
5093   DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
5094   return QualType(T, 0);
5095 }
5096 
5097 TemplateArgument ASTContext::getInjectedTemplateArg(NamedDecl *Param) {
5098   TemplateArgument Arg;
5099   if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
5100     QualType ArgType = getTypeDeclType(TTP);
5101     if (TTP->isParameterPack())
5102       ArgType = getPackExpansionType(ArgType, None);
5103 
5104     Arg = TemplateArgument(ArgType);
5105   } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5106     QualType T =
5107         NTTP->getType().getNonPackExpansionType().getNonLValueExprType(*this);
5108     // For class NTTPs, ensure we include the 'const' so the type matches that
5109     // of a real template argument.
5110     // FIXME: It would be more faithful to model this as something like an
5111     // lvalue-to-rvalue conversion applied to a const-qualified lvalue.
5112     if (T->isRecordType())
5113       T.addConst();
5114     Expr *E = new (*this) DeclRefExpr(
5115         *this, NTTP, /*enclosing*/ false, T,
5116         Expr::getValueKindForType(NTTP->getType()), NTTP->getLocation());
5117 
5118     if (NTTP->isParameterPack())
5119       E = new (*this) PackExpansionExpr(DependentTy, E, NTTP->getLocation(),
5120                                         None);
5121     Arg = TemplateArgument(E);
5122   } else {
5123     auto *TTP = cast<TemplateTemplateParmDecl>(Param);
5124     if (TTP->isParameterPack())
5125       Arg = TemplateArgument(TemplateName(TTP), Optional<unsigned>());
5126     else
5127       Arg = TemplateArgument(TemplateName(TTP));
5128   }
5129 
5130   if (Param->isTemplateParameterPack())
5131     Arg = TemplateArgument::CreatePackCopy(*this, Arg);
5132 
5133   return Arg;
5134 }
5135 
5136 void
5137 ASTContext::getInjectedTemplateArgs(const TemplateParameterList *Params,
5138                                     SmallVectorImpl<TemplateArgument> &Args) {
5139   Args.reserve(Args.size() + Params->size());
5140 
5141   for (NamedDecl *Param : *Params)
5142     Args.push_back(getInjectedTemplateArg(Param));
5143 }
5144 
5145 QualType ASTContext::getPackExpansionType(QualType Pattern,
5146                                           Optional<unsigned> NumExpansions,
5147                                           bool ExpectPackInType) {
5148   assert((!ExpectPackInType || Pattern->containsUnexpandedParameterPack()) &&
5149          "Pack expansions must expand one or more parameter packs");
5150 
5151   llvm::FoldingSetNodeID ID;
5152   PackExpansionType::Profile(ID, Pattern, NumExpansions);
5153 
5154   void *InsertPos = nullptr;
5155   PackExpansionType *T = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
5156   if (T)
5157     return QualType(T, 0);
5158 
5159   QualType Canon;
5160   if (!Pattern.isCanonical()) {
5161     Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions,
5162                                  /*ExpectPackInType=*/false);
5163 
5164     // Find the insert position again, in case we inserted an element into
5165     // PackExpansionTypes and invalidated our insert position.
5166     PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
5167   }
5168 
5169   T = new (*this, TypeAlignment)
5170       PackExpansionType(Pattern, Canon, NumExpansions);
5171   Types.push_back(T);
5172   PackExpansionTypes.InsertNode(T, InsertPos);
5173   return QualType(T, 0);
5174 }
5175 
5176 /// CmpProtocolNames - Comparison predicate for sorting protocols
5177 /// alphabetically.
5178 static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
5179                             ObjCProtocolDecl *const *RHS) {
5180   return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
5181 }
5182 
5183 static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) {
5184   if (Protocols.empty()) return true;
5185 
5186   if (Protocols[0]->getCanonicalDecl() != Protocols[0])
5187     return false;
5188 
5189   for (unsigned i = 1; i != Protocols.size(); ++i)
5190     if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
5191         Protocols[i]->getCanonicalDecl() != Protocols[i])
5192       return false;
5193   return true;
5194 }
5195 
5196 static void
5197 SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
5198   // Sort protocols, keyed by name.
5199   llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
5200 
5201   // Canonicalize.
5202   for (ObjCProtocolDecl *&P : Protocols)
5203     P = P->getCanonicalDecl();
5204 
5205   // Remove duplicates.
5206   auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
5207   Protocols.erase(ProtocolsEnd, Protocols.end());
5208 }
5209 
5210 QualType ASTContext::getObjCObjectType(QualType BaseType,
5211                                        ObjCProtocolDecl * const *Protocols,
5212                                        unsigned NumProtocols) const {
5213   return getObjCObjectType(BaseType, {},
5214                            llvm::makeArrayRef(Protocols, NumProtocols),
5215                            /*isKindOf=*/false);
5216 }
5217 
5218 QualType ASTContext::getObjCObjectType(
5219            QualType baseType,
5220            ArrayRef<QualType> typeArgs,
5221            ArrayRef<ObjCProtocolDecl *> protocols,
5222            bool isKindOf) const {
5223   // If the base type is an interface and there aren't any protocols or
5224   // type arguments to add, then the interface type will do just fine.
5225   if (typeArgs.empty() && protocols.empty() && !isKindOf &&
5226       isa<ObjCInterfaceType>(baseType))
5227     return baseType;
5228 
5229   // Look in the folding set for an existing type.
5230   llvm::FoldingSetNodeID ID;
5231   ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
5232   void *InsertPos = nullptr;
5233   if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
5234     return QualType(QT, 0);
5235 
5236   // Determine the type arguments to be used for canonicalization,
5237   // which may be explicitly specified here or written on the base
5238   // type.
5239   ArrayRef<QualType> effectiveTypeArgs = typeArgs;
5240   if (effectiveTypeArgs.empty()) {
5241     if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
5242       effectiveTypeArgs = baseObject->getTypeArgs();
5243   }
5244 
5245   // Build the canonical type, which has the canonical base type and a
5246   // sorted-and-uniqued list of protocols and the type arguments
5247   // canonicalized.
5248   QualType canonical;
5249   bool typeArgsAreCanonical = llvm::all_of(
5250       effectiveTypeArgs, [&](QualType type) { return type.isCanonical(); });
5251   bool protocolsSorted = areSortedAndUniqued(protocols);
5252   if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
5253     // Determine the canonical type arguments.
5254     ArrayRef<QualType> canonTypeArgs;
5255     SmallVector<QualType, 4> canonTypeArgsVec;
5256     if (!typeArgsAreCanonical) {
5257       canonTypeArgsVec.reserve(effectiveTypeArgs.size());
5258       for (auto typeArg : effectiveTypeArgs)
5259         canonTypeArgsVec.push_back(getCanonicalType(typeArg));
5260       canonTypeArgs = canonTypeArgsVec;
5261     } else {
5262       canonTypeArgs = effectiveTypeArgs;
5263     }
5264 
5265     ArrayRef<ObjCProtocolDecl *> canonProtocols;
5266     SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
5267     if (!protocolsSorted) {
5268       canonProtocolsVec.append(protocols.begin(), protocols.end());
5269       SortAndUniqueProtocols(canonProtocolsVec);
5270       canonProtocols = canonProtocolsVec;
5271     } else {
5272       canonProtocols = protocols;
5273     }
5274 
5275     canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
5276                                   canonProtocols, isKindOf);
5277 
5278     // Regenerate InsertPos.
5279     ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
5280   }
5281 
5282   unsigned size = sizeof(ObjCObjectTypeImpl);
5283   size += typeArgs.size() * sizeof(QualType);
5284   size += protocols.size() * sizeof(ObjCProtocolDecl *);
5285   void *mem = Allocate(size, TypeAlignment);
5286   auto *T =
5287     new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
5288                                  isKindOf);
5289 
5290   Types.push_back(T);
5291   ObjCObjectTypes.InsertNode(T, InsertPos);
5292   return QualType(T, 0);
5293 }
5294 
5295 /// Apply Objective-C protocol qualifiers to the given type.
5296 /// If this is for the canonical type of a type parameter, we can apply
5297 /// protocol qualifiers on the ObjCObjectPointerType.
5298 QualType
5299 ASTContext::applyObjCProtocolQualifiers(QualType type,
5300                   ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
5301                   bool allowOnPointerType) const {
5302   hasError = false;
5303 
5304   if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
5305     return getObjCTypeParamType(objT->getDecl(), protocols);
5306   }
5307 
5308   // Apply protocol qualifiers to ObjCObjectPointerType.
5309   if (allowOnPointerType) {
5310     if (const auto *objPtr =
5311             dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
5312       const ObjCObjectType *objT = objPtr->getObjectType();
5313       // Merge protocol lists and construct ObjCObjectType.
5314       SmallVector<ObjCProtocolDecl*, 8> protocolsVec;
5315       protocolsVec.append(objT->qual_begin(),
5316                           objT->qual_end());
5317       protocolsVec.append(protocols.begin(), protocols.end());
5318       ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
5319       type = getObjCObjectType(
5320              objT->getBaseType(),
5321              objT->getTypeArgsAsWritten(),
5322              protocols,
5323              objT->isKindOfTypeAsWritten());
5324       return getObjCObjectPointerType(type);
5325     }
5326   }
5327 
5328   // Apply protocol qualifiers to ObjCObjectType.
5329   if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
5330     // FIXME: Check for protocols to which the class type is already
5331     // known to conform.
5332 
5333     return getObjCObjectType(objT->getBaseType(),
5334                              objT->getTypeArgsAsWritten(),
5335                              protocols,
5336                              objT->isKindOfTypeAsWritten());
5337   }
5338 
5339   // If the canonical type is ObjCObjectType, ...
5340   if (type->isObjCObjectType()) {
5341     // Silently overwrite any existing protocol qualifiers.
5342     // TODO: determine whether that's the right thing to do.
5343 
5344     // FIXME: Check for protocols to which the class type is already
5345     // known to conform.
5346     return getObjCObjectType(type, {}, protocols, false);
5347   }
5348 
5349   // id<protocol-list>
5350   if (type->isObjCIdType()) {
5351     const auto *objPtr = type->castAs<ObjCObjectPointerType>();
5352     type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols,
5353                                  objPtr->isKindOfType());
5354     return getObjCObjectPointerType(type);
5355   }
5356 
5357   // Class<protocol-list>
5358   if (type->isObjCClassType()) {
5359     const auto *objPtr = type->castAs<ObjCObjectPointerType>();
5360     type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols,
5361                                  objPtr->isKindOfType());
5362     return getObjCObjectPointerType(type);
5363   }
5364 
5365   hasError = true;
5366   return type;
5367 }
5368 
5369 QualType
5370 ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
5371                                  ArrayRef<ObjCProtocolDecl *> protocols) const {
5372   // Look in the folding set for an existing type.
5373   llvm::FoldingSetNodeID ID;
5374   ObjCTypeParamType::Profile(ID, Decl, Decl->getUnderlyingType(), protocols);
5375   void *InsertPos = nullptr;
5376   if (ObjCTypeParamType *TypeParam =
5377       ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
5378     return QualType(TypeParam, 0);
5379 
5380   // We canonicalize to the underlying type.
5381   QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
5382   if (!protocols.empty()) {
5383     // Apply the protocol qualifers.
5384     bool hasError;
5385     Canonical = getCanonicalType(applyObjCProtocolQualifiers(
5386         Canonical, protocols, hasError, true /*allowOnPointerType*/));
5387     assert(!hasError && "Error when apply protocol qualifier to bound type");
5388   }
5389 
5390   unsigned size = sizeof(ObjCTypeParamType);
5391   size += protocols.size() * sizeof(ObjCProtocolDecl *);
5392   void *mem = Allocate(size, TypeAlignment);
5393   auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
5394 
5395   Types.push_back(newType);
5396   ObjCTypeParamTypes.InsertNode(newType, InsertPos);
5397   return QualType(newType, 0);
5398 }
5399 
5400 void ASTContext::adjustObjCTypeParamBoundType(const ObjCTypeParamDecl *Orig,
5401                                               ObjCTypeParamDecl *New) const {
5402   New->setTypeSourceInfo(getTrivialTypeSourceInfo(Orig->getUnderlyingType()));
5403   // Update TypeForDecl after updating TypeSourceInfo.
5404   auto NewTypeParamTy = cast<ObjCTypeParamType>(New->getTypeForDecl());
5405   SmallVector<ObjCProtocolDecl *, 8> protocols;
5406   protocols.append(NewTypeParamTy->qual_begin(), NewTypeParamTy->qual_end());
5407   QualType UpdatedTy = getObjCTypeParamType(New, protocols);
5408   New->setTypeForDecl(UpdatedTy.getTypePtr());
5409 }
5410 
5411 /// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
5412 /// protocol list adopt all protocols in QT's qualified-id protocol
5413 /// list.
5414 bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
5415                                                 ObjCInterfaceDecl *IC) {
5416   if (!QT->isObjCQualifiedIdType())
5417     return false;
5418 
5419   if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
5420     // If both the right and left sides have qualifiers.
5421     for (auto *Proto : OPT->quals()) {
5422       if (!IC->ClassImplementsProtocol(Proto, false))
5423         return false;
5424     }
5425     return true;
5426   }
5427   return false;
5428 }
5429 
5430 /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
5431 /// QT's qualified-id protocol list adopt all protocols in IDecl's list
5432 /// of protocols.
5433 bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
5434                                                 ObjCInterfaceDecl *IDecl) {
5435   if (!QT->isObjCQualifiedIdType())
5436     return false;
5437   const auto *OPT = QT->getAs<ObjCObjectPointerType>();
5438   if (!OPT)
5439     return false;
5440   if (!IDecl->hasDefinition())
5441     return false;
5442   llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
5443   CollectInheritedProtocols(IDecl, InheritedProtocols);
5444   if (InheritedProtocols.empty())
5445     return false;
5446   // Check that if every protocol in list of id<plist> conforms to a protocol
5447   // of IDecl's, then bridge casting is ok.
5448   bool Conforms = false;
5449   for (auto *Proto : OPT->quals()) {
5450     Conforms = false;
5451     for (auto *PI : InheritedProtocols) {
5452       if (ProtocolCompatibleWithProtocol(Proto, PI)) {
5453         Conforms = true;
5454         break;
5455       }
5456     }
5457     if (!Conforms)
5458       break;
5459   }
5460   if (Conforms)
5461     return true;
5462 
5463   for (auto *PI : InheritedProtocols) {
5464     // If both the right and left sides have qualifiers.
5465     bool Adopts = false;
5466     for (auto *Proto : OPT->quals()) {
5467       // return 'true' if 'PI' is in the inheritance hierarchy of Proto
5468       if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
5469         break;
5470     }
5471     if (!Adopts)
5472       return false;
5473   }
5474   return true;
5475 }
5476 
5477 /// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
5478 /// the given object type.
5479 QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
5480   llvm::FoldingSetNodeID ID;
5481   ObjCObjectPointerType::Profile(ID, ObjectT);
5482 
5483   void *InsertPos = nullptr;
5484   if (ObjCObjectPointerType *QT =
5485               ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
5486     return QualType(QT, 0);
5487 
5488   // Find the canonical object type.
5489   QualType Canonical;
5490   if (!ObjectT.isCanonical()) {
5491     Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
5492 
5493     // Regenerate InsertPos.
5494     ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
5495   }
5496 
5497   // No match.
5498   void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
5499   auto *QType =
5500     new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
5501 
5502   Types.push_back(QType);
5503   ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
5504   return QualType(QType, 0);
5505 }
5506 
5507 /// getObjCInterfaceType - Return the unique reference to the type for the
5508 /// specified ObjC interface decl. The list of protocols is optional.
5509 QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
5510                                           ObjCInterfaceDecl *PrevDecl) const {
5511   if (Decl->TypeForDecl)
5512     return QualType(Decl->TypeForDecl, 0);
5513 
5514   if (PrevDecl) {
5515     assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
5516     Decl->TypeForDecl = PrevDecl->TypeForDecl;
5517     return QualType(PrevDecl->TypeForDecl, 0);
5518   }
5519 
5520   // Prefer the definition, if there is one.
5521   if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
5522     Decl = Def;
5523 
5524   void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
5525   auto *T = new (Mem) ObjCInterfaceType(Decl);
5526   Decl->TypeForDecl = T;
5527   Types.push_back(T);
5528   return QualType(T, 0);
5529 }
5530 
5531 /// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
5532 /// TypeOfExprType AST's (since expression's are never shared). For example,
5533 /// multiple declarations that refer to "typeof(x)" all contain different
5534 /// DeclRefExpr's. This doesn't effect the type checker, since it operates
5535 /// on canonical type's (which are always unique).
5536 QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
5537   TypeOfExprType *toe;
5538   if (tofExpr->isTypeDependent()) {
5539     llvm::FoldingSetNodeID ID;
5540     DependentTypeOfExprType::Profile(ID, *this, tofExpr);
5541 
5542     void *InsertPos = nullptr;
5543     DependentTypeOfExprType *Canon
5544       = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
5545     if (Canon) {
5546       // We already have a "canonical" version of an identical, dependent
5547       // typeof(expr) type. Use that as our canonical type.
5548       toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
5549                                           QualType((TypeOfExprType*)Canon, 0));
5550     } else {
5551       // Build a new, canonical typeof(expr) type.
5552       Canon
5553         = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
5554       DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
5555       toe = Canon;
5556     }
5557   } else {
5558     QualType Canonical = getCanonicalType(tofExpr->getType());
5559     toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
5560   }
5561   Types.push_back(toe);
5562   return QualType(toe, 0);
5563 }
5564 
5565 /// getTypeOfType -  Unlike many "get<Type>" functions, we don't unique
5566 /// TypeOfType nodes. The only motivation to unique these nodes would be
5567 /// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
5568 /// an issue. This doesn't affect the type checker, since it operates
5569 /// on canonical types (which are always unique).
5570 QualType ASTContext::getTypeOfType(QualType tofType) const {
5571   QualType Canonical = getCanonicalType(tofType);
5572   auto *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
5573   Types.push_back(tot);
5574   return QualType(tot, 0);
5575 }
5576 
5577 /// getReferenceQualifiedType - Given an expr, will return the type for
5578 /// that expression, as in [dcl.type.simple]p4 but without taking id-expressions
5579 /// and class member access into account.
5580 QualType ASTContext::getReferenceQualifiedType(const Expr *E) const {
5581   // C++11 [dcl.type.simple]p4:
5582   //   [...]
5583   QualType T = E->getType();
5584   switch (E->getValueKind()) {
5585   //     - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
5586   //       type of e;
5587   case VK_XValue:
5588     return getRValueReferenceType(T);
5589   //     - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
5590   //       type of e;
5591   case VK_LValue:
5592     return getLValueReferenceType(T);
5593   //  - otherwise, decltype(e) is the type of e.
5594   case VK_PRValue:
5595     return T;
5596   }
5597   llvm_unreachable("Unknown value kind");
5598 }
5599 
5600 /// Unlike many "get<Type>" functions, we don't unique DecltypeType
5601 /// nodes. This would never be helpful, since each such type has its own
5602 /// expression, and would not give a significant memory saving, since there
5603 /// is an Expr tree under each such type.
5604 QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
5605   DecltypeType *dt;
5606 
5607   // C++11 [temp.type]p2:
5608   //   If an expression e involves a template parameter, decltype(e) denotes a
5609   //   unique dependent type. Two such decltype-specifiers refer to the same
5610   //   type only if their expressions are equivalent (14.5.6.1).
5611   if (e->isInstantiationDependent()) {
5612     llvm::FoldingSetNodeID ID;
5613     DependentDecltypeType::Profile(ID, *this, e);
5614 
5615     void *InsertPos = nullptr;
5616     DependentDecltypeType *Canon
5617       = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
5618     if (!Canon) {
5619       // Build a new, canonical decltype(expr) type.
5620       Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
5621       DependentDecltypeTypes.InsertNode(Canon, InsertPos);
5622     }
5623     dt = new (*this, TypeAlignment)
5624         DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
5625   } else {
5626     dt = new (*this, TypeAlignment)
5627         DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
5628   }
5629   Types.push_back(dt);
5630   return QualType(dt, 0);
5631 }
5632 
5633 /// getUnaryTransformationType - We don't unique these, since the memory
5634 /// savings are minimal and these are rare.
5635 QualType ASTContext::getUnaryTransformType(QualType BaseType,
5636                                            QualType UnderlyingType,
5637                                            UnaryTransformType::UTTKind Kind)
5638     const {
5639   UnaryTransformType *ut = nullptr;
5640 
5641   if (BaseType->isDependentType()) {
5642     // Look in the folding set for an existing type.
5643     llvm::FoldingSetNodeID ID;
5644     DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind);
5645 
5646     void *InsertPos = nullptr;
5647     DependentUnaryTransformType *Canon
5648       = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
5649 
5650     if (!Canon) {
5651       // Build a new, canonical __underlying_type(type) type.
5652       Canon = new (*this, TypeAlignment)
5653              DependentUnaryTransformType(*this, getCanonicalType(BaseType),
5654                                          Kind);
5655       DependentUnaryTransformTypes.InsertNode(Canon, InsertPos);
5656     }
5657     ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
5658                                                         QualType(), Kind,
5659                                                         QualType(Canon, 0));
5660   } else {
5661     QualType CanonType = getCanonicalType(UnderlyingType);
5662     ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
5663                                                         UnderlyingType, Kind,
5664                                                         CanonType);
5665   }
5666   Types.push_back(ut);
5667   return QualType(ut, 0);
5668 }
5669 
5670 QualType ASTContext::getAutoTypeInternal(
5671     QualType DeducedType, AutoTypeKeyword Keyword, bool IsDependent,
5672     bool IsPack, ConceptDecl *TypeConstraintConcept,
5673     ArrayRef<TemplateArgument> TypeConstraintArgs, bool IsCanon) const {
5674   if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto &&
5675       !TypeConstraintConcept && !IsDependent)
5676     return getAutoDeductType();
5677 
5678   // Look in the folding set for an existing type.
5679   void *InsertPos = nullptr;
5680   llvm::FoldingSetNodeID ID;
5681   AutoType::Profile(ID, *this, DeducedType, Keyword, IsDependent,
5682                     TypeConstraintConcept, TypeConstraintArgs);
5683   if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
5684     return QualType(AT, 0);
5685 
5686   QualType Canon;
5687   if (!IsCanon) {
5688     if (DeducedType.isNull()) {
5689       SmallVector<TemplateArgument, 4> CanonArgs;
5690       bool AnyNonCanonArgs =
5691           ::getCanonicalTemplateArguments(*this, TypeConstraintArgs, CanonArgs);
5692       if (AnyNonCanonArgs) {
5693         Canon = getAutoTypeInternal(QualType(), Keyword, IsDependent, IsPack,
5694                                     TypeConstraintConcept, CanonArgs, true);
5695         // Find the insert position again.
5696         AutoTypes.FindNodeOrInsertPos(ID, InsertPos);
5697       }
5698     } else {
5699       Canon = DeducedType.getCanonicalType();
5700     }
5701   }
5702 
5703   void *Mem = Allocate(sizeof(AutoType) +
5704                            sizeof(TemplateArgument) * TypeConstraintArgs.size(),
5705                        TypeAlignment);
5706   auto *AT = new (Mem) AutoType(
5707       DeducedType, Keyword,
5708       (IsDependent ? TypeDependence::DependentInstantiation
5709                    : TypeDependence::None) |
5710           (IsPack ? TypeDependence::UnexpandedPack : TypeDependence::None),
5711       Canon, TypeConstraintConcept, TypeConstraintArgs);
5712   Types.push_back(AT);
5713   AutoTypes.InsertNode(AT, InsertPos);
5714   return QualType(AT, 0);
5715 }
5716 
5717 /// getAutoType - Return the uniqued reference to the 'auto' type which has been
5718 /// deduced to the given type, or to the canonical undeduced 'auto' type, or the
5719 /// canonical deduced-but-dependent 'auto' type.
5720 QualType
5721 ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
5722                         bool IsDependent, bool IsPack,
5723                         ConceptDecl *TypeConstraintConcept,
5724                         ArrayRef<TemplateArgument> TypeConstraintArgs) const {
5725   assert((!IsPack || IsDependent) && "only use IsPack for a dependent pack");
5726   assert((!IsDependent || DeducedType.isNull()) &&
5727          "A dependent auto should be undeduced");
5728   return getAutoTypeInternal(DeducedType, Keyword, IsDependent, IsPack,
5729                              TypeConstraintConcept, TypeConstraintArgs);
5730 }
5731 
5732 /// Return the uniqued reference to the deduced template specialization type
5733 /// which has been deduced to the given type, or to the canonical undeduced
5734 /// such type, or the canonical deduced-but-dependent such type.
5735 QualType ASTContext::getDeducedTemplateSpecializationType(
5736     TemplateName Template, QualType DeducedType, bool IsDependent) const {
5737   // Look in the folding set for an existing type.
5738   void *InsertPos = nullptr;
5739   llvm::FoldingSetNodeID ID;
5740   DeducedTemplateSpecializationType::Profile(ID, Template, DeducedType,
5741                                              IsDependent);
5742   if (DeducedTemplateSpecializationType *DTST =
5743           DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
5744     return QualType(DTST, 0);
5745 
5746   auto *DTST = new (*this, TypeAlignment)
5747       DeducedTemplateSpecializationType(Template, DeducedType, IsDependent);
5748   llvm::FoldingSetNodeID TempID;
5749   DTST->Profile(TempID);
5750   assert(ID == TempID && "ID does not match");
5751   Types.push_back(DTST);
5752   DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
5753   return QualType(DTST, 0);
5754 }
5755 
5756 /// getAtomicType - Return the uniqued reference to the atomic type for
5757 /// the given value type.
5758 QualType ASTContext::getAtomicType(QualType T) const {
5759   // Unique pointers, to guarantee there is only one pointer of a particular
5760   // structure.
5761   llvm::FoldingSetNodeID ID;
5762   AtomicType::Profile(ID, T);
5763 
5764   void *InsertPos = nullptr;
5765   if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
5766     return QualType(AT, 0);
5767 
5768   // If the atomic value type isn't canonical, this won't be a canonical type
5769   // either, so fill in the canonical type field.
5770   QualType Canonical;
5771   if (!T.isCanonical()) {
5772     Canonical = getAtomicType(getCanonicalType(T));
5773 
5774     // Get the new insert position for the node we care about.
5775     AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
5776     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
5777   }
5778   auto *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
5779   Types.push_back(New);
5780   AtomicTypes.InsertNode(New, InsertPos);
5781   return QualType(New, 0);
5782 }
5783 
5784 /// getAutoDeductType - Get type pattern for deducing against 'auto'.
5785 QualType ASTContext::getAutoDeductType() const {
5786   if (AutoDeductTy.isNull())
5787     AutoDeductTy = QualType(new (*this, TypeAlignment)
5788                                 AutoType(QualType(), AutoTypeKeyword::Auto,
5789                                          TypeDependence::None, QualType(),
5790                                          /*concept*/ nullptr, /*args*/ {}),
5791                             0);
5792   return AutoDeductTy;
5793 }
5794 
5795 /// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
5796 QualType ASTContext::getAutoRRefDeductType() const {
5797   if (AutoRRefDeductTy.isNull())
5798     AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
5799   assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
5800   return AutoRRefDeductTy;
5801 }
5802 
5803 /// getTagDeclType - Return the unique reference to the type for the
5804 /// specified TagDecl (struct/union/class/enum) decl.
5805 QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
5806   assert(Decl);
5807   // FIXME: What is the design on getTagDeclType when it requires casting
5808   // away const?  mutable?
5809   return getTypeDeclType(const_cast<TagDecl*>(Decl));
5810 }
5811 
5812 /// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
5813 /// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
5814 /// needs to agree with the definition in <stddef.h>.
5815 CanQualType ASTContext::getSizeType() const {
5816   return getFromTargetType(Target->getSizeType());
5817 }
5818 
5819 /// Return the unique signed counterpart of the integer type
5820 /// corresponding to size_t.
5821 CanQualType ASTContext::getSignedSizeType() const {
5822   return getFromTargetType(Target->getSignedSizeType());
5823 }
5824 
5825 /// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
5826 CanQualType ASTContext::getIntMaxType() const {
5827   return getFromTargetType(Target->getIntMaxType());
5828 }
5829 
5830 /// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
5831 CanQualType ASTContext::getUIntMaxType() const {
5832   return getFromTargetType(Target->getUIntMaxType());
5833 }
5834 
5835 /// getSignedWCharType - Return the type of "signed wchar_t".
5836 /// Used when in C++, as a GCC extension.
5837 QualType ASTContext::getSignedWCharType() const {
5838   // FIXME: derive from "Target" ?
5839   return WCharTy;
5840 }
5841 
5842 /// getUnsignedWCharType - Return the type of "unsigned wchar_t".
5843 /// Used when in C++, as a GCC extension.
5844 QualType ASTContext::getUnsignedWCharType() const {
5845   // FIXME: derive from "Target" ?
5846   return UnsignedIntTy;
5847 }
5848 
5849 QualType ASTContext::getIntPtrType() const {
5850   return getFromTargetType(Target->getIntPtrType());
5851 }
5852 
5853 QualType ASTContext::getUIntPtrType() const {
5854   return getCorrespondingUnsignedType(getIntPtrType());
5855 }
5856 
5857 /// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
5858 /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
5859 QualType ASTContext::getPointerDiffType() const {
5860   return getFromTargetType(Target->getPtrDiffType(0));
5861 }
5862 
5863 /// Return the unique unsigned counterpart of "ptrdiff_t"
5864 /// integer type. The standard (C11 7.21.6.1p7) refers to this type
5865 /// in the definition of %tu format specifier.
5866 QualType ASTContext::getUnsignedPointerDiffType() const {
5867   return getFromTargetType(Target->getUnsignedPtrDiffType(0));
5868 }
5869 
5870 /// Return the unique type for "pid_t" defined in
5871 /// <sys/types.h>. We need this to compute the correct type for vfork().
5872 QualType ASTContext::getProcessIDType() const {
5873   return getFromTargetType(Target->getProcessIDType());
5874 }
5875 
5876 //===----------------------------------------------------------------------===//
5877 //                              Type Operators
5878 //===----------------------------------------------------------------------===//
5879 
5880 CanQualType ASTContext::getCanonicalParamType(QualType T) const {
5881   // Push qualifiers into arrays, and then discard any remaining
5882   // qualifiers.
5883   T = getCanonicalType(T);
5884   T = getVariableArrayDecayedType(T);
5885   const Type *Ty = T.getTypePtr();
5886   QualType Result;
5887   if (isa<ArrayType>(Ty)) {
5888     Result = getArrayDecayedType(QualType(Ty,0));
5889   } else if (isa<FunctionType>(Ty)) {
5890     Result = getPointerType(QualType(Ty, 0));
5891   } else {
5892     Result = QualType(Ty, 0);
5893   }
5894 
5895   return CanQualType::CreateUnsafe(Result);
5896 }
5897 
5898 QualType ASTContext::getUnqualifiedArrayType(QualType type,
5899                                              Qualifiers &quals) {
5900   SplitQualType splitType = type.getSplitUnqualifiedType();
5901 
5902   // FIXME: getSplitUnqualifiedType() actually walks all the way to
5903   // the unqualified desugared type and then drops it on the floor.
5904   // We then have to strip that sugar back off with
5905   // getUnqualifiedDesugaredType(), which is silly.
5906   const auto *AT =
5907       dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
5908 
5909   // If we don't have an array, just use the results in splitType.
5910   if (!AT) {
5911     quals = splitType.Quals;
5912     return QualType(splitType.Ty, 0);
5913   }
5914 
5915   // Otherwise, recurse on the array's element type.
5916   QualType elementType = AT->getElementType();
5917   QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
5918 
5919   // If that didn't change the element type, AT has no qualifiers, so we
5920   // can just use the results in splitType.
5921   if (elementType == unqualElementType) {
5922     assert(quals.empty()); // from the recursive call
5923     quals = splitType.Quals;
5924     return QualType(splitType.Ty, 0);
5925   }
5926 
5927   // Otherwise, add in the qualifiers from the outermost type, then
5928   // build the type back up.
5929   quals.addConsistentQualifiers(splitType.Quals);
5930 
5931   if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
5932     return getConstantArrayType(unqualElementType, CAT->getSize(),
5933                                 CAT->getSizeExpr(), CAT->getSizeModifier(), 0);
5934   }
5935 
5936   if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) {
5937     return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
5938   }
5939 
5940   if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) {
5941     return getVariableArrayType(unqualElementType,
5942                                 VAT->getSizeExpr(),
5943                                 VAT->getSizeModifier(),
5944                                 VAT->getIndexTypeCVRQualifiers(),
5945                                 VAT->getBracketsRange());
5946   }
5947 
5948   const auto *DSAT = cast<DependentSizedArrayType>(AT);
5949   return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
5950                                     DSAT->getSizeModifier(), 0,
5951                                     SourceRange());
5952 }
5953 
5954 /// Attempt to unwrap two types that may both be array types with the same bound
5955 /// (or both be array types of unknown bound) for the purpose of comparing the
5956 /// cv-decomposition of two types per C++ [conv.qual].
5957 ///
5958 /// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
5959 ///        C++20 [conv.qual], if permitted by the current language mode.
5960 void ASTContext::UnwrapSimilarArrayTypes(QualType &T1, QualType &T2,
5961                                          bool AllowPiMismatch) {
5962   while (true) {
5963     auto *AT1 = getAsArrayType(T1);
5964     if (!AT1)
5965       return;
5966 
5967     auto *AT2 = getAsArrayType(T2);
5968     if (!AT2)
5969       return;
5970 
5971     // If we don't have two array types with the same constant bound nor two
5972     // incomplete array types, we've unwrapped everything we can.
5973     // C++20 also permits one type to be a constant array type and the other
5974     // to be an incomplete array type.
5975     // FIXME: Consider also unwrapping array of unknown bound and VLA.
5976     if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) {
5977       auto *CAT2 = dyn_cast<ConstantArrayType>(AT2);
5978       if (!((CAT2 && CAT1->getSize() == CAT2->getSize()) ||
5979             (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
5980              isa<IncompleteArrayType>(AT2))))
5981         return;
5982     } else if (isa<IncompleteArrayType>(AT1)) {
5983       if (!(isa<IncompleteArrayType>(AT2) ||
5984             (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
5985              isa<ConstantArrayType>(AT2))))
5986         return;
5987     } else {
5988       return;
5989     }
5990 
5991     T1 = AT1->getElementType();
5992     T2 = AT2->getElementType();
5993   }
5994 }
5995 
5996 /// Attempt to unwrap two types that may be similar (C++ [conv.qual]).
5997 ///
5998 /// If T1 and T2 are both pointer types of the same kind, or both array types
5999 /// with the same bound, unwraps layers from T1 and T2 until a pointer type is
6000 /// unwrapped. Top-level qualifiers on T1 and T2 are ignored.
6001 ///
6002 /// This function will typically be called in a loop that successively
6003 /// "unwraps" pointer and pointer-to-member types to compare them at each
6004 /// level.
6005 ///
6006 /// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
6007 ///        C++20 [conv.qual], if permitted by the current language mode.
6008 ///
6009 /// \return \c true if a pointer type was unwrapped, \c false if we reached a
6010 /// pair of types that can't be unwrapped further.
6011 bool ASTContext::UnwrapSimilarTypes(QualType &T1, QualType &T2,
6012                                     bool AllowPiMismatch) {
6013   UnwrapSimilarArrayTypes(T1, T2, AllowPiMismatch);
6014 
6015   const auto *T1PtrType = T1->getAs<PointerType>();
6016   const auto *T2PtrType = T2->getAs<PointerType>();
6017   if (T1PtrType && T2PtrType) {
6018     T1 = T1PtrType->getPointeeType();
6019     T2 = T2PtrType->getPointeeType();
6020     return true;
6021   }
6022 
6023   const auto *T1MPType = T1->getAs<MemberPointerType>();
6024   const auto *T2MPType = T2->getAs<MemberPointerType>();
6025   if (T1MPType && T2MPType &&
6026       hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
6027                              QualType(T2MPType->getClass(), 0))) {
6028     T1 = T1MPType->getPointeeType();
6029     T2 = T2MPType->getPointeeType();
6030     return true;
6031   }
6032 
6033   if (getLangOpts().ObjC) {
6034     const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
6035     const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
6036     if (T1OPType && T2OPType) {
6037       T1 = T1OPType->getPointeeType();
6038       T2 = T2OPType->getPointeeType();
6039       return true;
6040     }
6041   }
6042 
6043   // FIXME: Block pointers, too?
6044 
6045   return false;
6046 }
6047 
6048 bool ASTContext::hasSimilarType(QualType T1, QualType T2) {
6049   while (true) {
6050     Qualifiers Quals;
6051     T1 = getUnqualifiedArrayType(T1, Quals);
6052     T2 = getUnqualifiedArrayType(T2, Quals);
6053     if (hasSameType(T1, T2))
6054       return true;
6055     if (!UnwrapSimilarTypes(T1, T2))
6056       return false;
6057   }
6058 }
6059 
6060 bool ASTContext::hasCvrSimilarType(QualType T1, QualType T2) {
6061   while (true) {
6062     Qualifiers Quals1, Quals2;
6063     T1 = getUnqualifiedArrayType(T1, Quals1);
6064     T2 = getUnqualifiedArrayType(T2, Quals2);
6065 
6066     Quals1.removeCVRQualifiers();
6067     Quals2.removeCVRQualifiers();
6068     if (Quals1 != Quals2)
6069       return false;
6070 
6071     if (hasSameType(T1, T2))
6072       return true;
6073 
6074     if (!UnwrapSimilarTypes(T1, T2, /*AllowPiMismatch*/ false))
6075       return false;
6076   }
6077 }
6078 
6079 DeclarationNameInfo
6080 ASTContext::getNameForTemplate(TemplateName Name,
6081                                SourceLocation NameLoc) const {
6082   switch (Name.getKind()) {
6083   case TemplateName::QualifiedTemplate:
6084   case TemplateName::Template:
6085     // DNInfo work in progress: CHECKME: what about DNLoc?
6086     return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
6087                                NameLoc);
6088 
6089   case TemplateName::OverloadedTemplate: {
6090     OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
6091     // DNInfo work in progress: CHECKME: what about DNLoc?
6092     return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
6093   }
6094 
6095   case TemplateName::AssumedTemplate: {
6096     AssumedTemplateStorage *Storage = Name.getAsAssumedTemplateName();
6097     return DeclarationNameInfo(Storage->getDeclName(), NameLoc);
6098   }
6099 
6100   case TemplateName::DependentTemplate: {
6101     DependentTemplateName *DTN = Name.getAsDependentTemplateName();
6102     DeclarationName DName;
6103     if (DTN->isIdentifier()) {
6104       DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
6105       return DeclarationNameInfo(DName, NameLoc);
6106     } else {
6107       DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
6108       // DNInfo work in progress: FIXME: source locations?
6109       DeclarationNameLoc DNLoc =
6110           DeclarationNameLoc::makeCXXOperatorNameLoc(SourceRange());
6111       return DeclarationNameInfo(DName, NameLoc, DNLoc);
6112     }
6113   }
6114 
6115   case TemplateName::SubstTemplateTemplateParm: {
6116     SubstTemplateTemplateParmStorage *subst
6117       = Name.getAsSubstTemplateTemplateParm();
6118     return DeclarationNameInfo(subst->getParameter()->getDeclName(),
6119                                NameLoc);
6120   }
6121 
6122   case TemplateName::SubstTemplateTemplateParmPack: {
6123     SubstTemplateTemplateParmPackStorage *subst
6124       = Name.getAsSubstTemplateTemplateParmPack();
6125     return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
6126                                NameLoc);
6127   }
6128   }
6129 
6130   llvm_unreachable("bad template name kind!");
6131 }
6132 
6133 TemplateName
6134 ASTContext::getCanonicalTemplateName(const TemplateName &Name) const {
6135   switch (Name.getKind()) {
6136   case TemplateName::QualifiedTemplate:
6137   case TemplateName::Template: {
6138     TemplateDecl *Template = Name.getAsTemplateDecl();
6139     if (auto *TTP  = dyn_cast<TemplateTemplateParmDecl>(Template))
6140       Template = getCanonicalTemplateTemplateParmDecl(TTP);
6141 
6142     // The canonical template name is the canonical template declaration.
6143     return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
6144   }
6145 
6146   case TemplateName::OverloadedTemplate:
6147   case TemplateName::AssumedTemplate:
6148     llvm_unreachable("cannot canonicalize unresolved template");
6149 
6150   case TemplateName::DependentTemplate: {
6151     DependentTemplateName *DTN = Name.getAsDependentTemplateName();
6152     assert(DTN && "Non-dependent template names must refer to template decls.");
6153     return DTN->CanonicalTemplateName;
6154   }
6155 
6156   case TemplateName::SubstTemplateTemplateParm: {
6157     SubstTemplateTemplateParmStorage *subst
6158       = Name.getAsSubstTemplateTemplateParm();
6159     return getCanonicalTemplateName(subst->getReplacement());
6160   }
6161 
6162   case TemplateName::SubstTemplateTemplateParmPack: {
6163     SubstTemplateTemplateParmPackStorage *subst
6164                                   = Name.getAsSubstTemplateTemplateParmPack();
6165     TemplateTemplateParmDecl *canonParameter
6166       = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
6167     TemplateArgument canonArgPack
6168       = getCanonicalTemplateArgument(subst->getArgumentPack());
6169     return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
6170   }
6171   }
6172 
6173   llvm_unreachable("bad template name!");
6174 }
6175 
6176 bool ASTContext::hasSameTemplateName(const TemplateName &X,
6177                                      const TemplateName &Y) const {
6178   return getCanonicalTemplateName(X).getAsVoidPointer() ==
6179          getCanonicalTemplateName(Y).getAsVoidPointer();
6180 }
6181 
6182 bool ASTContext::isSameTemplateParameter(const NamedDecl *X,
6183                                          const NamedDecl *Y) {
6184   if (X->getKind() != Y->getKind())
6185     return false;
6186 
6187   if (auto *TX = dyn_cast<TemplateTypeParmDecl>(X)) {
6188     auto *TY = cast<TemplateTypeParmDecl>(Y);
6189     if (TX->isParameterPack() != TY->isParameterPack())
6190       return false;
6191     if (TX->hasTypeConstraint() != TY->hasTypeConstraint())
6192       return false;
6193     const TypeConstraint *TXTC = TX->getTypeConstraint();
6194     const TypeConstraint *TYTC = TY->getTypeConstraint();
6195     if (!TXTC != !TYTC)
6196       return false;
6197     if (TXTC && TYTC) {
6198       auto *NCX = TXTC->getNamedConcept();
6199       auto *NCY = TYTC->getNamedConcept();
6200       if (!NCX || !NCY || !isSameEntity(NCX, NCY))
6201         return false;
6202       if (TXTC->hasExplicitTemplateArgs() != TYTC->hasExplicitTemplateArgs())
6203         return false;
6204       if (TXTC->hasExplicitTemplateArgs()) {
6205         auto *TXTCArgs = TXTC->getTemplateArgsAsWritten();
6206         auto *TYTCArgs = TYTC->getTemplateArgsAsWritten();
6207         if (TXTCArgs->NumTemplateArgs != TYTCArgs->NumTemplateArgs)
6208           return false;
6209         llvm::FoldingSetNodeID XID, YID;
6210         for (auto &ArgLoc : TXTCArgs->arguments())
6211           ArgLoc.getArgument().Profile(XID, X->getASTContext());
6212         for (auto &ArgLoc : TYTCArgs->arguments())
6213           ArgLoc.getArgument().Profile(YID, Y->getASTContext());
6214         if (XID != YID)
6215           return false;
6216       }
6217     }
6218     return true;
6219   }
6220 
6221   if (auto *TX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
6222     auto *TY = cast<NonTypeTemplateParmDecl>(Y);
6223     return TX->isParameterPack() == TY->isParameterPack() &&
6224            TX->getASTContext().hasSameType(TX->getType(), TY->getType());
6225   }
6226 
6227   auto *TX = cast<TemplateTemplateParmDecl>(X);
6228   auto *TY = cast<TemplateTemplateParmDecl>(Y);
6229   return TX->isParameterPack() == TY->isParameterPack() &&
6230          isSameTemplateParameterList(TX->getTemplateParameters(),
6231                                      TY->getTemplateParameters());
6232 }
6233 
6234 bool ASTContext::isSameTemplateParameterList(const TemplateParameterList *X,
6235                                              const TemplateParameterList *Y) {
6236   if (X->size() != Y->size())
6237     return false;
6238 
6239   for (unsigned I = 0, N = X->size(); I != N; ++I)
6240     if (!isSameTemplateParameter(X->getParam(I), Y->getParam(I)))
6241       return false;
6242 
6243   const Expr *XRC = X->getRequiresClause();
6244   const Expr *YRC = Y->getRequiresClause();
6245   if (!XRC != !YRC)
6246     return false;
6247   if (XRC) {
6248     llvm::FoldingSetNodeID XRCID, YRCID;
6249     XRC->Profile(XRCID, *this, /*Canonical=*/true);
6250     YRC->Profile(YRCID, *this, /*Canonical=*/true);
6251     if (XRCID != YRCID)
6252       return false;
6253   }
6254 
6255   return true;
6256 }
6257 
6258 static NamespaceDecl *getNamespace(const NestedNameSpecifier *X) {
6259   if (auto *NS = X->getAsNamespace())
6260     return NS;
6261   if (auto *NAS = X->getAsNamespaceAlias())
6262     return NAS->getNamespace();
6263   return nullptr;
6264 }
6265 
6266 static bool isSameQualifier(const NestedNameSpecifier *X,
6267                             const NestedNameSpecifier *Y) {
6268   if (auto *NSX = getNamespace(X)) {
6269     auto *NSY = getNamespace(Y);
6270     if (!NSY || NSX->getCanonicalDecl() != NSY->getCanonicalDecl())
6271       return false;
6272   } else if (X->getKind() != Y->getKind())
6273     return false;
6274 
6275   // FIXME: For namespaces and types, we're permitted to check that the entity
6276   // is named via the same tokens. We should probably do so.
6277   switch (X->getKind()) {
6278   case NestedNameSpecifier::Identifier:
6279     if (X->getAsIdentifier() != Y->getAsIdentifier())
6280       return false;
6281     break;
6282   case NestedNameSpecifier::Namespace:
6283   case NestedNameSpecifier::NamespaceAlias:
6284     // We've already checked that we named the same namespace.
6285     break;
6286   case NestedNameSpecifier::TypeSpec:
6287   case NestedNameSpecifier::TypeSpecWithTemplate:
6288     if (X->getAsType()->getCanonicalTypeInternal() !=
6289         Y->getAsType()->getCanonicalTypeInternal())
6290       return false;
6291     break;
6292   case NestedNameSpecifier::Global:
6293   case NestedNameSpecifier::Super:
6294     return true;
6295   }
6296 
6297   // Recurse into earlier portion of NNS, if any.
6298   auto *PX = X->getPrefix();
6299   auto *PY = Y->getPrefix();
6300   if (PX && PY)
6301     return isSameQualifier(PX, PY);
6302   return !PX && !PY;
6303 }
6304 
6305 /// Determine whether the attributes we can overload on are identical for A and
6306 /// B. Will ignore any overloadable attrs represented in the type of A and B.
6307 static bool hasSameOverloadableAttrs(const FunctionDecl *A,
6308                                      const FunctionDecl *B) {
6309   // Note that pass_object_size attributes are represented in the function's
6310   // ExtParameterInfo, so we don't need to check them here.
6311 
6312   llvm::FoldingSetNodeID Cand1ID, Cand2ID;
6313   auto AEnableIfAttrs = A->specific_attrs<EnableIfAttr>();
6314   auto BEnableIfAttrs = B->specific_attrs<EnableIfAttr>();
6315 
6316   for (auto Pair : zip_longest(AEnableIfAttrs, BEnableIfAttrs)) {
6317     Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
6318     Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
6319 
6320     // Return false if the number of enable_if attributes is different.
6321     if (!Cand1A || !Cand2A)
6322       return false;
6323 
6324     Cand1ID.clear();
6325     Cand2ID.clear();
6326 
6327     (*Cand1A)->getCond()->Profile(Cand1ID, A->getASTContext(), true);
6328     (*Cand2A)->getCond()->Profile(Cand2ID, B->getASTContext(), true);
6329 
6330     // Return false if any of the enable_if expressions of A and B are
6331     // different.
6332     if (Cand1ID != Cand2ID)
6333       return false;
6334   }
6335   return true;
6336 }
6337 
6338 bool ASTContext::isSameEntity(const NamedDecl *X, const NamedDecl *Y) {
6339   if (X == Y)
6340     return true;
6341 
6342   if (X->getDeclName() != Y->getDeclName())
6343     return false;
6344 
6345   // Must be in the same context.
6346   //
6347   // Note that we can't use DeclContext::Equals here, because the DeclContexts
6348   // could be two different declarations of the same function. (We will fix the
6349   // semantic DC to refer to the primary definition after merging.)
6350   if (!declaresSameEntity(cast<Decl>(X->getDeclContext()->getRedeclContext()),
6351                           cast<Decl>(Y->getDeclContext()->getRedeclContext())))
6352     return false;
6353 
6354   // Two typedefs refer to the same entity if they have the same underlying
6355   // type.
6356   if (const auto *TypedefX = dyn_cast<TypedefNameDecl>(X))
6357     if (const auto *TypedefY = dyn_cast<TypedefNameDecl>(Y))
6358       return hasSameType(TypedefX->getUnderlyingType(),
6359                          TypedefY->getUnderlyingType());
6360 
6361   // Must have the same kind.
6362   if (X->getKind() != Y->getKind())
6363     return false;
6364 
6365   // Objective-C classes and protocols with the same name always match.
6366   if (isa<ObjCInterfaceDecl>(X) || isa<ObjCProtocolDecl>(X))
6367     return true;
6368 
6369   if (isa<ClassTemplateSpecializationDecl>(X)) {
6370     // No need to handle these here: we merge them when adding them to the
6371     // template.
6372     return false;
6373   }
6374 
6375   // Compatible tags match.
6376   if (const auto *TagX = dyn_cast<TagDecl>(X)) {
6377     const auto *TagY = cast<TagDecl>(Y);
6378     return (TagX->getTagKind() == TagY->getTagKind()) ||
6379            ((TagX->getTagKind() == TTK_Struct ||
6380              TagX->getTagKind() == TTK_Class ||
6381              TagX->getTagKind() == TTK_Interface) &&
6382             (TagY->getTagKind() == TTK_Struct ||
6383              TagY->getTagKind() == TTK_Class ||
6384              TagY->getTagKind() == TTK_Interface));
6385   }
6386 
6387   // Functions with the same type and linkage match.
6388   // FIXME: This needs to cope with merging of prototyped/non-prototyped
6389   // functions, etc.
6390   if (const auto *FuncX = dyn_cast<FunctionDecl>(X)) {
6391     const auto *FuncY = cast<FunctionDecl>(Y);
6392     if (const auto *CtorX = dyn_cast<CXXConstructorDecl>(X)) {
6393       const auto *CtorY = cast<CXXConstructorDecl>(Y);
6394       if (CtorX->getInheritedConstructor() &&
6395           !isSameEntity(CtorX->getInheritedConstructor().getConstructor(),
6396                         CtorY->getInheritedConstructor().getConstructor()))
6397         return false;
6398     }
6399 
6400     if (FuncX->isMultiVersion() != FuncY->isMultiVersion())
6401       return false;
6402 
6403     // Multiversioned functions with different feature strings are represented
6404     // as separate declarations.
6405     if (FuncX->isMultiVersion()) {
6406       const auto *TAX = FuncX->getAttr<TargetAttr>();
6407       const auto *TAY = FuncY->getAttr<TargetAttr>();
6408       assert(TAX && TAY && "Multiversion Function without target attribute");
6409 
6410       if (TAX->getFeaturesStr() != TAY->getFeaturesStr())
6411         return false;
6412     }
6413 
6414     const Expr *XRC = FuncX->getTrailingRequiresClause();
6415     const Expr *YRC = FuncY->getTrailingRequiresClause();
6416     if (!XRC != !YRC)
6417       return false;
6418     if (XRC) {
6419       llvm::FoldingSetNodeID XRCID, YRCID;
6420       XRC->Profile(XRCID, *this, /*Canonical=*/true);
6421       YRC->Profile(YRCID, *this, /*Canonical=*/true);
6422       if (XRCID != YRCID)
6423         return false;
6424     }
6425 
6426     auto GetTypeAsWritten = [](const FunctionDecl *FD) {
6427       // Map to the first declaration that we've already merged into this one.
6428       // The TSI of redeclarations might not match (due to calling conventions
6429       // being inherited onto the type but not the TSI), but the TSI type of
6430       // the first declaration of the function should match across modules.
6431       FD = FD->getCanonicalDecl();
6432       return FD->getTypeSourceInfo() ? FD->getTypeSourceInfo()->getType()
6433                                      : FD->getType();
6434     };
6435     QualType XT = GetTypeAsWritten(FuncX), YT = GetTypeAsWritten(FuncY);
6436     if (!hasSameType(XT, YT)) {
6437       // We can get functions with different types on the redecl chain in C++17
6438       // if they have differing exception specifications and at least one of
6439       // the excpetion specs is unresolved.
6440       auto *XFPT = XT->getAs<FunctionProtoType>();
6441       auto *YFPT = YT->getAs<FunctionProtoType>();
6442       if (getLangOpts().CPlusPlus17 && XFPT && YFPT &&
6443           (isUnresolvedExceptionSpec(XFPT->getExceptionSpecType()) ||
6444            isUnresolvedExceptionSpec(YFPT->getExceptionSpecType())) &&
6445           // FIXME: We could make isSameEntity const after we make
6446           // hasSameFunctionTypeIgnoringExceptionSpec const.
6447           hasSameFunctionTypeIgnoringExceptionSpec(XT, YT))
6448         return true;
6449       return false;
6450     }
6451 
6452     return FuncX->getLinkageInternal() == FuncY->getLinkageInternal() &&
6453            hasSameOverloadableAttrs(FuncX, FuncY);
6454   }
6455 
6456   // Variables with the same type and linkage match.
6457   if (const auto *VarX = dyn_cast<VarDecl>(X)) {
6458     const auto *VarY = cast<VarDecl>(Y);
6459     if (VarX->getLinkageInternal() == VarY->getLinkageInternal()) {
6460       if (hasSameType(VarX->getType(), VarY->getType()))
6461         return true;
6462 
6463       // We can get decls with different types on the redecl chain. Eg.
6464       // template <typename T> struct S { static T Var[]; }; // #1
6465       // template <typename T> T S<T>::Var[sizeof(T)]; // #2
6466       // Only? happens when completing an incomplete array type. In this case
6467       // when comparing #1 and #2 we should go through their element type.
6468       const ArrayType *VarXTy = getAsArrayType(VarX->getType());
6469       const ArrayType *VarYTy = getAsArrayType(VarY->getType());
6470       if (!VarXTy || !VarYTy)
6471         return false;
6472       if (VarXTy->isIncompleteArrayType() || VarYTy->isIncompleteArrayType())
6473         return hasSameType(VarXTy->getElementType(), VarYTy->getElementType());
6474     }
6475     return false;
6476   }
6477 
6478   // Namespaces with the same name and inlinedness match.
6479   if (const auto *NamespaceX = dyn_cast<NamespaceDecl>(X)) {
6480     const auto *NamespaceY = cast<NamespaceDecl>(Y);
6481     return NamespaceX->isInline() == NamespaceY->isInline();
6482   }
6483 
6484   // Identical template names and kinds match if their template parameter lists
6485   // and patterns match.
6486   if (const auto *TemplateX = dyn_cast<TemplateDecl>(X)) {
6487     const auto *TemplateY = cast<TemplateDecl>(Y);
6488     return isSameEntity(TemplateX->getTemplatedDecl(),
6489                         TemplateY->getTemplatedDecl()) &&
6490            isSameTemplateParameterList(TemplateX->getTemplateParameters(),
6491                                        TemplateY->getTemplateParameters());
6492   }
6493 
6494   // Fields with the same name and the same type match.
6495   if (const auto *FDX = dyn_cast<FieldDecl>(X)) {
6496     const auto *FDY = cast<FieldDecl>(Y);
6497     // FIXME: Also check the bitwidth is odr-equivalent, if any.
6498     return hasSameType(FDX->getType(), FDY->getType());
6499   }
6500 
6501   // Indirect fields with the same target field match.
6502   if (const auto *IFDX = dyn_cast<IndirectFieldDecl>(X)) {
6503     const auto *IFDY = cast<IndirectFieldDecl>(Y);
6504     return IFDX->getAnonField()->getCanonicalDecl() ==
6505            IFDY->getAnonField()->getCanonicalDecl();
6506   }
6507 
6508   // Enumerators with the same name match.
6509   if (isa<EnumConstantDecl>(X))
6510     // FIXME: Also check the value is odr-equivalent.
6511     return true;
6512 
6513   // Using shadow declarations with the same target match.
6514   if (const auto *USX = dyn_cast<UsingShadowDecl>(X)) {
6515     const auto *USY = cast<UsingShadowDecl>(Y);
6516     return USX->getTargetDecl() == USY->getTargetDecl();
6517   }
6518 
6519   // Using declarations with the same qualifier match. (We already know that
6520   // the name matches.)
6521   if (const auto *UX = dyn_cast<UsingDecl>(X)) {
6522     const auto *UY = cast<UsingDecl>(Y);
6523     return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
6524            UX->hasTypename() == UY->hasTypename() &&
6525            UX->isAccessDeclaration() == UY->isAccessDeclaration();
6526   }
6527   if (const auto *UX = dyn_cast<UnresolvedUsingValueDecl>(X)) {
6528     const auto *UY = cast<UnresolvedUsingValueDecl>(Y);
6529     return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
6530            UX->isAccessDeclaration() == UY->isAccessDeclaration();
6531   }
6532   if (const auto *UX = dyn_cast<UnresolvedUsingTypenameDecl>(X)) {
6533     return isSameQualifier(
6534         UX->getQualifier(),
6535         cast<UnresolvedUsingTypenameDecl>(Y)->getQualifier());
6536   }
6537 
6538   // Using-pack declarations are only created by instantiation, and match if
6539   // they're instantiated from matching UnresolvedUsing...Decls.
6540   if (const auto *UX = dyn_cast<UsingPackDecl>(X)) {
6541     return declaresSameEntity(
6542         UX->getInstantiatedFromUsingDecl(),
6543         cast<UsingPackDecl>(Y)->getInstantiatedFromUsingDecl());
6544   }
6545 
6546   // Namespace alias definitions with the same target match.
6547   if (const auto *NAX = dyn_cast<NamespaceAliasDecl>(X)) {
6548     const auto *NAY = cast<NamespaceAliasDecl>(Y);
6549     return NAX->getNamespace()->Equals(NAY->getNamespace());
6550   }
6551 
6552   return false;
6553 }
6554 
6555 TemplateArgument
6556 ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
6557   switch (Arg.getKind()) {
6558     case TemplateArgument::Null:
6559       return Arg;
6560 
6561     case TemplateArgument::Expression:
6562       return Arg;
6563 
6564     case TemplateArgument::Declaration: {
6565       auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
6566       return TemplateArgument(D, Arg.getParamTypeForDecl());
6567     }
6568 
6569     case TemplateArgument::NullPtr:
6570       return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
6571                               /*isNullPtr*/true);
6572 
6573     case TemplateArgument::Template:
6574       return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
6575 
6576     case TemplateArgument::TemplateExpansion:
6577       return TemplateArgument(getCanonicalTemplateName(
6578                                          Arg.getAsTemplateOrTemplatePattern()),
6579                               Arg.getNumTemplateExpansions());
6580 
6581     case TemplateArgument::Integral:
6582       return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
6583 
6584     case TemplateArgument::Type:
6585       return TemplateArgument(getCanonicalType(Arg.getAsType()));
6586 
6587     case TemplateArgument::Pack: {
6588       if (Arg.pack_size() == 0)
6589         return Arg;
6590 
6591       auto *CanonArgs = new (*this) TemplateArgument[Arg.pack_size()];
6592       unsigned Idx = 0;
6593       for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
6594                                         AEnd = Arg.pack_end();
6595            A != AEnd; (void)++A, ++Idx)
6596         CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
6597 
6598       return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
6599     }
6600   }
6601 
6602   // Silence GCC warning
6603   llvm_unreachable("Unhandled template argument kind");
6604 }
6605 
6606 NestedNameSpecifier *
6607 ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
6608   if (!NNS)
6609     return nullptr;
6610 
6611   switch (NNS->getKind()) {
6612   case NestedNameSpecifier::Identifier:
6613     // Canonicalize the prefix but keep the identifier the same.
6614     return NestedNameSpecifier::Create(*this,
6615                          getCanonicalNestedNameSpecifier(NNS->getPrefix()),
6616                                        NNS->getAsIdentifier());
6617 
6618   case NestedNameSpecifier::Namespace:
6619     // A namespace is canonical; build a nested-name-specifier with
6620     // this namespace and no prefix.
6621     return NestedNameSpecifier::Create(*this, nullptr,
6622                                  NNS->getAsNamespace()->getOriginalNamespace());
6623 
6624   case NestedNameSpecifier::NamespaceAlias:
6625     // A namespace is canonical; build a nested-name-specifier with
6626     // this namespace and no prefix.
6627     return NestedNameSpecifier::Create(*this, nullptr,
6628                                     NNS->getAsNamespaceAlias()->getNamespace()
6629                                                       ->getOriginalNamespace());
6630 
6631   // The difference between TypeSpec and TypeSpecWithTemplate is that the
6632   // latter will have the 'template' keyword when printed.
6633   case NestedNameSpecifier::TypeSpec:
6634   case NestedNameSpecifier::TypeSpecWithTemplate: {
6635     const Type *T = getCanonicalType(NNS->getAsType());
6636 
6637     // If we have some kind of dependent-named type (e.g., "typename T::type"),
6638     // break it apart into its prefix and identifier, then reconsititute those
6639     // as the canonical nested-name-specifier. This is required to canonicalize
6640     // a dependent nested-name-specifier involving typedefs of dependent-name
6641     // types, e.g.,
6642     //   typedef typename T::type T1;
6643     //   typedef typename T1::type T2;
6644     if (const auto *DNT = T->getAs<DependentNameType>())
6645       return NestedNameSpecifier::Create(
6646           *this, DNT->getQualifier(),
6647           const_cast<IdentifierInfo *>(DNT->getIdentifier()));
6648     if (const auto *DTST = T->getAs<DependentTemplateSpecializationType>())
6649       return NestedNameSpecifier::Create(*this, DTST->getQualifier(), true,
6650                                          const_cast<Type *>(T));
6651 
6652     // TODO: Set 'Template' parameter to true for other template types.
6653     return NestedNameSpecifier::Create(*this, nullptr, false,
6654                                        const_cast<Type *>(T));
6655   }
6656 
6657   case NestedNameSpecifier::Global:
6658   case NestedNameSpecifier::Super:
6659     // The global specifier and __super specifer are canonical and unique.
6660     return NNS;
6661   }
6662 
6663   llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
6664 }
6665 
6666 const ArrayType *ASTContext::getAsArrayType(QualType T) const {
6667   // Handle the non-qualified case efficiently.
6668   if (!T.hasLocalQualifiers()) {
6669     // Handle the common positive case fast.
6670     if (const auto *AT = dyn_cast<ArrayType>(T))
6671       return AT;
6672   }
6673 
6674   // Handle the common negative case fast.
6675   if (!isa<ArrayType>(T.getCanonicalType()))
6676     return nullptr;
6677 
6678   // Apply any qualifiers from the array type to the element type.  This
6679   // implements C99 6.7.3p8: "If the specification of an array type includes
6680   // any type qualifiers, the element type is so qualified, not the array type."
6681 
6682   // If we get here, we either have type qualifiers on the type, or we have
6683   // sugar such as a typedef in the way.  If we have type qualifiers on the type
6684   // we must propagate them down into the element type.
6685 
6686   SplitQualType split = T.getSplitDesugaredType();
6687   Qualifiers qs = split.Quals;
6688 
6689   // If we have a simple case, just return now.
6690   const auto *ATy = dyn_cast<ArrayType>(split.Ty);
6691   if (!ATy || qs.empty())
6692     return ATy;
6693 
6694   // Otherwise, we have an array and we have qualifiers on it.  Push the
6695   // qualifiers into the array element type and return a new array type.
6696   QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
6697 
6698   if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy))
6699     return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
6700                                                 CAT->getSizeExpr(),
6701                                                 CAT->getSizeModifier(),
6702                                            CAT->getIndexTypeCVRQualifiers()));
6703   if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy))
6704     return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
6705                                                   IAT->getSizeModifier(),
6706                                            IAT->getIndexTypeCVRQualifiers()));
6707 
6708   if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy))
6709     return cast<ArrayType>(
6710                      getDependentSizedArrayType(NewEltTy,
6711                                                 DSAT->getSizeExpr(),
6712                                                 DSAT->getSizeModifier(),
6713                                               DSAT->getIndexTypeCVRQualifiers(),
6714                                                 DSAT->getBracketsRange()));
6715 
6716   const auto *VAT = cast<VariableArrayType>(ATy);
6717   return cast<ArrayType>(getVariableArrayType(NewEltTy,
6718                                               VAT->getSizeExpr(),
6719                                               VAT->getSizeModifier(),
6720                                               VAT->getIndexTypeCVRQualifiers(),
6721                                               VAT->getBracketsRange()));
6722 }
6723 
6724 QualType ASTContext::getAdjustedParameterType(QualType T) const {
6725   if (T->isArrayType() || T->isFunctionType())
6726     return getDecayedType(T);
6727   return T;
6728 }
6729 
6730 QualType ASTContext::getSignatureParameterType(QualType T) const {
6731   T = getVariableArrayDecayedType(T);
6732   T = getAdjustedParameterType(T);
6733   return T.getUnqualifiedType();
6734 }
6735 
6736 QualType ASTContext::getExceptionObjectType(QualType T) const {
6737   // C++ [except.throw]p3:
6738   //   A throw-expression initializes a temporary object, called the exception
6739   //   object, the type of which is determined by removing any top-level
6740   //   cv-qualifiers from the static type of the operand of throw and adjusting
6741   //   the type from "array of T" or "function returning T" to "pointer to T"
6742   //   or "pointer to function returning T", [...]
6743   T = getVariableArrayDecayedType(T);
6744   if (T->isArrayType() || T->isFunctionType())
6745     T = getDecayedType(T);
6746   return T.getUnqualifiedType();
6747 }
6748 
6749 /// getArrayDecayedType - Return the properly qualified result of decaying the
6750 /// specified array type to a pointer.  This operation is non-trivial when
6751 /// handling typedefs etc.  The canonical type of "T" must be an array type,
6752 /// this returns a pointer to a properly qualified element of the array.
6753 ///
6754 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
6755 QualType ASTContext::getArrayDecayedType(QualType Ty) const {
6756   // Get the element type with 'getAsArrayType' so that we don't lose any
6757   // typedefs in the element type of the array.  This also handles propagation
6758   // of type qualifiers from the array type into the element type if present
6759   // (C99 6.7.3p8).
6760   const ArrayType *PrettyArrayType = getAsArrayType(Ty);
6761   assert(PrettyArrayType && "Not an array type!");
6762 
6763   QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
6764 
6765   // int x[restrict 4] ->  int *restrict
6766   QualType Result = getQualifiedType(PtrTy,
6767                                      PrettyArrayType->getIndexTypeQualifiers());
6768 
6769   // int x[_Nullable] -> int * _Nullable
6770   if (auto Nullability = Ty->getNullability(*this)) {
6771     Result = const_cast<ASTContext *>(this)->getAttributedType(
6772         AttributedType::getNullabilityAttrKind(*Nullability), Result, Result);
6773   }
6774   return Result;
6775 }
6776 
6777 QualType ASTContext::getBaseElementType(const ArrayType *array) const {
6778   return getBaseElementType(array->getElementType());
6779 }
6780 
6781 QualType ASTContext::getBaseElementType(QualType type) const {
6782   Qualifiers qs;
6783   while (true) {
6784     SplitQualType split = type.getSplitDesugaredType();
6785     const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
6786     if (!array) break;
6787 
6788     type = array->getElementType();
6789     qs.addConsistentQualifiers(split.Quals);
6790   }
6791 
6792   return getQualifiedType(type, qs);
6793 }
6794 
6795 /// getConstantArrayElementCount - Returns number of constant array elements.
6796 uint64_t
6797 ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA)  const {
6798   uint64_t ElementCount = 1;
6799   do {
6800     ElementCount *= CA->getSize().getZExtValue();
6801     CA = dyn_cast_or_null<ConstantArrayType>(
6802       CA->getElementType()->getAsArrayTypeUnsafe());
6803   } while (CA);
6804   return ElementCount;
6805 }
6806 
6807 /// getFloatingRank - Return a relative rank for floating point types.
6808 /// This routine will assert if passed a built-in type that isn't a float.
6809 static FloatingRank getFloatingRank(QualType T) {
6810   if (const auto *CT = T->getAs<ComplexType>())
6811     return getFloatingRank(CT->getElementType());
6812 
6813   switch (T->castAs<BuiltinType>()->getKind()) {
6814   default: llvm_unreachable("getFloatingRank(): not a floating type");
6815   case BuiltinType::Float16:    return Float16Rank;
6816   case BuiltinType::Half:       return HalfRank;
6817   case BuiltinType::Float:      return FloatRank;
6818   case BuiltinType::Double:     return DoubleRank;
6819   case BuiltinType::LongDouble: return LongDoubleRank;
6820   case BuiltinType::Float128:   return Float128Rank;
6821   case BuiltinType::BFloat16:   return BFloat16Rank;
6822   case BuiltinType::Ibm128:     return Ibm128Rank;
6823   }
6824 }
6825 
6826 /// getFloatingTypeOrder - Compare the rank of the two specified floating
6827 /// point types, ignoring the domain of the type (i.e. 'double' ==
6828 /// '_Complex double').  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
6829 /// LHS < RHS, return -1.
6830 int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
6831   FloatingRank LHSR = getFloatingRank(LHS);
6832   FloatingRank RHSR = getFloatingRank(RHS);
6833 
6834   if (LHSR == RHSR)
6835     return 0;
6836   if (LHSR > RHSR)
6837     return 1;
6838   return -1;
6839 }
6840 
6841 int ASTContext::getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const {
6842   if (&getFloatTypeSemantics(LHS) == &getFloatTypeSemantics(RHS))
6843     return 0;
6844   return getFloatingTypeOrder(LHS, RHS);
6845 }
6846 
6847 /// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
6848 /// routine will assert if passed a built-in type that isn't an integer or enum,
6849 /// or if it is not canonicalized.
6850 unsigned ASTContext::getIntegerRank(const Type *T) const {
6851   assert(T->isCanonicalUnqualified() && "T should be canonicalized");
6852 
6853   // Results in this 'losing' to any type of the same size, but winning if
6854   // larger.
6855   if (const auto *EIT = dyn_cast<BitIntType>(T))
6856     return 0 + (EIT->getNumBits() << 3);
6857 
6858   switch (cast<BuiltinType>(T)->getKind()) {
6859   default: llvm_unreachable("getIntegerRank(): not a built-in integer");
6860   case BuiltinType::Bool:
6861     return 1 + (getIntWidth(BoolTy) << 3);
6862   case BuiltinType::Char_S:
6863   case BuiltinType::Char_U:
6864   case BuiltinType::SChar:
6865   case BuiltinType::UChar:
6866     return 2 + (getIntWidth(CharTy) << 3);
6867   case BuiltinType::Short:
6868   case BuiltinType::UShort:
6869     return 3 + (getIntWidth(ShortTy) << 3);
6870   case BuiltinType::Int:
6871   case BuiltinType::UInt:
6872     return 4 + (getIntWidth(IntTy) << 3);
6873   case BuiltinType::Long:
6874   case BuiltinType::ULong:
6875     return 5 + (getIntWidth(LongTy) << 3);
6876   case BuiltinType::LongLong:
6877   case BuiltinType::ULongLong:
6878     return 6 + (getIntWidth(LongLongTy) << 3);
6879   case BuiltinType::Int128:
6880   case BuiltinType::UInt128:
6881     return 7 + (getIntWidth(Int128Ty) << 3);
6882   }
6883 }
6884 
6885 /// Whether this is a promotable bitfield reference according
6886 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
6887 ///
6888 /// \returns the type this bit-field will promote to, or NULL if no
6889 /// promotion occurs.
6890 QualType ASTContext::isPromotableBitField(Expr *E) const {
6891   if (E->isTypeDependent() || E->isValueDependent())
6892     return {};
6893 
6894   // C++ [conv.prom]p5:
6895   //    If the bit-field has an enumerated type, it is treated as any other
6896   //    value of that type for promotion purposes.
6897   if (getLangOpts().CPlusPlus && E->getType()->isEnumeralType())
6898     return {};
6899 
6900   // FIXME: We should not do this unless E->refersToBitField() is true. This
6901   // matters in C where getSourceBitField() will find bit-fields for various
6902   // cases where the source expression is not a bit-field designator.
6903 
6904   FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
6905   if (!Field)
6906     return {};
6907 
6908   QualType FT = Field->getType();
6909 
6910   uint64_t BitWidth = Field->getBitWidthValue(*this);
6911   uint64_t IntSize = getTypeSize(IntTy);
6912   // C++ [conv.prom]p5:
6913   //   A prvalue for an integral bit-field can be converted to a prvalue of type
6914   //   int if int can represent all the values of the bit-field; otherwise, it
6915   //   can be converted to unsigned int if unsigned int can represent all the
6916   //   values of the bit-field. If the bit-field is larger yet, no integral
6917   //   promotion applies to it.
6918   // C11 6.3.1.1/2:
6919   //   [For a bit-field of type _Bool, int, signed int, or unsigned int:]
6920   //   If an int can represent all values of the original type (as restricted by
6921   //   the width, for a bit-field), the value is converted to an int; otherwise,
6922   //   it is converted to an unsigned int.
6923   //
6924   // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
6925   //        We perform that promotion here to match GCC and C++.
6926   // FIXME: C does not permit promotion of an enum bit-field whose rank is
6927   //        greater than that of 'int'. We perform that promotion to match GCC.
6928   if (BitWidth < IntSize)
6929     return IntTy;
6930 
6931   if (BitWidth == IntSize)
6932     return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
6933 
6934   // Bit-fields wider than int are not subject to promotions, and therefore act
6935   // like the base type. GCC has some weird bugs in this area that we
6936   // deliberately do not follow (GCC follows a pre-standard resolution to
6937   // C's DR315 which treats bit-width as being part of the type, and this leaks
6938   // into their semantics in some cases).
6939   return {};
6940 }
6941 
6942 /// getPromotedIntegerType - Returns the type that Promotable will
6943 /// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
6944 /// integer type.
6945 QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
6946   assert(!Promotable.isNull());
6947   assert(Promotable->isPromotableIntegerType());
6948   if (const auto *ET = Promotable->getAs<EnumType>())
6949     return ET->getDecl()->getPromotionType();
6950 
6951   if (const auto *BT = Promotable->getAs<BuiltinType>()) {
6952     // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
6953     // (3.9.1) can be converted to a prvalue of the first of the following
6954     // types that can represent all the values of its underlying type:
6955     // int, unsigned int, long int, unsigned long int, long long int, or
6956     // unsigned long long int [...]
6957     // FIXME: Is there some better way to compute this?
6958     if (BT->getKind() == BuiltinType::WChar_S ||
6959         BT->getKind() == BuiltinType::WChar_U ||
6960         BT->getKind() == BuiltinType::Char8 ||
6961         BT->getKind() == BuiltinType::Char16 ||
6962         BT->getKind() == BuiltinType::Char32) {
6963       bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
6964       uint64_t FromSize = getTypeSize(BT);
6965       QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
6966                                   LongLongTy, UnsignedLongLongTy };
6967       for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
6968         uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
6969         if (FromSize < ToSize ||
6970             (FromSize == ToSize &&
6971              FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
6972           return PromoteTypes[Idx];
6973       }
6974       llvm_unreachable("char type should fit into long long");
6975     }
6976   }
6977 
6978   // At this point, we should have a signed or unsigned integer type.
6979   if (Promotable->isSignedIntegerType())
6980     return IntTy;
6981   uint64_t PromotableSize = getIntWidth(Promotable);
6982   uint64_t IntSize = getIntWidth(IntTy);
6983   assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
6984   return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
6985 }
6986 
6987 /// Recurses in pointer/array types until it finds an objc retainable
6988 /// type and returns its ownership.
6989 Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
6990   while (!T.isNull()) {
6991     if (T.getObjCLifetime() != Qualifiers::OCL_None)
6992       return T.getObjCLifetime();
6993     if (T->isArrayType())
6994       T = getBaseElementType(T);
6995     else if (const auto *PT = T->getAs<PointerType>())
6996       T = PT->getPointeeType();
6997     else if (const auto *RT = T->getAs<ReferenceType>())
6998       T = RT->getPointeeType();
6999     else
7000       break;
7001   }
7002 
7003   return Qualifiers::OCL_None;
7004 }
7005 
7006 static const Type *getIntegerTypeForEnum(const EnumType *ET) {
7007   // Incomplete enum types are not treated as integer types.
7008   // FIXME: In C++, enum types are never integer types.
7009   if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
7010     return ET->getDecl()->getIntegerType().getTypePtr();
7011   return nullptr;
7012 }
7013 
7014 /// getIntegerTypeOrder - Returns the highest ranked integer type:
7015 /// C99 6.3.1.8p1.  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
7016 /// LHS < RHS, return -1.
7017 int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
7018   const Type *LHSC = getCanonicalType(LHS).getTypePtr();
7019   const Type *RHSC = getCanonicalType(RHS).getTypePtr();
7020 
7021   // Unwrap enums to their underlying type.
7022   if (const auto *ET = dyn_cast<EnumType>(LHSC))
7023     LHSC = getIntegerTypeForEnum(ET);
7024   if (const auto *ET = dyn_cast<EnumType>(RHSC))
7025     RHSC = getIntegerTypeForEnum(ET);
7026 
7027   if (LHSC == RHSC) return 0;
7028 
7029   bool LHSUnsigned = LHSC->isUnsignedIntegerType();
7030   bool RHSUnsigned = RHSC->isUnsignedIntegerType();
7031 
7032   unsigned LHSRank = getIntegerRank(LHSC);
7033   unsigned RHSRank = getIntegerRank(RHSC);
7034 
7035   if (LHSUnsigned == RHSUnsigned) {  // Both signed or both unsigned.
7036     if (LHSRank == RHSRank) return 0;
7037     return LHSRank > RHSRank ? 1 : -1;
7038   }
7039 
7040   // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
7041   if (LHSUnsigned) {
7042     // If the unsigned [LHS] type is larger, return it.
7043     if (LHSRank >= RHSRank)
7044       return 1;
7045 
7046     // If the signed type can represent all values of the unsigned type, it
7047     // wins.  Because we are dealing with 2's complement and types that are
7048     // powers of two larger than each other, this is always safe.
7049     return -1;
7050   }
7051 
7052   // If the unsigned [RHS] type is larger, return it.
7053   if (RHSRank >= LHSRank)
7054     return -1;
7055 
7056   // If the signed type can represent all values of the unsigned type, it
7057   // wins.  Because we are dealing with 2's complement and types that are
7058   // powers of two larger than each other, this is always safe.
7059   return 1;
7060 }
7061 
7062 TypedefDecl *ASTContext::getCFConstantStringDecl() const {
7063   if (CFConstantStringTypeDecl)
7064     return CFConstantStringTypeDecl;
7065 
7066   assert(!CFConstantStringTagDecl &&
7067          "tag and typedef should be initialized together");
7068   CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
7069   CFConstantStringTagDecl->startDefinition();
7070 
7071   struct {
7072     QualType Type;
7073     const char *Name;
7074   } Fields[5];
7075   unsigned Count = 0;
7076 
7077   /// Objective-C ABI
7078   ///
7079   ///    typedef struct __NSConstantString_tag {
7080   ///      const int *isa;
7081   ///      int flags;
7082   ///      const char *str;
7083   ///      long length;
7084   ///    } __NSConstantString;
7085   ///
7086   /// Swift ABI (4.1, 4.2)
7087   ///
7088   ///    typedef struct __NSConstantString_tag {
7089   ///      uintptr_t _cfisa;
7090   ///      uintptr_t _swift_rc;
7091   ///      _Atomic(uint64_t) _cfinfoa;
7092   ///      const char *_ptr;
7093   ///      uint32_t _length;
7094   ///    } __NSConstantString;
7095   ///
7096   /// Swift ABI (5.0)
7097   ///
7098   ///    typedef struct __NSConstantString_tag {
7099   ///      uintptr_t _cfisa;
7100   ///      uintptr_t _swift_rc;
7101   ///      _Atomic(uint64_t) _cfinfoa;
7102   ///      const char *_ptr;
7103   ///      uintptr_t _length;
7104   ///    } __NSConstantString;
7105 
7106   const auto CFRuntime = getLangOpts().CFRuntime;
7107   if (static_cast<unsigned>(CFRuntime) <
7108       static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) {
7109     Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" };
7110     Fields[Count++] = { IntTy, "flags" };
7111     Fields[Count++] = { getPointerType(CharTy.withConst()), "str" };
7112     Fields[Count++] = { LongTy, "length" };
7113   } else {
7114     Fields[Count++] = { getUIntPtrType(), "_cfisa" };
7115     Fields[Count++] = { getUIntPtrType(), "_swift_rc" };
7116     Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" };
7117     Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" };
7118     if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
7119         CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
7120       Fields[Count++] = { IntTy, "_ptr" };
7121     else
7122       Fields[Count++] = { getUIntPtrType(), "_ptr" };
7123   }
7124 
7125   // Create fields
7126   for (unsigned i = 0; i < Count; ++i) {
7127     FieldDecl *Field =
7128         FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(),
7129                           SourceLocation(), &Idents.get(Fields[i].Name),
7130                           Fields[i].Type, /*TInfo=*/nullptr,
7131                           /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
7132     Field->setAccess(AS_public);
7133     CFConstantStringTagDecl->addDecl(Field);
7134   }
7135 
7136   CFConstantStringTagDecl->completeDefinition();
7137   // This type is designed to be compatible with NSConstantString, but cannot
7138   // use the same name, since NSConstantString is an interface.
7139   auto tagType = getTagDeclType(CFConstantStringTagDecl);
7140   CFConstantStringTypeDecl =
7141       buildImplicitTypedef(tagType, "__NSConstantString");
7142 
7143   return CFConstantStringTypeDecl;
7144 }
7145 
7146 RecordDecl *ASTContext::getCFConstantStringTagDecl() const {
7147   if (!CFConstantStringTagDecl)
7148     getCFConstantStringDecl(); // Build the tag and the typedef.
7149   return CFConstantStringTagDecl;
7150 }
7151 
7152 // getCFConstantStringType - Return the type used for constant CFStrings.
7153 QualType ASTContext::getCFConstantStringType() const {
7154   return getTypedefType(getCFConstantStringDecl());
7155 }
7156 
7157 QualType ASTContext::getObjCSuperType() const {
7158   if (ObjCSuperType.isNull()) {
7159     RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
7160     getTranslationUnitDecl()->addDecl(ObjCSuperTypeDecl);
7161     ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
7162   }
7163   return ObjCSuperType;
7164 }
7165 
7166 void ASTContext::setCFConstantStringType(QualType T) {
7167   const auto *TD = T->castAs<TypedefType>();
7168   CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl());
7169   const auto *TagType =
7170       CFConstantStringTypeDecl->getUnderlyingType()->castAs<RecordType>();
7171   CFConstantStringTagDecl = TagType->getDecl();
7172 }
7173 
7174 QualType ASTContext::getBlockDescriptorType() const {
7175   if (BlockDescriptorType)
7176     return getTagDeclType(BlockDescriptorType);
7177 
7178   RecordDecl *RD;
7179   // FIXME: Needs the FlagAppleBlock bit.
7180   RD = buildImplicitRecord("__block_descriptor");
7181   RD->startDefinition();
7182 
7183   QualType FieldTypes[] = {
7184     UnsignedLongTy,
7185     UnsignedLongTy,
7186   };
7187 
7188   static const char *const FieldNames[] = {
7189     "reserved",
7190     "Size"
7191   };
7192 
7193   for (size_t i = 0; i < 2; ++i) {
7194     FieldDecl *Field = FieldDecl::Create(
7195         *this, RD, SourceLocation(), SourceLocation(),
7196         &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
7197         /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
7198     Field->setAccess(AS_public);
7199     RD->addDecl(Field);
7200   }
7201 
7202   RD->completeDefinition();
7203 
7204   BlockDescriptorType = RD;
7205 
7206   return getTagDeclType(BlockDescriptorType);
7207 }
7208 
7209 QualType ASTContext::getBlockDescriptorExtendedType() const {
7210   if (BlockDescriptorExtendedType)
7211     return getTagDeclType(BlockDescriptorExtendedType);
7212 
7213   RecordDecl *RD;
7214   // FIXME: Needs the FlagAppleBlock bit.
7215   RD = buildImplicitRecord("__block_descriptor_withcopydispose");
7216   RD->startDefinition();
7217 
7218   QualType FieldTypes[] = {
7219     UnsignedLongTy,
7220     UnsignedLongTy,
7221     getPointerType(VoidPtrTy),
7222     getPointerType(VoidPtrTy)
7223   };
7224 
7225   static const char *const FieldNames[] = {
7226     "reserved",
7227     "Size",
7228     "CopyFuncPtr",
7229     "DestroyFuncPtr"
7230   };
7231 
7232   for (size_t i = 0; i < 4; ++i) {
7233     FieldDecl *Field = FieldDecl::Create(
7234         *this, RD, SourceLocation(), SourceLocation(),
7235         &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
7236         /*BitWidth=*/nullptr,
7237         /*Mutable=*/false, ICIS_NoInit);
7238     Field->setAccess(AS_public);
7239     RD->addDecl(Field);
7240   }
7241 
7242   RD->completeDefinition();
7243 
7244   BlockDescriptorExtendedType = RD;
7245   return getTagDeclType(BlockDescriptorExtendedType);
7246 }
7247 
7248 OpenCLTypeKind ASTContext::getOpenCLTypeKind(const Type *T) const {
7249   const auto *BT = dyn_cast<BuiltinType>(T);
7250 
7251   if (!BT) {
7252     if (isa<PipeType>(T))
7253       return OCLTK_Pipe;
7254 
7255     return OCLTK_Default;
7256   }
7257 
7258   switch (BT->getKind()) {
7259 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix)                   \
7260   case BuiltinType::Id:                                                        \
7261     return OCLTK_Image;
7262 #include "clang/Basic/OpenCLImageTypes.def"
7263 
7264   case BuiltinType::OCLClkEvent:
7265     return OCLTK_ClkEvent;
7266 
7267   case BuiltinType::OCLEvent:
7268     return OCLTK_Event;
7269 
7270   case BuiltinType::OCLQueue:
7271     return OCLTK_Queue;
7272 
7273   case BuiltinType::OCLReserveID:
7274     return OCLTK_ReserveID;
7275 
7276   case BuiltinType::OCLSampler:
7277     return OCLTK_Sampler;
7278 
7279   default:
7280     return OCLTK_Default;
7281   }
7282 }
7283 
7284 LangAS ASTContext::getOpenCLTypeAddrSpace(const Type *T) const {
7285   return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
7286 }
7287 
7288 /// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
7289 /// requires copy/dispose. Note that this must match the logic
7290 /// in buildByrefHelpers.
7291 bool ASTContext::BlockRequiresCopying(QualType Ty,
7292                                       const VarDecl *D) {
7293   if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
7294     const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr();
7295     if (!copyExpr && record->hasTrivialDestructor()) return false;
7296 
7297     return true;
7298   }
7299 
7300   // The block needs copy/destroy helpers if Ty is non-trivial to destructively
7301   // move or destroy.
7302   if (Ty.isNonTrivialToPrimitiveDestructiveMove() || Ty.isDestructedType())
7303     return true;
7304 
7305   if (!Ty->isObjCRetainableType()) return false;
7306 
7307   Qualifiers qs = Ty.getQualifiers();
7308 
7309   // If we have lifetime, that dominates.
7310   if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
7311     switch (lifetime) {
7312       case Qualifiers::OCL_None: llvm_unreachable("impossible");
7313 
7314       // These are just bits as far as the runtime is concerned.
7315       case Qualifiers::OCL_ExplicitNone:
7316       case Qualifiers::OCL_Autoreleasing:
7317         return false;
7318 
7319       // These cases should have been taken care of when checking the type's
7320       // non-triviality.
7321       case Qualifiers::OCL_Weak:
7322       case Qualifiers::OCL_Strong:
7323         llvm_unreachable("impossible");
7324     }
7325     llvm_unreachable("fell out of lifetime switch!");
7326   }
7327   return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
7328           Ty->isObjCObjectPointerType());
7329 }
7330 
7331 bool ASTContext::getByrefLifetime(QualType Ty,
7332                               Qualifiers::ObjCLifetime &LifeTime,
7333                               bool &HasByrefExtendedLayout) const {
7334   if (!getLangOpts().ObjC ||
7335       getLangOpts().getGC() != LangOptions::NonGC)
7336     return false;
7337 
7338   HasByrefExtendedLayout = false;
7339   if (Ty->isRecordType()) {
7340     HasByrefExtendedLayout = true;
7341     LifeTime = Qualifiers::OCL_None;
7342   } else if ((LifeTime = Ty.getObjCLifetime())) {
7343     // Honor the ARC qualifiers.
7344   } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
7345     // The MRR rule.
7346     LifeTime = Qualifiers::OCL_ExplicitNone;
7347   } else {
7348     LifeTime = Qualifiers::OCL_None;
7349   }
7350   return true;
7351 }
7352 
7353 CanQualType ASTContext::getNSUIntegerType() const {
7354   assert(Target && "Expected target to be initialized");
7355   const llvm::Triple &T = Target->getTriple();
7356   // Windows is LLP64 rather than LP64
7357   if (T.isOSWindows() && T.isArch64Bit())
7358     return UnsignedLongLongTy;
7359   return UnsignedLongTy;
7360 }
7361 
7362 CanQualType ASTContext::getNSIntegerType() const {
7363   assert(Target && "Expected target to be initialized");
7364   const llvm::Triple &T = Target->getTriple();
7365   // Windows is LLP64 rather than LP64
7366   if (T.isOSWindows() && T.isArch64Bit())
7367     return LongLongTy;
7368   return LongTy;
7369 }
7370 
7371 TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
7372   if (!ObjCInstanceTypeDecl)
7373     ObjCInstanceTypeDecl =
7374         buildImplicitTypedef(getObjCIdType(), "instancetype");
7375   return ObjCInstanceTypeDecl;
7376 }
7377 
7378 // This returns true if a type has been typedefed to BOOL:
7379 // typedef <type> BOOL;
7380 static bool isTypeTypedefedAsBOOL(QualType T) {
7381   if (const auto *TT = dyn_cast<TypedefType>(T))
7382     if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
7383       return II->isStr("BOOL");
7384 
7385   return false;
7386 }
7387 
7388 /// getObjCEncodingTypeSize returns size of type for objective-c encoding
7389 /// purpose.
7390 CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
7391   if (!type->isIncompleteArrayType() && type->isIncompleteType())
7392     return CharUnits::Zero();
7393 
7394   CharUnits sz = getTypeSizeInChars(type);
7395 
7396   // Make all integer and enum types at least as large as an int
7397   if (sz.isPositive() && type->isIntegralOrEnumerationType())
7398     sz = std::max(sz, getTypeSizeInChars(IntTy));
7399   // Treat arrays as pointers, since that's how they're passed in.
7400   else if (type->isArrayType())
7401     sz = getTypeSizeInChars(VoidPtrTy);
7402   return sz;
7403 }
7404 
7405 bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
7406   return getTargetInfo().getCXXABI().isMicrosoft() &&
7407          VD->isStaticDataMember() &&
7408          VD->getType()->isIntegralOrEnumerationType() &&
7409          !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
7410 }
7411 
7412 ASTContext::InlineVariableDefinitionKind
7413 ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const {
7414   if (!VD->isInline())
7415     return InlineVariableDefinitionKind::None;
7416 
7417   // In almost all cases, it's a weak definition.
7418   auto *First = VD->getFirstDecl();
7419   if (First->isInlineSpecified() || !First->isStaticDataMember())
7420     return InlineVariableDefinitionKind::Weak;
7421 
7422   // If there's a file-context declaration in this translation unit, it's a
7423   // non-discardable definition.
7424   for (auto *D : VD->redecls())
7425     if (D->getLexicalDeclContext()->isFileContext() &&
7426         !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
7427       return InlineVariableDefinitionKind::Strong;
7428 
7429   // If we've not seen one yet, we don't know.
7430   return InlineVariableDefinitionKind::WeakUnknown;
7431 }
7432 
7433 static std::string charUnitsToString(const CharUnits &CU) {
7434   return llvm::itostr(CU.getQuantity());
7435 }
7436 
7437 /// getObjCEncodingForBlock - Return the encoded type for this block
7438 /// declaration.
7439 std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
7440   std::string S;
7441 
7442   const BlockDecl *Decl = Expr->getBlockDecl();
7443   QualType BlockTy =
7444       Expr->getType()->castAs<BlockPointerType>()->getPointeeType();
7445   QualType BlockReturnTy = BlockTy->castAs<FunctionType>()->getReturnType();
7446   // Encode result type.
7447   if (getLangOpts().EncodeExtendedBlockSig)
7448     getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, BlockReturnTy, S,
7449                                       true /*Extended*/);
7450   else
7451     getObjCEncodingForType(BlockReturnTy, S);
7452   // Compute size of all parameters.
7453   // Start with computing size of a pointer in number of bytes.
7454   // FIXME: There might(should) be a better way of doing this computation!
7455   CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
7456   CharUnits ParmOffset = PtrSize;
7457   for (auto PI : Decl->parameters()) {
7458     QualType PType = PI->getType();
7459     CharUnits sz = getObjCEncodingTypeSize(PType);
7460     if (sz.isZero())
7461       continue;
7462     assert(sz.isPositive() && "BlockExpr - Incomplete param type");
7463     ParmOffset += sz;
7464   }
7465   // Size of the argument frame
7466   S += charUnitsToString(ParmOffset);
7467   // Block pointer and offset.
7468   S += "@?0";
7469 
7470   // Argument types.
7471   ParmOffset = PtrSize;
7472   for (auto PVDecl : Decl->parameters()) {
7473     QualType PType = PVDecl->getOriginalType();
7474     if (const auto *AT =
7475             dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
7476       // Use array's original type only if it has known number of
7477       // elements.
7478       if (!isa<ConstantArrayType>(AT))
7479         PType = PVDecl->getType();
7480     } else if (PType->isFunctionType())
7481       PType = PVDecl->getType();
7482     if (getLangOpts().EncodeExtendedBlockSig)
7483       getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
7484                                       S, true /*Extended*/);
7485     else
7486       getObjCEncodingForType(PType, S);
7487     S += charUnitsToString(ParmOffset);
7488     ParmOffset += getObjCEncodingTypeSize(PType);
7489   }
7490 
7491   return S;
7492 }
7493 
7494 std::string
7495 ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const {
7496   std::string S;
7497   // Encode result type.
7498   getObjCEncodingForType(Decl->getReturnType(), S);
7499   CharUnits ParmOffset;
7500   // Compute size of all parameters.
7501   for (auto PI : Decl->parameters()) {
7502     QualType PType = PI->getType();
7503     CharUnits sz = getObjCEncodingTypeSize(PType);
7504     if (sz.isZero())
7505       continue;
7506 
7507     assert(sz.isPositive() &&
7508            "getObjCEncodingForFunctionDecl - Incomplete param type");
7509     ParmOffset += sz;
7510   }
7511   S += charUnitsToString(ParmOffset);
7512   ParmOffset = CharUnits::Zero();
7513 
7514   // Argument types.
7515   for (auto PVDecl : Decl->parameters()) {
7516     QualType PType = PVDecl->getOriginalType();
7517     if (const auto *AT =
7518             dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
7519       // Use array's original type only if it has known number of
7520       // elements.
7521       if (!isa<ConstantArrayType>(AT))
7522         PType = PVDecl->getType();
7523     } else if (PType->isFunctionType())
7524       PType = PVDecl->getType();
7525     getObjCEncodingForType(PType, S);
7526     S += charUnitsToString(ParmOffset);
7527     ParmOffset += getObjCEncodingTypeSize(PType);
7528   }
7529 
7530   return S;
7531 }
7532 
7533 /// getObjCEncodingForMethodParameter - Return the encoded type for a single
7534 /// method parameter or return type. If Extended, include class names and
7535 /// block object types.
7536 void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
7537                                                    QualType T, std::string& S,
7538                                                    bool Extended) const {
7539   // Encode type qualifier, 'in', 'inout', etc. for the parameter.
7540   getObjCEncodingForTypeQualifier(QT, S);
7541   // Encode parameter type.
7542   ObjCEncOptions Options = ObjCEncOptions()
7543                                .setExpandPointedToStructures()
7544                                .setExpandStructures()
7545                                .setIsOutermostType();
7546   if (Extended)
7547     Options.setEncodeBlockParameters().setEncodeClassNames();
7548   getObjCEncodingForTypeImpl(T, S, Options, /*Field=*/nullptr);
7549 }
7550 
7551 /// getObjCEncodingForMethodDecl - Return the encoded type for this method
7552 /// declaration.
7553 std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
7554                                                      bool Extended) const {
7555   // FIXME: This is not very efficient.
7556   // Encode return type.
7557   std::string S;
7558   getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
7559                                     Decl->getReturnType(), S, Extended);
7560   // Compute size of all parameters.
7561   // Start with computing size of a pointer in number of bytes.
7562   // FIXME: There might(should) be a better way of doing this computation!
7563   CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
7564   // The first two arguments (self and _cmd) are pointers; account for
7565   // their size.
7566   CharUnits ParmOffset = 2 * PtrSize;
7567   for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
7568        E = Decl->sel_param_end(); PI != E; ++PI) {
7569     QualType PType = (*PI)->getType();
7570     CharUnits sz = getObjCEncodingTypeSize(PType);
7571     if (sz.isZero())
7572       continue;
7573 
7574     assert(sz.isPositive() &&
7575            "getObjCEncodingForMethodDecl - Incomplete param type");
7576     ParmOffset += sz;
7577   }
7578   S += charUnitsToString(ParmOffset);
7579   S += "@0:";
7580   S += charUnitsToString(PtrSize);
7581 
7582   // Argument types.
7583   ParmOffset = 2 * PtrSize;
7584   for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
7585        E = Decl->sel_param_end(); PI != E; ++PI) {
7586     const ParmVarDecl *PVDecl = *PI;
7587     QualType PType = PVDecl->getOriginalType();
7588     if (const auto *AT =
7589             dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
7590       // Use array's original type only if it has known number of
7591       // elements.
7592       if (!isa<ConstantArrayType>(AT))
7593         PType = PVDecl->getType();
7594     } else if (PType->isFunctionType())
7595       PType = PVDecl->getType();
7596     getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
7597                                       PType, S, Extended);
7598     S += charUnitsToString(ParmOffset);
7599     ParmOffset += getObjCEncodingTypeSize(PType);
7600   }
7601 
7602   return S;
7603 }
7604 
7605 ObjCPropertyImplDecl *
7606 ASTContext::getObjCPropertyImplDeclForPropertyDecl(
7607                                       const ObjCPropertyDecl *PD,
7608                                       const Decl *Container) const {
7609   if (!Container)
7610     return nullptr;
7611   if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) {
7612     for (auto *PID : CID->property_impls())
7613       if (PID->getPropertyDecl() == PD)
7614         return PID;
7615   } else {
7616     const auto *OID = cast<ObjCImplementationDecl>(Container);
7617     for (auto *PID : OID->property_impls())
7618       if (PID->getPropertyDecl() == PD)
7619         return PID;
7620   }
7621   return nullptr;
7622 }
7623 
7624 /// getObjCEncodingForPropertyDecl - Return the encoded type for this
7625 /// property declaration. If non-NULL, Container must be either an
7626 /// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
7627 /// NULL when getting encodings for protocol properties.
7628 /// Property attributes are stored as a comma-delimited C string. The simple
7629 /// attributes readonly and bycopy are encoded as single characters. The
7630 /// parametrized attributes, getter=name, setter=name, and ivar=name, are
7631 /// encoded as single characters, followed by an identifier. Property types
7632 /// are also encoded as a parametrized attribute. The characters used to encode
7633 /// these attributes are defined by the following enumeration:
7634 /// @code
7635 /// enum PropertyAttributes {
7636 /// kPropertyReadOnly = 'R',   // property is read-only.
7637 /// kPropertyBycopy = 'C',     // property is a copy of the value last assigned
7638 /// kPropertyByref = '&',  // property is a reference to the value last assigned
7639 /// kPropertyDynamic = 'D',    // property is dynamic
7640 /// kPropertyGetter = 'G',     // followed by getter selector name
7641 /// kPropertySetter = 'S',     // followed by setter selector name
7642 /// kPropertyInstanceVariable = 'V'  // followed by instance variable  name
7643 /// kPropertyType = 'T'              // followed by old-style type encoding.
7644 /// kPropertyWeak = 'W'              // 'weak' property
7645 /// kPropertyStrong = 'P'            // property GC'able
7646 /// kPropertyNonAtomic = 'N'         // property non-atomic
7647 /// };
7648 /// @endcode
7649 std::string
7650 ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
7651                                            const Decl *Container) const {
7652   // Collect information from the property implementation decl(s).
7653   bool Dynamic = false;
7654   ObjCPropertyImplDecl *SynthesizePID = nullptr;
7655 
7656   if (ObjCPropertyImplDecl *PropertyImpDecl =
7657       getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
7658     if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
7659       Dynamic = true;
7660     else
7661       SynthesizePID = PropertyImpDecl;
7662   }
7663 
7664   // FIXME: This is not very efficient.
7665   std::string S = "T";
7666 
7667   // Encode result type.
7668   // GCC has some special rules regarding encoding of properties which
7669   // closely resembles encoding of ivars.
7670   getObjCEncodingForPropertyType(PD->getType(), S);
7671 
7672   if (PD->isReadOnly()) {
7673     S += ",R";
7674     if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_copy)
7675       S += ",C";
7676     if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_retain)
7677       S += ",&";
7678     if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_weak)
7679       S += ",W";
7680   } else {
7681     switch (PD->getSetterKind()) {
7682     case ObjCPropertyDecl::Assign: break;
7683     case ObjCPropertyDecl::Copy:   S += ",C"; break;
7684     case ObjCPropertyDecl::Retain: S += ",&"; break;
7685     case ObjCPropertyDecl::Weak:   S += ",W"; break;
7686     }
7687   }
7688 
7689   // It really isn't clear at all what this means, since properties
7690   // are "dynamic by default".
7691   if (Dynamic)
7692     S += ",D";
7693 
7694   if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_nonatomic)
7695     S += ",N";
7696 
7697   if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_getter) {
7698     S += ",G";
7699     S += PD->getGetterName().getAsString();
7700   }
7701 
7702   if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_setter) {
7703     S += ",S";
7704     S += PD->getSetterName().getAsString();
7705   }
7706 
7707   if (SynthesizePID) {
7708     const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
7709     S += ",V";
7710     S += OID->getNameAsString();
7711   }
7712 
7713   // FIXME: OBJCGC: weak & strong
7714   return S;
7715 }
7716 
7717 /// getLegacyIntegralTypeEncoding -
7718 /// Another legacy compatibility encoding: 32-bit longs are encoded as
7719 /// 'l' or 'L' , but not always.  For typedefs, we need to use
7720 /// 'i' or 'I' instead if encoding a struct field, or a pointer!
7721 void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
7722   if (isa<TypedefType>(PointeeTy.getTypePtr())) {
7723     if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
7724       if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
7725         PointeeTy = UnsignedIntTy;
7726       else
7727         if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
7728           PointeeTy = IntTy;
7729     }
7730   }
7731 }
7732 
7733 void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
7734                                         const FieldDecl *Field,
7735                                         QualType *NotEncodedT) const {
7736   // We follow the behavior of gcc, expanding structures which are
7737   // directly pointed to, and expanding embedded structures. Note that
7738   // these rules are sufficient to prevent recursive encoding of the
7739   // same type.
7740   getObjCEncodingForTypeImpl(T, S,
7741                              ObjCEncOptions()
7742                                  .setExpandPointedToStructures()
7743                                  .setExpandStructures()
7744                                  .setIsOutermostType(),
7745                              Field, NotEncodedT);
7746 }
7747 
7748 void ASTContext::getObjCEncodingForPropertyType(QualType T,
7749                                                 std::string& S) const {
7750   // Encode result type.
7751   // GCC has some special rules regarding encoding of properties which
7752   // closely resembles encoding of ivars.
7753   getObjCEncodingForTypeImpl(T, S,
7754                              ObjCEncOptions()
7755                                  .setExpandPointedToStructures()
7756                                  .setExpandStructures()
7757                                  .setIsOutermostType()
7758                                  .setEncodingProperty(),
7759                              /*Field=*/nullptr);
7760 }
7761 
7762 static char getObjCEncodingForPrimitiveType(const ASTContext *C,
7763                                             const BuiltinType *BT) {
7764     BuiltinType::Kind kind = BT->getKind();
7765     switch (kind) {
7766     case BuiltinType::Void:       return 'v';
7767     case BuiltinType::Bool:       return 'B';
7768     case BuiltinType::Char8:
7769     case BuiltinType::Char_U:
7770     case BuiltinType::UChar:      return 'C';
7771     case BuiltinType::Char16:
7772     case BuiltinType::UShort:     return 'S';
7773     case BuiltinType::Char32:
7774     case BuiltinType::UInt:       return 'I';
7775     case BuiltinType::ULong:
7776         return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
7777     case BuiltinType::UInt128:    return 'T';
7778     case BuiltinType::ULongLong:  return 'Q';
7779     case BuiltinType::Char_S:
7780     case BuiltinType::SChar:      return 'c';
7781     case BuiltinType::Short:      return 's';
7782     case BuiltinType::WChar_S:
7783     case BuiltinType::WChar_U:
7784     case BuiltinType::Int:        return 'i';
7785     case BuiltinType::Long:
7786       return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
7787     case BuiltinType::LongLong:   return 'q';
7788     case BuiltinType::Int128:     return 't';
7789     case BuiltinType::Float:      return 'f';
7790     case BuiltinType::Double:     return 'd';
7791     case BuiltinType::LongDouble: return 'D';
7792     case BuiltinType::NullPtr:    return '*'; // like char*
7793 
7794     case BuiltinType::BFloat16:
7795     case BuiltinType::Float16:
7796     case BuiltinType::Float128:
7797     case BuiltinType::Ibm128:
7798     case BuiltinType::Half:
7799     case BuiltinType::ShortAccum:
7800     case BuiltinType::Accum:
7801     case BuiltinType::LongAccum:
7802     case BuiltinType::UShortAccum:
7803     case BuiltinType::UAccum:
7804     case BuiltinType::ULongAccum:
7805     case BuiltinType::ShortFract:
7806     case BuiltinType::Fract:
7807     case BuiltinType::LongFract:
7808     case BuiltinType::UShortFract:
7809     case BuiltinType::UFract:
7810     case BuiltinType::ULongFract:
7811     case BuiltinType::SatShortAccum:
7812     case BuiltinType::SatAccum:
7813     case BuiltinType::SatLongAccum:
7814     case BuiltinType::SatUShortAccum:
7815     case BuiltinType::SatUAccum:
7816     case BuiltinType::SatULongAccum:
7817     case BuiltinType::SatShortFract:
7818     case BuiltinType::SatFract:
7819     case BuiltinType::SatLongFract:
7820     case BuiltinType::SatUShortFract:
7821     case BuiltinType::SatUFract:
7822     case BuiltinType::SatULongFract:
7823       // FIXME: potentially need @encodes for these!
7824       return ' ';
7825 
7826 #define SVE_TYPE(Name, Id, SingletonId) \
7827     case BuiltinType::Id:
7828 #include "clang/Basic/AArch64SVEACLETypes.def"
7829 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
7830 #include "clang/Basic/RISCVVTypes.def"
7831       {
7832         DiagnosticsEngine &Diags = C->getDiagnostics();
7833         unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
7834                                                 "cannot yet @encode type %0");
7835         Diags.Report(DiagID) << BT->getName(C->getPrintingPolicy());
7836         return ' ';
7837       }
7838 
7839     case BuiltinType::ObjCId:
7840     case BuiltinType::ObjCClass:
7841     case BuiltinType::ObjCSel:
7842       llvm_unreachable("@encoding ObjC primitive type");
7843 
7844     // OpenCL and placeholder types don't need @encodings.
7845 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7846     case BuiltinType::Id:
7847 #include "clang/Basic/OpenCLImageTypes.def"
7848 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
7849     case BuiltinType::Id:
7850 #include "clang/Basic/OpenCLExtensionTypes.def"
7851     case BuiltinType::OCLEvent:
7852     case BuiltinType::OCLClkEvent:
7853     case BuiltinType::OCLQueue:
7854     case BuiltinType::OCLReserveID:
7855     case BuiltinType::OCLSampler:
7856     case BuiltinType::Dependent:
7857 #define PPC_VECTOR_TYPE(Name, Id, Size) \
7858     case BuiltinType::Id:
7859 #include "clang/Basic/PPCTypes.def"
7860 #define BUILTIN_TYPE(KIND, ID)
7861 #define PLACEHOLDER_TYPE(KIND, ID) \
7862     case BuiltinType::KIND:
7863 #include "clang/AST/BuiltinTypes.def"
7864       llvm_unreachable("invalid builtin type for @encode");
7865     }
7866     llvm_unreachable("invalid BuiltinType::Kind value");
7867 }
7868 
7869 static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
7870   EnumDecl *Enum = ET->getDecl();
7871 
7872   // The encoding of an non-fixed enum type is always 'i', regardless of size.
7873   if (!Enum->isFixed())
7874     return 'i';
7875 
7876   // The encoding of a fixed enum type matches its fixed underlying type.
7877   const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
7878   return getObjCEncodingForPrimitiveType(C, BT);
7879 }
7880 
7881 static void EncodeBitField(const ASTContext *Ctx, std::string& S,
7882                            QualType T, const FieldDecl *FD) {
7883   assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
7884   S += 'b';
7885   // The NeXT runtime encodes bit fields as b followed by the number of bits.
7886   // The GNU runtime requires more information; bitfields are encoded as b,
7887   // then the offset (in bits) of the first element, then the type of the
7888   // bitfield, then the size in bits.  For example, in this structure:
7889   //
7890   // struct
7891   // {
7892   //    int integer;
7893   //    int flags:2;
7894   // };
7895   // On a 32-bit system, the encoding for flags would be b2 for the NeXT
7896   // runtime, but b32i2 for the GNU runtime.  The reason for this extra
7897   // information is not especially sensible, but we're stuck with it for
7898   // compatibility with GCC, although providing it breaks anything that
7899   // actually uses runtime introspection and wants to work on both runtimes...
7900   if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
7901     uint64_t Offset;
7902 
7903     if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
7904       Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), nullptr,
7905                                          IVD);
7906     } else {
7907       const RecordDecl *RD = FD->getParent();
7908       const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
7909       Offset = RL.getFieldOffset(FD->getFieldIndex());
7910     }
7911 
7912     S += llvm::utostr(Offset);
7913 
7914     if (const auto *ET = T->getAs<EnumType>())
7915       S += ObjCEncodingForEnumType(Ctx, ET);
7916     else {
7917       const auto *BT = T->castAs<BuiltinType>();
7918       S += getObjCEncodingForPrimitiveType(Ctx, BT);
7919     }
7920   }
7921   S += llvm::utostr(FD->getBitWidthValue(*Ctx));
7922 }
7923 
7924 // Helper function for determining whether the encoded type string would include
7925 // a template specialization type.
7926 static bool hasTemplateSpecializationInEncodedString(const Type *T,
7927                                                      bool VisitBasesAndFields) {
7928   T = T->getBaseElementTypeUnsafe();
7929 
7930   if (auto *PT = T->getAs<PointerType>())
7931     return hasTemplateSpecializationInEncodedString(
7932         PT->getPointeeType().getTypePtr(), false);
7933 
7934   auto *CXXRD = T->getAsCXXRecordDecl();
7935 
7936   if (!CXXRD)
7937     return false;
7938 
7939   if (isa<ClassTemplateSpecializationDecl>(CXXRD))
7940     return true;
7941 
7942   if (!CXXRD->hasDefinition() || !VisitBasesAndFields)
7943     return false;
7944 
7945   for (auto B : CXXRD->bases())
7946     if (hasTemplateSpecializationInEncodedString(B.getType().getTypePtr(),
7947                                                  true))
7948       return true;
7949 
7950   for (auto *FD : CXXRD->fields())
7951     if (hasTemplateSpecializationInEncodedString(FD->getType().getTypePtr(),
7952                                                  true))
7953       return true;
7954 
7955   return false;
7956 }
7957 
7958 // FIXME: Use SmallString for accumulating string.
7959 void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
7960                                             const ObjCEncOptions Options,
7961                                             const FieldDecl *FD,
7962                                             QualType *NotEncodedT) const {
7963   CanQualType CT = getCanonicalType(T);
7964   switch (CT->getTypeClass()) {
7965   case Type::Builtin:
7966   case Type::Enum:
7967     if (FD && FD->isBitField())
7968       return EncodeBitField(this, S, T, FD);
7969     if (const auto *BT = dyn_cast<BuiltinType>(CT))
7970       S += getObjCEncodingForPrimitiveType(this, BT);
7971     else
7972       S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
7973     return;
7974 
7975   case Type::Complex:
7976     S += 'j';
7977     getObjCEncodingForTypeImpl(T->castAs<ComplexType>()->getElementType(), S,
7978                                ObjCEncOptions(),
7979                                /*Field=*/nullptr);
7980     return;
7981 
7982   case Type::Atomic:
7983     S += 'A';
7984     getObjCEncodingForTypeImpl(T->castAs<AtomicType>()->getValueType(), S,
7985                                ObjCEncOptions(),
7986                                /*Field=*/nullptr);
7987     return;
7988 
7989   // encoding for pointer or reference types.
7990   case Type::Pointer:
7991   case Type::LValueReference:
7992   case Type::RValueReference: {
7993     QualType PointeeTy;
7994     if (isa<PointerType>(CT)) {
7995       const auto *PT = T->castAs<PointerType>();
7996       if (PT->isObjCSelType()) {
7997         S += ':';
7998         return;
7999       }
8000       PointeeTy = PT->getPointeeType();
8001     } else {
8002       PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
8003     }
8004 
8005     bool isReadOnly = false;
8006     // For historical/compatibility reasons, the read-only qualifier of the
8007     // pointee gets emitted _before_ the '^'.  The read-only qualifier of
8008     // the pointer itself gets ignored, _unless_ we are looking at a typedef!
8009     // Also, do not emit the 'r' for anything but the outermost type!
8010     if (isa<TypedefType>(T.getTypePtr())) {
8011       if (Options.IsOutermostType() && T.isConstQualified()) {
8012         isReadOnly = true;
8013         S += 'r';
8014       }
8015     } else if (Options.IsOutermostType()) {
8016       QualType P = PointeeTy;
8017       while (auto PT = P->getAs<PointerType>())
8018         P = PT->getPointeeType();
8019       if (P.isConstQualified()) {
8020         isReadOnly = true;
8021         S += 'r';
8022       }
8023     }
8024     if (isReadOnly) {
8025       // Another legacy compatibility encoding. Some ObjC qualifier and type
8026       // combinations need to be rearranged.
8027       // Rewrite "in const" from "nr" to "rn"
8028       if (StringRef(S).endswith("nr"))
8029         S.replace(S.end()-2, S.end(), "rn");
8030     }
8031 
8032     if (PointeeTy->isCharType()) {
8033       // char pointer types should be encoded as '*' unless it is a
8034       // type that has been typedef'd to 'BOOL'.
8035       if (!isTypeTypedefedAsBOOL(PointeeTy)) {
8036         S += '*';
8037         return;
8038       }
8039     } else if (const auto *RTy = PointeeTy->getAs<RecordType>()) {
8040       // GCC binary compat: Need to convert "struct objc_class *" to "#".
8041       if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
8042         S += '#';
8043         return;
8044       }
8045       // GCC binary compat: Need to convert "struct objc_object *" to "@".
8046       if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
8047         S += '@';
8048         return;
8049       }
8050       // If the encoded string for the class includes template names, just emit
8051       // "^v" for pointers to the class.
8052       if (getLangOpts().CPlusPlus &&
8053           (!getLangOpts().EncodeCXXClassTemplateSpec &&
8054            hasTemplateSpecializationInEncodedString(
8055                RTy, Options.ExpandPointedToStructures()))) {
8056         S += "^v";
8057         return;
8058       }
8059       // fall through...
8060     }
8061     S += '^';
8062     getLegacyIntegralTypeEncoding(PointeeTy);
8063 
8064     ObjCEncOptions NewOptions;
8065     if (Options.ExpandPointedToStructures())
8066       NewOptions.setExpandStructures();
8067     getObjCEncodingForTypeImpl(PointeeTy, S, NewOptions,
8068                                /*Field=*/nullptr, NotEncodedT);
8069     return;
8070   }
8071 
8072   case Type::ConstantArray:
8073   case Type::IncompleteArray:
8074   case Type::VariableArray: {
8075     const auto *AT = cast<ArrayType>(CT);
8076 
8077     if (isa<IncompleteArrayType>(AT) && !Options.IsStructField()) {
8078       // Incomplete arrays are encoded as a pointer to the array element.
8079       S += '^';
8080 
8081       getObjCEncodingForTypeImpl(
8082           AT->getElementType(), S,
8083           Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD);
8084     } else {
8085       S += '[';
8086 
8087       if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
8088         S += llvm::utostr(CAT->getSize().getZExtValue());
8089       else {
8090         //Variable length arrays are encoded as a regular array with 0 elements.
8091         assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
8092                "Unknown array type!");
8093         S += '0';
8094       }
8095 
8096       getObjCEncodingForTypeImpl(
8097           AT->getElementType(), S,
8098           Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD,
8099           NotEncodedT);
8100       S += ']';
8101     }
8102     return;
8103   }
8104 
8105   case Type::FunctionNoProto:
8106   case Type::FunctionProto:
8107     S += '?';
8108     return;
8109 
8110   case Type::Record: {
8111     RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
8112     S += RDecl->isUnion() ? '(' : '{';
8113     // Anonymous structures print as '?'
8114     if (const IdentifierInfo *II = RDecl->getIdentifier()) {
8115       S += II->getName();
8116       if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
8117         const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
8118         llvm::raw_string_ostream OS(S);
8119         printTemplateArgumentList(OS, TemplateArgs.asArray(),
8120                                   getPrintingPolicy());
8121       }
8122     } else {
8123       S += '?';
8124     }
8125     if (Options.ExpandStructures()) {
8126       S += '=';
8127       if (!RDecl->isUnion()) {
8128         getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
8129       } else {
8130         for (const auto *Field : RDecl->fields()) {
8131           if (FD) {
8132             S += '"';
8133             S += Field->getNameAsString();
8134             S += '"';
8135           }
8136 
8137           // Special case bit-fields.
8138           if (Field->isBitField()) {
8139             getObjCEncodingForTypeImpl(Field->getType(), S,
8140                                        ObjCEncOptions().setExpandStructures(),
8141                                        Field);
8142           } else {
8143             QualType qt = Field->getType();
8144             getLegacyIntegralTypeEncoding(qt);
8145             getObjCEncodingForTypeImpl(
8146                 qt, S,
8147                 ObjCEncOptions().setExpandStructures().setIsStructField(), FD,
8148                 NotEncodedT);
8149           }
8150         }
8151       }
8152     }
8153     S += RDecl->isUnion() ? ')' : '}';
8154     return;
8155   }
8156 
8157   case Type::BlockPointer: {
8158     const auto *BT = T->castAs<BlockPointerType>();
8159     S += "@?"; // Unlike a pointer-to-function, which is "^?".
8160     if (Options.EncodeBlockParameters()) {
8161       const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
8162 
8163       S += '<';
8164       // Block return type
8165       getObjCEncodingForTypeImpl(FT->getReturnType(), S,
8166                                  Options.forComponentType(), FD, NotEncodedT);
8167       // Block self
8168       S += "@?";
8169       // Block parameters
8170       if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) {
8171         for (const auto &I : FPT->param_types())
8172           getObjCEncodingForTypeImpl(I, S, Options.forComponentType(), FD,
8173                                      NotEncodedT);
8174       }
8175       S += '>';
8176     }
8177     return;
8178   }
8179 
8180   case Type::ObjCObject: {
8181     // hack to match legacy encoding of *id and *Class
8182     QualType Ty = getObjCObjectPointerType(CT);
8183     if (Ty->isObjCIdType()) {
8184       S += "{objc_object=}";
8185       return;
8186     }
8187     else if (Ty->isObjCClassType()) {
8188       S += "{objc_class=}";
8189       return;
8190     }
8191     // TODO: Double check to make sure this intentionally falls through.
8192     LLVM_FALLTHROUGH;
8193   }
8194 
8195   case Type::ObjCInterface: {
8196     // Ignore protocol qualifiers when mangling at this level.
8197     // @encode(class_name)
8198     ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
8199     S += '{';
8200     S += OI->getObjCRuntimeNameAsString();
8201     if (Options.ExpandStructures()) {
8202       S += '=';
8203       SmallVector<const ObjCIvarDecl*, 32> Ivars;
8204       DeepCollectObjCIvars(OI, true, Ivars);
8205       for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
8206         const FieldDecl *Field = Ivars[i];
8207         if (Field->isBitField())
8208           getObjCEncodingForTypeImpl(Field->getType(), S,
8209                                      ObjCEncOptions().setExpandStructures(),
8210                                      Field);
8211         else
8212           getObjCEncodingForTypeImpl(Field->getType(), S,
8213                                      ObjCEncOptions().setExpandStructures(), FD,
8214                                      NotEncodedT);
8215       }
8216     }
8217     S += '}';
8218     return;
8219   }
8220 
8221   case Type::ObjCObjectPointer: {
8222     const auto *OPT = T->castAs<ObjCObjectPointerType>();
8223     if (OPT->isObjCIdType()) {
8224       S += '@';
8225       return;
8226     }
8227 
8228     if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
8229       // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
8230       // Since this is a binary compatibility issue, need to consult with
8231       // runtime folks. Fortunately, this is a *very* obscure construct.
8232       S += '#';
8233       return;
8234     }
8235 
8236     if (OPT->isObjCQualifiedIdType()) {
8237       getObjCEncodingForTypeImpl(
8238           getObjCIdType(), S,
8239           Options.keepingOnly(ObjCEncOptions()
8240                                   .setExpandPointedToStructures()
8241                                   .setExpandStructures()),
8242           FD);
8243       if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) {
8244         // Note that we do extended encoding of protocol qualifier list
8245         // Only when doing ivar or property encoding.
8246         S += '"';
8247         for (const auto *I : OPT->quals()) {
8248           S += '<';
8249           S += I->getObjCRuntimeNameAsString();
8250           S += '>';
8251         }
8252         S += '"';
8253       }
8254       return;
8255     }
8256 
8257     S += '@';
8258     if (OPT->getInterfaceDecl() &&
8259         (FD || Options.EncodingProperty() || Options.EncodeClassNames())) {
8260       S += '"';
8261       S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
8262       for (const auto *I : OPT->quals()) {
8263         S += '<';
8264         S += I->getObjCRuntimeNameAsString();
8265         S += '>';
8266       }
8267       S += '"';
8268     }
8269     return;
8270   }
8271 
8272   // gcc just blithely ignores member pointers.
8273   // FIXME: we should do better than that.  'M' is available.
8274   case Type::MemberPointer:
8275   // This matches gcc's encoding, even though technically it is insufficient.
8276   //FIXME. We should do a better job than gcc.
8277   case Type::Vector:
8278   case Type::ExtVector:
8279   // Until we have a coherent encoding of these three types, issue warning.
8280     if (NotEncodedT)
8281       *NotEncodedT = T;
8282     return;
8283 
8284   case Type::ConstantMatrix:
8285     if (NotEncodedT)
8286       *NotEncodedT = T;
8287     return;
8288 
8289   case Type::BitInt:
8290     if (NotEncodedT)
8291       *NotEncodedT = T;
8292     return;
8293 
8294   // We could see an undeduced auto type here during error recovery.
8295   // Just ignore it.
8296   case Type::Auto:
8297   case Type::DeducedTemplateSpecialization:
8298     return;
8299 
8300   case Type::Pipe:
8301 #define ABSTRACT_TYPE(KIND, BASE)
8302 #define TYPE(KIND, BASE)
8303 #define DEPENDENT_TYPE(KIND, BASE) \
8304   case Type::KIND:
8305 #define NON_CANONICAL_TYPE(KIND, BASE) \
8306   case Type::KIND:
8307 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
8308   case Type::KIND:
8309 #include "clang/AST/TypeNodes.inc"
8310     llvm_unreachable("@encode for dependent type!");
8311   }
8312   llvm_unreachable("bad type kind!");
8313 }
8314 
8315 void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
8316                                                  std::string &S,
8317                                                  const FieldDecl *FD,
8318                                                  bool includeVBases,
8319                                                  QualType *NotEncodedT) const {
8320   assert(RDecl && "Expected non-null RecordDecl");
8321   assert(!RDecl->isUnion() && "Should not be called for unions");
8322   if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
8323     return;
8324 
8325   const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
8326   std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
8327   const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
8328 
8329   if (CXXRec) {
8330     for (const auto &BI : CXXRec->bases()) {
8331       if (!BI.isVirtual()) {
8332         CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
8333         if (base->isEmpty())
8334           continue;
8335         uint64_t offs = toBits(layout.getBaseClassOffset(base));
8336         FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
8337                                   std::make_pair(offs, base));
8338       }
8339     }
8340   }
8341 
8342   unsigned i = 0;
8343   for (FieldDecl *Field : RDecl->fields()) {
8344     if (!Field->isZeroLengthBitField(*this) && Field->isZeroSize(*this))
8345       continue;
8346     uint64_t offs = layout.getFieldOffset(i);
8347     FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
8348                               std::make_pair(offs, Field));
8349     ++i;
8350   }
8351 
8352   if (CXXRec && includeVBases) {
8353     for (const auto &BI : CXXRec->vbases()) {
8354       CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
8355       if (base->isEmpty())
8356         continue;
8357       uint64_t offs = toBits(layout.getVBaseClassOffset(base));
8358       if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
8359           FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
8360         FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
8361                                   std::make_pair(offs, base));
8362     }
8363   }
8364 
8365   CharUnits size;
8366   if (CXXRec) {
8367     size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
8368   } else {
8369     size = layout.getSize();
8370   }
8371 
8372 #ifndef NDEBUG
8373   uint64_t CurOffs = 0;
8374 #endif
8375   std::multimap<uint64_t, NamedDecl *>::iterator
8376     CurLayObj = FieldOrBaseOffsets.begin();
8377 
8378   if (CXXRec && CXXRec->isDynamicClass() &&
8379       (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
8380     if (FD) {
8381       S += "\"_vptr$";
8382       std::string recname = CXXRec->getNameAsString();
8383       if (recname.empty()) recname = "?";
8384       S += recname;
8385       S += '"';
8386     }
8387     S += "^^?";
8388 #ifndef NDEBUG
8389     CurOffs += getTypeSize(VoidPtrTy);
8390 #endif
8391   }
8392 
8393   if (!RDecl->hasFlexibleArrayMember()) {
8394     // Mark the end of the structure.
8395     uint64_t offs = toBits(size);
8396     FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
8397                               std::make_pair(offs, nullptr));
8398   }
8399 
8400   for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
8401 #ifndef NDEBUG
8402     assert(CurOffs <= CurLayObj->first);
8403     if (CurOffs < CurLayObj->first) {
8404       uint64_t padding = CurLayObj->first - CurOffs;
8405       // FIXME: There doesn't seem to be a way to indicate in the encoding that
8406       // packing/alignment of members is different that normal, in which case
8407       // the encoding will be out-of-sync with the real layout.
8408       // If the runtime switches to just consider the size of types without
8409       // taking into account alignment, we could make padding explicit in the
8410       // encoding (e.g. using arrays of chars). The encoding strings would be
8411       // longer then though.
8412       CurOffs += padding;
8413     }
8414 #endif
8415 
8416     NamedDecl *dcl = CurLayObj->second;
8417     if (!dcl)
8418       break; // reached end of structure.
8419 
8420     if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) {
8421       // We expand the bases without their virtual bases since those are going
8422       // in the initial structure. Note that this differs from gcc which
8423       // expands virtual bases each time one is encountered in the hierarchy,
8424       // making the encoding type bigger than it really is.
8425       getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
8426                                       NotEncodedT);
8427       assert(!base->isEmpty());
8428 #ifndef NDEBUG
8429       CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
8430 #endif
8431     } else {
8432       const auto *field = cast<FieldDecl>(dcl);
8433       if (FD) {
8434         S += '"';
8435         S += field->getNameAsString();
8436         S += '"';
8437       }
8438 
8439       if (field->isBitField()) {
8440         EncodeBitField(this, S, field->getType(), field);
8441 #ifndef NDEBUG
8442         CurOffs += field->getBitWidthValue(*this);
8443 #endif
8444       } else {
8445         QualType qt = field->getType();
8446         getLegacyIntegralTypeEncoding(qt);
8447         getObjCEncodingForTypeImpl(
8448             qt, S, ObjCEncOptions().setExpandStructures().setIsStructField(),
8449             FD, NotEncodedT);
8450 #ifndef NDEBUG
8451         CurOffs += getTypeSize(field->getType());
8452 #endif
8453       }
8454     }
8455   }
8456 }
8457 
8458 void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
8459                                                  std::string& S) const {
8460   if (QT & Decl::OBJC_TQ_In)
8461     S += 'n';
8462   if (QT & Decl::OBJC_TQ_Inout)
8463     S += 'N';
8464   if (QT & Decl::OBJC_TQ_Out)
8465     S += 'o';
8466   if (QT & Decl::OBJC_TQ_Bycopy)
8467     S += 'O';
8468   if (QT & Decl::OBJC_TQ_Byref)
8469     S += 'R';
8470   if (QT & Decl::OBJC_TQ_Oneway)
8471     S += 'V';
8472 }
8473 
8474 TypedefDecl *ASTContext::getObjCIdDecl() const {
8475   if (!ObjCIdDecl) {
8476     QualType T = getObjCObjectType(ObjCBuiltinIdTy, {}, {});
8477     T = getObjCObjectPointerType(T);
8478     ObjCIdDecl = buildImplicitTypedef(T, "id");
8479   }
8480   return ObjCIdDecl;
8481 }
8482 
8483 TypedefDecl *ASTContext::getObjCSelDecl() const {
8484   if (!ObjCSelDecl) {
8485     QualType T = getPointerType(ObjCBuiltinSelTy);
8486     ObjCSelDecl = buildImplicitTypedef(T, "SEL");
8487   }
8488   return ObjCSelDecl;
8489 }
8490 
8491 TypedefDecl *ASTContext::getObjCClassDecl() const {
8492   if (!ObjCClassDecl) {
8493     QualType T = getObjCObjectType(ObjCBuiltinClassTy, {}, {});
8494     T = getObjCObjectPointerType(T);
8495     ObjCClassDecl = buildImplicitTypedef(T, "Class");
8496   }
8497   return ObjCClassDecl;
8498 }
8499 
8500 ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
8501   if (!ObjCProtocolClassDecl) {
8502     ObjCProtocolClassDecl
8503       = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
8504                                   SourceLocation(),
8505                                   &Idents.get("Protocol"),
8506                                   /*typeParamList=*/nullptr,
8507                                   /*PrevDecl=*/nullptr,
8508                                   SourceLocation(), true);
8509   }
8510 
8511   return ObjCProtocolClassDecl;
8512 }
8513 
8514 //===----------------------------------------------------------------------===//
8515 // __builtin_va_list Construction Functions
8516 //===----------------------------------------------------------------------===//
8517 
8518 static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
8519                                                  StringRef Name) {
8520   // typedef char* __builtin[_ms]_va_list;
8521   QualType T = Context->getPointerType(Context->CharTy);
8522   return Context->buildImplicitTypedef(T, Name);
8523 }
8524 
8525 static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
8526   return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
8527 }
8528 
8529 static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
8530   return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
8531 }
8532 
8533 static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
8534   // typedef void* __builtin_va_list;
8535   QualType T = Context->getPointerType(Context->VoidTy);
8536   return Context->buildImplicitTypedef(T, "__builtin_va_list");
8537 }
8538 
8539 static TypedefDecl *
8540 CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
8541   // struct __va_list
8542   RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
8543   if (Context->getLangOpts().CPlusPlus) {
8544     // namespace std { struct __va_list {
8545     auto *NS = NamespaceDecl::Create(
8546         const_cast<ASTContext &>(*Context), Context->getTranslationUnitDecl(),
8547         /*Inline*/ false, SourceLocation(), SourceLocation(),
8548         &Context->Idents.get("std"),
8549         /*PrevDecl*/ nullptr);
8550     NS->setImplicit();
8551     VaListTagDecl->setDeclContext(NS);
8552   }
8553 
8554   VaListTagDecl->startDefinition();
8555 
8556   const size_t NumFields = 5;
8557   QualType FieldTypes[NumFields];
8558   const char *FieldNames[NumFields];
8559 
8560   // void *__stack;
8561   FieldTypes[0] = Context->getPointerType(Context->VoidTy);
8562   FieldNames[0] = "__stack";
8563 
8564   // void *__gr_top;
8565   FieldTypes[1] = Context->getPointerType(Context->VoidTy);
8566   FieldNames[1] = "__gr_top";
8567 
8568   // void *__vr_top;
8569   FieldTypes[2] = Context->getPointerType(Context->VoidTy);
8570   FieldNames[2] = "__vr_top";
8571 
8572   // int __gr_offs;
8573   FieldTypes[3] = Context->IntTy;
8574   FieldNames[3] = "__gr_offs";
8575 
8576   // int __vr_offs;
8577   FieldTypes[4] = Context->IntTy;
8578   FieldNames[4] = "__vr_offs";
8579 
8580   // Create fields
8581   for (unsigned i = 0; i < NumFields; ++i) {
8582     FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
8583                                          VaListTagDecl,
8584                                          SourceLocation(),
8585                                          SourceLocation(),
8586                                          &Context->Idents.get(FieldNames[i]),
8587                                          FieldTypes[i], /*TInfo=*/nullptr,
8588                                          /*BitWidth=*/nullptr,
8589                                          /*Mutable=*/false,
8590                                          ICIS_NoInit);
8591     Field->setAccess(AS_public);
8592     VaListTagDecl->addDecl(Field);
8593   }
8594   VaListTagDecl->completeDefinition();
8595   Context->VaListTagDecl = VaListTagDecl;
8596   QualType VaListTagType = Context->getRecordType(VaListTagDecl);
8597 
8598   // } __builtin_va_list;
8599   return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
8600 }
8601 
8602 static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
8603   // typedef struct __va_list_tag {
8604   RecordDecl *VaListTagDecl;
8605 
8606   VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
8607   VaListTagDecl->startDefinition();
8608 
8609   const size_t NumFields = 5;
8610   QualType FieldTypes[NumFields];
8611   const char *FieldNames[NumFields];
8612 
8613   //   unsigned char gpr;
8614   FieldTypes[0] = Context->UnsignedCharTy;
8615   FieldNames[0] = "gpr";
8616 
8617   //   unsigned char fpr;
8618   FieldTypes[1] = Context->UnsignedCharTy;
8619   FieldNames[1] = "fpr";
8620 
8621   //   unsigned short reserved;
8622   FieldTypes[2] = Context->UnsignedShortTy;
8623   FieldNames[2] = "reserved";
8624 
8625   //   void* overflow_arg_area;
8626   FieldTypes[3] = Context->getPointerType(Context->VoidTy);
8627   FieldNames[3] = "overflow_arg_area";
8628 
8629   //   void* reg_save_area;
8630   FieldTypes[4] = Context->getPointerType(Context->VoidTy);
8631   FieldNames[4] = "reg_save_area";
8632 
8633   // Create fields
8634   for (unsigned i = 0; i < NumFields; ++i) {
8635     FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
8636                                          SourceLocation(),
8637                                          SourceLocation(),
8638                                          &Context->Idents.get(FieldNames[i]),
8639                                          FieldTypes[i], /*TInfo=*/nullptr,
8640                                          /*BitWidth=*/nullptr,
8641                                          /*Mutable=*/false,
8642                                          ICIS_NoInit);
8643     Field->setAccess(AS_public);
8644     VaListTagDecl->addDecl(Field);
8645   }
8646   VaListTagDecl->completeDefinition();
8647   Context->VaListTagDecl = VaListTagDecl;
8648   QualType VaListTagType = Context->getRecordType(VaListTagDecl);
8649 
8650   // } __va_list_tag;
8651   TypedefDecl *VaListTagTypedefDecl =
8652       Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
8653 
8654   QualType VaListTagTypedefType =
8655     Context->getTypedefType(VaListTagTypedefDecl);
8656 
8657   // typedef __va_list_tag __builtin_va_list[1];
8658   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
8659   QualType VaListTagArrayType
8660     = Context->getConstantArrayType(VaListTagTypedefType,
8661                                     Size, nullptr, ArrayType::Normal, 0);
8662   return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
8663 }
8664 
8665 static TypedefDecl *
8666 CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
8667   // struct __va_list_tag {
8668   RecordDecl *VaListTagDecl;
8669   VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
8670   VaListTagDecl->startDefinition();
8671 
8672   const size_t NumFields = 4;
8673   QualType FieldTypes[NumFields];
8674   const char *FieldNames[NumFields];
8675 
8676   //   unsigned gp_offset;
8677   FieldTypes[0] = Context->UnsignedIntTy;
8678   FieldNames[0] = "gp_offset";
8679 
8680   //   unsigned fp_offset;
8681   FieldTypes[1] = Context->UnsignedIntTy;
8682   FieldNames[1] = "fp_offset";
8683 
8684   //   void* overflow_arg_area;
8685   FieldTypes[2] = Context->getPointerType(Context->VoidTy);
8686   FieldNames[2] = "overflow_arg_area";
8687 
8688   //   void* reg_save_area;
8689   FieldTypes[3] = Context->getPointerType(Context->VoidTy);
8690   FieldNames[3] = "reg_save_area";
8691 
8692   // Create fields
8693   for (unsigned i = 0; i < NumFields; ++i) {
8694     FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
8695                                          VaListTagDecl,
8696                                          SourceLocation(),
8697                                          SourceLocation(),
8698                                          &Context->Idents.get(FieldNames[i]),
8699                                          FieldTypes[i], /*TInfo=*/nullptr,
8700                                          /*BitWidth=*/nullptr,
8701                                          /*Mutable=*/false,
8702                                          ICIS_NoInit);
8703     Field->setAccess(AS_public);
8704     VaListTagDecl->addDecl(Field);
8705   }
8706   VaListTagDecl->completeDefinition();
8707   Context->VaListTagDecl = VaListTagDecl;
8708   QualType VaListTagType = Context->getRecordType(VaListTagDecl);
8709 
8710   // };
8711 
8712   // typedef struct __va_list_tag __builtin_va_list[1];
8713   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
8714   QualType VaListTagArrayType = Context->getConstantArrayType(
8715       VaListTagType, Size, nullptr, ArrayType::Normal, 0);
8716   return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
8717 }
8718 
8719 static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
8720   // typedef int __builtin_va_list[4];
8721   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
8722   QualType IntArrayType = Context->getConstantArrayType(
8723       Context->IntTy, Size, nullptr, ArrayType::Normal, 0);
8724   return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
8725 }
8726 
8727 static TypedefDecl *
8728 CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
8729   // struct __va_list
8730   RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
8731   if (Context->getLangOpts().CPlusPlus) {
8732     // namespace std { struct __va_list {
8733     NamespaceDecl *NS;
8734     NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
8735                                Context->getTranslationUnitDecl(),
8736                                /*Inline*/false, SourceLocation(),
8737                                SourceLocation(), &Context->Idents.get("std"),
8738                                /*PrevDecl*/ nullptr);
8739     NS->setImplicit();
8740     VaListDecl->setDeclContext(NS);
8741   }
8742 
8743   VaListDecl->startDefinition();
8744 
8745   // void * __ap;
8746   FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
8747                                        VaListDecl,
8748                                        SourceLocation(),
8749                                        SourceLocation(),
8750                                        &Context->Idents.get("__ap"),
8751                                        Context->getPointerType(Context->VoidTy),
8752                                        /*TInfo=*/nullptr,
8753                                        /*BitWidth=*/nullptr,
8754                                        /*Mutable=*/false,
8755                                        ICIS_NoInit);
8756   Field->setAccess(AS_public);
8757   VaListDecl->addDecl(Field);
8758 
8759   // };
8760   VaListDecl->completeDefinition();
8761   Context->VaListTagDecl = VaListDecl;
8762 
8763   // typedef struct __va_list __builtin_va_list;
8764   QualType T = Context->getRecordType(VaListDecl);
8765   return Context->buildImplicitTypedef(T, "__builtin_va_list");
8766 }
8767 
8768 static TypedefDecl *
8769 CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
8770   // struct __va_list_tag {
8771   RecordDecl *VaListTagDecl;
8772   VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
8773   VaListTagDecl->startDefinition();
8774 
8775   const size_t NumFields = 4;
8776   QualType FieldTypes[NumFields];
8777   const char *FieldNames[NumFields];
8778 
8779   //   long __gpr;
8780   FieldTypes[0] = Context->LongTy;
8781   FieldNames[0] = "__gpr";
8782 
8783   //   long __fpr;
8784   FieldTypes[1] = Context->LongTy;
8785   FieldNames[1] = "__fpr";
8786 
8787   //   void *__overflow_arg_area;
8788   FieldTypes[2] = Context->getPointerType(Context->VoidTy);
8789   FieldNames[2] = "__overflow_arg_area";
8790 
8791   //   void *__reg_save_area;
8792   FieldTypes[3] = Context->getPointerType(Context->VoidTy);
8793   FieldNames[3] = "__reg_save_area";
8794 
8795   // Create fields
8796   for (unsigned i = 0; i < NumFields; ++i) {
8797     FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
8798                                          VaListTagDecl,
8799                                          SourceLocation(),
8800                                          SourceLocation(),
8801                                          &Context->Idents.get(FieldNames[i]),
8802                                          FieldTypes[i], /*TInfo=*/nullptr,
8803                                          /*BitWidth=*/nullptr,
8804                                          /*Mutable=*/false,
8805                                          ICIS_NoInit);
8806     Field->setAccess(AS_public);
8807     VaListTagDecl->addDecl(Field);
8808   }
8809   VaListTagDecl->completeDefinition();
8810   Context->VaListTagDecl = VaListTagDecl;
8811   QualType VaListTagType = Context->getRecordType(VaListTagDecl);
8812 
8813   // };
8814 
8815   // typedef __va_list_tag __builtin_va_list[1];
8816   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
8817   QualType VaListTagArrayType = Context->getConstantArrayType(
8818       VaListTagType, Size, nullptr, ArrayType::Normal, 0);
8819 
8820   return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
8821 }
8822 
8823 static TypedefDecl *CreateHexagonBuiltinVaListDecl(const ASTContext *Context) {
8824   // typedef struct __va_list_tag {
8825   RecordDecl *VaListTagDecl;
8826   VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
8827   VaListTagDecl->startDefinition();
8828 
8829   const size_t NumFields = 3;
8830   QualType FieldTypes[NumFields];
8831   const char *FieldNames[NumFields];
8832 
8833   //   void *CurrentSavedRegisterArea;
8834   FieldTypes[0] = Context->getPointerType(Context->VoidTy);
8835   FieldNames[0] = "__current_saved_reg_area_pointer";
8836 
8837   //   void *SavedRegAreaEnd;
8838   FieldTypes[1] = Context->getPointerType(Context->VoidTy);
8839   FieldNames[1] = "__saved_reg_area_end_pointer";
8840 
8841   //   void *OverflowArea;
8842   FieldTypes[2] = Context->getPointerType(Context->VoidTy);
8843   FieldNames[2] = "__overflow_area_pointer";
8844 
8845   // Create fields
8846   for (unsigned i = 0; i < NumFields; ++i) {
8847     FieldDecl *Field = FieldDecl::Create(
8848         const_cast<ASTContext &>(*Context), VaListTagDecl, SourceLocation(),
8849         SourceLocation(), &Context->Idents.get(FieldNames[i]), FieldTypes[i],
8850         /*TInfo=*/nullptr,
8851         /*BitWidth=*/nullptr,
8852         /*Mutable=*/false, ICIS_NoInit);
8853     Field->setAccess(AS_public);
8854     VaListTagDecl->addDecl(Field);
8855   }
8856   VaListTagDecl->completeDefinition();
8857   Context->VaListTagDecl = VaListTagDecl;
8858   QualType VaListTagType = Context->getRecordType(VaListTagDecl);
8859 
8860   // } __va_list_tag;
8861   TypedefDecl *VaListTagTypedefDecl =
8862       Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
8863 
8864   QualType VaListTagTypedefType = Context->getTypedefType(VaListTagTypedefDecl);
8865 
8866   // typedef __va_list_tag __builtin_va_list[1];
8867   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
8868   QualType VaListTagArrayType = Context->getConstantArrayType(
8869       VaListTagTypedefType, Size, nullptr, ArrayType::Normal, 0);
8870 
8871   return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
8872 }
8873 
8874 static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
8875                                      TargetInfo::BuiltinVaListKind Kind) {
8876   switch (Kind) {
8877   case TargetInfo::CharPtrBuiltinVaList:
8878     return CreateCharPtrBuiltinVaListDecl(Context);
8879   case TargetInfo::VoidPtrBuiltinVaList:
8880     return CreateVoidPtrBuiltinVaListDecl(Context);
8881   case TargetInfo::AArch64ABIBuiltinVaList:
8882     return CreateAArch64ABIBuiltinVaListDecl(Context);
8883   case TargetInfo::PowerABIBuiltinVaList:
8884     return CreatePowerABIBuiltinVaListDecl(Context);
8885   case TargetInfo::X86_64ABIBuiltinVaList:
8886     return CreateX86_64ABIBuiltinVaListDecl(Context);
8887   case TargetInfo::PNaClABIBuiltinVaList:
8888     return CreatePNaClABIBuiltinVaListDecl(Context);
8889   case TargetInfo::AAPCSABIBuiltinVaList:
8890     return CreateAAPCSABIBuiltinVaListDecl(Context);
8891   case TargetInfo::SystemZBuiltinVaList:
8892     return CreateSystemZBuiltinVaListDecl(Context);
8893   case TargetInfo::HexagonBuiltinVaList:
8894     return CreateHexagonBuiltinVaListDecl(Context);
8895   }
8896 
8897   llvm_unreachable("Unhandled __builtin_va_list type kind");
8898 }
8899 
8900 TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
8901   if (!BuiltinVaListDecl) {
8902     BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
8903     assert(BuiltinVaListDecl->isImplicit());
8904   }
8905 
8906   return BuiltinVaListDecl;
8907 }
8908 
8909 Decl *ASTContext::getVaListTagDecl() const {
8910   // Force the creation of VaListTagDecl by building the __builtin_va_list
8911   // declaration.
8912   if (!VaListTagDecl)
8913     (void)getBuiltinVaListDecl();
8914 
8915   return VaListTagDecl;
8916 }
8917 
8918 TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
8919   if (!BuiltinMSVaListDecl)
8920     BuiltinMSVaListDecl = CreateMSVaListDecl(this);
8921 
8922   return BuiltinMSVaListDecl;
8923 }
8924 
8925 bool ASTContext::canBuiltinBeRedeclared(const FunctionDecl *FD) const {
8926   return BuiltinInfo.canBeRedeclared(FD->getBuiltinID());
8927 }
8928 
8929 void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
8930   assert(ObjCConstantStringType.isNull() &&
8931          "'NSConstantString' type already set!");
8932 
8933   ObjCConstantStringType = getObjCInterfaceType(Decl);
8934 }
8935 
8936 /// Retrieve the template name that corresponds to a non-empty
8937 /// lookup.
8938 TemplateName
8939 ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
8940                                       UnresolvedSetIterator End) const {
8941   unsigned size = End - Begin;
8942   assert(size > 1 && "set is not overloaded!");
8943 
8944   void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
8945                           size * sizeof(FunctionTemplateDecl*));
8946   auto *OT = new (memory) OverloadedTemplateStorage(size);
8947 
8948   NamedDecl **Storage = OT->getStorage();
8949   for (UnresolvedSetIterator I = Begin; I != End; ++I) {
8950     NamedDecl *D = *I;
8951     assert(isa<FunctionTemplateDecl>(D) ||
8952            isa<UnresolvedUsingValueDecl>(D) ||
8953            (isa<UsingShadowDecl>(D) &&
8954             isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
8955     *Storage++ = D;
8956   }
8957 
8958   return TemplateName(OT);
8959 }
8960 
8961 /// Retrieve a template name representing an unqualified-id that has been
8962 /// assumed to name a template for ADL purposes.
8963 TemplateName ASTContext::getAssumedTemplateName(DeclarationName Name) const {
8964   auto *OT = new (*this) AssumedTemplateStorage(Name);
8965   return TemplateName(OT);
8966 }
8967 
8968 /// Retrieve the template name that represents a qualified
8969 /// template name such as \c std::vector.
8970 TemplateName
8971 ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
8972                                      bool TemplateKeyword,
8973                                      TemplateDecl *Template) const {
8974   assert(NNS && "Missing nested-name-specifier in qualified template name");
8975 
8976   // FIXME: Canonicalization?
8977   llvm::FoldingSetNodeID ID;
8978   QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
8979 
8980   void *InsertPos = nullptr;
8981   QualifiedTemplateName *QTN =
8982     QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
8983   if (!QTN) {
8984     QTN = new (*this, alignof(QualifiedTemplateName))
8985         QualifiedTemplateName(NNS, TemplateKeyword, Template);
8986     QualifiedTemplateNames.InsertNode(QTN, InsertPos);
8987   }
8988 
8989   return TemplateName(QTN);
8990 }
8991 
8992 /// Retrieve the template name that represents a dependent
8993 /// template name such as \c MetaFun::template apply.
8994 TemplateName
8995 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
8996                                      const IdentifierInfo *Name) const {
8997   assert((!NNS || NNS->isDependent()) &&
8998          "Nested name specifier must be dependent");
8999 
9000   llvm::FoldingSetNodeID ID;
9001   DependentTemplateName::Profile(ID, NNS, Name);
9002 
9003   void *InsertPos = nullptr;
9004   DependentTemplateName *QTN =
9005     DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
9006 
9007   if (QTN)
9008     return TemplateName(QTN);
9009 
9010   NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
9011   if (CanonNNS == NNS) {
9012     QTN = new (*this, alignof(DependentTemplateName))
9013         DependentTemplateName(NNS, Name);
9014   } else {
9015     TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
9016     QTN = new (*this, alignof(DependentTemplateName))
9017         DependentTemplateName(NNS, Name, Canon);
9018     DependentTemplateName *CheckQTN =
9019       DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
9020     assert(!CheckQTN && "Dependent type name canonicalization broken");
9021     (void)CheckQTN;
9022   }
9023 
9024   DependentTemplateNames.InsertNode(QTN, InsertPos);
9025   return TemplateName(QTN);
9026 }
9027 
9028 /// Retrieve the template name that represents a dependent
9029 /// template name such as \c MetaFun::template operator+.
9030 TemplateName
9031 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
9032                                      OverloadedOperatorKind Operator) const {
9033   assert((!NNS || NNS->isDependent()) &&
9034          "Nested name specifier must be dependent");
9035 
9036   llvm::FoldingSetNodeID ID;
9037   DependentTemplateName::Profile(ID, NNS, Operator);
9038 
9039   void *InsertPos = nullptr;
9040   DependentTemplateName *QTN
9041     = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
9042 
9043   if (QTN)
9044     return TemplateName(QTN);
9045 
9046   NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
9047   if (CanonNNS == NNS) {
9048     QTN = new (*this, alignof(DependentTemplateName))
9049         DependentTemplateName(NNS, Operator);
9050   } else {
9051     TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
9052     QTN = new (*this, alignof(DependentTemplateName))
9053         DependentTemplateName(NNS, Operator, Canon);
9054 
9055     DependentTemplateName *CheckQTN
9056       = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
9057     assert(!CheckQTN && "Dependent template name canonicalization broken");
9058     (void)CheckQTN;
9059   }
9060 
9061   DependentTemplateNames.InsertNode(QTN, InsertPos);
9062   return TemplateName(QTN);
9063 }
9064 
9065 TemplateName
9066 ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
9067                                          TemplateName replacement) const {
9068   llvm::FoldingSetNodeID ID;
9069   SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
9070 
9071   void *insertPos = nullptr;
9072   SubstTemplateTemplateParmStorage *subst
9073     = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
9074 
9075   if (!subst) {
9076     subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
9077     SubstTemplateTemplateParms.InsertNode(subst, insertPos);
9078   }
9079 
9080   return TemplateName(subst);
9081 }
9082 
9083 TemplateName
9084 ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
9085                                        const TemplateArgument &ArgPack) const {
9086   auto &Self = const_cast<ASTContext &>(*this);
9087   llvm::FoldingSetNodeID ID;
9088   SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
9089 
9090   void *InsertPos = nullptr;
9091   SubstTemplateTemplateParmPackStorage *Subst
9092     = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
9093 
9094   if (!Subst) {
9095     Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
9096                                                            ArgPack.pack_size(),
9097                                                          ArgPack.pack_begin());
9098     SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
9099   }
9100 
9101   return TemplateName(Subst);
9102 }
9103 
9104 /// getFromTargetType - Given one of the integer types provided by
9105 /// TargetInfo, produce the corresponding type. The unsigned @p Type
9106 /// is actually a value of type @c TargetInfo::IntType.
9107 CanQualType ASTContext::getFromTargetType(unsigned Type) const {
9108   switch (Type) {
9109   case TargetInfo::NoInt: return {};
9110   case TargetInfo::SignedChar: return SignedCharTy;
9111   case TargetInfo::UnsignedChar: return UnsignedCharTy;
9112   case TargetInfo::SignedShort: return ShortTy;
9113   case TargetInfo::UnsignedShort: return UnsignedShortTy;
9114   case TargetInfo::SignedInt: return IntTy;
9115   case TargetInfo::UnsignedInt: return UnsignedIntTy;
9116   case TargetInfo::SignedLong: return LongTy;
9117   case TargetInfo::UnsignedLong: return UnsignedLongTy;
9118   case TargetInfo::SignedLongLong: return LongLongTy;
9119   case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
9120   }
9121 
9122   llvm_unreachable("Unhandled TargetInfo::IntType value");
9123 }
9124 
9125 //===----------------------------------------------------------------------===//
9126 //                        Type Predicates.
9127 //===----------------------------------------------------------------------===//
9128 
9129 /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
9130 /// garbage collection attribute.
9131 ///
9132 Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
9133   if (getLangOpts().getGC() == LangOptions::NonGC)
9134     return Qualifiers::GCNone;
9135 
9136   assert(getLangOpts().ObjC);
9137   Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
9138 
9139   // Default behaviour under objective-C's gc is for ObjC pointers
9140   // (or pointers to them) be treated as though they were declared
9141   // as __strong.
9142   if (GCAttrs == Qualifiers::GCNone) {
9143     if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
9144       return Qualifiers::Strong;
9145     else if (Ty->isPointerType())
9146       return getObjCGCAttrKind(Ty->castAs<PointerType>()->getPointeeType());
9147   } else {
9148     // It's not valid to set GC attributes on anything that isn't a
9149     // pointer.
9150 #ifndef NDEBUG
9151     QualType CT = Ty->getCanonicalTypeInternal();
9152     while (const auto *AT = dyn_cast<ArrayType>(CT))
9153       CT = AT->getElementType();
9154     assert(CT->isAnyPointerType() || CT->isBlockPointerType());
9155 #endif
9156   }
9157   return GCAttrs;
9158 }
9159 
9160 //===----------------------------------------------------------------------===//
9161 //                        Type Compatibility Testing
9162 //===----------------------------------------------------------------------===//
9163 
9164 /// areCompatVectorTypes - Return true if the two specified vector types are
9165 /// compatible.
9166 static bool areCompatVectorTypes(const VectorType *LHS,
9167                                  const VectorType *RHS) {
9168   assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
9169   return LHS->getElementType() == RHS->getElementType() &&
9170          LHS->getNumElements() == RHS->getNumElements();
9171 }
9172 
9173 /// areCompatMatrixTypes - Return true if the two specified matrix types are
9174 /// compatible.
9175 static bool areCompatMatrixTypes(const ConstantMatrixType *LHS,
9176                                  const ConstantMatrixType *RHS) {
9177   assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
9178   return LHS->getElementType() == RHS->getElementType() &&
9179          LHS->getNumRows() == RHS->getNumRows() &&
9180          LHS->getNumColumns() == RHS->getNumColumns();
9181 }
9182 
9183 bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
9184                                           QualType SecondVec) {
9185   assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
9186   assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
9187 
9188   if (hasSameUnqualifiedType(FirstVec, SecondVec))
9189     return true;
9190 
9191   // Treat Neon vector types and most AltiVec vector types as if they are the
9192   // equivalent GCC vector types.
9193   const auto *First = FirstVec->castAs<VectorType>();
9194   const auto *Second = SecondVec->castAs<VectorType>();
9195   if (First->getNumElements() == Second->getNumElements() &&
9196       hasSameType(First->getElementType(), Second->getElementType()) &&
9197       First->getVectorKind() != VectorType::AltiVecPixel &&
9198       First->getVectorKind() != VectorType::AltiVecBool &&
9199       Second->getVectorKind() != VectorType::AltiVecPixel &&
9200       Second->getVectorKind() != VectorType::AltiVecBool &&
9201       First->getVectorKind() != VectorType::SveFixedLengthDataVector &&
9202       First->getVectorKind() != VectorType::SveFixedLengthPredicateVector &&
9203       Second->getVectorKind() != VectorType::SveFixedLengthDataVector &&
9204       Second->getVectorKind() != VectorType::SveFixedLengthPredicateVector)
9205     return true;
9206 
9207   return false;
9208 }
9209 
9210 /// getSVETypeSize - Return SVE vector or predicate register size.
9211 static uint64_t getSVETypeSize(ASTContext &Context, const BuiltinType *Ty) {
9212   assert(Ty->isVLSTBuiltinType() && "Invalid SVE Type");
9213   return Ty->getKind() == BuiltinType::SveBool
9214              ? (Context.getLangOpts().VScaleMin * 128) / Context.getCharWidth()
9215              : Context.getLangOpts().VScaleMin * 128;
9216 }
9217 
9218 bool ASTContext::areCompatibleSveTypes(QualType FirstType,
9219                                        QualType SecondType) {
9220   assert(((FirstType->isSizelessBuiltinType() && SecondType->isVectorType()) ||
9221           (FirstType->isVectorType() && SecondType->isSizelessBuiltinType())) &&
9222          "Expected SVE builtin type and vector type!");
9223 
9224   auto IsValidCast = [this](QualType FirstType, QualType SecondType) {
9225     if (const auto *BT = FirstType->getAs<BuiltinType>()) {
9226       if (const auto *VT = SecondType->getAs<VectorType>()) {
9227         // Predicates have the same representation as uint8 so we also have to
9228         // check the kind to make these types incompatible.
9229         if (VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector)
9230           return BT->getKind() == BuiltinType::SveBool;
9231         else if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector)
9232           return VT->getElementType().getCanonicalType() ==
9233                  FirstType->getSveEltType(*this);
9234         else if (VT->getVectorKind() == VectorType::GenericVector)
9235           return getTypeSize(SecondType) == getSVETypeSize(*this, BT) &&
9236                  hasSameType(VT->getElementType(),
9237                              getBuiltinVectorTypeInfo(BT).ElementType);
9238       }
9239     }
9240     return false;
9241   };
9242 
9243   return IsValidCast(FirstType, SecondType) ||
9244          IsValidCast(SecondType, FirstType);
9245 }
9246 
9247 bool ASTContext::areLaxCompatibleSveTypes(QualType FirstType,
9248                                           QualType SecondType) {
9249   assert(((FirstType->isSizelessBuiltinType() && SecondType->isVectorType()) ||
9250           (FirstType->isVectorType() && SecondType->isSizelessBuiltinType())) &&
9251          "Expected SVE builtin type and vector type!");
9252 
9253   auto IsLaxCompatible = [this](QualType FirstType, QualType SecondType) {
9254     const auto *BT = FirstType->getAs<BuiltinType>();
9255     if (!BT)
9256       return false;
9257 
9258     const auto *VecTy = SecondType->getAs<VectorType>();
9259     if (VecTy &&
9260         (VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector ||
9261          VecTy->getVectorKind() == VectorType::GenericVector)) {
9262       const LangOptions::LaxVectorConversionKind LVCKind =
9263           getLangOpts().getLaxVectorConversions();
9264 
9265       // Can not convert between sve predicates and sve vectors because of
9266       // different size.
9267       if (BT->getKind() == BuiltinType::SveBool &&
9268           VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector)
9269         return false;
9270 
9271       // If __ARM_FEATURE_SVE_BITS != N do not allow GNU vector lax conversion.
9272       // "Whenever __ARM_FEATURE_SVE_BITS==N, GNUT implicitly
9273       // converts to VLAT and VLAT implicitly converts to GNUT."
9274       // ACLE Spec Version 00bet6, 3.7.3.2. Behavior common to vectors and
9275       // predicates.
9276       if (VecTy->getVectorKind() == VectorType::GenericVector &&
9277           getTypeSize(SecondType) != getSVETypeSize(*this, BT))
9278         return false;
9279 
9280       // If -flax-vector-conversions=all is specified, the types are
9281       // certainly compatible.
9282       if (LVCKind == LangOptions::LaxVectorConversionKind::All)
9283         return true;
9284 
9285       // If -flax-vector-conversions=integer is specified, the types are
9286       // compatible if the elements are integer types.
9287       if (LVCKind == LangOptions::LaxVectorConversionKind::Integer)
9288         return VecTy->getElementType().getCanonicalType()->isIntegerType() &&
9289                FirstType->getSveEltType(*this)->isIntegerType();
9290     }
9291 
9292     return false;
9293   };
9294 
9295   return IsLaxCompatible(FirstType, SecondType) ||
9296          IsLaxCompatible(SecondType, FirstType);
9297 }
9298 
9299 bool ASTContext::hasDirectOwnershipQualifier(QualType Ty) const {
9300   while (true) {
9301     // __strong id
9302     if (const AttributedType *Attr = dyn_cast<AttributedType>(Ty)) {
9303       if (Attr->getAttrKind() == attr::ObjCOwnership)
9304         return true;
9305 
9306       Ty = Attr->getModifiedType();
9307 
9308     // X *__strong (...)
9309     } else if (const ParenType *Paren = dyn_cast<ParenType>(Ty)) {
9310       Ty = Paren->getInnerType();
9311 
9312     // We do not want to look through typedefs, typeof(expr),
9313     // typeof(type), or any other way that the type is somehow
9314     // abstracted.
9315     } else {
9316       return false;
9317     }
9318   }
9319 }
9320 
9321 //===----------------------------------------------------------------------===//
9322 // ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
9323 //===----------------------------------------------------------------------===//
9324 
9325 /// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
9326 /// inheritance hierarchy of 'rProto'.
9327 bool
9328 ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
9329                                            ObjCProtocolDecl *rProto) const {
9330   if (declaresSameEntity(lProto, rProto))
9331     return true;
9332   for (auto *PI : rProto->protocols())
9333     if (ProtocolCompatibleWithProtocol(lProto, PI))
9334       return true;
9335   return false;
9336 }
9337 
9338 /// ObjCQualifiedClassTypesAreCompatible - compare  Class<pr,...> and
9339 /// Class<pr1, ...>.
9340 bool ASTContext::ObjCQualifiedClassTypesAreCompatible(
9341     const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs) {
9342   for (auto *lhsProto : lhs->quals()) {
9343     bool match = false;
9344     for (auto *rhsProto : rhs->quals()) {
9345       if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
9346         match = true;
9347         break;
9348       }
9349     }
9350     if (!match)
9351       return false;
9352   }
9353   return true;
9354 }
9355 
9356 /// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
9357 /// ObjCQualifiedIDType.
9358 bool ASTContext::ObjCQualifiedIdTypesAreCompatible(
9359     const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs,
9360     bool compare) {
9361   // Allow id<P..> and an 'id' in all cases.
9362   if (lhs->isObjCIdType() || rhs->isObjCIdType())
9363     return true;
9364 
9365   // Don't allow id<P..> to convert to Class or Class<P..> in either direction.
9366   if (lhs->isObjCClassType() || lhs->isObjCQualifiedClassType() ||
9367       rhs->isObjCClassType() || rhs->isObjCQualifiedClassType())
9368     return false;
9369 
9370   if (lhs->isObjCQualifiedIdType()) {
9371     if (rhs->qual_empty()) {
9372       // If the RHS is a unqualified interface pointer "NSString*",
9373       // make sure we check the class hierarchy.
9374       if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
9375         for (auto *I : lhs->quals()) {
9376           // when comparing an id<P> on lhs with a static type on rhs,
9377           // see if static class implements all of id's protocols, directly or
9378           // through its super class and categories.
9379           if (!rhsID->ClassImplementsProtocol(I, true))
9380             return false;
9381         }
9382       }
9383       // If there are no qualifiers and no interface, we have an 'id'.
9384       return true;
9385     }
9386     // Both the right and left sides have qualifiers.
9387     for (auto *lhsProto : lhs->quals()) {
9388       bool match = false;
9389 
9390       // when comparing an id<P> on lhs with a static type on rhs,
9391       // see if static class implements all of id's protocols, directly or
9392       // through its super class and categories.
9393       for (auto *rhsProto : rhs->quals()) {
9394         if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
9395             (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
9396           match = true;
9397           break;
9398         }
9399       }
9400       // If the RHS is a qualified interface pointer "NSString<P>*",
9401       // make sure we check the class hierarchy.
9402       if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
9403         for (auto *I : lhs->quals()) {
9404           // when comparing an id<P> on lhs with a static type on rhs,
9405           // see if static class implements all of id's protocols, directly or
9406           // through its super class and categories.
9407           if (rhsID->ClassImplementsProtocol(I, true)) {
9408             match = true;
9409             break;
9410           }
9411         }
9412       }
9413       if (!match)
9414         return false;
9415     }
9416 
9417     return true;
9418   }
9419 
9420   assert(rhs->isObjCQualifiedIdType() && "One of the LHS/RHS should be id<x>");
9421 
9422   if (lhs->getInterfaceType()) {
9423     // If both the right and left sides have qualifiers.
9424     for (auto *lhsProto : lhs->quals()) {
9425       bool match = false;
9426 
9427       // when comparing an id<P> on rhs with a static type on lhs,
9428       // see if static class implements all of id's protocols, directly or
9429       // through its super class and categories.
9430       // First, lhs protocols in the qualifier list must be found, direct
9431       // or indirect in rhs's qualifier list or it is a mismatch.
9432       for (auto *rhsProto : rhs->quals()) {
9433         if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
9434             (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
9435           match = true;
9436           break;
9437         }
9438       }
9439       if (!match)
9440         return false;
9441     }
9442 
9443     // Static class's protocols, or its super class or category protocols
9444     // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
9445     if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) {
9446       llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
9447       CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
9448       // This is rather dubious but matches gcc's behavior. If lhs has
9449       // no type qualifier and its class has no static protocol(s)
9450       // assume that it is mismatch.
9451       if (LHSInheritedProtocols.empty() && lhs->qual_empty())
9452         return false;
9453       for (auto *lhsProto : LHSInheritedProtocols) {
9454         bool match = false;
9455         for (auto *rhsProto : rhs->quals()) {
9456           if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
9457               (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
9458             match = true;
9459             break;
9460           }
9461         }
9462         if (!match)
9463           return false;
9464       }
9465     }
9466     return true;
9467   }
9468   return false;
9469 }
9470 
9471 /// canAssignObjCInterfaces - Return true if the two interface types are
9472 /// compatible for assignment from RHS to LHS.  This handles validation of any
9473 /// protocol qualifiers on the LHS or RHS.
9474 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
9475                                          const ObjCObjectPointerType *RHSOPT) {
9476   const ObjCObjectType* LHS = LHSOPT->getObjectType();
9477   const ObjCObjectType* RHS = RHSOPT->getObjectType();
9478 
9479   // If either type represents the built-in 'id' type, return true.
9480   if (LHS->isObjCUnqualifiedId() || RHS->isObjCUnqualifiedId())
9481     return true;
9482 
9483   // Function object that propagates a successful result or handles
9484   // __kindof types.
9485   auto finish = [&](bool succeeded) -> bool {
9486     if (succeeded)
9487       return true;
9488 
9489     if (!RHS->isKindOfType())
9490       return false;
9491 
9492     // Strip off __kindof and protocol qualifiers, then check whether
9493     // we can assign the other way.
9494     return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
9495                                    LHSOPT->stripObjCKindOfTypeAndQuals(*this));
9496   };
9497 
9498   // Casts from or to id<P> are allowed when the other side has compatible
9499   // protocols.
9500   if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
9501     return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false));
9502   }
9503 
9504   // Verify protocol compatibility for casts from Class<P1> to Class<P2>.
9505   if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
9506     return finish(ObjCQualifiedClassTypesAreCompatible(LHSOPT, RHSOPT));
9507   }
9508 
9509   // Casts from Class to Class<Foo>, or vice-versa, are allowed.
9510   if (LHS->isObjCClass() && RHS->isObjCClass()) {
9511     return true;
9512   }
9513 
9514   // If we have 2 user-defined types, fall into that path.
9515   if (LHS->getInterface() && RHS->getInterface()) {
9516     return finish(canAssignObjCInterfaces(LHS, RHS));
9517   }
9518 
9519   return false;
9520 }
9521 
9522 /// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
9523 /// for providing type-safety for objective-c pointers used to pass/return
9524 /// arguments in block literals. When passed as arguments, passing 'A*' where
9525 /// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
9526 /// not OK. For the return type, the opposite is not OK.
9527 bool ASTContext::canAssignObjCInterfacesInBlockPointer(
9528                                          const ObjCObjectPointerType *LHSOPT,
9529                                          const ObjCObjectPointerType *RHSOPT,
9530                                          bool BlockReturnType) {
9531 
9532   // Function object that propagates a successful result or handles
9533   // __kindof types.
9534   auto finish = [&](bool succeeded) -> bool {
9535     if (succeeded)
9536       return true;
9537 
9538     const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
9539     if (!Expected->isKindOfType())
9540       return false;
9541 
9542     // Strip off __kindof and protocol qualifiers, then check whether
9543     // we can assign the other way.
9544     return canAssignObjCInterfacesInBlockPointer(
9545              RHSOPT->stripObjCKindOfTypeAndQuals(*this),
9546              LHSOPT->stripObjCKindOfTypeAndQuals(*this),
9547              BlockReturnType);
9548   };
9549 
9550   if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
9551     return true;
9552 
9553   if (LHSOPT->isObjCBuiltinType()) {
9554     return finish(RHSOPT->isObjCBuiltinType() ||
9555                   RHSOPT->isObjCQualifiedIdType());
9556   }
9557 
9558   if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) {
9559     if (getLangOpts().CompatibilityQualifiedIdBlockParamTypeChecking)
9560       // Use for block parameters previous type checking for compatibility.
9561       return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false) ||
9562                     // Or corrected type checking as in non-compat mode.
9563                     (!BlockReturnType &&
9564                      ObjCQualifiedIdTypesAreCompatible(RHSOPT, LHSOPT, false)));
9565     else
9566       return finish(ObjCQualifiedIdTypesAreCompatible(
9567           (BlockReturnType ? LHSOPT : RHSOPT),
9568           (BlockReturnType ? RHSOPT : LHSOPT), false));
9569   }
9570 
9571   const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
9572   const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
9573   if (LHS && RHS)  { // We have 2 user-defined types.
9574     if (LHS != RHS) {
9575       if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
9576         return finish(BlockReturnType);
9577       if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
9578         return finish(!BlockReturnType);
9579     }
9580     else
9581       return true;
9582   }
9583   return false;
9584 }
9585 
9586 /// Comparison routine for Objective-C protocols to be used with
9587 /// llvm::array_pod_sort.
9588 static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
9589                                       ObjCProtocolDecl * const *rhs) {
9590   return (*lhs)->getName().compare((*rhs)->getName());
9591 }
9592 
9593 /// getIntersectionOfProtocols - This routine finds the intersection of set
9594 /// of protocols inherited from two distinct objective-c pointer objects with
9595 /// the given common base.
9596 /// It is used to build composite qualifier list of the composite type of
9597 /// the conditional expression involving two objective-c pointer objects.
9598 static
9599 void getIntersectionOfProtocols(ASTContext &Context,
9600                                 const ObjCInterfaceDecl *CommonBase,
9601                                 const ObjCObjectPointerType *LHSOPT,
9602                                 const ObjCObjectPointerType *RHSOPT,
9603       SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
9604 
9605   const ObjCObjectType* LHS = LHSOPT->getObjectType();
9606   const ObjCObjectType* RHS = RHSOPT->getObjectType();
9607   assert(LHS->getInterface() && "LHS must have an interface base");
9608   assert(RHS->getInterface() && "RHS must have an interface base");
9609 
9610   // Add all of the protocols for the LHS.
9611   llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
9612 
9613   // Start with the protocol qualifiers.
9614   for (auto proto : LHS->quals()) {
9615     Context.CollectInheritedProtocols(proto, LHSProtocolSet);
9616   }
9617 
9618   // Also add the protocols associated with the LHS interface.
9619   Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
9620 
9621   // Add all of the protocols for the RHS.
9622   llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
9623 
9624   // Start with the protocol qualifiers.
9625   for (auto proto : RHS->quals()) {
9626     Context.CollectInheritedProtocols(proto, RHSProtocolSet);
9627   }
9628 
9629   // Also add the protocols associated with the RHS interface.
9630   Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
9631 
9632   // Compute the intersection of the collected protocol sets.
9633   for (auto proto : LHSProtocolSet) {
9634     if (RHSProtocolSet.count(proto))
9635       IntersectionSet.push_back(proto);
9636   }
9637 
9638   // Compute the set of protocols that is implied by either the common type or
9639   // the protocols within the intersection.
9640   llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
9641   Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
9642 
9643   // Remove any implied protocols from the list of inherited protocols.
9644   if (!ImpliedProtocols.empty()) {
9645     llvm::erase_if(IntersectionSet, [&](ObjCProtocolDecl *proto) -> bool {
9646       return ImpliedProtocols.contains(proto);
9647     });
9648   }
9649 
9650   // Sort the remaining protocols by name.
9651   llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
9652                        compareObjCProtocolsByName);
9653 }
9654 
9655 /// Determine whether the first type is a subtype of the second.
9656 static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
9657                                      QualType rhs) {
9658   // Common case: two object pointers.
9659   const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
9660   const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
9661   if (lhsOPT && rhsOPT)
9662     return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
9663 
9664   // Two block pointers.
9665   const auto *lhsBlock = lhs->getAs<BlockPointerType>();
9666   const auto *rhsBlock = rhs->getAs<BlockPointerType>();
9667   if (lhsBlock && rhsBlock)
9668     return ctx.typesAreBlockPointerCompatible(lhs, rhs);
9669 
9670   // If either is an unqualified 'id' and the other is a block, it's
9671   // acceptable.
9672   if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
9673       (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
9674     return true;
9675 
9676   return false;
9677 }
9678 
9679 // Check that the given Objective-C type argument lists are equivalent.
9680 static bool sameObjCTypeArgs(ASTContext &ctx,
9681                              const ObjCInterfaceDecl *iface,
9682                              ArrayRef<QualType> lhsArgs,
9683                              ArrayRef<QualType> rhsArgs,
9684                              bool stripKindOf) {
9685   if (lhsArgs.size() != rhsArgs.size())
9686     return false;
9687 
9688   ObjCTypeParamList *typeParams = iface->getTypeParamList();
9689   for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
9690     if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
9691       continue;
9692 
9693     switch (typeParams->begin()[i]->getVariance()) {
9694     case ObjCTypeParamVariance::Invariant:
9695       if (!stripKindOf ||
9696           !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
9697                            rhsArgs[i].stripObjCKindOfType(ctx))) {
9698         return false;
9699       }
9700       break;
9701 
9702     case ObjCTypeParamVariance::Covariant:
9703       if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
9704         return false;
9705       break;
9706 
9707     case ObjCTypeParamVariance::Contravariant:
9708       if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
9709         return false;
9710       break;
9711     }
9712   }
9713 
9714   return true;
9715 }
9716 
9717 QualType ASTContext::areCommonBaseCompatible(
9718            const ObjCObjectPointerType *Lptr,
9719            const ObjCObjectPointerType *Rptr) {
9720   const ObjCObjectType *LHS = Lptr->getObjectType();
9721   const ObjCObjectType *RHS = Rptr->getObjectType();
9722   const ObjCInterfaceDecl* LDecl = LHS->getInterface();
9723   const ObjCInterfaceDecl* RDecl = RHS->getInterface();
9724 
9725   if (!LDecl || !RDecl)
9726     return {};
9727 
9728   // When either LHS or RHS is a kindof type, we should return a kindof type.
9729   // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
9730   // kindof(A).
9731   bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
9732 
9733   // Follow the left-hand side up the class hierarchy until we either hit a
9734   // root or find the RHS. Record the ancestors in case we don't find it.
9735   llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
9736     LHSAncestors;
9737   while (true) {
9738     // Record this ancestor. We'll need this if the common type isn't in the
9739     // path from the LHS to the root.
9740     LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
9741 
9742     if (declaresSameEntity(LHS->getInterface(), RDecl)) {
9743       // Get the type arguments.
9744       ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
9745       bool anyChanges = false;
9746       if (LHS->isSpecialized() && RHS->isSpecialized()) {
9747         // Both have type arguments, compare them.
9748         if (!sameObjCTypeArgs(*this, LHS->getInterface(),
9749                               LHS->getTypeArgs(), RHS->getTypeArgs(),
9750                               /*stripKindOf=*/true))
9751           return {};
9752       } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
9753         // If only one has type arguments, the result will not have type
9754         // arguments.
9755         LHSTypeArgs = {};
9756         anyChanges = true;
9757       }
9758 
9759       // Compute the intersection of protocols.
9760       SmallVector<ObjCProtocolDecl *, 8> Protocols;
9761       getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
9762                                  Protocols);
9763       if (!Protocols.empty())
9764         anyChanges = true;
9765 
9766       // If anything in the LHS will have changed, build a new result type.
9767       // If we need to return a kindof type but LHS is not a kindof type, we
9768       // build a new result type.
9769       if (anyChanges || LHS->isKindOfType() != anyKindOf) {
9770         QualType Result = getObjCInterfaceType(LHS->getInterface());
9771         Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
9772                                    anyKindOf || LHS->isKindOfType());
9773         return getObjCObjectPointerType(Result);
9774       }
9775 
9776       return getObjCObjectPointerType(QualType(LHS, 0));
9777     }
9778 
9779     // Find the superclass.
9780     QualType LHSSuperType = LHS->getSuperClassType();
9781     if (LHSSuperType.isNull())
9782       break;
9783 
9784     LHS = LHSSuperType->castAs<ObjCObjectType>();
9785   }
9786 
9787   // We didn't find anything by following the LHS to its root; now check
9788   // the RHS against the cached set of ancestors.
9789   while (true) {
9790     auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
9791     if (KnownLHS != LHSAncestors.end()) {
9792       LHS = KnownLHS->second;
9793 
9794       // Get the type arguments.
9795       ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
9796       bool anyChanges = false;
9797       if (LHS->isSpecialized() && RHS->isSpecialized()) {
9798         // Both have type arguments, compare them.
9799         if (!sameObjCTypeArgs(*this, LHS->getInterface(),
9800                               LHS->getTypeArgs(), RHS->getTypeArgs(),
9801                               /*stripKindOf=*/true))
9802           return {};
9803       } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
9804         // If only one has type arguments, the result will not have type
9805         // arguments.
9806         RHSTypeArgs = {};
9807         anyChanges = true;
9808       }
9809 
9810       // Compute the intersection of protocols.
9811       SmallVector<ObjCProtocolDecl *, 8> Protocols;
9812       getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
9813                                  Protocols);
9814       if (!Protocols.empty())
9815         anyChanges = true;
9816 
9817       // If we need to return a kindof type but RHS is not a kindof type, we
9818       // build a new result type.
9819       if (anyChanges || RHS->isKindOfType() != anyKindOf) {
9820         QualType Result = getObjCInterfaceType(RHS->getInterface());
9821         Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
9822                                    anyKindOf || RHS->isKindOfType());
9823         return getObjCObjectPointerType(Result);
9824       }
9825 
9826       return getObjCObjectPointerType(QualType(RHS, 0));
9827     }
9828 
9829     // Find the superclass of the RHS.
9830     QualType RHSSuperType = RHS->getSuperClassType();
9831     if (RHSSuperType.isNull())
9832       break;
9833 
9834     RHS = RHSSuperType->castAs<ObjCObjectType>();
9835   }
9836 
9837   return {};
9838 }
9839 
9840 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
9841                                          const ObjCObjectType *RHS) {
9842   assert(LHS->getInterface() && "LHS is not an interface type");
9843   assert(RHS->getInterface() && "RHS is not an interface type");
9844 
9845   // Verify that the base decls are compatible: the RHS must be a subclass of
9846   // the LHS.
9847   ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
9848   bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
9849   if (!IsSuperClass)
9850     return false;
9851 
9852   // If the LHS has protocol qualifiers, determine whether all of them are
9853   // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
9854   // LHS).
9855   if (LHS->getNumProtocols() > 0) {
9856     // OK if conversion of LHS to SuperClass results in narrowing of types
9857     // ; i.e., SuperClass may implement at least one of the protocols
9858     // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
9859     // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
9860     llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
9861     CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
9862     // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
9863     // qualifiers.
9864     for (auto *RHSPI : RHS->quals())
9865       CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
9866     // If there is no protocols associated with RHS, it is not a match.
9867     if (SuperClassInheritedProtocols.empty())
9868       return false;
9869 
9870     for (const auto *LHSProto : LHS->quals()) {
9871       bool SuperImplementsProtocol = false;
9872       for (auto *SuperClassProto : SuperClassInheritedProtocols)
9873         if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
9874           SuperImplementsProtocol = true;
9875           break;
9876         }
9877       if (!SuperImplementsProtocol)
9878         return false;
9879     }
9880   }
9881 
9882   // If the LHS is specialized, we may need to check type arguments.
9883   if (LHS->isSpecialized()) {
9884     // Follow the superclass chain until we've matched the LHS class in the
9885     // hierarchy. This substitutes type arguments through.
9886     const ObjCObjectType *RHSSuper = RHS;
9887     while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
9888       RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
9889 
9890     // If the RHS is specializd, compare type arguments.
9891     if (RHSSuper->isSpecialized() &&
9892         !sameObjCTypeArgs(*this, LHS->getInterface(),
9893                           LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
9894                           /*stripKindOf=*/true)) {
9895       return false;
9896     }
9897   }
9898 
9899   return true;
9900 }
9901 
9902 bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
9903   // get the "pointed to" types
9904   const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
9905   const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
9906 
9907   if (!LHSOPT || !RHSOPT)
9908     return false;
9909 
9910   return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
9911          canAssignObjCInterfaces(RHSOPT, LHSOPT);
9912 }
9913 
9914 bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
9915   return canAssignObjCInterfaces(
9916       getObjCObjectPointerType(To)->castAs<ObjCObjectPointerType>(),
9917       getObjCObjectPointerType(From)->castAs<ObjCObjectPointerType>());
9918 }
9919 
9920 /// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
9921 /// both shall have the identically qualified version of a compatible type.
9922 /// C99 6.2.7p1: Two types have compatible types if their types are the
9923 /// same. See 6.7.[2,3,5] for additional rules.
9924 bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
9925                                     bool CompareUnqualified) {
9926   if (getLangOpts().CPlusPlus)
9927     return hasSameType(LHS, RHS);
9928 
9929   return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
9930 }
9931 
9932 bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
9933   return typesAreCompatible(LHS, RHS);
9934 }
9935 
9936 bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
9937   return !mergeTypes(LHS, RHS, true).isNull();
9938 }
9939 
9940 /// mergeTransparentUnionType - if T is a transparent union type and a member
9941 /// of T is compatible with SubType, return the merged type, else return
9942 /// QualType()
9943 QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
9944                                                bool OfBlockPointer,
9945                                                bool Unqualified) {
9946   if (const RecordType *UT = T->getAsUnionType()) {
9947     RecordDecl *UD = UT->getDecl();
9948     if (UD->hasAttr<TransparentUnionAttr>()) {
9949       for (const auto *I : UD->fields()) {
9950         QualType ET = I->getType().getUnqualifiedType();
9951         QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
9952         if (!MT.isNull())
9953           return MT;
9954       }
9955     }
9956   }
9957 
9958   return {};
9959 }
9960 
9961 /// mergeFunctionParameterTypes - merge two types which appear as function
9962 /// parameter types
9963 QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
9964                                                  bool OfBlockPointer,
9965                                                  bool Unqualified) {
9966   // GNU extension: two types are compatible if they appear as a function
9967   // argument, one of the types is a transparent union type and the other
9968   // type is compatible with a union member
9969   QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
9970                                               Unqualified);
9971   if (!lmerge.isNull())
9972     return lmerge;
9973 
9974   QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
9975                                               Unqualified);
9976   if (!rmerge.isNull())
9977     return rmerge;
9978 
9979   return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
9980 }
9981 
9982 QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
9983                                         bool OfBlockPointer, bool Unqualified,
9984                                         bool AllowCXX) {
9985   const auto *lbase = lhs->castAs<FunctionType>();
9986   const auto *rbase = rhs->castAs<FunctionType>();
9987   const auto *lproto = dyn_cast<FunctionProtoType>(lbase);
9988   const auto *rproto = dyn_cast<FunctionProtoType>(rbase);
9989   bool allLTypes = true;
9990   bool allRTypes = true;
9991 
9992   // Check return type
9993   QualType retType;
9994   if (OfBlockPointer) {
9995     QualType RHS = rbase->getReturnType();
9996     QualType LHS = lbase->getReturnType();
9997     bool UnqualifiedResult = Unqualified;
9998     if (!UnqualifiedResult)
9999       UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
10000     retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
10001   }
10002   else
10003     retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
10004                          Unqualified);
10005   if (retType.isNull())
10006     return {};
10007 
10008   if (Unqualified)
10009     retType = retType.getUnqualifiedType();
10010 
10011   CanQualType LRetType = getCanonicalType(lbase->getReturnType());
10012   CanQualType RRetType = getCanonicalType(rbase->getReturnType());
10013   if (Unqualified) {
10014     LRetType = LRetType.getUnqualifiedType();
10015     RRetType = RRetType.getUnqualifiedType();
10016   }
10017 
10018   if (getCanonicalType(retType) != LRetType)
10019     allLTypes = false;
10020   if (getCanonicalType(retType) != RRetType)
10021     allRTypes = false;
10022 
10023   // FIXME: double check this
10024   // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
10025   //                           rbase->getRegParmAttr() != 0 &&
10026   //                           lbase->getRegParmAttr() != rbase->getRegParmAttr()?
10027   FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
10028   FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
10029 
10030   // Compatible functions must have compatible calling conventions
10031   if (lbaseInfo.getCC() != rbaseInfo.getCC())
10032     return {};
10033 
10034   // Regparm is part of the calling convention.
10035   if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
10036     return {};
10037   if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
10038     return {};
10039 
10040   if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
10041     return {};
10042   if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
10043     return {};
10044   if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
10045     return {};
10046 
10047   // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
10048   bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
10049 
10050   if (lbaseInfo.getNoReturn() != NoReturn)
10051     allLTypes = false;
10052   if (rbaseInfo.getNoReturn() != NoReturn)
10053     allRTypes = false;
10054 
10055   FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
10056 
10057   if (lproto && rproto) { // two C99 style function prototypes
10058     assert((AllowCXX ||
10059             (!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec())) &&
10060            "C++ shouldn't be here");
10061     // Compatible functions must have the same number of parameters
10062     if (lproto->getNumParams() != rproto->getNumParams())
10063       return {};
10064 
10065     // Variadic and non-variadic functions aren't compatible
10066     if (lproto->isVariadic() != rproto->isVariadic())
10067       return {};
10068 
10069     if (lproto->getMethodQuals() != rproto->getMethodQuals())
10070       return {};
10071 
10072     SmallVector<FunctionProtoType::ExtParameterInfo, 4> newParamInfos;
10073     bool canUseLeft, canUseRight;
10074     if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight,
10075                                newParamInfos))
10076       return {};
10077 
10078     if (!canUseLeft)
10079       allLTypes = false;
10080     if (!canUseRight)
10081       allRTypes = false;
10082 
10083     // Check parameter type compatibility
10084     SmallVector<QualType, 10> types;
10085     for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
10086       QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
10087       QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
10088       QualType paramType = mergeFunctionParameterTypes(
10089           lParamType, rParamType, OfBlockPointer, Unqualified);
10090       if (paramType.isNull())
10091         return {};
10092 
10093       if (Unqualified)
10094         paramType = paramType.getUnqualifiedType();
10095 
10096       types.push_back(paramType);
10097       if (Unqualified) {
10098         lParamType = lParamType.getUnqualifiedType();
10099         rParamType = rParamType.getUnqualifiedType();
10100       }
10101 
10102       if (getCanonicalType(paramType) != getCanonicalType(lParamType))
10103         allLTypes = false;
10104       if (getCanonicalType(paramType) != getCanonicalType(rParamType))
10105         allRTypes = false;
10106     }
10107 
10108     if (allLTypes) return lhs;
10109     if (allRTypes) return rhs;
10110 
10111     FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
10112     EPI.ExtInfo = einfo;
10113     EPI.ExtParameterInfos =
10114         newParamInfos.empty() ? nullptr : newParamInfos.data();
10115     return getFunctionType(retType, types, EPI);
10116   }
10117 
10118   if (lproto) allRTypes = false;
10119   if (rproto) allLTypes = false;
10120 
10121   const FunctionProtoType *proto = lproto ? lproto : rproto;
10122   if (proto) {
10123     assert((AllowCXX || !proto->hasExceptionSpec()) && "C++ shouldn't be here");
10124     if (proto->isVariadic())
10125       return {};
10126     // Check that the types are compatible with the types that
10127     // would result from default argument promotions (C99 6.7.5.3p15).
10128     // The only types actually affected are promotable integer
10129     // types and floats, which would be passed as a different
10130     // type depending on whether the prototype is visible.
10131     for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
10132       QualType paramTy = proto->getParamType(i);
10133 
10134       // Look at the converted type of enum types, since that is the type used
10135       // to pass enum values.
10136       if (const auto *Enum = paramTy->getAs<EnumType>()) {
10137         paramTy = Enum->getDecl()->getIntegerType();
10138         if (paramTy.isNull())
10139           return {};
10140       }
10141 
10142       if (paramTy->isPromotableIntegerType() ||
10143           getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
10144         return {};
10145     }
10146 
10147     if (allLTypes) return lhs;
10148     if (allRTypes) return rhs;
10149 
10150     FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
10151     EPI.ExtInfo = einfo;
10152     return getFunctionType(retType, proto->getParamTypes(), EPI);
10153   }
10154 
10155   if (allLTypes) return lhs;
10156   if (allRTypes) return rhs;
10157   return getFunctionNoProtoType(retType, einfo);
10158 }
10159 
10160 /// Given that we have an enum type and a non-enum type, try to merge them.
10161 static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
10162                                      QualType other, bool isBlockReturnType) {
10163   // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
10164   // a signed integer type, or an unsigned integer type.
10165   // Compatibility is based on the underlying type, not the promotion
10166   // type.
10167   QualType underlyingType = ET->getDecl()->getIntegerType();
10168   if (underlyingType.isNull())
10169     return {};
10170   if (Context.hasSameType(underlyingType, other))
10171     return other;
10172 
10173   // In block return types, we're more permissive and accept any
10174   // integral type of the same size.
10175   if (isBlockReturnType && other->isIntegerType() &&
10176       Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
10177     return other;
10178 
10179   return {};
10180 }
10181 
10182 QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
10183                                 bool OfBlockPointer,
10184                                 bool Unqualified, bool BlockReturnType) {
10185   // For C++ we will not reach this code with reference types (see below),
10186   // for OpenMP variant call overloading we might.
10187   //
10188   // C++ [expr]: If an expression initially has the type "reference to T", the
10189   // type is adjusted to "T" prior to any further analysis, the expression
10190   // designates the object or function denoted by the reference, and the
10191   // expression is an lvalue unless the reference is an rvalue reference and
10192   // the expression is a function call (possibly inside parentheses).
10193   auto *LHSRefTy = LHS->getAs<ReferenceType>();
10194   auto *RHSRefTy = RHS->getAs<ReferenceType>();
10195   if (LangOpts.OpenMP && LHSRefTy && RHSRefTy &&
10196       LHS->getTypeClass() == RHS->getTypeClass())
10197     return mergeTypes(LHSRefTy->getPointeeType(), RHSRefTy->getPointeeType(),
10198                       OfBlockPointer, Unqualified, BlockReturnType);
10199   if (LHSRefTy || RHSRefTy)
10200     return {};
10201 
10202   if (Unqualified) {
10203     LHS = LHS.getUnqualifiedType();
10204     RHS = RHS.getUnqualifiedType();
10205   }
10206 
10207   QualType LHSCan = getCanonicalType(LHS),
10208            RHSCan = getCanonicalType(RHS);
10209 
10210   // If two types are identical, they are compatible.
10211   if (LHSCan == RHSCan)
10212     return LHS;
10213 
10214   // If the qualifiers are different, the types aren't compatible... mostly.
10215   Qualifiers LQuals = LHSCan.getLocalQualifiers();
10216   Qualifiers RQuals = RHSCan.getLocalQualifiers();
10217   if (LQuals != RQuals) {
10218     // If any of these qualifiers are different, we have a type
10219     // mismatch.
10220     if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
10221         LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
10222         LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
10223         LQuals.hasUnaligned() != RQuals.hasUnaligned())
10224       return {};
10225 
10226     // Exactly one GC qualifier difference is allowed: __strong is
10227     // okay if the other type has no GC qualifier but is an Objective
10228     // C object pointer (i.e. implicitly strong by default).  We fix
10229     // this by pretending that the unqualified type was actually
10230     // qualified __strong.
10231     Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
10232     Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
10233     assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
10234 
10235     if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
10236       return {};
10237 
10238     if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
10239       return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
10240     }
10241     if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
10242       return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
10243     }
10244     return {};
10245   }
10246 
10247   // Okay, qualifiers are equal.
10248 
10249   Type::TypeClass LHSClass = LHSCan->getTypeClass();
10250   Type::TypeClass RHSClass = RHSCan->getTypeClass();
10251 
10252   // We want to consider the two function types to be the same for these
10253   // comparisons, just force one to the other.
10254   if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
10255   if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
10256 
10257   // Same as above for arrays
10258   if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
10259     LHSClass = Type::ConstantArray;
10260   if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
10261     RHSClass = Type::ConstantArray;
10262 
10263   // ObjCInterfaces are just specialized ObjCObjects.
10264   if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
10265   if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
10266 
10267   // Canonicalize ExtVector -> Vector.
10268   if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
10269   if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
10270 
10271   // If the canonical type classes don't match.
10272   if (LHSClass != RHSClass) {
10273     // Note that we only have special rules for turning block enum
10274     // returns into block int returns, not vice-versa.
10275     if (const auto *ETy = LHS->getAs<EnumType>()) {
10276       return mergeEnumWithInteger(*this, ETy, RHS, false);
10277     }
10278     if (const EnumType* ETy = RHS->getAs<EnumType>()) {
10279       return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
10280     }
10281     // allow block pointer type to match an 'id' type.
10282     if (OfBlockPointer && !BlockReturnType) {
10283        if (LHS->isObjCIdType() && RHS->isBlockPointerType())
10284          return LHS;
10285       if (RHS->isObjCIdType() && LHS->isBlockPointerType())
10286         return RHS;
10287     }
10288     // Allow __auto_type to match anything; it merges to the type with more
10289     // information.
10290     if (const auto *AT = LHS->getAs<AutoType>()) {
10291       if (AT->isGNUAutoType())
10292         return RHS;
10293     }
10294     if (const auto *AT = RHS->getAs<AutoType>()) {
10295       if (AT->isGNUAutoType())
10296         return LHS;
10297     }
10298     return {};
10299   }
10300 
10301   // The canonical type classes match.
10302   switch (LHSClass) {
10303 #define TYPE(Class, Base)
10304 #define ABSTRACT_TYPE(Class, Base)
10305 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
10306 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
10307 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
10308 #include "clang/AST/TypeNodes.inc"
10309     llvm_unreachable("Non-canonical and dependent types shouldn't get here");
10310 
10311   case Type::Auto:
10312   case Type::DeducedTemplateSpecialization:
10313   case Type::LValueReference:
10314   case Type::RValueReference:
10315   case Type::MemberPointer:
10316     llvm_unreachable("C++ should never be in mergeTypes");
10317 
10318   case Type::ObjCInterface:
10319   case Type::IncompleteArray:
10320   case Type::VariableArray:
10321   case Type::FunctionProto:
10322   case Type::ExtVector:
10323     llvm_unreachable("Types are eliminated above");
10324 
10325   case Type::Pointer:
10326   {
10327     // Merge two pointer types, while trying to preserve typedef info
10328     QualType LHSPointee = LHS->castAs<PointerType>()->getPointeeType();
10329     QualType RHSPointee = RHS->castAs<PointerType>()->getPointeeType();
10330     if (Unqualified) {
10331       LHSPointee = LHSPointee.getUnqualifiedType();
10332       RHSPointee = RHSPointee.getUnqualifiedType();
10333     }
10334     QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
10335                                      Unqualified);
10336     if (ResultType.isNull())
10337       return {};
10338     if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
10339       return LHS;
10340     if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
10341       return RHS;
10342     return getPointerType(ResultType);
10343   }
10344   case Type::BlockPointer:
10345   {
10346     // Merge two block pointer types, while trying to preserve typedef info
10347     QualType LHSPointee = LHS->castAs<BlockPointerType>()->getPointeeType();
10348     QualType RHSPointee = RHS->castAs<BlockPointerType>()->getPointeeType();
10349     if (Unqualified) {
10350       LHSPointee = LHSPointee.getUnqualifiedType();
10351       RHSPointee = RHSPointee.getUnqualifiedType();
10352     }
10353     if (getLangOpts().OpenCL) {
10354       Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
10355       Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
10356       // Blocks can't be an expression in a ternary operator (OpenCL v2.0
10357       // 6.12.5) thus the following check is asymmetric.
10358       if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual))
10359         return {};
10360       LHSPteeQual.removeAddressSpace();
10361       RHSPteeQual.removeAddressSpace();
10362       LHSPointee =
10363           QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
10364       RHSPointee =
10365           QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
10366     }
10367     QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
10368                                      Unqualified);
10369     if (ResultType.isNull())
10370       return {};
10371     if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
10372       return LHS;
10373     if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
10374       return RHS;
10375     return getBlockPointerType(ResultType);
10376   }
10377   case Type::Atomic:
10378   {
10379     // Merge two pointer types, while trying to preserve typedef info
10380     QualType LHSValue = LHS->castAs<AtomicType>()->getValueType();
10381     QualType RHSValue = RHS->castAs<AtomicType>()->getValueType();
10382     if (Unqualified) {
10383       LHSValue = LHSValue.getUnqualifiedType();
10384       RHSValue = RHSValue.getUnqualifiedType();
10385     }
10386     QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
10387                                      Unqualified);
10388     if (ResultType.isNull())
10389       return {};
10390     if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
10391       return LHS;
10392     if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
10393       return RHS;
10394     return getAtomicType(ResultType);
10395   }
10396   case Type::ConstantArray:
10397   {
10398     const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
10399     const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
10400     if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
10401       return {};
10402 
10403     QualType LHSElem = getAsArrayType(LHS)->getElementType();
10404     QualType RHSElem = getAsArrayType(RHS)->getElementType();
10405     if (Unqualified) {
10406       LHSElem = LHSElem.getUnqualifiedType();
10407       RHSElem = RHSElem.getUnqualifiedType();
10408     }
10409 
10410     QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
10411     if (ResultType.isNull())
10412       return {};
10413 
10414     const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
10415     const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
10416 
10417     // If either side is a variable array, and both are complete, check whether
10418     // the current dimension is definite.
10419     if (LVAT || RVAT) {
10420       auto SizeFetch = [this](const VariableArrayType* VAT,
10421           const ConstantArrayType* CAT)
10422           -> std::pair<bool,llvm::APInt> {
10423         if (VAT) {
10424           Optional<llvm::APSInt> TheInt;
10425           Expr *E = VAT->getSizeExpr();
10426           if (E && (TheInt = E->getIntegerConstantExpr(*this)))
10427             return std::make_pair(true, *TheInt);
10428           return std::make_pair(false, llvm::APSInt());
10429         }
10430         if (CAT)
10431           return std::make_pair(true, CAT->getSize());
10432         return std::make_pair(false, llvm::APInt());
10433       };
10434 
10435       bool HaveLSize, HaveRSize;
10436       llvm::APInt LSize, RSize;
10437       std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT);
10438       std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT);
10439       if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize))
10440         return {}; // Definite, but unequal, array dimension
10441     }
10442 
10443     if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
10444       return LHS;
10445     if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
10446       return RHS;
10447     if (LCAT)
10448       return getConstantArrayType(ResultType, LCAT->getSize(),
10449                                   LCAT->getSizeExpr(),
10450                                   ArrayType::ArraySizeModifier(), 0);
10451     if (RCAT)
10452       return getConstantArrayType(ResultType, RCAT->getSize(),
10453                                   RCAT->getSizeExpr(),
10454                                   ArrayType::ArraySizeModifier(), 0);
10455     if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
10456       return LHS;
10457     if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
10458       return RHS;
10459     if (LVAT) {
10460       // FIXME: This isn't correct! But tricky to implement because
10461       // the array's size has to be the size of LHS, but the type
10462       // has to be different.
10463       return LHS;
10464     }
10465     if (RVAT) {
10466       // FIXME: This isn't correct! But tricky to implement because
10467       // the array's size has to be the size of RHS, but the type
10468       // has to be different.
10469       return RHS;
10470     }
10471     if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
10472     if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
10473     return getIncompleteArrayType(ResultType,
10474                                   ArrayType::ArraySizeModifier(), 0);
10475   }
10476   case Type::FunctionNoProto:
10477     return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
10478   case Type::Record:
10479   case Type::Enum:
10480     return {};
10481   case Type::Builtin:
10482     // Only exactly equal builtin types are compatible, which is tested above.
10483     return {};
10484   case Type::Complex:
10485     // Distinct complex types are incompatible.
10486     return {};
10487   case Type::Vector:
10488     // FIXME: The merged type should be an ExtVector!
10489     if (areCompatVectorTypes(LHSCan->castAs<VectorType>(),
10490                              RHSCan->castAs<VectorType>()))
10491       return LHS;
10492     return {};
10493   case Type::ConstantMatrix:
10494     if (areCompatMatrixTypes(LHSCan->castAs<ConstantMatrixType>(),
10495                              RHSCan->castAs<ConstantMatrixType>()))
10496       return LHS;
10497     return {};
10498   case Type::ObjCObject: {
10499     // Check if the types are assignment compatible.
10500     // FIXME: This should be type compatibility, e.g. whether
10501     // "LHS x; RHS x;" at global scope is legal.
10502     if (canAssignObjCInterfaces(LHS->castAs<ObjCObjectType>(),
10503                                 RHS->castAs<ObjCObjectType>()))
10504       return LHS;
10505     return {};
10506   }
10507   case Type::ObjCObjectPointer:
10508     if (OfBlockPointer) {
10509       if (canAssignObjCInterfacesInBlockPointer(
10510               LHS->castAs<ObjCObjectPointerType>(),
10511               RHS->castAs<ObjCObjectPointerType>(), BlockReturnType))
10512         return LHS;
10513       return {};
10514     }
10515     if (canAssignObjCInterfaces(LHS->castAs<ObjCObjectPointerType>(),
10516                                 RHS->castAs<ObjCObjectPointerType>()))
10517       return LHS;
10518     return {};
10519   case Type::Pipe:
10520     assert(LHS != RHS &&
10521            "Equivalent pipe types should have already been handled!");
10522     return {};
10523   case Type::BitInt: {
10524     // Merge two bit-precise int types, while trying to preserve typedef info.
10525     bool LHSUnsigned = LHS->castAs<BitIntType>()->isUnsigned();
10526     bool RHSUnsigned = RHS->castAs<BitIntType>()->isUnsigned();
10527     unsigned LHSBits = LHS->castAs<BitIntType>()->getNumBits();
10528     unsigned RHSBits = RHS->castAs<BitIntType>()->getNumBits();
10529 
10530     // Like unsigned/int, shouldn't have a type if they don't match.
10531     if (LHSUnsigned != RHSUnsigned)
10532       return {};
10533 
10534     if (LHSBits != RHSBits)
10535       return {};
10536     return LHS;
10537   }
10538   }
10539 
10540   llvm_unreachable("Invalid Type::Class!");
10541 }
10542 
10543 bool ASTContext::mergeExtParameterInfo(
10544     const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
10545     bool &CanUseFirst, bool &CanUseSecond,
10546     SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos) {
10547   assert(NewParamInfos.empty() && "param info list not empty");
10548   CanUseFirst = CanUseSecond = true;
10549   bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
10550   bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
10551 
10552   // Fast path: if the first type doesn't have ext parameter infos,
10553   // we match if and only if the second type also doesn't have them.
10554   if (!FirstHasInfo && !SecondHasInfo)
10555     return true;
10556 
10557   bool NeedParamInfo = false;
10558   size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
10559                           : SecondFnType->getExtParameterInfos().size();
10560 
10561   for (size_t I = 0; I < E; ++I) {
10562     FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
10563     if (FirstHasInfo)
10564       FirstParam = FirstFnType->getExtParameterInfo(I);
10565     if (SecondHasInfo)
10566       SecondParam = SecondFnType->getExtParameterInfo(I);
10567 
10568     // Cannot merge unless everything except the noescape flag matches.
10569     if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false))
10570       return false;
10571 
10572     bool FirstNoEscape = FirstParam.isNoEscape();
10573     bool SecondNoEscape = SecondParam.isNoEscape();
10574     bool IsNoEscape = FirstNoEscape && SecondNoEscape;
10575     NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape));
10576     if (NewParamInfos.back().getOpaqueValue())
10577       NeedParamInfo = true;
10578     if (FirstNoEscape != IsNoEscape)
10579       CanUseFirst = false;
10580     if (SecondNoEscape != IsNoEscape)
10581       CanUseSecond = false;
10582   }
10583 
10584   if (!NeedParamInfo)
10585     NewParamInfos.clear();
10586 
10587   return true;
10588 }
10589 
10590 void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) {
10591   ObjCLayouts[CD] = nullptr;
10592 }
10593 
10594 /// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
10595 /// 'RHS' attributes and returns the merged version; including for function
10596 /// return types.
10597 QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
10598   QualType LHSCan = getCanonicalType(LHS),
10599   RHSCan = getCanonicalType(RHS);
10600   // If two types are identical, they are compatible.
10601   if (LHSCan == RHSCan)
10602     return LHS;
10603   if (RHSCan->isFunctionType()) {
10604     if (!LHSCan->isFunctionType())
10605       return {};
10606     QualType OldReturnType =
10607         cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
10608     QualType NewReturnType =
10609         cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
10610     QualType ResReturnType =
10611       mergeObjCGCQualifiers(NewReturnType, OldReturnType);
10612     if (ResReturnType.isNull())
10613       return {};
10614     if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
10615       // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
10616       // In either case, use OldReturnType to build the new function type.
10617       const auto *F = LHS->castAs<FunctionType>();
10618       if (const auto *FPT = cast<FunctionProtoType>(F)) {
10619         FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10620         EPI.ExtInfo = getFunctionExtInfo(LHS);
10621         QualType ResultType =
10622             getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
10623         return ResultType;
10624       }
10625     }
10626     return {};
10627   }
10628 
10629   // If the qualifiers are different, the types can still be merged.
10630   Qualifiers LQuals = LHSCan.getLocalQualifiers();
10631   Qualifiers RQuals = RHSCan.getLocalQualifiers();
10632   if (LQuals != RQuals) {
10633     // If any of these qualifiers are different, we have a type mismatch.
10634     if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
10635         LQuals.getAddressSpace() != RQuals.getAddressSpace())
10636       return {};
10637 
10638     // Exactly one GC qualifier difference is allowed: __strong is
10639     // okay if the other type has no GC qualifier but is an Objective
10640     // C object pointer (i.e. implicitly strong by default).  We fix
10641     // this by pretending that the unqualified type was actually
10642     // qualified __strong.
10643     Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
10644     Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
10645     assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
10646 
10647     if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
10648       return {};
10649 
10650     if (GC_L == Qualifiers::Strong)
10651       return LHS;
10652     if (GC_R == Qualifiers::Strong)
10653       return RHS;
10654     return {};
10655   }
10656 
10657   if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
10658     QualType LHSBaseQT = LHS->castAs<ObjCObjectPointerType>()->getPointeeType();
10659     QualType RHSBaseQT = RHS->castAs<ObjCObjectPointerType>()->getPointeeType();
10660     QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
10661     if (ResQT == LHSBaseQT)
10662       return LHS;
10663     if (ResQT == RHSBaseQT)
10664       return RHS;
10665   }
10666   return {};
10667 }
10668 
10669 //===----------------------------------------------------------------------===//
10670 //                         Integer Predicates
10671 //===----------------------------------------------------------------------===//
10672 
10673 unsigned ASTContext::getIntWidth(QualType T) const {
10674   if (const auto *ET = T->getAs<EnumType>())
10675     T = ET->getDecl()->getIntegerType();
10676   if (T->isBooleanType())
10677     return 1;
10678   if (const auto *EIT = T->getAs<BitIntType>())
10679     return EIT->getNumBits();
10680   // For builtin types, just use the standard type sizing method
10681   return (unsigned)getTypeSize(T);
10682 }
10683 
10684 QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
10685   assert((T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) &&
10686          "Unexpected type");
10687 
10688   // Turn <4 x signed int> -> <4 x unsigned int>
10689   if (const auto *VTy = T->getAs<VectorType>())
10690     return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
10691                          VTy->getNumElements(), VTy->getVectorKind());
10692 
10693   // For _BitInt, return an unsigned _BitInt with same width.
10694   if (const auto *EITy = T->getAs<BitIntType>())
10695     return getBitIntType(/*Unsigned=*/true, EITy->getNumBits());
10696 
10697   // For enums, get the underlying integer type of the enum, and let the general
10698   // integer type signchanging code handle it.
10699   if (const auto *ETy = T->getAs<EnumType>())
10700     T = ETy->getDecl()->getIntegerType();
10701 
10702   switch (T->castAs<BuiltinType>()->getKind()) {
10703   case BuiltinType::Char_S:
10704   case BuiltinType::SChar:
10705     return UnsignedCharTy;
10706   case BuiltinType::Short:
10707     return UnsignedShortTy;
10708   case BuiltinType::Int:
10709     return UnsignedIntTy;
10710   case BuiltinType::Long:
10711     return UnsignedLongTy;
10712   case BuiltinType::LongLong:
10713     return UnsignedLongLongTy;
10714   case BuiltinType::Int128:
10715     return UnsignedInt128Ty;
10716   // wchar_t is special. It is either signed or not, but when it's signed,
10717   // there's no matching "unsigned wchar_t". Therefore we return the unsigned
10718   // version of it's underlying type instead.
10719   case BuiltinType::WChar_S:
10720     return getUnsignedWCharType();
10721 
10722   case BuiltinType::ShortAccum:
10723     return UnsignedShortAccumTy;
10724   case BuiltinType::Accum:
10725     return UnsignedAccumTy;
10726   case BuiltinType::LongAccum:
10727     return UnsignedLongAccumTy;
10728   case BuiltinType::SatShortAccum:
10729     return SatUnsignedShortAccumTy;
10730   case BuiltinType::SatAccum:
10731     return SatUnsignedAccumTy;
10732   case BuiltinType::SatLongAccum:
10733     return SatUnsignedLongAccumTy;
10734   case BuiltinType::ShortFract:
10735     return UnsignedShortFractTy;
10736   case BuiltinType::Fract:
10737     return UnsignedFractTy;
10738   case BuiltinType::LongFract:
10739     return UnsignedLongFractTy;
10740   case BuiltinType::SatShortFract:
10741     return SatUnsignedShortFractTy;
10742   case BuiltinType::SatFract:
10743     return SatUnsignedFractTy;
10744   case BuiltinType::SatLongFract:
10745     return SatUnsignedLongFractTy;
10746   default:
10747     llvm_unreachable("Unexpected signed integer or fixed point type");
10748   }
10749 }
10750 
10751 QualType ASTContext::getCorrespondingSignedType(QualType T) const {
10752   assert((T->hasUnsignedIntegerRepresentation() ||
10753           T->isUnsignedFixedPointType()) &&
10754          "Unexpected type");
10755 
10756   // Turn <4 x unsigned int> -> <4 x signed int>
10757   if (const auto *VTy = T->getAs<VectorType>())
10758     return getVectorType(getCorrespondingSignedType(VTy->getElementType()),
10759                          VTy->getNumElements(), VTy->getVectorKind());
10760 
10761   // For _BitInt, return a signed _BitInt with same width.
10762   if (const auto *EITy = T->getAs<BitIntType>())
10763     return getBitIntType(/*Unsigned=*/false, EITy->getNumBits());
10764 
10765   // For enums, get the underlying integer type of the enum, and let the general
10766   // integer type signchanging code handle it.
10767   if (const auto *ETy = T->getAs<EnumType>())
10768     T = ETy->getDecl()->getIntegerType();
10769 
10770   switch (T->castAs<BuiltinType>()->getKind()) {
10771   case BuiltinType::Char_U:
10772   case BuiltinType::UChar:
10773     return SignedCharTy;
10774   case BuiltinType::UShort:
10775     return ShortTy;
10776   case BuiltinType::UInt:
10777     return IntTy;
10778   case BuiltinType::ULong:
10779     return LongTy;
10780   case BuiltinType::ULongLong:
10781     return LongLongTy;
10782   case BuiltinType::UInt128:
10783     return Int128Ty;
10784   // wchar_t is special. It is either unsigned or not, but when it's unsigned,
10785   // there's no matching "signed wchar_t". Therefore we return the signed
10786   // version of it's underlying type instead.
10787   case BuiltinType::WChar_U:
10788     return getSignedWCharType();
10789 
10790   case BuiltinType::UShortAccum:
10791     return ShortAccumTy;
10792   case BuiltinType::UAccum:
10793     return AccumTy;
10794   case BuiltinType::ULongAccum:
10795     return LongAccumTy;
10796   case BuiltinType::SatUShortAccum:
10797     return SatShortAccumTy;
10798   case BuiltinType::SatUAccum:
10799     return SatAccumTy;
10800   case BuiltinType::SatULongAccum:
10801     return SatLongAccumTy;
10802   case BuiltinType::UShortFract:
10803     return ShortFractTy;
10804   case BuiltinType::UFract:
10805     return FractTy;
10806   case BuiltinType::ULongFract:
10807     return LongFractTy;
10808   case BuiltinType::SatUShortFract:
10809     return SatShortFractTy;
10810   case BuiltinType::SatUFract:
10811     return SatFractTy;
10812   case BuiltinType::SatULongFract:
10813     return SatLongFractTy;
10814   default:
10815     llvm_unreachable("Unexpected unsigned integer or fixed point type");
10816   }
10817 }
10818 
10819 ASTMutationListener::~ASTMutationListener() = default;
10820 
10821 void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
10822                                             QualType ReturnType) {}
10823 
10824 //===----------------------------------------------------------------------===//
10825 //                          Builtin Type Computation
10826 //===----------------------------------------------------------------------===//
10827 
10828 /// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
10829 /// pointer over the consumed characters.  This returns the resultant type.  If
10830 /// AllowTypeModifiers is false then modifier like * are not parsed, just basic
10831 /// types.  This allows "v2i*" to be parsed as a pointer to a v2i instead of
10832 /// a vector of "i*".
10833 ///
10834 /// RequiresICE is filled in on return to indicate whether the value is required
10835 /// to be an Integer Constant Expression.
10836 static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
10837                                   ASTContext::GetBuiltinTypeError &Error,
10838                                   bool &RequiresICE,
10839                                   bool AllowTypeModifiers) {
10840   // Modifiers.
10841   int HowLong = 0;
10842   bool Signed = false, Unsigned = false;
10843   RequiresICE = false;
10844 
10845   // Read the prefixed modifiers first.
10846   bool Done = false;
10847   #ifndef NDEBUG
10848   bool IsSpecial = false;
10849   #endif
10850   while (!Done) {
10851     switch (*Str++) {
10852     default: Done = true; --Str; break;
10853     case 'I':
10854       RequiresICE = true;
10855       break;
10856     case 'S':
10857       assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
10858       assert(!Signed && "Can't use 'S' modifier multiple times!");
10859       Signed = true;
10860       break;
10861     case 'U':
10862       assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
10863       assert(!Unsigned && "Can't use 'U' modifier multiple times!");
10864       Unsigned = true;
10865       break;
10866     case 'L':
10867       assert(!IsSpecial && "Can't use 'L' with 'W', 'N', 'Z' or 'O' modifiers");
10868       assert(HowLong <= 2 && "Can't have LLLL modifier");
10869       ++HowLong;
10870       break;
10871     case 'N':
10872       // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
10873       assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
10874       assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
10875       #ifndef NDEBUG
10876       IsSpecial = true;
10877       #endif
10878       if (Context.getTargetInfo().getLongWidth() == 32)
10879         ++HowLong;
10880       break;
10881     case 'W':
10882       // This modifier represents int64 type.
10883       assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
10884       assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
10885       #ifndef NDEBUG
10886       IsSpecial = true;
10887       #endif
10888       switch (Context.getTargetInfo().getInt64Type()) {
10889       default:
10890         llvm_unreachable("Unexpected integer type");
10891       case TargetInfo::SignedLong:
10892         HowLong = 1;
10893         break;
10894       case TargetInfo::SignedLongLong:
10895         HowLong = 2;
10896         break;
10897       }
10898       break;
10899     case 'Z':
10900       // This modifier represents int32 type.
10901       assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
10902       assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!");
10903       #ifndef NDEBUG
10904       IsSpecial = true;
10905       #endif
10906       switch (Context.getTargetInfo().getIntTypeByWidth(32, true)) {
10907       default:
10908         llvm_unreachable("Unexpected integer type");
10909       case TargetInfo::SignedInt:
10910         HowLong = 0;
10911         break;
10912       case TargetInfo::SignedLong:
10913         HowLong = 1;
10914         break;
10915       case TargetInfo::SignedLongLong:
10916         HowLong = 2;
10917         break;
10918       }
10919       break;
10920     case 'O':
10921       assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
10922       assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!");
10923       #ifndef NDEBUG
10924       IsSpecial = true;
10925       #endif
10926       if (Context.getLangOpts().OpenCL)
10927         HowLong = 1;
10928       else
10929         HowLong = 2;
10930       break;
10931     }
10932   }
10933 
10934   QualType Type;
10935 
10936   // Read the base type.
10937   switch (*Str++) {
10938   default: llvm_unreachable("Unknown builtin type letter!");
10939   case 'x':
10940     assert(HowLong == 0 && !Signed && !Unsigned &&
10941            "Bad modifiers used with 'x'!");
10942     Type = Context.Float16Ty;
10943     break;
10944   case 'y':
10945     assert(HowLong == 0 && !Signed && !Unsigned &&
10946            "Bad modifiers used with 'y'!");
10947     Type = Context.BFloat16Ty;
10948     break;
10949   case 'v':
10950     assert(HowLong == 0 && !Signed && !Unsigned &&
10951            "Bad modifiers used with 'v'!");
10952     Type = Context.VoidTy;
10953     break;
10954   case 'h':
10955     assert(HowLong == 0 && !Signed && !Unsigned &&
10956            "Bad modifiers used with 'h'!");
10957     Type = Context.HalfTy;
10958     break;
10959   case 'f':
10960     assert(HowLong == 0 && !Signed && !Unsigned &&
10961            "Bad modifiers used with 'f'!");
10962     Type = Context.FloatTy;
10963     break;
10964   case 'd':
10965     assert(HowLong < 3 && !Signed && !Unsigned &&
10966            "Bad modifiers used with 'd'!");
10967     if (HowLong == 1)
10968       Type = Context.LongDoubleTy;
10969     else if (HowLong == 2)
10970       Type = Context.Float128Ty;
10971     else
10972       Type = Context.DoubleTy;
10973     break;
10974   case 's':
10975     assert(HowLong == 0 && "Bad modifiers used with 's'!");
10976     if (Unsigned)
10977       Type = Context.UnsignedShortTy;
10978     else
10979       Type = Context.ShortTy;
10980     break;
10981   case 'i':
10982     if (HowLong == 3)
10983       Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
10984     else if (HowLong == 2)
10985       Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
10986     else if (HowLong == 1)
10987       Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
10988     else
10989       Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
10990     break;
10991   case 'c':
10992     assert(HowLong == 0 && "Bad modifiers used with 'c'!");
10993     if (Signed)
10994       Type = Context.SignedCharTy;
10995     else if (Unsigned)
10996       Type = Context.UnsignedCharTy;
10997     else
10998       Type = Context.CharTy;
10999     break;
11000   case 'b': // boolean
11001     assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
11002     Type = Context.BoolTy;
11003     break;
11004   case 'z':  // size_t.
11005     assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
11006     Type = Context.getSizeType();
11007     break;
11008   case 'w':  // wchar_t.
11009     assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
11010     Type = Context.getWideCharType();
11011     break;
11012   case 'F':
11013     Type = Context.getCFConstantStringType();
11014     break;
11015   case 'G':
11016     Type = Context.getObjCIdType();
11017     break;
11018   case 'H':
11019     Type = Context.getObjCSelType();
11020     break;
11021   case 'M':
11022     Type = Context.getObjCSuperType();
11023     break;
11024   case 'a':
11025     Type = Context.getBuiltinVaListType();
11026     assert(!Type.isNull() && "builtin va list type not initialized!");
11027     break;
11028   case 'A':
11029     // This is a "reference" to a va_list; however, what exactly
11030     // this means depends on how va_list is defined. There are two
11031     // different kinds of va_list: ones passed by value, and ones
11032     // passed by reference.  An example of a by-value va_list is
11033     // x86, where va_list is a char*. An example of by-ref va_list
11034     // is x86-64, where va_list is a __va_list_tag[1]. For x86,
11035     // we want this argument to be a char*&; for x86-64, we want
11036     // it to be a __va_list_tag*.
11037     Type = Context.getBuiltinVaListType();
11038     assert(!Type.isNull() && "builtin va list type not initialized!");
11039     if (Type->isArrayType())
11040       Type = Context.getArrayDecayedType(Type);
11041     else
11042       Type = Context.getLValueReferenceType(Type);
11043     break;
11044   case 'q': {
11045     char *End;
11046     unsigned NumElements = strtoul(Str, &End, 10);
11047     assert(End != Str && "Missing vector size");
11048     Str = End;
11049 
11050     QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
11051                                              RequiresICE, false);
11052     assert(!RequiresICE && "Can't require vector ICE");
11053 
11054     Type = Context.getScalableVectorType(ElementType, NumElements);
11055     break;
11056   }
11057   case 'V': {
11058     char *End;
11059     unsigned NumElements = strtoul(Str, &End, 10);
11060     assert(End != Str && "Missing vector size");
11061     Str = End;
11062 
11063     QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
11064                                              RequiresICE, false);
11065     assert(!RequiresICE && "Can't require vector ICE");
11066 
11067     // TODO: No way to make AltiVec vectors in builtins yet.
11068     Type = Context.getVectorType(ElementType, NumElements,
11069                                  VectorType::GenericVector);
11070     break;
11071   }
11072   case 'E': {
11073     char *End;
11074 
11075     unsigned NumElements = strtoul(Str, &End, 10);
11076     assert(End != Str && "Missing vector size");
11077 
11078     Str = End;
11079 
11080     QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
11081                                              false);
11082     Type = Context.getExtVectorType(ElementType, NumElements);
11083     break;
11084   }
11085   case 'X': {
11086     QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
11087                                              false);
11088     assert(!RequiresICE && "Can't require complex ICE");
11089     Type = Context.getComplexType(ElementType);
11090     break;
11091   }
11092   case 'Y':
11093     Type = Context.getPointerDiffType();
11094     break;
11095   case 'P':
11096     Type = Context.getFILEType();
11097     if (Type.isNull()) {
11098       Error = ASTContext::GE_Missing_stdio;
11099       return {};
11100     }
11101     break;
11102   case 'J':
11103     if (Signed)
11104       Type = Context.getsigjmp_bufType();
11105     else
11106       Type = Context.getjmp_bufType();
11107 
11108     if (Type.isNull()) {
11109       Error = ASTContext::GE_Missing_setjmp;
11110       return {};
11111     }
11112     break;
11113   case 'K':
11114     assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
11115     Type = Context.getucontext_tType();
11116 
11117     if (Type.isNull()) {
11118       Error = ASTContext::GE_Missing_ucontext;
11119       return {};
11120     }
11121     break;
11122   case 'p':
11123     Type = Context.getProcessIDType();
11124     break;
11125   }
11126 
11127   // If there are modifiers and if we're allowed to parse them, go for it.
11128   Done = !AllowTypeModifiers;
11129   while (!Done) {
11130     switch (char c = *Str++) {
11131     default: Done = true; --Str; break;
11132     case '*':
11133     case '&': {
11134       // Both pointers and references can have their pointee types
11135       // qualified with an address space.
11136       char *End;
11137       unsigned AddrSpace = strtoul(Str, &End, 10);
11138       if (End != Str) {
11139         // Note AddrSpace == 0 is not the same as an unspecified address space.
11140         Type = Context.getAddrSpaceQualType(
11141           Type,
11142           Context.getLangASForBuiltinAddressSpace(AddrSpace));
11143         Str = End;
11144       }
11145       if (c == '*')
11146         Type = Context.getPointerType(Type);
11147       else
11148         Type = Context.getLValueReferenceType(Type);
11149       break;
11150     }
11151     // FIXME: There's no way to have a built-in with an rvalue ref arg.
11152     case 'C':
11153       Type = Type.withConst();
11154       break;
11155     case 'D':
11156       Type = Context.getVolatileType(Type);
11157       break;
11158     case 'R':
11159       Type = Type.withRestrict();
11160       break;
11161     }
11162   }
11163 
11164   assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
11165          "Integer constant 'I' type must be an integer");
11166 
11167   return Type;
11168 }
11169 
11170 // On some targets such as PowerPC, some of the builtins are defined with custom
11171 // type descriptors for target-dependent types. These descriptors are decoded in
11172 // other functions, but it may be useful to be able to fall back to default
11173 // descriptor decoding to define builtins mixing target-dependent and target-
11174 // independent types. This function allows decoding one type descriptor with
11175 // default decoding.
11176 QualType ASTContext::DecodeTypeStr(const char *&Str, const ASTContext &Context,
11177                                    GetBuiltinTypeError &Error, bool &RequireICE,
11178                                    bool AllowTypeModifiers) const {
11179   return DecodeTypeFromStr(Str, Context, Error, RequireICE, AllowTypeModifiers);
11180 }
11181 
11182 /// GetBuiltinType - Return the type for the specified builtin.
11183 QualType ASTContext::GetBuiltinType(unsigned Id,
11184                                     GetBuiltinTypeError &Error,
11185                                     unsigned *IntegerConstantArgs) const {
11186   const char *TypeStr = BuiltinInfo.getTypeString(Id);
11187   if (TypeStr[0] == '\0') {
11188     Error = GE_Missing_type;
11189     return {};
11190   }
11191 
11192   SmallVector<QualType, 8> ArgTypes;
11193 
11194   bool RequiresICE = false;
11195   Error = GE_None;
11196   QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
11197                                        RequiresICE, true);
11198   if (Error != GE_None)
11199     return {};
11200 
11201   assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
11202 
11203   while (TypeStr[0] && TypeStr[0] != '.') {
11204     QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
11205     if (Error != GE_None)
11206       return {};
11207 
11208     // If this argument is required to be an IntegerConstantExpression and the
11209     // caller cares, fill in the bitmask we return.
11210     if (RequiresICE && IntegerConstantArgs)
11211       *IntegerConstantArgs |= 1 << ArgTypes.size();
11212 
11213     // Do array -> pointer decay.  The builtin should use the decayed type.
11214     if (Ty->isArrayType())
11215       Ty = getArrayDecayedType(Ty);
11216 
11217     ArgTypes.push_back(Ty);
11218   }
11219 
11220   if (Id == Builtin::BI__GetExceptionInfo)
11221     return {};
11222 
11223   assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
11224          "'.' should only occur at end of builtin type list!");
11225 
11226   bool Variadic = (TypeStr[0] == '.');
11227 
11228   FunctionType::ExtInfo EI(getDefaultCallingConvention(
11229       Variadic, /*IsCXXMethod=*/false, /*IsBuiltin=*/true));
11230   if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
11231 
11232 
11233   // We really shouldn't be making a no-proto type here.
11234   if (ArgTypes.empty() && Variadic && !getLangOpts().CPlusPlus)
11235     return getFunctionNoProtoType(ResType, EI);
11236 
11237   FunctionProtoType::ExtProtoInfo EPI;
11238   EPI.ExtInfo = EI;
11239   EPI.Variadic = Variadic;
11240   if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id))
11241     EPI.ExceptionSpec.Type =
11242         getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
11243 
11244   return getFunctionType(ResType, ArgTypes, EPI);
11245 }
11246 
11247 static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
11248                                              const FunctionDecl *FD) {
11249   if (!FD->isExternallyVisible())
11250     return GVA_Internal;
11251 
11252   // Non-user-provided functions get emitted as weak definitions with every
11253   // use, no matter whether they've been explicitly instantiated etc.
11254   if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
11255     if (!MD->isUserProvided())
11256       return GVA_DiscardableODR;
11257 
11258   GVALinkage External;
11259   switch (FD->getTemplateSpecializationKind()) {
11260   case TSK_Undeclared:
11261   case TSK_ExplicitSpecialization:
11262     External = GVA_StrongExternal;
11263     break;
11264 
11265   case TSK_ExplicitInstantiationDefinition:
11266     return GVA_StrongODR;
11267 
11268   // C++11 [temp.explicit]p10:
11269   //   [ Note: The intent is that an inline function that is the subject of
11270   //   an explicit instantiation declaration will still be implicitly
11271   //   instantiated when used so that the body can be considered for
11272   //   inlining, but that no out-of-line copy of the inline function would be
11273   //   generated in the translation unit. -- end note ]
11274   case TSK_ExplicitInstantiationDeclaration:
11275     return GVA_AvailableExternally;
11276 
11277   case TSK_ImplicitInstantiation:
11278     External = GVA_DiscardableODR;
11279     break;
11280   }
11281 
11282   if (!FD->isInlined())
11283     return External;
11284 
11285   if ((!Context.getLangOpts().CPlusPlus &&
11286        !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
11287        !FD->hasAttr<DLLExportAttr>()) ||
11288       FD->hasAttr<GNUInlineAttr>()) {
11289     // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
11290 
11291     // GNU or C99 inline semantics. Determine whether this symbol should be
11292     // externally visible.
11293     if (FD->isInlineDefinitionExternallyVisible())
11294       return External;
11295 
11296     // C99 inline semantics, where the symbol is not externally visible.
11297     return GVA_AvailableExternally;
11298   }
11299 
11300   // Functions specified with extern and inline in -fms-compatibility mode
11301   // forcibly get emitted.  While the body of the function cannot be later
11302   // replaced, the function definition cannot be discarded.
11303   if (FD->isMSExternInline())
11304     return GVA_StrongODR;
11305 
11306   return GVA_DiscardableODR;
11307 }
11308 
11309 static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context,
11310                                                 const Decl *D, GVALinkage L) {
11311   // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
11312   // dllexport/dllimport on inline functions.
11313   if (D->hasAttr<DLLImportAttr>()) {
11314     if (L == GVA_DiscardableODR || L == GVA_StrongODR)
11315       return GVA_AvailableExternally;
11316   } else if (D->hasAttr<DLLExportAttr>()) {
11317     if (L == GVA_DiscardableODR)
11318       return GVA_StrongODR;
11319   } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice) {
11320     // Device-side functions with __global__ attribute must always be
11321     // visible externally so they can be launched from host.
11322     if (D->hasAttr<CUDAGlobalAttr>() &&
11323         (L == GVA_DiscardableODR || L == GVA_Internal))
11324       return GVA_StrongODR;
11325     // Single source offloading languages like CUDA/HIP need to be able to
11326     // access static device variables from host code of the same compilation
11327     // unit. This is done by externalizing the static variable with a shared
11328     // name between the host and device compilation which is the same for the
11329     // same compilation unit whereas different among different compilation
11330     // units.
11331     if (Context.shouldExternalizeStaticVar(D))
11332       return GVA_StrongExternal;
11333   }
11334   return L;
11335 }
11336 
11337 /// Adjust the GVALinkage for a declaration based on what an external AST source
11338 /// knows about whether there can be other definitions of this declaration.
11339 static GVALinkage
11340 adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D,
11341                                           GVALinkage L) {
11342   ExternalASTSource *Source = Ctx.getExternalSource();
11343   if (!Source)
11344     return L;
11345 
11346   switch (Source->hasExternalDefinitions(D)) {
11347   case ExternalASTSource::EK_Never:
11348     // Other translation units rely on us to provide the definition.
11349     if (L == GVA_DiscardableODR)
11350       return GVA_StrongODR;
11351     break;
11352 
11353   case ExternalASTSource::EK_Always:
11354     return GVA_AvailableExternally;
11355 
11356   case ExternalASTSource::EK_ReplyHazy:
11357     break;
11358   }
11359   return L;
11360 }
11361 
11362 GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
11363   return adjustGVALinkageForExternalDefinitionKind(*this, FD,
11364            adjustGVALinkageForAttributes(*this, FD,
11365              basicGVALinkageForFunction(*this, FD)));
11366 }
11367 
11368 static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
11369                                              const VarDecl *VD) {
11370   if (!VD->isExternallyVisible())
11371     return GVA_Internal;
11372 
11373   if (VD->isStaticLocal()) {
11374     const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
11375     while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
11376       LexicalContext = LexicalContext->getLexicalParent();
11377 
11378     // ObjC Blocks can create local variables that don't have a FunctionDecl
11379     // LexicalContext.
11380     if (!LexicalContext)
11381       return GVA_DiscardableODR;
11382 
11383     // Otherwise, let the static local variable inherit its linkage from the
11384     // nearest enclosing function.
11385     auto StaticLocalLinkage =
11386         Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
11387 
11388     // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
11389     // be emitted in any object with references to the symbol for the object it
11390     // contains, whether inline or out-of-line."
11391     // Similar behavior is observed with MSVC. An alternative ABI could use
11392     // StrongODR/AvailableExternally to match the function, but none are
11393     // known/supported currently.
11394     if (StaticLocalLinkage == GVA_StrongODR ||
11395         StaticLocalLinkage == GVA_AvailableExternally)
11396       return GVA_DiscardableODR;
11397     return StaticLocalLinkage;
11398   }
11399 
11400   // MSVC treats in-class initialized static data members as definitions.
11401   // By giving them non-strong linkage, out-of-line definitions won't
11402   // cause link errors.
11403   if (Context.isMSStaticDataMemberInlineDefinition(VD))
11404     return GVA_DiscardableODR;
11405 
11406   // Most non-template variables have strong linkage; inline variables are
11407   // linkonce_odr or (occasionally, for compatibility) weak_odr.
11408   GVALinkage StrongLinkage;
11409   switch (Context.getInlineVariableDefinitionKind(VD)) {
11410   case ASTContext::InlineVariableDefinitionKind::None:
11411     StrongLinkage = GVA_StrongExternal;
11412     break;
11413   case ASTContext::InlineVariableDefinitionKind::Weak:
11414   case ASTContext::InlineVariableDefinitionKind::WeakUnknown:
11415     StrongLinkage = GVA_DiscardableODR;
11416     break;
11417   case ASTContext::InlineVariableDefinitionKind::Strong:
11418     StrongLinkage = GVA_StrongODR;
11419     break;
11420   }
11421 
11422   switch (VD->getTemplateSpecializationKind()) {
11423   case TSK_Undeclared:
11424     return StrongLinkage;
11425 
11426   case TSK_ExplicitSpecialization:
11427     return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
11428                    VD->isStaticDataMember()
11429                ? GVA_StrongODR
11430                : StrongLinkage;
11431 
11432   case TSK_ExplicitInstantiationDefinition:
11433     return GVA_StrongODR;
11434 
11435   case TSK_ExplicitInstantiationDeclaration:
11436     return GVA_AvailableExternally;
11437 
11438   case TSK_ImplicitInstantiation:
11439     return GVA_DiscardableODR;
11440   }
11441 
11442   llvm_unreachable("Invalid Linkage!");
11443 }
11444 
11445 GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
11446   return adjustGVALinkageForExternalDefinitionKind(*this, VD,
11447            adjustGVALinkageForAttributes(*this, VD,
11448              basicGVALinkageForVariable(*this, VD)));
11449 }
11450 
11451 bool ASTContext::DeclMustBeEmitted(const Decl *D) {
11452   if (const auto *VD = dyn_cast<VarDecl>(D)) {
11453     if (!VD->isFileVarDecl())
11454       return false;
11455     // Global named register variables (GNU extension) are never emitted.
11456     if (VD->getStorageClass() == SC_Register)
11457       return false;
11458     if (VD->getDescribedVarTemplate() ||
11459         isa<VarTemplatePartialSpecializationDecl>(VD))
11460       return false;
11461   } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
11462     // We never need to emit an uninstantiated function template.
11463     if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
11464       return false;
11465   } else if (isa<PragmaCommentDecl>(D))
11466     return true;
11467   else if (isa<PragmaDetectMismatchDecl>(D))
11468     return true;
11469   else if (isa<OMPRequiresDecl>(D))
11470     return true;
11471   else if (isa<OMPThreadPrivateDecl>(D))
11472     return !D->getDeclContext()->isDependentContext();
11473   else if (isa<OMPAllocateDecl>(D))
11474     return !D->getDeclContext()->isDependentContext();
11475   else if (isa<OMPDeclareReductionDecl>(D) || isa<OMPDeclareMapperDecl>(D))
11476     return !D->getDeclContext()->isDependentContext();
11477   else if (isa<ImportDecl>(D))
11478     return true;
11479   else
11480     return false;
11481 
11482   // If this is a member of a class template, we do not need to emit it.
11483   if (D->getDeclContext()->isDependentContext())
11484     return false;
11485 
11486   // Weak references don't produce any output by themselves.
11487   if (D->hasAttr<WeakRefAttr>())
11488     return false;
11489 
11490   // Aliases and used decls are required.
11491   if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
11492     return true;
11493 
11494   if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
11495     // Forward declarations aren't required.
11496     if (!FD->doesThisDeclarationHaveABody())
11497       return FD->doesDeclarationForceExternallyVisibleDefinition();
11498 
11499     // Constructors and destructors are required.
11500     if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
11501       return true;
11502 
11503     // The key function for a class is required.  This rule only comes
11504     // into play when inline functions can be key functions, though.
11505     if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
11506       if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
11507         const CXXRecordDecl *RD = MD->getParent();
11508         if (MD->isOutOfLine() && RD->isDynamicClass()) {
11509           const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
11510           if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
11511             return true;
11512         }
11513       }
11514     }
11515 
11516     GVALinkage Linkage = GetGVALinkageForFunction(FD);
11517 
11518     // static, static inline, always_inline, and extern inline functions can
11519     // always be deferred.  Normal inline functions can be deferred in C99/C++.
11520     // Implicit template instantiations can also be deferred in C++.
11521     return !isDiscardableGVALinkage(Linkage);
11522   }
11523 
11524   const auto *VD = cast<VarDecl>(D);
11525   assert(VD->isFileVarDecl() && "Expected file scoped var");
11526 
11527   // If the decl is marked as `declare target to`, it should be emitted for the
11528   // host and for the device.
11529   if (LangOpts.OpenMP &&
11530       OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
11531     return true;
11532 
11533   if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
11534       !isMSStaticDataMemberInlineDefinition(VD))
11535     return false;
11536 
11537   // Variables that can be needed in other TUs are required.
11538   auto Linkage = GetGVALinkageForVariable(VD);
11539   if (!isDiscardableGVALinkage(Linkage))
11540     return true;
11541 
11542   // We never need to emit a variable that is available in another TU.
11543   if (Linkage == GVA_AvailableExternally)
11544     return false;
11545 
11546   // Variables that have destruction with side-effects are required.
11547   if (VD->needsDestruction(*this))
11548     return true;
11549 
11550   // Variables that have initialization with side-effects are required.
11551   if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
11552       // We can get a value-dependent initializer during error recovery.
11553       (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
11554     return true;
11555 
11556   // Likewise, variables with tuple-like bindings are required if their
11557   // bindings have side-effects.
11558   if (const auto *DD = dyn_cast<DecompositionDecl>(VD))
11559     for (const auto *BD : DD->bindings())
11560       if (const auto *BindingVD = BD->getHoldingVar())
11561         if (DeclMustBeEmitted(BindingVD))
11562           return true;
11563 
11564   return false;
11565 }
11566 
11567 void ASTContext::forEachMultiversionedFunctionVersion(
11568     const FunctionDecl *FD,
11569     llvm::function_ref<void(FunctionDecl *)> Pred) const {
11570   assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
11571   llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
11572   FD = FD->getMostRecentDecl();
11573   // FIXME: The order of traversal here matters and depends on the order of
11574   // lookup results, which happens to be (mostly) oldest-to-newest, but we
11575   // shouldn't rely on that.
11576   for (auto *CurDecl :
11577        FD->getDeclContext()->getRedeclContext()->lookup(FD->getDeclName())) {
11578     FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl();
11579     if (CurFD && hasSameType(CurFD->getType(), FD->getType()) &&
11580         std::end(SeenDecls) == llvm::find(SeenDecls, CurFD)) {
11581       SeenDecls.insert(CurFD);
11582       Pred(CurFD);
11583     }
11584   }
11585 }
11586 
11587 CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
11588                                                     bool IsCXXMethod,
11589                                                     bool IsBuiltin) const {
11590   // Pass through to the C++ ABI object
11591   if (IsCXXMethod)
11592     return ABI->getDefaultMethodCallConv(IsVariadic);
11593 
11594   // Builtins ignore user-specified default calling convention and remain the
11595   // Target's default calling convention.
11596   if (!IsBuiltin) {
11597     switch (LangOpts.getDefaultCallingConv()) {
11598     case LangOptions::DCC_None:
11599       break;
11600     case LangOptions::DCC_CDecl:
11601       return CC_C;
11602     case LangOptions::DCC_FastCall:
11603       if (getTargetInfo().hasFeature("sse2") && !IsVariadic)
11604         return CC_X86FastCall;
11605       break;
11606     case LangOptions::DCC_StdCall:
11607       if (!IsVariadic)
11608         return CC_X86StdCall;
11609       break;
11610     case LangOptions::DCC_VectorCall:
11611       // __vectorcall cannot be applied to variadic functions.
11612       if (!IsVariadic)
11613         return CC_X86VectorCall;
11614       break;
11615     case LangOptions::DCC_RegCall:
11616       // __regcall cannot be applied to variadic functions.
11617       if (!IsVariadic)
11618         return CC_X86RegCall;
11619       break;
11620     }
11621   }
11622   return Target->getDefaultCallingConv();
11623 }
11624 
11625 bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
11626   // Pass through to the C++ ABI object
11627   return ABI->isNearlyEmpty(RD);
11628 }
11629 
11630 VTableContextBase *ASTContext::getVTableContext() {
11631   if (!VTContext.get()) {
11632     auto ABI = Target->getCXXABI();
11633     if (ABI.isMicrosoft())
11634       VTContext.reset(new MicrosoftVTableContext(*this));
11635     else {
11636       auto ComponentLayout = getLangOpts().RelativeCXXABIVTables
11637                                  ? ItaniumVTableContext::Relative
11638                                  : ItaniumVTableContext::Pointer;
11639       VTContext.reset(new ItaniumVTableContext(*this, ComponentLayout));
11640     }
11641   }
11642   return VTContext.get();
11643 }
11644 
11645 MangleContext *ASTContext::createMangleContext(const TargetInfo *T) {
11646   if (!T)
11647     T = Target;
11648   switch (T->getCXXABI().getKind()) {
11649   case TargetCXXABI::AppleARM64:
11650   case TargetCXXABI::Fuchsia:
11651   case TargetCXXABI::GenericAArch64:
11652   case TargetCXXABI::GenericItanium:
11653   case TargetCXXABI::GenericARM:
11654   case TargetCXXABI::GenericMIPS:
11655   case TargetCXXABI::iOS:
11656   case TargetCXXABI::WebAssembly:
11657   case TargetCXXABI::WatchOS:
11658   case TargetCXXABI::XL:
11659     return ItaniumMangleContext::create(*this, getDiagnostics());
11660   case TargetCXXABI::Microsoft:
11661     return MicrosoftMangleContext::create(*this, getDiagnostics());
11662   }
11663   llvm_unreachable("Unsupported ABI");
11664 }
11665 
11666 MangleContext *ASTContext::createDeviceMangleContext(const TargetInfo &T) {
11667   assert(T.getCXXABI().getKind() != TargetCXXABI::Microsoft &&
11668          "Device mangle context does not support Microsoft mangling.");
11669   switch (T.getCXXABI().getKind()) {
11670   case TargetCXXABI::AppleARM64:
11671   case TargetCXXABI::Fuchsia:
11672   case TargetCXXABI::GenericAArch64:
11673   case TargetCXXABI::GenericItanium:
11674   case TargetCXXABI::GenericARM:
11675   case TargetCXXABI::GenericMIPS:
11676   case TargetCXXABI::iOS:
11677   case TargetCXXABI::WebAssembly:
11678   case TargetCXXABI::WatchOS:
11679   case TargetCXXABI::XL:
11680     return ItaniumMangleContext::create(
11681         *this, getDiagnostics(),
11682         [](ASTContext &, const NamedDecl *ND) -> llvm::Optional<unsigned> {
11683           if (const auto *RD = dyn_cast<CXXRecordDecl>(ND))
11684             return RD->getDeviceLambdaManglingNumber();
11685           return llvm::None;
11686         });
11687   case TargetCXXABI::Microsoft:
11688     return MicrosoftMangleContext::create(*this, getDiagnostics());
11689   }
11690   llvm_unreachable("Unsupported ABI");
11691 }
11692 
11693 CXXABI::~CXXABI() = default;
11694 
11695 size_t ASTContext::getSideTableAllocatedMemory() const {
11696   return ASTRecordLayouts.getMemorySize() +
11697          llvm::capacity_in_bytes(ObjCLayouts) +
11698          llvm::capacity_in_bytes(KeyFunctions) +
11699          llvm::capacity_in_bytes(ObjCImpls) +
11700          llvm::capacity_in_bytes(BlockVarCopyInits) +
11701          llvm::capacity_in_bytes(DeclAttrs) +
11702          llvm::capacity_in_bytes(TemplateOrInstantiation) +
11703          llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
11704          llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
11705          llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
11706          llvm::capacity_in_bytes(OverriddenMethods) +
11707          llvm::capacity_in_bytes(Types) +
11708          llvm::capacity_in_bytes(VariableArrayTypes);
11709 }
11710 
11711 /// getIntTypeForBitwidth -
11712 /// sets integer QualTy according to specified details:
11713 /// bitwidth, signed/unsigned.
11714 /// Returns empty type if there is no appropriate target types.
11715 QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
11716                                            unsigned Signed) const {
11717   TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
11718   CanQualType QualTy = getFromTargetType(Ty);
11719   if (!QualTy && DestWidth == 128)
11720     return Signed ? Int128Ty : UnsignedInt128Ty;
11721   return QualTy;
11722 }
11723 
11724 /// getRealTypeForBitwidth -
11725 /// sets floating point QualTy according to specified bitwidth.
11726 /// Returns empty type if there is no appropriate target types.
11727 QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth,
11728                                             FloatModeKind ExplicitType) const {
11729   FloatModeKind Ty =
11730       getTargetInfo().getRealTypeByWidth(DestWidth, ExplicitType);
11731   switch (Ty) {
11732   case FloatModeKind::Float:
11733     return FloatTy;
11734   case FloatModeKind::Double:
11735     return DoubleTy;
11736   case FloatModeKind::LongDouble:
11737     return LongDoubleTy;
11738   case FloatModeKind::Float128:
11739     return Float128Ty;
11740   case FloatModeKind::Ibm128:
11741     return Ibm128Ty;
11742   case FloatModeKind::NoFloat:
11743     return {};
11744   }
11745 
11746   llvm_unreachable("Unhandled TargetInfo::RealType value");
11747 }
11748 
11749 void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
11750   if (Number > 1)
11751     MangleNumbers[ND] = Number;
11752 }
11753 
11754 unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
11755   auto I = MangleNumbers.find(ND);
11756   return I != MangleNumbers.end() ? I->second : 1;
11757 }
11758 
11759 void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
11760   if (Number > 1)
11761     StaticLocalNumbers[VD] = Number;
11762 }
11763 
11764 unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
11765   auto I = StaticLocalNumbers.find(VD);
11766   return I != StaticLocalNumbers.end() ? I->second : 1;
11767 }
11768 
11769 MangleNumberingContext &
11770 ASTContext::getManglingNumberContext(const DeclContext *DC) {
11771   assert(LangOpts.CPlusPlus);  // We don't need mangling numbers for plain C.
11772   std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
11773   if (!MCtx)
11774     MCtx = createMangleNumberingContext();
11775   return *MCtx;
11776 }
11777 
11778 MangleNumberingContext &
11779 ASTContext::getManglingNumberContext(NeedExtraManglingDecl_t, const Decl *D) {
11780   assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
11781   std::unique_ptr<MangleNumberingContext> &MCtx =
11782       ExtraMangleNumberingContexts[D];
11783   if (!MCtx)
11784     MCtx = createMangleNumberingContext();
11785   return *MCtx;
11786 }
11787 
11788 std::unique_ptr<MangleNumberingContext>
11789 ASTContext::createMangleNumberingContext() const {
11790   return ABI->createMangleNumberingContext();
11791 }
11792 
11793 const CXXConstructorDecl *
11794 ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
11795   return ABI->getCopyConstructorForExceptionObject(
11796       cast<CXXRecordDecl>(RD->getFirstDecl()));
11797 }
11798 
11799 void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
11800                                                       CXXConstructorDecl *CD) {
11801   return ABI->addCopyConstructorForExceptionObject(
11802       cast<CXXRecordDecl>(RD->getFirstDecl()),
11803       cast<CXXConstructorDecl>(CD->getFirstDecl()));
11804 }
11805 
11806 void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
11807                                                  TypedefNameDecl *DD) {
11808   return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
11809 }
11810 
11811 TypedefNameDecl *
11812 ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
11813   return ABI->getTypedefNameForUnnamedTagDecl(TD);
11814 }
11815 
11816 void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
11817                                                 DeclaratorDecl *DD) {
11818   return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
11819 }
11820 
11821 DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
11822   return ABI->getDeclaratorForUnnamedTagDecl(TD);
11823 }
11824 
11825 void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
11826   ParamIndices[D] = index;
11827 }
11828 
11829 unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
11830   ParameterIndexTable::const_iterator I = ParamIndices.find(D);
11831   assert(I != ParamIndices.end() &&
11832          "ParmIndices lacks entry set by ParmVarDecl");
11833   return I->second;
11834 }
11835 
11836 QualType ASTContext::getStringLiteralArrayType(QualType EltTy,
11837                                                unsigned Length) const {
11838   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
11839   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
11840     EltTy = EltTy.withConst();
11841 
11842   EltTy = adjustStringLiteralBaseType(EltTy);
11843 
11844   // Get an array type for the string, according to C99 6.4.5. This includes
11845   // the null terminator character.
11846   return getConstantArrayType(EltTy, llvm::APInt(32, Length + 1), nullptr,
11847                               ArrayType::Normal, /*IndexTypeQuals*/ 0);
11848 }
11849 
11850 StringLiteral *
11851 ASTContext::getPredefinedStringLiteralFromCache(StringRef Key) const {
11852   StringLiteral *&Result = StringLiteralCache[Key];
11853   if (!Result)
11854     Result = StringLiteral::Create(
11855         *this, Key, StringLiteral::Ascii,
11856         /*Pascal*/ false, getStringLiteralArrayType(CharTy, Key.size()),
11857         SourceLocation());
11858   return Result;
11859 }
11860 
11861 MSGuidDecl *
11862 ASTContext::getMSGuidDecl(MSGuidDecl::Parts Parts) const {
11863   assert(MSGuidTagDecl && "building MS GUID without MS extensions?");
11864 
11865   llvm::FoldingSetNodeID ID;
11866   MSGuidDecl::Profile(ID, Parts);
11867 
11868   void *InsertPos;
11869   if (MSGuidDecl *Existing = MSGuidDecls.FindNodeOrInsertPos(ID, InsertPos))
11870     return Existing;
11871 
11872   QualType GUIDType = getMSGuidType().withConst();
11873   MSGuidDecl *New = MSGuidDecl::Create(*this, GUIDType, Parts);
11874   MSGuidDecls.InsertNode(New, InsertPos);
11875   return New;
11876 }
11877 
11878 UnnamedGlobalConstantDecl *
11879 ASTContext::getUnnamedGlobalConstantDecl(QualType Ty,
11880                                          const APValue &APVal) const {
11881   llvm::FoldingSetNodeID ID;
11882   UnnamedGlobalConstantDecl::Profile(ID, Ty, APVal);
11883 
11884   void *InsertPos;
11885   if (UnnamedGlobalConstantDecl *Existing =
11886           UnnamedGlobalConstantDecls.FindNodeOrInsertPos(ID, InsertPos))
11887     return Existing;
11888 
11889   UnnamedGlobalConstantDecl *New =
11890       UnnamedGlobalConstantDecl::Create(*this, Ty, APVal);
11891   UnnamedGlobalConstantDecls.InsertNode(New, InsertPos);
11892   return New;
11893 }
11894 
11895 TemplateParamObjectDecl *
11896 ASTContext::getTemplateParamObjectDecl(QualType T, const APValue &V) const {
11897   assert(T->isRecordType() && "template param object of unexpected type");
11898 
11899   // C++ [temp.param]p8:
11900   //   [...] a static storage duration object of type 'const T' [...]
11901   T.addConst();
11902 
11903   llvm::FoldingSetNodeID ID;
11904   TemplateParamObjectDecl::Profile(ID, T, V);
11905 
11906   void *InsertPos;
11907   if (TemplateParamObjectDecl *Existing =
11908           TemplateParamObjectDecls.FindNodeOrInsertPos(ID, InsertPos))
11909     return Existing;
11910 
11911   TemplateParamObjectDecl *New = TemplateParamObjectDecl::Create(*this, T, V);
11912   TemplateParamObjectDecls.InsertNode(New, InsertPos);
11913   return New;
11914 }
11915 
11916 bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
11917   const llvm::Triple &T = getTargetInfo().getTriple();
11918   if (!T.isOSDarwin())
11919     return false;
11920 
11921   if (!(T.isiOS() && T.isOSVersionLT(7)) &&
11922       !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
11923     return false;
11924 
11925   QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
11926   CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
11927   uint64_t Size = sizeChars.getQuantity();
11928   CharUnits alignChars = getTypeAlignInChars(AtomicTy);
11929   unsigned Align = alignChars.getQuantity();
11930   unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
11931   return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
11932 }
11933 
11934 bool
11935 ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
11936                                 const ObjCMethodDecl *MethodImpl) {
11937   // No point trying to match an unavailable/deprecated mothod.
11938   if (MethodDecl->hasAttr<UnavailableAttr>()
11939       || MethodDecl->hasAttr<DeprecatedAttr>())
11940     return false;
11941   if (MethodDecl->getObjCDeclQualifier() !=
11942       MethodImpl->getObjCDeclQualifier())
11943     return false;
11944   if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
11945     return false;
11946 
11947   if (MethodDecl->param_size() != MethodImpl->param_size())
11948     return false;
11949 
11950   for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
11951        IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
11952        EF = MethodDecl->param_end();
11953        IM != EM && IF != EF; ++IM, ++IF) {
11954     const ParmVarDecl *DeclVar = (*IF);
11955     const ParmVarDecl *ImplVar = (*IM);
11956     if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
11957       return false;
11958     if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
11959       return false;
11960   }
11961 
11962   return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
11963 }
11964 
11965 uint64_t ASTContext::getTargetNullPointerValue(QualType QT) const {
11966   LangAS AS;
11967   if (QT->getUnqualifiedDesugaredType()->isNullPtrType())
11968     AS = LangAS::Default;
11969   else
11970     AS = QT->getPointeeType().getAddressSpace();
11971 
11972   return getTargetInfo().getNullPointerValue(AS);
11973 }
11974 
11975 unsigned ASTContext::getTargetAddressSpace(QualType T) const {
11976   // Return the address space for the type. If the type is a
11977   // function type without an address space qualifier, the
11978   // program address space is used. Otherwise, the target picks
11979   // the best address space based on the type information
11980   return T->isFunctionType() && !T.hasAddressSpace()
11981              ? getTargetInfo().getProgramAddressSpace()
11982              : getTargetAddressSpace(T.getQualifiers());
11983 }
11984 
11985 unsigned ASTContext::getTargetAddressSpace(Qualifiers Q) const {
11986   return getTargetAddressSpace(Q.getAddressSpace());
11987 }
11988 
11989 unsigned ASTContext::getTargetAddressSpace(LangAS AS) const {
11990   if (isTargetAddressSpace(AS))
11991     return toTargetAddressSpace(AS);
11992   else
11993     return (*AddrSpaceMap)[(unsigned)AS];
11994 }
11995 
11996 QualType ASTContext::getCorrespondingSaturatedType(QualType Ty) const {
11997   assert(Ty->isFixedPointType());
11998 
11999   if (Ty->isSaturatedFixedPointType()) return Ty;
12000 
12001   switch (Ty->castAs<BuiltinType>()->getKind()) {
12002     default:
12003       llvm_unreachable("Not a fixed point type!");
12004     case BuiltinType::ShortAccum:
12005       return SatShortAccumTy;
12006     case BuiltinType::Accum:
12007       return SatAccumTy;
12008     case BuiltinType::LongAccum:
12009       return SatLongAccumTy;
12010     case BuiltinType::UShortAccum:
12011       return SatUnsignedShortAccumTy;
12012     case BuiltinType::UAccum:
12013       return SatUnsignedAccumTy;
12014     case BuiltinType::ULongAccum:
12015       return SatUnsignedLongAccumTy;
12016     case BuiltinType::ShortFract:
12017       return SatShortFractTy;
12018     case BuiltinType::Fract:
12019       return SatFractTy;
12020     case BuiltinType::LongFract:
12021       return SatLongFractTy;
12022     case BuiltinType::UShortFract:
12023       return SatUnsignedShortFractTy;
12024     case BuiltinType::UFract:
12025       return SatUnsignedFractTy;
12026     case BuiltinType::ULongFract:
12027       return SatUnsignedLongFractTy;
12028   }
12029 }
12030 
12031 LangAS ASTContext::getLangASForBuiltinAddressSpace(unsigned AS) const {
12032   if (LangOpts.OpenCL)
12033     return getTargetInfo().getOpenCLBuiltinAddressSpace(AS);
12034 
12035   if (LangOpts.CUDA)
12036     return getTargetInfo().getCUDABuiltinAddressSpace(AS);
12037 
12038   return getLangASFromTargetAS(AS);
12039 }
12040 
12041 // Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
12042 // doesn't include ASTContext.h
12043 template
12044 clang::LazyGenerationalUpdatePtr<
12045     const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
12046 clang::LazyGenerationalUpdatePtr<
12047     const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
12048         const clang::ASTContext &Ctx, Decl *Value);
12049 
12050 unsigned char ASTContext::getFixedPointScale(QualType Ty) const {
12051   assert(Ty->isFixedPointType());
12052 
12053   const TargetInfo &Target = getTargetInfo();
12054   switch (Ty->castAs<BuiltinType>()->getKind()) {
12055     default:
12056       llvm_unreachable("Not a fixed point type!");
12057     case BuiltinType::ShortAccum:
12058     case BuiltinType::SatShortAccum:
12059       return Target.getShortAccumScale();
12060     case BuiltinType::Accum:
12061     case BuiltinType::SatAccum:
12062       return Target.getAccumScale();
12063     case BuiltinType::LongAccum:
12064     case BuiltinType::SatLongAccum:
12065       return Target.getLongAccumScale();
12066     case BuiltinType::UShortAccum:
12067     case BuiltinType::SatUShortAccum:
12068       return Target.getUnsignedShortAccumScale();
12069     case BuiltinType::UAccum:
12070     case BuiltinType::SatUAccum:
12071       return Target.getUnsignedAccumScale();
12072     case BuiltinType::ULongAccum:
12073     case BuiltinType::SatULongAccum:
12074       return Target.getUnsignedLongAccumScale();
12075     case BuiltinType::ShortFract:
12076     case BuiltinType::SatShortFract:
12077       return Target.getShortFractScale();
12078     case BuiltinType::Fract:
12079     case BuiltinType::SatFract:
12080       return Target.getFractScale();
12081     case BuiltinType::LongFract:
12082     case BuiltinType::SatLongFract:
12083       return Target.getLongFractScale();
12084     case BuiltinType::UShortFract:
12085     case BuiltinType::SatUShortFract:
12086       return Target.getUnsignedShortFractScale();
12087     case BuiltinType::UFract:
12088     case BuiltinType::SatUFract:
12089       return Target.getUnsignedFractScale();
12090     case BuiltinType::ULongFract:
12091     case BuiltinType::SatULongFract:
12092       return Target.getUnsignedLongFractScale();
12093   }
12094 }
12095 
12096 unsigned char ASTContext::getFixedPointIBits(QualType Ty) const {
12097   assert(Ty->isFixedPointType());
12098 
12099   const TargetInfo &Target = getTargetInfo();
12100   switch (Ty->castAs<BuiltinType>()->getKind()) {
12101     default:
12102       llvm_unreachable("Not a fixed point type!");
12103     case BuiltinType::ShortAccum:
12104     case BuiltinType::SatShortAccum:
12105       return Target.getShortAccumIBits();
12106     case BuiltinType::Accum:
12107     case BuiltinType::SatAccum:
12108       return Target.getAccumIBits();
12109     case BuiltinType::LongAccum:
12110     case BuiltinType::SatLongAccum:
12111       return Target.getLongAccumIBits();
12112     case BuiltinType::UShortAccum:
12113     case BuiltinType::SatUShortAccum:
12114       return Target.getUnsignedShortAccumIBits();
12115     case BuiltinType::UAccum:
12116     case BuiltinType::SatUAccum:
12117       return Target.getUnsignedAccumIBits();
12118     case BuiltinType::ULongAccum:
12119     case BuiltinType::SatULongAccum:
12120       return Target.getUnsignedLongAccumIBits();
12121     case BuiltinType::ShortFract:
12122     case BuiltinType::SatShortFract:
12123     case BuiltinType::Fract:
12124     case BuiltinType::SatFract:
12125     case BuiltinType::LongFract:
12126     case BuiltinType::SatLongFract:
12127     case BuiltinType::UShortFract:
12128     case BuiltinType::SatUShortFract:
12129     case BuiltinType::UFract:
12130     case BuiltinType::SatUFract:
12131     case BuiltinType::ULongFract:
12132     case BuiltinType::SatULongFract:
12133       return 0;
12134   }
12135 }
12136 
12137 llvm::FixedPointSemantics
12138 ASTContext::getFixedPointSemantics(QualType Ty) const {
12139   assert((Ty->isFixedPointType() || Ty->isIntegerType()) &&
12140          "Can only get the fixed point semantics for a "
12141          "fixed point or integer type.");
12142   if (Ty->isIntegerType())
12143     return llvm::FixedPointSemantics::GetIntegerSemantics(
12144         getIntWidth(Ty), Ty->isSignedIntegerType());
12145 
12146   bool isSigned = Ty->isSignedFixedPointType();
12147   return llvm::FixedPointSemantics(
12148       static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned,
12149       Ty->isSaturatedFixedPointType(),
12150       !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding());
12151 }
12152 
12153 llvm::APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const {
12154   assert(Ty->isFixedPointType());
12155   return llvm::APFixedPoint::getMax(getFixedPointSemantics(Ty));
12156 }
12157 
12158 llvm::APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const {
12159   assert(Ty->isFixedPointType());
12160   return llvm::APFixedPoint::getMin(getFixedPointSemantics(Ty));
12161 }
12162 
12163 QualType ASTContext::getCorrespondingSignedFixedPointType(QualType Ty) const {
12164   assert(Ty->isUnsignedFixedPointType() &&
12165          "Expected unsigned fixed point type");
12166 
12167   switch (Ty->castAs<BuiltinType>()->getKind()) {
12168   case BuiltinType::UShortAccum:
12169     return ShortAccumTy;
12170   case BuiltinType::UAccum:
12171     return AccumTy;
12172   case BuiltinType::ULongAccum:
12173     return LongAccumTy;
12174   case BuiltinType::SatUShortAccum:
12175     return SatShortAccumTy;
12176   case BuiltinType::SatUAccum:
12177     return SatAccumTy;
12178   case BuiltinType::SatULongAccum:
12179     return SatLongAccumTy;
12180   case BuiltinType::UShortFract:
12181     return ShortFractTy;
12182   case BuiltinType::UFract:
12183     return FractTy;
12184   case BuiltinType::ULongFract:
12185     return LongFractTy;
12186   case BuiltinType::SatUShortFract:
12187     return SatShortFractTy;
12188   case BuiltinType::SatUFract:
12189     return SatFractTy;
12190   case BuiltinType::SatULongFract:
12191     return SatLongFractTy;
12192   default:
12193     llvm_unreachable("Unexpected unsigned fixed point type");
12194   }
12195 }
12196 
12197 ParsedTargetAttr
12198 ASTContext::filterFunctionTargetAttrs(const TargetAttr *TD) const {
12199   assert(TD != nullptr);
12200   ParsedTargetAttr ParsedAttr = TD->parse();
12201 
12202   llvm::erase_if(ParsedAttr.Features, [&](const std::string &Feat) {
12203     return !Target->isValidFeatureName(StringRef{Feat}.substr(1));
12204   });
12205   return ParsedAttr;
12206 }
12207 
12208 void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
12209                                        const FunctionDecl *FD) const {
12210   if (FD)
12211     getFunctionFeatureMap(FeatureMap, GlobalDecl().getWithDecl(FD));
12212   else
12213     Target->initFeatureMap(FeatureMap, getDiagnostics(),
12214                            Target->getTargetOpts().CPU,
12215                            Target->getTargetOpts().Features);
12216 }
12217 
12218 // Fills in the supplied string map with the set of target features for the
12219 // passed in function.
12220 void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
12221                                        GlobalDecl GD) const {
12222   StringRef TargetCPU = Target->getTargetOpts().CPU;
12223   const FunctionDecl *FD = GD.getDecl()->getAsFunction();
12224   if (const auto *TD = FD->getAttr<TargetAttr>()) {
12225     ParsedTargetAttr ParsedAttr = filterFunctionTargetAttrs(TD);
12226 
12227     // Make a copy of the features as passed on the command line into the
12228     // beginning of the additional features from the function to override.
12229     ParsedAttr.Features.insert(
12230         ParsedAttr.Features.begin(),
12231         Target->getTargetOpts().FeaturesAsWritten.begin(),
12232         Target->getTargetOpts().FeaturesAsWritten.end());
12233 
12234     if (ParsedAttr.Architecture != "" &&
12235         Target->isValidCPUName(ParsedAttr.Architecture))
12236       TargetCPU = ParsedAttr.Architecture;
12237 
12238     // Now populate the feature map, first with the TargetCPU which is either
12239     // the default or a new one from the target attribute string. Then we'll use
12240     // the passed in features (FeaturesAsWritten) along with the new ones from
12241     // the attribute.
12242     Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU,
12243                            ParsedAttr.Features);
12244   } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) {
12245     llvm::SmallVector<StringRef, 32> FeaturesTmp;
12246     Target->getCPUSpecificCPUDispatchFeatures(
12247         SD->getCPUName(GD.getMultiVersionIndex())->getName(), FeaturesTmp);
12248     std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end());
12249     Features.insert(Features.begin(),
12250                     Target->getTargetOpts().FeaturesAsWritten.begin(),
12251                     Target->getTargetOpts().FeaturesAsWritten.end());
12252     Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
12253   } else if (const auto *TC = FD->getAttr<TargetClonesAttr>()) {
12254     std::vector<std::string> Features;
12255     StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
12256     if (VersionStr.startswith("arch="))
12257       TargetCPU = VersionStr.drop_front(sizeof("arch=") - 1);
12258     else if (VersionStr != "default")
12259       Features.push_back((StringRef{"+"} + VersionStr).str());
12260 
12261     Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
12262   } else {
12263     FeatureMap = Target->getTargetOpts().FeatureMap;
12264   }
12265 }
12266 
12267 OMPTraitInfo &ASTContext::getNewOMPTraitInfo() {
12268   OMPTraitInfoVector.emplace_back(new OMPTraitInfo());
12269   return *OMPTraitInfoVector.back();
12270 }
12271 
12272 const StreamingDiagnostic &clang::
12273 operator<<(const StreamingDiagnostic &DB,
12274            const ASTContext::SectionInfo &Section) {
12275   if (Section.Decl)
12276     return DB << Section.Decl;
12277   return DB << "a prior #pragma section";
12278 }
12279 
12280 bool ASTContext::mayExternalizeStaticVar(const Decl *D) const {
12281   bool IsStaticVar =
12282       isa<VarDecl>(D) && cast<VarDecl>(D)->getStorageClass() == SC_Static;
12283   bool IsExplicitDeviceVar = (D->hasAttr<CUDADeviceAttr>() &&
12284                               !D->getAttr<CUDADeviceAttr>()->isImplicit()) ||
12285                              (D->hasAttr<CUDAConstantAttr>() &&
12286                               !D->getAttr<CUDAConstantAttr>()->isImplicit());
12287   // CUDA/HIP: static managed variables need to be externalized since it is
12288   // a declaration in IR, therefore cannot have internal linkage.
12289   return IsStaticVar &&
12290          (D->hasAttr<HIPManagedAttr>() || IsExplicitDeviceVar);
12291 }
12292 
12293 bool ASTContext::shouldExternalizeStaticVar(const Decl *D) const {
12294   return mayExternalizeStaticVar(D) &&
12295          (D->hasAttr<HIPManagedAttr>() ||
12296           CUDADeviceVarODRUsedByHost.count(cast<VarDecl>(D)));
12297 }
12298 
12299 StringRef ASTContext::getCUIDHash() const {
12300   if (!CUIDHash.empty())
12301     return CUIDHash;
12302   if (LangOpts.CUID.empty())
12303     return StringRef();
12304   CUIDHash = llvm::utohexstr(llvm::MD5Hash(LangOpts.CUID), /*LowerCase=*/true);
12305   return CUIDHash;
12306 }
12307