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   case TemplateName::UsingTemplate:
6129     return DeclarationNameInfo(Name.getAsUsingShadowDecl()->getDeclName(),
6130                                NameLoc);
6131   }
6132 
6133   llvm_unreachable("bad template name kind!");
6134 }
6135 
6136 TemplateName
6137 ASTContext::getCanonicalTemplateName(const TemplateName &Name) const {
6138   switch (Name.getKind()) {
6139   case TemplateName::UsingTemplate:
6140   case TemplateName::QualifiedTemplate:
6141   case TemplateName::Template: {
6142     TemplateDecl *Template = Name.getAsTemplateDecl();
6143     if (auto *TTP  = dyn_cast<TemplateTemplateParmDecl>(Template))
6144       Template = getCanonicalTemplateTemplateParmDecl(TTP);
6145 
6146     // The canonical template name is the canonical template declaration.
6147     return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
6148   }
6149 
6150   case TemplateName::OverloadedTemplate:
6151   case TemplateName::AssumedTemplate:
6152     llvm_unreachable("cannot canonicalize unresolved template");
6153 
6154   case TemplateName::DependentTemplate: {
6155     DependentTemplateName *DTN = Name.getAsDependentTemplateName();
6156     assert(DTN && "Non-dependent template names must refer to template decls.");
6157     return DTN->CanonicalTemplateName;
6158   }
6159 
6160   case TemplateName::SubstTemplateTemplateParm: {
6161     SubstTemplateTemplateParmStorage *subst
6162       = Name.getAsSubstTemplateTemplateParm();
6163     return getCanonicalTemplateName(subst->getReplacement());
6164   }
6165 
6166   case TemplateName::SubstTemplateTemplateParmPack: {
6167     SubstTemplateTemplateParmPackStorage *subst
6168                                   = Name.getAsSubstTemplateTemplateParmPack();
6169     TemplateTemplateParmDecl *canonParameter
6170       = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
6171     TemplateArgument canonArgPack
6172       = getCanonicalTemplateArgument(subst->getArgumentPack());
6173     return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
6174   }
6175   }
6176 
6177   llvm_unreachable("bad template name!");
6178 }
6179 
6180 bool ASTContext::hasSameTemplateName(const TemplateName &X,
6181                                      const TemplateName &Y) const {
6182   return getCanonicalTemplateName(X).getAsVoidPointer() ==
6183          getCanonicalTemplateName(Y).getAsVoidPointer();
6184 }
6185 
6186 bool ASTContext::isSameTemplateParameter(const NamedDecl *X,
6187                                          const NamedDecl *Y) {
6188   if (X->getKind() != Y->getKind())
6189     return false;
6190 
6191   if (auto *TX = dyn_cast<TemplateTypeParmDecl>(X)) {
6192     auto *TY = cast<TemplateTypeParmDecl>(Y);
6193     if (TX->isParameterPack() != TY->isParameterPack())
6194       return false;
6195     if (TX->hasTypeConstraint() != TY->hasTypeConstraint())
6196       return false;
6197     const TypeConstraint *TXTC = TX->getTypeConstraint();
6198     const TypeConstraint *TYTC = TY->getTypeConstraint();
6199     if (!TXTC != !TYTC)
6200       return false;
6201     if (TXTC && TYTC) {
6202       auto *NCX = TXTC->getNamedConcept();
6203       auto *NCY = TYTC->getNamedConcept();
6204       if (!NCX || !NCY || !isSameEntity(NCX, NCY))
6205         return false;
6206       if (TXTC->hasExplicitTemplateArgs() != TYTC->hasExplicitTemplateArgs())
6207         return false;
6208       if (TXTC->hasExplicitTemplateArgs()) {
6209         auto *TXTCArgs = TXTC->getTemplateArgsAsWritten();
6210         auto *TYTCArgs = TYTC->getTemplateArgsAsWritten();
6211         if (TXTCArgs->NumTemplateArgs != TYTCArgs->NumTemplateArgs)
6212           return false;
6213         llvm::FoldingSetNodeID XID, YID;
6214         for (auto &ArgLoc : TXTCArgs->arguments())
6215           ArgLoc.getArgument().Profile(XID, X->getASTContext());
6216         for (auto &ArgLoc : TYTCArgs->arguments())
6217           ArgLoc.getArgument().Profile(YID, Y->getASTContext());
6218         if (XID != YID)
6219           return false;
6220       }
6221     }
6222     return true;
6223   }
6224 
6225   if (auto *TX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
6226     auto *TY = cast<NonTypeTemplateParmDecl>(Y);
6227     return TX->isParameterPack() == TY->isParameterPack() &&
6228            TX->getASTContext().hasSameType(TX->getType(), TY->getType());
6229   }
6230 
6231   auto *TX = cast<TemplateTemplateParmDecl>(X);
6232   auto *TY = cast<TemplateTemplateParmDecl>(Y);
6233   return TX->isParameterPack() == TY->isParameterPack() &&
6234          isSameTemplateParameterList(TX->getTemplateParameters(),
6235                                      TY->getTemplateParameters());
6236 }
6237 
6238 bool ASTContext::isSameTemplateParameterList(const TemplateParameterList *X,
6239                                              const TemplateParameterList *Y) {
6240   if (X->size() != Y->size())
6241     return false;
6242 
6243   for (unsigned I = 0, N = X->size(); I != N; ++I)
6244     if (!isSameTemplateParameter(X->getParam(I), Y->getParam(I)))
6245       return false;
6246 
6247   const Expr *XRC = X->getRequiresClause();
6248   const Expr *YRC = Y->getRequiresClause();
6249   if (!XRC != !YRC)
6250     return false;
6251   if (XRC) {
6252     llvm::FoldingSetNodeID XRCID, YRCID;
6253     XRC->Profile(XRCID, *this, /*Canonical=*/true);
6254     YRC->Profile(YRCID, *this, /*Canonical=*/true);
6255     if (XRCID != YRCID)
6256       return false;
6257   }
6258 
6259   return true;
6260 }
6261 
6262 static NamespaceDecl *getNamespace(const NestedNameSpecifier *X) {
6263   if (auto *NS = X->getAsNamespace())
6264     return NS;
6265   if (auto *NAS = X->getAsNamespaceAlias())
6266     return NAS->getNamespace();
6267   return nullptr;
6268 }
6269 
6270 static bool isSameQualifier(const NestedNameSpecifier *X,
6271                             const NestedNameSpecifier *Y) {
6272   if (auto *NSX = getNamespace(X)) {
6273     auto *NSY = getNamespace(Y);
6274     if (!NSY || NSX->getCanonicalDecl() != NSY->getCanonicalDecl())
6275       return false;
6276   } else if (X->getKind() != Y->getKind())
6277     return false;
6278 
6279   // FIXME: For namespaces and types, we're permitted to check that the entity
6280   // is named via the same tokens. We should probably do so.
6281   switch (X->getKind()) {
6282   case NestedNameSpecifier::Identifier:
6283     if (X->getAsIdentifier() != Y->getAsIdentifier())
6284       return false;
6285     break;
6286   case NestedNameSpecifier::Namespace:
6287   case NestedNameSpecifier::NamespaceAlias:
6288     // We've already checked that we named the same namespace.
6289     break;
6290   case NestedNameSpecifier::TypeSpec:
6291   case NestedNameSpecifier::TypeSpecWithTemplate:
6292     if (X->getAsType()->getCanonicalTypeInternal() !=
6293         Y->getAsType()->getCanonicalTypeInternal())
6294       return false;
6295     break;
6296   case NestedNameSpecifier::Global:
6297   case NestedNameSpecifier::Super:
6298     return true;
6299   }
6300 
6301   // Recurse into earlier portion of NNS, if any.
6302   auto *PX = X->getPrefix();
6303   auto *PY = Y->getPrefix();
6304   if (PX && PY)
6305     return isSameQualifier(PX, PY);
6306   return !PX && !PY;
6307 }
6308 
6309 /// Determine whether the attributes we can overload on are identical for A and
6310 /// B. Will ignore any overloadable attrs represented in the type of A and B.
6311 static bool hasSameOverloadableAttrs(const FunctionDecl *A,
6312                                      const FunctionDecl *B) {
6313   // Note that pass_object_size attributes are represented in the function's
6314   // ExtParameterInfo, so we don't need to check them here.
6315 
6316   llvm::FoldingSetNodeID Cand1ID, Cand2ID;
6317   auto AEnableIfAttrs = A->specific_attrs<EnableIfAttr>();
6318   auto BEnableIfAttrs = B->specific_attrs<EnableIfAttr>();
6319 
6320   for (auto Pair : zip_longest(AEnableIfAttrs, BEnableIfAttrs)) {
6321     Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
6322     Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
6323 
6324     // Return false if the number of enable_if attributes is different.
6325     if (!Cand1A || !Cand2A)
6326       return false;
6327 
6328     Cand1ID.clear();
6329     Cand2ID.clear();
6330 
6331     (*Cand1A)->getCond()->Profile(Cand1ID, A->getASTContext(), true);
6332     (*Cand2A)->getCond()->Profile(Cand2ID, B->getASTContext(), true);
6333 
6334     // Return false if any of the enable_if expressions of A and B are
6335     // different.
6336     if (Cand1ID != Cand2ID)
6337       return false;
6338   }
6339   return true;
6340 }
6341 
6342 bool ASTContext::isSameEntity(const NamedDecl *X, const NamedDecl *Y) {
6343   if (X == Y)
6344     return true;
6345 
6346   if (X->getDeclName() != Y->getDeclName())
6347     return false;
6348 
6349   // Must be in the same context.
6350   //
6351   // Note that we can't use DeclContext::Equals here, because the DeclContexts
6352   // could be two different declarations of the same function. (We will fix the
6353   // semantic DC to refer to the primary definition after merging.)
6354   if (!declaresSameEntity(cast<Decl>(X->getDeclContext()->getRedeclContext()),
6355                           cast<Decl>(Y->getDeclContext()->getRedeclContext())))
6356     return false;
6357 
6358   // Two typedefs refer to the same entity if they have the same underlying
6359   // type.
6360   if (const auto *TypedefX = dyn_cast<TypedefNameDecl>(X))
6361     if (const auto *TypedefY = dyn_cast<TypedefNameDecl>(Y))
6362       return hasSameType(TypedefX->getUnderlyingType(),
6363                          TypedefY->getUnderlyingType());
6364 
6365   // Must have the same kind.
6366   if (X->getKind() != Y->getKind())
6367     return false;
6368 
6369   // Objective-C classes and protocols with the same name always match.
6370   if (isa<ObjCInterfaceDecl>(X) || isa<ObjCProtocolDecl>(X))
6371     return true;
6372 
6373   if (isa<ClassTemplateSpecializationDecl>(X)) {
6374     // No need to handle these here: we merge them when adding them to the
6375     // template.
6376     return false;
6377   }
6378 
6379   // Compatible tags match.
6380   if (const auto *TagX = dyn_cast<TagDecl>(X)) {
6381     const auto *TagY = cast<TagDecl>(Y);
6382     return (TagX->getTagKind() == TagY->getTagKind()) ||
6383            ((TagX->getTagKind() == TTK_Struct ||
6384              TagX->getTagKind() == TTK_Class ||
6385              TagX->getTagKind() == TTK_Interface) &&
6386             (TagY->getTagKind() == TTK_Struct ||
6387              TagY->getTagKind() == TTK_Class ||
6388              TagY->getTagKind() == TTK_Interface));
6389   }
6390 
6391   // Functions with the same type and linkage match.
6392   // FIXME: This needs to cope with merging of prototyped/non-prototyped
6393   // functions, etc.
6394   if (const auto *FuncX = dyn_cast<FunctionDecl>(X)) {
6395     const auto *FuncY = cast<FunctionDecl>(Y);
6396     if (const auto *CtorX = dyn_cast<CXXConstructorDecl>(X)) {
6397       const auto *CtorY = cast<CXXConstructorDecl>(Y);
6398       if (CtorX->getInheritedConstructor() &&
6399           !isSameEntity(CtorX->getInheritedConstructor().getConstructor(),
6400                         CtorY->getInheritedConstructor().getConstructor()))
6401         return false;
6402     }
6403 
6404     if (FuncX->isMultiVersion() != FuncY->isMultiVersion())
6405       return false;
6406 
6407     // Multiversioned functions with different feature strings are represented
6408     // as separate declarations.
6409     if (FuncX->isMultiVersion()) {
6410       const auto *TAX = FuncX->getAttr<TargetAttr>();
6411       const auto *TAY = FuncY->getAttr<TargetAttr>();
6412       assert(TAX && TAY && "Multiversion Function without target attribute");
6413 
6414       if (TAX->getFeaturesStr() != TAY->getFeaturesStr())
6415         return false;
6416     }
6417 
6418     const Expr *XRC = FuncX->getTrailingRequiresClause();
6419     const Expr *YRC = FuncY->getTrailingRequiresClause();
6420     if (!XRC != !YRC)
6421       return false;
6422     if (XRC) {
6423       llvm::FoldingSetNodeID XRCID, YRCID;
6424       XRC->Profile(XRCID, *this, /*Canonical=*/true);
6425       YRC->Profile(YRCID, *this, /*Canonical=*/true);
6426       if (XRCID != YRCID)
6427         return false;
6428     }
6429 
6430     auto GetTypeAsWritten = [](const FunctionDecl *FD) {
6431       // Map to the first declaration that we've already merged into this one.
6432       // The TSI of redeclarations might not match (due to calling conventions
6433       // being inherited onto the type but not the TSI), but the TSI type of
6434       // the first declaration of the function should match across modules.
6435       FD = FD->getCanonicalDecl();
6436       return FD->getTypeSourceInfo() ? FD->getTypeSourceInfo()->getType()
6437                                      : FD->getType();
6438     };
6439     QualType XT = GetTypeAsWritten(FuncX), YT = GetTypeAsWritten(FuncY);
6440     if (!hasSameType(XT, YT)) {
6441       // We can get functions with different types on the redecl chain in C++17
6442       // if they have differing exception specifications and at least one of
6443       // the excpetion specs is unresolved.
6444       auto *XFPT = XT->getAs<FunctionProtoType>();
6445       auto *YFPT = YT->getAs<FunctionProtoType>();
6446       if (getLangOpts().CPlusPlus17 && XFPT && YFPT &&
6447           (isUnresolvedExceptionSpec(XFPT->getExceptionSpecType()) ||
6448            isUnresolvedExceptionSpec(YFPT->getExceptionSpecType())) &&
6449           // FIXME: We could make isSameEntity const after we make
6450           // hasSameFunctionTypeIgnoringExceptionSpec const.
6451           hasSameFunctionTypeIgnoringExceptionSpec(XT, YT))
6452         return true;
6453       return false;
6454     }
6455 
6456     return FuncX->getLinkageInternal() == FuncY->getLinkageInternal() &&
6457            hasSameOverloadableAttrs(FuncX, FuncY);
6458   }
6459 
6460   // Variables with the same type and linkage match.
6461   if (const auto *VarX = dyn_cast<VarDecl>(X)) {
6462     const auto *VarY = cast<VarDecl>(Y);
6463     if (VarX->getLinkageInternal() == VarY->getLinkageInternal()) {
6464       if (hasSameType(VarX->getType(), VarY->getType()))
6465         return true;
6466 
6467       // We can get decls with different types on the redecl chain. Eg.
6468       // template <typename T> struct S { static T Var[]; }; // #1
6469       // template <typename T> T S<T>::Var[sizeof(T)]; // #2
6470       // Only? happens when completing an incomplete array type. In this case
6471       // when comparing #1 and #2 we should go through their element type.
6472       const ArrayType *VarXTy = getAsArrayType(VarX->getType());
6473       const ArrayType *VarYTy = getAsArrayType(VarY->getType());
6474       if (!VarXTy || !VarYTy)
6475         return false;
6476       if (VarXTy->isIncompleteArrayType() || VarYTy->isIncompleteArrayType())
6477         return hasSameType(VarXTy->getElementType(), VarYTy->getElementType());
6478     }
6479     return false;
6480   }
6481 
6482   // Namespaces with the same name and inlinedness match.
6483   if (const auto *NamespaceX = dyn_cast<NamespaceDecl>(X)) {
6484     const auto *NamespaceY = cast<NamespaceDecl>(Y);
6485     return NamespaceX->isInline() == NamespaceY->isInline();
6486   }
6487 
6488   // Identical template names and kinds match if their template parameter lists
6489   // and patterns match.
6490   if (const auto *TemplateX = dyn_cast<TemplateDecl>(X)) {
6491     const auto *TemplateY = cast<TemplateDecl>(Y);
6492     return isSameEntity(TemplateX->getTemplatedDecl(),
6493                         TemplateY->getTemplatedDecl()) &&
6494            isSameTemplateParameterList(TemplateX->getTemplateParameters(),
6495                                        TemplateY->getTemplateParameters());
6496   }
6497 
6498   // Fields with the same name and the same type match.
6499   if (const auto *FDX = dyn_cast<FieldDecl>(X)) {
6500     const auto *FDY = cast<FieldDecl>(Y);
6501     // FIXME: Also check the bitwidth is odr-equivalent, if any.
6502     return hasSameType(FDX->getType(), FDY->getType());
6503   }
6504 
6505   // Indirect fields with the same target field match.
6506   if (const auto *IFDX = dyn_cast<IndirectFieldDecl>(X)) {
6507     const auto *IFDY = cast<IndirectFieldDecl>(Y);
6508     return IFDX->getAnonField()->getCanonicalDecl() ==
6509            IFDY->getAnonField()->getCanonicalDecl();
6510   }
6511 
6512   // Enumerators with the same name match.
6513   if (isa<EnumConstantDecl>(X))
6514     // FIXME: Also check the value is odr-equivalent.
6515     return true;
6516 
6517   // Using shadow declarations with the same target match.
6518   if (const auto *USX = dyn_cast<UsingShadowDecl>(X)) {
6519     const auto *USY = cast<UsingShadowDecl>(Y);
6520     return USX->getTargetDecl() == USY->getTargetDecl();
6521   }
6522 
6523   // Using declarations with the same qualifier match. (We already know that
6524   // the name matches.)
6525   if (const auto *UX = dyn_cast<UsingDecl>(X)) {
6526     const auto *UY = cast<UsingDecl>(Y);
6527     return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
6528            UX->hasTypename() == UY->hasTypename() &&
6529            UX->isAccessDeclaration() == UY->isAccessDeclaration();
6530   }
6531   if (const auto *UX = dyn_cast<UnresolvedUsingValueDecl>(X)) {
6532     const auto *UY = cast<UnresolvedUsingValueDecl>(Y);
6533     return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
6534            UX->isAccessDeclaration() == UY->isAccessDeclaration();
6535   }
6536   if (const auto *UX = dyn_cast<UnresolvedUsingTypenameDecl>(X)) {
6537     return isSameQualifier(
6538         UX->getQualifier(),
6539         cast<UnresolvedUsingTypenameDecl>(Y)->getQualifier());
6540   }
6541 
6542   // Using-pack declarations are only created by instantiation, and match if
6543   // they're instantiated from matching UnresolvedUsing...Decls.
6544   if (const auto *UX = dyn_cast<UsingPackDecl>(X)) {
6545     return declaresSameEntity(
6546         UX->getInstantiatedFromUsingDecl(),
6547         cast<UsingPackDecl>(Y)->getInstantiatedFromUsingDecl());
6548   }
6549 
6550   // Namespace alias definitions with the same target match.
6551   if (const auto *NAX = dyn_cast<NamespaceAliasDecl>(X)) {
6552     const auto *NAY = cast<NamespaceAliasDecl>(Y);
6553     return NAX->getNamespace()->Equals(NAY->getNamespace());
6554   }
6555 
6556   return false;
6557 }
6558 
6559 TemplateArgument
6560 ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
6561   switch (Arg.getKind()) {
6562     case TemplateArgument::Null:
6563       return Arg;
6564 
6565     case TemplateArgument::Expression:
6566       return Arg;
6567 
6568     case TemplateArgument::Declaration: {
6569       auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
6570       return TemplateArgument(D, Arg.getParamTypeForDecl());
6571     }
6572 
6573     case TemplateArgument::NullPtr:
6574       return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
6575                               /*isNullPtr*/true);
6576 
6577     case TemplateArgument::Template:
6578       return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
6579 
6580     case TemplateArgument::TemplateExpansion:
6581       return TemplateArgument(getCanonicalTemplateName(
6582                                          Arg.getAsTemplateOrTemplatePattern()),
6583                               Arg.getNumTemplateExpansions());
6584 
6585     case TemplateArgument::Integral:
6586       return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
6587 
6588     case TemplateArgument::Type:
6589       return TemplateArgument(getCanonicalType(Arg.getAsType()));
6590 
6591     case TemplateArgument::Pack: {
6592       if (Arg.pack_size() == 0)
6593         return Arg;
6594 
6595       auto *CanonArgs = new (*this) TemplateArgument[Arg.pack_size()];
6596       unsigned Idx = 0;
6597       for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
6598                                         AEnd = Arg.pack_end();
6599            A != AEnd; (void)++A, ++Idx)
6600         CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
6601 
6602       return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
6603     }
6604   }
6605 
6606   // Silence GCC warning
6607   llvm_unreachable("Unhandled template argument kind");
6608 }
6609 
6610 NestedNameSpecifier *
6611 ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
6612   if (!NNS)
6613     return nullptr;
6614 
6615   switch (NNS->getKind()) {
6616   case NestedNameSpecifier::Identifier:
6617     // Canonicalize the prefix but keep the identifier the same.
6618     return NestedNameSpecifier::Create(*this,
6619                          getCanonicalNestedNameSpecifier(NNS->getPrefix()),
6620                                        NNS->getAsIdentifier());
6621 
6622   case NestedNameSpecifier::Namespace:
6623     // A namespace is canonical; build a nested-name-specifier with
6624     // this namespace and no prefix.
6625     return NestedNameSpecifier::Create(*this, nullptr,
6626                                  NNS->getAsNamespace()->getOriginalNamespace());
6627 
6628   case NestedNameSpecifier::NamespaceAlias:
6629     // A namespace is canonical; build a nested-name-specifier with
6630     // this namespace and no prefix.
6631     return NestedNameSpecifier::Create(*this, nullptr,
6632                                     NNS->getAsNamespaceAlias()->getNamespace()
6633                                                       ->getOriginalNamespace());
6634 
6635   // The difference between TypeSpec and TypeSpecWithTemplate is that the
6636   // latter will have the 'template' keyword when printed.
6637   case NestedNameSpecifier::TypeSpec:
6638   case NestedNameSpecifier::TypeSpecWithTemplate: {
6639     const Type *T = getCanonicalType(NNS->getAsType());
6640 
6641     // If we have some kind of dependent-named type (e.g., "typename T::type"),
6642     // break it apart into its prefix and identifier, then reconsititute those
6643     // as the canonical nested-name-specifier. This is required to canonicalize
6644     // a dependent nested-name-specifier involving typedefs of dependent-name
6645     // types, e.g.,
6646     //   typedef typename T::type T1;
6647     //   typedef typename T1::type T2;
6648     if (const auto *DNT = T->getAs<DependentNameType>())
6649       return NestedNameSpecifier::Create(
6650           *this, DNT->getQualifier(),
6651           const_cast<IdentifierInfo *>(DNT->getIdentifier()));
6652     if (const auto *DTST = T->getAs<DependentTemplateSpecializationType>())
6653       return NestedNameSpecifier::Create(*this, DTST->getQualifier(), true,
6654                                          const_cast<Type *>(T));
6655 
6656     // TODO: Set 'Template' parameter to true for other template types.
6657     return NestedNameSpecifier::Create(*this, nullptr, false,
6658                                        const_cast<Type *>(T));
6659   }
6660 
6661   case NestedNameSpecifier::Global:
6662   case NestedNameSpecifier::Super:
6663     // The global specifier and __super specifer are canonical and unique.
6664     return NNS;
6665   }
6666 
6667   llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
6668 }
6669 
6670 const ArrayType *ASTContext::getAsArrayType(QualType T) const {
6671   // Handle the non-qualified case efficiently.
6672   if (!T.hasLocalQualifiers()) {
6673     // Handle the common positive case fast.
6674     if (const auto *AT = dyn_cast<ArrayType>(T))
6675       return AT;
6676   }
6677 
6678   // Handle the common negative case fast.
6679   if (!isa<ArrayType>(T.getCanonicalType()))
6680     return nullptr;
6681 
6682   // Apply any qualifiers from the array type to the element type.  This
6683   // implements C99 6.7.3p8: "If the specification of an array type includes
6684   // any type qualifiers, the element type is so qualified, not the array type."
6685 
6686   // If we get here, we either have type qualifiers on the type, or we have
6687   // sugar such as a typedef in the way.  If we have type qualifiers on the type
6688   // we must propagate them down into the element type.
6689 
6690   SplitQualType split = T.getSplitDesugaredType();
6691   Qualifiers qs = split.Quals;
6692 
6693   // If we have a simple case, just return now.
6694   const auto *ATy = dyn_cast<ArrayType>(split.Ty);
6695   if (!ATy || qs.empty())
6696     return ATy;
6697 
6698   // Otherwise, we have an array and we have qualifiers on it.  Push the
6699   // qualifiers into the array element type and return a new array type.
6700   QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
6701 
6702   if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy))
6703     return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
6704                                                 CAT->getSizeExpr(),
6705                                                 CAT->getSizeModifier(),
6706                                            CAT->getIndexTypeCVRQualifiers()));
6707   if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy))
6708     return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
6709                                                   IAT->getSizeModifier(),
6710                                            IAT->getIndexTypeCVRQualifiers()));
6711 
6712   if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy))
6713     return cast<ArrayType>(
6714                      getDependentSizedArrayType(NewEltTy,
6715                                                 DSAT->getSizeExpr(),
6716                                                 DSAT->getSizeModifier(),
6717                                               DSAT->getIndexTypeCVRQualifiers(),
6718                                                 DSAT->getBracketsRange()));
6719 
6720   const auto *VAT = cast<VariableArrayType>(ATy);
6721   return cast<ArrayType>(getVariableArrayType(NewEltTy,
6722                                               VAT->getSizeExpr(),
6723                                               VAT->getSizeModifier(),
6724                                               VAT->getIndexTypeCVRQualifiers(),
6725                                               VAT->getBracketsRange()));
6726 }
6727 
6728 QualType ASTContext::getAdjustedParameterType(QualType T) const {
6729   if (T->isArrayType() || T->isFunctionType())
6730     return getDecayedType(T);
6731   return T;
6732 }
6733 
6734 QualType ASTContext::getSignatureParameterType(QualType T) const {
6735   T = getVariableArrayDecayedType(T);
6736   T = getAdjustedParameterType(T);
6737   return T.getUnqualifiedType();
6738 }
6739 
6740 QualType ASTContext::getExceptionObjectType(QualType T) const {
6741   // C++ [except.throw]p3:
6742   //   A throw-expression initializes a temporary object, called the exception
6743   //   object, the type of which is determined by removing any top-level
6744   //   cv-qualifiers from the static type of the operand of throw and adjusting
6745   //   the type from "array of T" or "function returning T" to "pointer to T"
6746   //   or "pointer to function returning T", [...]
6747   T = getVariableArrayDecayedType(T);
6748   if (T->isArrayType() || T->isFunctionType())
6749     T = getDecayedType(T);
6750   return T.getUnqualifiedType();
6751 }
6752 
6753 /// getArrayDecayedType - Return the properly qualified result of decaying the
6754 /// specified array type to a pointer.  This operation is non-trivial when
6755 /// handling typedefs etc.  The canonical type of "T" must be an array type,
6756 /// this returns a pointer to a properly qualified element of the array.
6757 ///
6758 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
6759 QualType ASTContext::getArrayDecayedType(QualType Ty) const {
6760   // Get the element type with 'getAsArrayType' so that we don't lose any
6761   // typedefs in the element type of the array.  This also handles propagation
6762   // of type qualifiers from the array type into the element type if present
6763   // (C99 6.7.3p8).
6764   const ArrayType *PrettyArrayType = getAsArrayType(Ty);
6765   assert(PrettyArrayType && "Not an array type!");
6766 
6767   QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
6768 
6769   // int x[restrict 4] ->  int *restrict
6770   QualType Result = getQualifiedType(PtrTy,
6771                                      PrettyArrayType->getIndexTypeQualifiers());
6772 
6773   // int x[_Nullable] -> int * _Nullable
6774   if (auto Nullability = Ty->getNullability(*this)) {
6775     Result = const_cast<ASTContext *>(this)->getAttributedType(
6776         AttributedType::getNullabilityAttrKind(*Nullability), Result, Result);
6777   }
6778   return Result;
6779 }
6780 
6781 QualType ASTContext::getBaseElementType(const ArrayType *array) const {
6782   return getBaseElementType(array->getElementType());
6783 }
6784 
6785 QualType ASTContext::getBaseElementType(QualType type) const {
6786   Qualifiers qs;
6787   while (true) {
6788     SplitQualType split = type.getSplitDesugaredType();
6789     const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
6790     if (!array) break;
6791 
6792     type = array->getElementType();
6793     qs.addConsistentQualifiers(split.Quals);
6794   }
6795 
6796   return getQualifiedType(type, qs);
6797 }
6798 
6799 /// getConstantArrayElementCount - Returns number of constant array elements.
6800 uint64_t
6801 ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA)  const {
6802   uint64_t ElementCount = 1;
6803   do {
6804     ElementCount *= CA->getSize().getZExtValue();
6805     CA = dyn_cast_or_null<ConstantArrayType>(
6806       CA->getElementType()->getAsArrayTypeUnsafe());
6807   } while (CA);
6808   return ElementCount;
6809 }
6810 
6811 /// getFloatingRank - Return a relative rank for floating point types.
6812 /// This routine will assert if passed a built-in type that isn't a float.
6813 static FloatingRank getFloatingRank(QualType T) {
6814   if (const auto *CT = T->getAs<ComplexType>())
6815     return getFloatingRank(CT->getElementType());
6816 
6817   switch (T->castAs<BuiltinType>()->getKind()) {
6818   default: llvm_unreachable("getFloatingRank(): not a floating type");
6819   case BuiltinType::Float16:    return Float16Rank;
6820   case BuiltinType::Half:       return HalfRank;
6821   case BuiltinType::Float:      return FloatRank;
6822   case BuiltinType::Double:     return DoubleRank;
6823   case BuiltinType::LongDouble: return LongDoubleRank;
6824   case BuiltinType::Float128:   return Float128Rank;
6825   case BuiltinType::BFloat16:   return BFloat16Rank;
6826   case BuiltinType::Ibm128:     return Ibm128Rank;
6827   }
6828 }
6829 
6830 /// getFloatingTypeOrder - Compare the rank of the two specified floating
6831 /// point types, ignoring the domain of the type (i.e. 'double' ==
6832 /// '_Complex double').  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
6833 /// LHS < RHS, return -1.
6834 int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
6835   FloatingRank LHSR = getFloatingRank(LHS);
6836   FloatingRank RHSR = getFloatingRank(RHS);
6837 
6838   if (LHSR == RHSR)
6839     return 0;
6840   if (LHSR > RHSR)
6841     return 1;
6842   return -1;
6843 }
6844 
6845 int ASTContext::getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const {
6846   if (&getFloatTypeSemantics(LHS) == &getFloatTypeSemantics(RHS))
6847     return 0;
6848   return getFloatingTypeOrder(LHS, RHS);
6849 }
6850 
6851 /// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
6852 /// routine will assert if passed a built-in type that isn't an integer or enum,
6853 /// or if it is not canonicalized.
6854 unsigned ASTContext::getIntegerRank(const Type *T) const {
6855   assert(T->isCanonicalUnqualified() && "T should be canonicalized");
6856 
6857   // Results in this 'losing' to any type of the same size, but winning if
6858   // larger.
6859   if (const auto *EIT = dyn_cast<BitIntType>(T))
6860     return 0 + (EIT->getNumBits() << 3);
6861 
6862   switch (cast<BuiltinType>(T)->getKind()) {
6863   default: llvm_unreachable("getIntegerRank(): not a built-in integer");
6864   case BuiltinType::Bool:
6865     return 1 + (getIntWidth(BoolTy) << 3);
6866   case BuiltinType::Char_S:
6867   case BuiltinType::Char_U:
6868   case BuiltinType::SChar:
6869   case BuiltinType::UChar:
6870     return 2 + (getIntWidth(CharTy) << 3);
6871   case BuiltinType::Short:
6872   case BuiltinType::UShort:
6873     return 3 + (getIntWidth(ShortTy) << 3);
6874   case BuiltinType::Int:
6875   case BuiltinType::UInt:
6876     return 4 + (getIntWidth(IntTy) << 3);
6877   case BuiltinType::Long:
6878   case BuiltinType::ULong:
6879     return 5 + (getIntWidth(LongTy) << 3);
6880   case BuiltinType::LongLong:
6881   case BuiltinType::ULongLong:
6882     return 6 + (getIntWidth(LongLongTy) << 3);
6883   case BuiltinType::Int128:
6884   case BuiltinType::UInt128:
6885     return 7 + (getIntWidth(Int128Ty) << 3);
6886   }
6887 }
6888 
6889 /// Whether this is a promotable bitfield reference according
6890 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
6891 ///
6892 /// \returns the type this bit-field will promote to, or NULL if no
6893 /// promotion occurs.
6894 QualType ASTContext::isPromotableBitField(Expr *E) const {
6895   if (E->isTypeDependent() || E->isValueDependent())
6896     return {};
6897 
6898   // C++ [conv.prom]p5:
6899   //    If the bit-field has an enumerated type, it is treated as any other
6900   //    value of that type for promotion purposes.
6901   if (getLangOpts().CPlusPlus && E->getType()->isEnumeralType())
6902     return {};
6903 
6904   // FIXME: We should not do this unless E->refersToBitField() is true. This
6905   // matters in C where getSourceBitField() will find bit-fields for various
6906   // cases where the source expression is not a bit-field designator.
6907 
6908   FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
6909   if (!Field)
6910     return {};
6911 
6912   QualType FT = Field->getType();
6913 
6914   uint64_t BitWidth = Field->getBitWidthValue(*this);
6915   uint64_t IntSize = getTypeSize(IntTy);
6916   // C++ [conv.prom]p5:
6917   //   A prvalue for an integral bit-field can be converted to a prvalue of type
6918   //   int if int can represent all the values of the bit-field; otherwise, it
6919   //   can be converted to unsigned int if unsigned int can represent all the
6920   //   values of the bit-field. If the bit-field is larger yet, no integral
6921   //   promotion applies to it.
6922   // C11 6.3.1.1/2:
6923   //   [For a bit-field of type _Bool, int, signed int, or unsigned int:]
6924   //   If an int can represent all values of the original type (as restricted by
6925   //   the width, for a bit-field), the value is converted to an int; otherwise,
6926   //   it is converted to an unsigned int.
6927   //
6928   // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
6929   //        We perform that promotion here to match GCC and C++.
6930   // FIXME: C does not permit promotion of an enum bit-field whose rank is
6931   //        greater than that of 'int'. We perform that promotion to match GCC.
6932   if (BitWidth < IntSize)
6933     return IntTy;
6934 
6935   if (BitWidth == IntSize)
6936     return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
6937 
6938   // Bit-fields wider than int are not subject to promotions, and therefore act
6939   // like the base type. GCC has some weird bugs in this area that we
6940   // deliberately do not follow (GCC follows a pre-standard resolution to
6941   // C's DR315 which treats bit-width as being part of the type, and this leaks
6942   // into their semantics in some cases).
6943   return {};
6944 }
6945 
6946 /// getPromotedIntegerType - Returns the type that Promotable will
6947 /// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
6948 /// integer type.
6949 QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
6950   assert(!Promotable.isNull());
6951   assert(Promotable->isPromotableIntegerType());
6952   if (const auto *ET = Promotable->getAs<EnumType>())
6953     return ET->getDecl()->getPromotionType();
6954 
6955   if (const auto *BT = Promotable->getAs<BuiltinType>()) {
6956     // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
6957     // (3.9.1) can be converted to a prvalue of the first of the following
6958     // types that can represent all the values of its underlying type:
6959     // int, unsigned int, long int, unsigned long int, long long int, or
6960     // unsigned long long int [...]
6961     // FIXME: Is there some better way to compute this?
6962     if (BT->getKind() == BuiltinType::WChar_S ||
6963         BT->getKind() == BuiltinType::WChar_U ||
6964         BT->getKind() == BuiltinType::Char8 ||
6965         BT->getKind() == BuiltinType::Char16 ||
6966         BT->getKind() == BuiltinType::Char32) {
6967       bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
6968       uint64_t FromSize = getTypeSize(BT);
6969       QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
6970                                   LongLongTy, UnsignedLongLongTy };
6971       for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
6972         uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
6973         if (FromSize < ToSize ||
6974             (FromSize == ToSize &&
6975              FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
6976           return PromoteTypes[Idx];
6977       }
6978       llvm_unreachable("char type should fit into long long");
6979     }
6980   }
6981 
6982   // At this point, we should have a signed or unsigned integer type.
6983   if (Promotable->isSignedIntegerType())
6984     return IntTy;
6985   uint64_t PromotableSize = getIntWidth(Promotable);
6986   uint64_t IntSize = getIntWidth(IntTy);
6987   assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
6988   return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
6989 }
6990 
6991 /// Recurses in pointer/array types until it finds an objc retainable
6992 /// type and returns its ownership.
6993 Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
6994   while (!T.isNull()) {
6995     if (T.getObjCLifetime() != Qualifiers::OCL_None)
6996       return T.getObjCLifetime();
6997     if (T->isArrayType())
6998       T = getBaseElementType(T);
6999     else if (const auto *PT = T->getAs<PointerType>())
7000       T = PT->getPointeeType();
7001     else if (const auto *RT = T->getAs<ReferenceType>())
7002       T = RT->getPointeeType();
7003     else
7004       break;
7005   }
7006 
7007   return Qualifiers::OCL_None;
7008 }
7009 
7010 static const Type *getIntegerTypeForEnum(const EnumType *ET) {
7011   // Incomplete enum types are not treated as integer types.
7012   // FIXME: In C++, enum types are never integer types.
7013   if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
7014     return ET->getDecl()->getIntegerType().getTypePtr();
7015   return nullptr;
7016 }
7017 
7018 /// getIntegerTypeOrder - Returns the highest ranked integer type:
7019 /// C99 6.3.1.8p1.  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
7020 /// LHS < RHS, return -1.
7021 int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
7022   const Type *LHSC = getCanonicalType(LHS).getTypePtr();
7023   const Type *RHSC = getCanonicalType(RHS).getTypePtr();
7024 
7025   // Unwrap enums to their underlying type.
7026   if (const auto *ET = dyn_cast<EnumType>(LHSC))
7027     LHSC = getIntegerTypeForEnum(ET);
7028   if (const auto *ET = dyn_cast<EnumType>(RHSC))
7029     RHSC = getIntegerTypeForEnum(ET);
7030 
7031   if (LHSC == RHSC) return 0;
7032 
7033   bool LHSUnsigned = LHSC->isUnsignedIntegerType();
7034   bool RHSUnsigned = RHSC->isUnsignedIntegerType();
7035 
7036   unsigned LHSRank = getIntegerRank(LHSC);
7037   unsigned RHSRank = getIntegerRank(RHSC);
7038 
7039   if (LHSUnsigned == RHSUnsigned) {  // Both signed or both unsigned.
7040     if (LHSRank == RHSRank) return 0;
7041     return LHSRank > RHSRank ? 1 : -1;
7042   }
7043 
7044   // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
7045   if (LHSUnsigned) {
7046     // If the unsigned [LHS] type is larger, return it.
7047     if (LHSRank >= RHSRank)
7048       return 1;
7049 
7050     // If the signed type can represent all values of the unsigned type, it
7051     // wins.  Because we are dealing with 2's complement and types that are
7052     // powers of two larger than each other, this is always safe.
7053     return -1;
7054   }
7055 
7056   // If the unsigned [RHS] type is larger, return it.
7057   if (RHSRank >= LHSRank)
7058     return -1;
7059 
7060   // If the signed type can represent all values of the unsigned type, it
7061   // wins.  Because we are dealing with 2's complement and types that are
7062   // powers of two larger than each other, this is always safe.
7063   return 1;
7064 }
7065 
7066 TypedefDecl *ASTContext::getCFConstantStringDecl() const {
7067   if (CFConstantStringTypeDecl)
7068     return CFConstantStringTypeDecl;
7069 
7070   assert(!CFConstantStringTagDecl &&
7071          "tag and typedef should be initialized together");
7072   CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
7073   CFConstantStringTagDecl->startDefinition();
7074 
7075   struct {
7076     QualType Type;
7077     const char *Name;
7078   } Fields[5];
7079   unsigned Count = 0;
7080 
7081   /// Objective-C ABI
7082   ///
7083   ///    typedef struct __NSConstantString_tag {
7084   ///      const int *isa;
7085   ///      int flags;
7086   ///      const char *str;
7087   ///      long length;
7088   ///    } __NSConstantString;
7089   ///
7090   /// Swift ABI (4.1, 4.2)
7091   ///
7092   ///    typedef struct __NSConstantString_tag {
7093   ///      uintptr_t _cfisa;
7094   ///      uintptr_t _swift_rc;
7095   ///      _Atomic(uint64_t) _cfinfoa;
7096   ///      const char *_ptr;
7097   ///      uint32_t _length;
7098   ///    } __NSConstantString;
7099   ///
7100   /// Swift ABI (5.0)
7101   ///
7102   ///    typedef struct __NSConstantString_tag {
7103   ///      uintptr_t _cfisa;
7104   ///      uintptr_t _swift_rc;
7105   ///      _Atomic(uint64_t) _cfinfoa;
7106   ///      const char *_ptr;
7107   ///      uintptr_t _length;
7108   ///    } __NSConstantString;
7109 
7110   const auto CFRuntime = getLangOpts().CFRuntime;
7111   if (static_cast<unsigned>(CFRuntime) <
7112       static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) {
7113     Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" };
7114     Fields[Count++] = { IntTy, "flags" };
7115     Fields[Count++] = { getPointerType(CharTy.withConst()), "str" };
7116     Fields[Count++] = { LongTy, "length" };
7117   } else {
7118     Fields[Count++] = { getUIntPtrType(), "_cfisa" };
7119     Fields[Count++] = { getUIntPtrType(), "_swift_rc" };
7120     Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" };
7121     Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" };
7122     if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
7123         CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
7124       Fields[Count++] = { IntTy, "_ptr" };
7125     else
7126       Fields[Count++] = { getUIntPtrType(), "_ptr" };
7127   }
7128 
7129   // Create fields
7130   for (unsigned i = 0; i < Count; ++i) {
7131     FieldDecl *Field =
7132         FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(),
7133                           SourceLocation(), &Idents.get(Fields[i].Name),
7134                           Fields[i].Type, /*TInfo=*/nullptr,
7135                           /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
7136     Field->setAccess(AS_public);
7137     CFConstantStringTagDecl->addDecl(Field);
7138   }
7139 
7140   CFConstantStringTagDecl->completeDefinition();
7141   // This type is designed to be compatible with NSConstantString, but cannot
7142   // use the same name, since NSConstantString is an interface.
7143   auto tagType = getTagDeclType(CFConstantStringTagDecl);
7144   CFConstantStringTypeDecl =
7145       buildImplicitTypedef(tagType, "__NSConstantString");
7146 
7147   return CFConstantStringTypeDecl;
7148 }
7149 
7150 RecordDecl *ASTContext::getCFConstantStringTagDecl() const {
7151   if (!CFConstantStringTagDecl)
7152     getCFConstantStringDecl(); // Build the tag and the typedef.
7153   return CFConstantStringTagDecl;
7154 }
7155 
7156 // getCFConstantStringType - Return the type used for constant CFStrings.
7157 QualType ASTContext::getCFConstantStringType() const {
7158   return getTypedefType(getCFConstantStringDecl());
7159 }
7160 
7161 QualType ASTContext::getObjCSuperType() const {
7162   if (ObjCSuperType.isNull()) {
7163     RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
7164     getTranslationUnitDecl()->addDecl(ObjCSuperTypeDecl);
7165     ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
7166   }
7167   return ObjCSuperType;
7168 }
7169 
7170 void ASTContext::setCFConstantStringType(QualType T) {
7171   const auto *TD = T->castAs<TypedefType>();
7172   CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl());
7173   const auto *TagType =
7174       CFConstantStringTypeDecl->getUnderlyingType()->castAs<RecordType>();
7175   CFConstantStringTagDecl = TagType->getDecl();
7176 }
7177 
7178 QualType ASTContext::getBlockDescriptorType() const {
7179   if (BlockDescriptorType)
7180     return getTagDeclType(BlockDescriptorType);
7181 
7182   RecordDecl *RD;
7183   // FIXME: Needs the FlagAppleBlock bit.
7184   RD = buildImplicitRecord("__block_descriptor");
7185   RD->startDefinition();
7186 
7187   QualType FieldTypes[] = {
7188     UnsignedLongTy,
7189     UnsignedLongTy,
7190   };
7191 
7192   static const char *const FieldNames[] = {
7193     "reserved",
7194     "Size"
7195   };
7196 
7197   for (size_t i = 0; i < 2; ++i) {
7198     FieldDecl *Field = FieldDecl::Create(
7199         *this, RD, SourceLocation(), SourceLocation(),
7200         &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
7201         /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
7202     Field->setAccess(AS_public);
7203     RD->addDecl(Field);
7204   }
7205 
7206   RD->completeDefinition();
7207 
7208   BlockDescriptorType = RD;
7209 
7210   return getTagDeclType(BlockDescriptorType);
7211 }
7212 
7213 QualType ASTContext::getBlockDescriptorExtendedType() const {
7214   if (BlockDescriptorExtendedType)
7215     return getTagDeclType(BlockDescriptorExtendedType);
7216 
7217   RecordDecl *RD;
7218   // FIXME: Needs the FlagAppleBlock bit.
7219   RD = buildImplicitRecord("__block_descriptor_withcopydispose");
7220   RD->startDefinition();
7221 
7222   QualType FieldTypes[] = {
7223     UnsignedLongTy,
7224     UnsignedLongTy,
7225     getPointerType(VoidPtrTy),
7226     getPointerType(VoidPtrTy)
7227   };
7228 
7229   static const char *const FieldNames[] = {
7230     "reserved",
7231     "Size",
7232     "CopyFuncPtr",
7233     "DestroyFuncPtr"
7234   };
7235 
7236   for (size_t i = 0; i < 4; ++i) {
7237     FieldDecl *Field = FieldDecl::Create(
7238         *this, RD, SourceLocation(), SourceLocation(),
7239         &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
7240         /*BitWidth=*/nullptr,
7241         /*Mutable=*/false, ICIS_NoInit);
7242     Field->setAccess(AS_public);
7243     RD->addDecl(Field);
7244   }
7245 
7246   RD->completeDefinition();
7247 
7248   BlockDescriptorExtendedType = RD;
7249   return getTagDeclType(BlockDescriptorExtendedType);
7250 }
7251 
7252 OpenCLTypeKind ASTContext::getOpenCLTypeKind(const Type *T) const {
7253   const auto *BT = dyn_cast<BuiltinType>(T);
7254 
7255   if (!BT) {
7256     if (isa<PipeType>(T))
7257       return OCLTK_Pipe;
7258 
7259     return OCLTK_Default;
7260   }
7261 
7262   switch (BT->getKind()) {
7263 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix)                   \
7264   case BuiltinType::Id:                                                        \
7265     return OCLTK_Image;
7266 #include "clang/Basic/OpenCLImageTypes.def"
7267 
7268   case BuiltinType::OCLClkEvent:
7269     return OCLTK_ClkEvent;
7270 
7271   case BuiltinType::OCLEvent:
7272     return OCLTK_Event;
7273 
7274   case BuiltinType::OCLQueue:
7275     return OCLTK_Queue;
7276 
7277   case BuiltinType::OCLReserveID:
7278     return OCLTK_ReserveID;
7279 
7280   case BuiltinType::OCLSampler:
7281     return OCLTK_Sampler;
7282 
7283   default:
7284     return OCLTK_Default;
7285   }
7286 }
7287 
7288 LangAS ASTContext::getOpenCLTypeAddrSpace(const Type *T) const {
7289   return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
7290 }
7291 
7292 /// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
7293 /// requires copy/dispose. Note that this must match the logic
7294 /// in buildByrefHelpers.
7295 bool ASTContext::BlockRequiresCopying(QualType Ty,
7296                                       const VarDecl *D) {
7297   if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
7298     const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr();
7299     if (!copyExpr && record->hasTrivialDestructor()) return false;
7300 
7301     return true;
7302   }
7303 
7304   // The block needs copy/destroy helpers if Ty is non-trivial to destructively
7305   // move or destroy.
7306   if (Ty.isNonTrivialToPrimitiveDestructiveMove() || Ty.isDestructedType())
7307     return true;
7308 
7309   if (!Ty->isObjCRetainableType()) return false;
7310 
7311   Qualifiers qs = Ty.getQualifiers();
7312 
7313   // If we have lifetime, that dominates.
7314   if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
7315     switch (lifetime) {
7316       case Qualifiers::OCL_None: llvm_unreachable("impossible");
7317 
7318       // These are just bits as far as the runtime is concerned.
7319       case Qualifiers::OCL_ExplicitNone:
7320       case Qualifiers::OCL_Autoreleasing:
7321         return false;
7322 
7323       // These cases should have been taken care of when checking the type's
7324       // non-triviality.
7325       case Qualifiers::OCL_Weak:
7326       case Qualifiers::OCL_Strong:
7327         llvm_unreachable("impossible");
7328     }
7329     llvm_unreachable("fell out of lifetime switch!");
7330   }
7331   return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
7332           Ty->isObjCObjectPointerType());
7333 }
7334 
7335 bool ASTContext::getByrefLifetime(QualType Ty,
7336                               Qualifiers::ObjCLifetime &LifeTime,
7337                               bool &HasByrefExtendedLayout) const {
7338   if (!getLangOpts().ObjC ||
7339       getLangOpts().getGC() != LangOptions::NonGC)
7340     return false;
7341 
7342   HasByrefExtendedLayout = false;
7343   if (Ty->isRecordType()) {
7344     HasByrefExtendedLayout = true;
7345     LifeTime = Qualifiers::OCL_None;
7346   } else if ((LifeTime = Ty.getObjCLifetime())) {
7347     // Honor the ARC qualifiers.
7348   } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
7349     // The MRR rule.
7350     LifeTime = Qualifiers::OCL_ExplicitNone;
7351   } else {
7352     LifeTime = Qualifiers::OCL_None;
7353   }
7354   return true;
7355 }
7356 
7357 CanQualType ASTContext::getNSUIntegerType() const {
7358   assert(Target && "Expected target to be initialized");
7359   const llvm::Triple &T = Target->getTriple();
7360   // Windows is LLP64 rather than LP64
7361   if (T.isOSWindows() && T.isArch64Bit())
7362     return UnsignedLongLongTy;
7363   return UnsignedLongTy;
7364 }
7365 
7366 CanQualType ASTContext::getNSIntegerType() const {
7367   assert(Target && "Expected target to be initialized");
7368   const llvm::Triple &T = Target->getTriple();
7369   // Windows is LLP64 rather than LP64
7370   if (T.isOSWindows() && T.isArch64Bit())
7371     return LongLongTy;
7372   return LongTy;
7373 }
7374 
7375 TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
7376   if (!ObjCInstanceTypeDecl)
7377     ObjCInstanceTypeDecl =
7378         buildImplicitTypedef(getObjCIdType(), "instancetype");
7379   return ObjCInstanceTypeDecl;
7380 }
7381 
7382 // This returns true if a type has been typedefed to BOOL:
7383 // typedef <type> BOOL;
7384 static bool isTypeTypedefedAsBOOL(QualType T) {
7385   if (const auto *TT = dyn_cast<TypedefType>(T))
7386     if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
7387       return II->isStr("BOOL");
7388 
7389   return false;
7390 }
7391 
7392 /// getObjCEncodingTypeSize returns size of type for objective-c encoding
7393 /// purpose.
7394 CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
7395   if (!type->isIncompleteArrayType() && type->isIncompleteType())
7396     return CharUnits::Zero();
7397 
7398   CharUnits sz = getTypeSizeInChars(type);
7399 
7400   // Make all integer and enum types at least as large as an int
7401   if (sz.isPositive() && type->isIntegralOrEnumerationType())
7402     sz = std::max(sz, getTypeSizeInChars(IntTy));
7403   // Treat arrays as pointers, since that's how they're passed in.
7404   else if (type->isArrayType())
7405     sz = getTypeSizeInChars(VoidPtrTy);
7406   return sz;
7407 }
7408 
7409 bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
7410   return getTargetInfo().getCXXABI().isMicrosoft() &&
7411          VD->isStaticDataMember() &&
7412          VD->getType()->isIntegralOrEnumerationType() &&
7413          !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
7414 }
7415 
7416 ASTContext::InlineVariableDefinitionKind
7417 ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const {
7418   if (!VD->isInline())
7419     return InlineVariableDefinitionKind::None;
7420 
7421   // In almost all cases, it's a weak definition.
7422   auto *First = VD->getFirstDecl();
7423   if (First->isInlineSpecified() || !First->isStaticDataMember())
7424     return InlineVariableDefinitionKind::Weak;
7425 
7426   // If there's a file-context declaration in this translation unit, it's a
7427   // non-discardable definition.
7428   for (auto *D : VD->redecls())
7429     if (D->getLexicalDeclContext()->isFileContext() &&
7430         !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
7431       return InlineVariableDefinitionKind::Strong;
7432 
7433   // If we've not seen one yet, we don't know.
7434   return InlineVariableDefinitionKind::WeakUnknown;
7435 }
7436 
7437 static std::string charUnitsToString(const CharUnits &CU) {
7438   return llvm::itostr(CU.getQuantity());
7439 }
7440 
7441 /// getObjCEncodingForBlock - Return the encoded type for this block
7442 /// declaration.
7443 std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
7444   std::string S;
7445 
7446   const BlockDecl *Decl = Expr->getBlockDecl();
7447   QualType BlockTy =
7448       Expr->getType()->castAs<BlockPointerType>()->getPointeeType();
7449   QualType BlockReturnTy = BlockTy->castAs<FunctionType>()->getReturnType();
7450   // Encode result type.
7451   if (getLangOpts().EncodeExtendedBlockSig)
7452     getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, BlockReturnTy, S,
7453                                       true /*Extended*/);
7454   else
7455     getObjCEncodingForType(BlockReturnTy, S);
7456   // Compute size of all parameters.
7457   // Start with computing size of a pointer in number of bytes.
7458   // FIXME: There might(should) be a better way of doing this computation!
7459   CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
7460   CharUnits ParmOffset = PtrSize;
7461   for (auto PI : Decl->parameters()) {
7462     QualType PType = PI->getType();
7463     CharUnits sz = getObjCEncodingTypeSize(PType);
7464     if (sz.isZero())
7465       continue;
7466     assert(sz.isPositive() && "BlockExpr - Incomplete param type");
7467     ParmOffset += sz;
7468   }
7469   // Size of the argument frame
7470   S += charUnitsToString(ParmOffset);
7471   // Block pointer and offset.
7472   S += "@?0";
7473 
7474   // Argument types.
7475   ParmOffset = PtrSize;
7476   for (auto PVDecl : Decl->parameters()) {
7477     QualType PType = PVDecl->getOriginalType();
7478     if (const auto *AT =
7479             dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
7480       // Use array's original type only if it has known number of
7481       // elements.
7482       if (!isa<ConstantArrayType>(AT))
7483         PType = PVDecl->getType();
7484     } else if (PType->isFunctionType())
7485       PType = PVDecl->getType();
7486     if (getLangOpts().EncodeExtendedBlockSig)
7487       getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
7488                                       S, true /*Extended*/);
7489     else
7490       getObjCEncodingForType(PType, S);
7491     S += charUnitsToString(ParmOffset);
7492     ParmOffset += getObjCEncodingTypeSize(PType);
7493   }
7494 
7495   return S;
7496 }
7497 
7498 std::string
7499 ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const {
7500   std::string S;
7501   // Encode result type.
7502   getObjCEncodingForType(Decl->getReturnType(), S);
7503   CharUnits ParmOffset;
7504   // Compute size of all parameters.
7505   for (auto PI : Decl->parameters()) {
7506     QualType PType = PI->getType();
7507     CharUnits sz = getObjCEncodingTypeSize(PType);
7508     if (sz.isZero())
7509       continue;
7510 
7511     assert(sz.isPositive() &&
7512            "getObjCEncodingForFunctionDecl - Incomplete param type");
7513     ParmOffset += sz;
7514   }
7515   S += charUnitsToString(ParmOffset);
7516   ParmOffset = CharUnits::Zero();
7517 
7518   // Argument types.
7519   for (auto PVDecl : Decl->parameters()) {
7520     QualType PType = PVDecl->getOriginalType();
7521     if (const auto *AT =
7522             dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
7523       // Use array's original type only if it has known number of
7524       // elements.
7525       if (!isa<ConstantArrayType>(AT))
7526         PType = PVDecl->getType();
7527     } else if (PType->isFunctionType())
7528       PType = PVDecl->getType();
7529     getObjCEncodingForType(PType, S);
7530     S += charUnitsToString(ParmOffset);
7531     ParmOffset += getObjCEncodingTypeSize(PType);
7532   }
7533 
7534   return S;
7535 }
7536 
7537 /// getObjCEncodingForMethodParameter - Return the encoded type for a single
7538 /// method parameter or return type. If Extended, include class names and
7539 /// block object types.
7540 void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
7541                                                    QualType T, std::string& S,
7542                                                    bool Extended) const {
7543   // Encode type qualifier, 'in', 'inout', etc. for the parameter.
7544   getObjCEncodingForTypeQualifier(QT, S);
7545   // Encode parameter type.
7546   ObjCEncOptions Options = ObjCEncOptions()
7547                                .setExpandPointedToStructures()
7548                                .setExpandStructures()
7549                                .setIsOutermostType();
7550   if (Extended)
7551     Options.setEncodeBlockParameters().setEncodeClassNames();
7552   getObjCEncodingForTypeImpl(T, S, Options, /*Field=*/nullptr);
7553 }
7554 
7555 /// getObjCEncodingForMethodDecl - Return the encoded type for this method
7556 /// declaration.
7557 std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
7558                                                      bool Extended) const {
7559   // FIXME: This is not very efficient.
7560   // Encode return type.
7561   std::string S;
7562   getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
7563                                     Decl->getReturnType(), S, Extended);
7564   // Compute size of all parameters.
7565   // Start with computing size of a pointer in number of bytes.
7566   // FIXME: There might(should) be a better way of doing this computation!
7567   CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
7568   // The first two arguments (self and _cmd) are pointers; account for
7569   // their size.
7570   CharUnits ParmOffset = 2 * PtrSize;
7571   for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
7572        E = Decl->sel_param_end(); PI != E; ++PI) {
7573     QualType PType = (*PI)->getType();
7574     CharUnits sz = getObjCEncodingTypeSize(PType);
7575     if (sz.isZero())
7576       continue;
7577 
7578     assert(sz.isPositive() &&
7579            "getObjCEncodingForMethodDecl - Incomplete param type");
7580     ParmOffset += sz;
7581   }
7582   S += charUnitsToString(ParmOffset);
7583   S += "@0:";
7584   S += charUnitsToString(PtrSize);
7585 
7586   // Argument types.
7587   ParmOffset = 2 * PtrSize;
7588   for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
7589        E = Decl->sel_param_end(); PI != E; ++PI) {
7590     const ParmVarDecl *PVDecl = *PI;
7591     QualType PType = PVDecl->getOriginalType();
7592     if (const auto *AT =
7593             dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
7594       // Use array's original type only if it has known number of
7595       // elements.
7596       if (!isa<ConstantArrayType>(AT))
7597         PType = PVDecl->getType();
7598     } else if (PType->isFunctionType())
7599       PType = PVDecl->getType();
7600     getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
7601                                       PType, S, Extended);
7602     S += charUnitsToString(ParmOffset);
7603     ParmOffset += getObjCEncodingTypeSize(PType);
7604   }
7605 
7606   return S;
7607 }
7608 
7609 ObjCPropertyImplDecl *
7610 ASTContext::getObjCPropertyImplDeclForPropertyDecl(
7611                                       const ObjCPropertyDecl *PD,
7612                                       const Decl *Container) const {
7613   if (!Container)
7614     return nullptr;
7615   if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) {
7616     for (auto *PID : CID->property_impls())
7617       if (PID->getPropertyDecl() == PD)
7618         return PID;
7619   } else {
7620     const auto *OID = cast<ObjCImplementationDecl>(Container);
7621     for (auto *PID : OID->property_impls())
7622       if (PID->getPropertyDecl() == PD)
7623         return PID;
7624   }
7625   return nullptr;
7626 }
7627 
7628 /// getObjCEncodingForPropertyDecl - Return the encoded type for this
7629 /// property declaration. If non-NULL, Container must be either an
7630 /// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
7631 /// NULL when getting encodings for protocol properties.
7632 /// Property attributes are stored as a comma-delimited C string. The simple
7633 /// attributes readonly and bycopy are encoded as single characters. The
7634 /// parametrized attributes, getter=name, setter=name, and ivar=name, are
7635 /// encoded as single characters, followed by an identifier. Property types
7636 /// are also encoded as a parametrized attribute. The characters used to encode
7637 /// these attributes are defined by the following enumeration:
7638 /// @code
7639 /// enum PropertyAttributes {
7640 /// kPropertyReadOnly = 'R',   // property is read-only.
7641 /// kPropertyBycopy = 'C',     // property is a copy of the value last assigned
7642 /// kPropertyByref = '&',  // property is a reference to the value last assigned
7643 /// kPropertyDynamic = 'D',    // property is dynamic
7644 /// kPropertyGetter = 'G',     // followed by getter selector name
7645 /// kPropertySetter = 'S',     // followed by setter selector name
7646 /// kPropertyInstanceVariable = 'V'  // followed by instance variable  name
7647 /// kPropertyType = 'T'              // followed by old-style type encoding.
7648 /// kPropertyWeak = 'W'              // 'weak' property
7649 /// kPropertyStrong = 'P'            // property GC'able
7650 /// kPropertyNonAtomic = 'N'         // property non-atomic
7651 /// };
7652 /// @endcode
7653 std::string
7654 ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
7655                                            const Decl *Container) const {
7656   // Collect information from the property implementation decl(s).
7657   bool Dynamic = false;
7658   ObjCPropertyImplDecl *SynthesizePID = nullptr;
7659 
7660   if (ObjCPropertyImplDecl *PropertyImpDecl =
7661       getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
7662     if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
7663       Dynamic = true;
7664     else
7665       SynthesizePID = PropertyImpDecl;
7666   }
7667 
7668   // FIXME: This is not very efficient.
7669   std::string S = "T";
7670 
7671   // Encode result type.
7672   // GCC has some special rules regarding encoding of properties which
7673   // closely resembles encoding of ivars.
7674   getObjCEncodingForPropertyType(PD->getType(), S);
7675 
7676   if (PD->isReadOnly()) {
7677     S += ",R";
7678     if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_copy)
7679       S += ",C";
7680     if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_retain)
7681       S += ",&";
7682     if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_weak)
7683       S += ",W";
7684   } else {
7685     switch (PD->getSetterKind()) {
7686     case ObjCPropertyDecl::Assign: break;
7687     case ObjCPropertyDecl::Copy:   S += ",C"; break;
7688     case ObjCPropertyDecl::Retain: S += ",&"; break;
7689     case ObjCPropertyDecl::Weak:   S += ",W"; break;
7690     }
7691   }
7692 
7693   // It really isn't clear at all what this means, since properties
7694   // are "dynamic by default".
7695   if (Dynamic)
7696     S += ",D";
7697 
7698   if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_nonatomic)
7699     S += ",N";
7700 
7701   if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_getter) {
7702     S += ",G";
7703     S += PD->getGetterName().getAsString();
7704   }
7705 
7706   if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_setter) {
7707     S += ",S";
7708     S += PD->getSetterName().getAsString();
7709   }
7710 
7711   if (SynthesizePID) {
7712     const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
7713     S += ",V";
7714     S += OID->getNameAsString();
7715   }
7716 
7717   // FIXME: OBJCGC: weak & strong
7718   return S;
7719 }
7720 
7721 /// getLegacyIntegralTypeEncoding -
7722 /// Another legacy compatibility encoding: 32-bit longs are encoded as
7723 /// 'l' or 'L' , but not always.  For typedefs, we need to use
7724 /// 'i' or 'I' instead if encoding a struct field, or a pointer!
7725 void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
7726   if (isa<TypedefType>(PointeeTy.getTypePtr())) {
7727     if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
7728       if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
7729         PointeeTy = UnsignedIntTy;
7730       else
7731         if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
7732           PointeeTy = IntTy;
7733     }
7734   }
7735 }
7736 
7737 void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
7738                                         const FieldDecl *Field,
7739                                         QualType *NotEncodedT) const {
7740   // We follow the behavior of gcc, expanding structures which are
7741   // directly pointed to, and expanding embedded structures. Note that
7742   // these rules are sufficient to prevent recursive encoding of the
7743   // same type.
7744   getObjCEncodingForTypeImpl(T, S,
7745                              ObjCEncOptions()
7746                                  .setExpandPointedToStructures()
7747                                  .setExpandStructures()
7748                                  .setIsOutermostType(),
7749                              Field, NotEncodedT);
7750 }
7751 
7752 void ASTContext::getObjCEncodingForPropertyType(QualType T,
7753                                                 std::string& S) const {
7754   // Encode result type.
7755   // GCC has some special rules regarding encoding of properties which
7756   // closely resembles encoding of ivars.
7757   getObjCEncodingForTypeImpl(T, S,
7758                              ObjCEncOptions()
7759                                  .setExpandPointedToStructures()
7760                                  .setExpandStructures()
7761                                  .setIsOutermostType()
7762                                  .setEncodingProperty(),
7763                              /*Field=*/nullptr);
7764 }
7765 
7766 static char getObjCEncodingForPrimitiveType(const ASTContext *C,
7767                                             const BuiltinType *BT) {
7768     BuiltinType::Kind kind = BT->getKind();
7769     switch (kind) {
7770     case BuiltinType::Void:       return 'v';
7771     case BuiltinType::Bool:       return 'B';
7772     case BuiltinType::Char8:
7773     case BuiltinType::Char_U:
7774     case BuiltinType::UChar:      return 'C';
7775     case BuiltinType::Char16:
7776     case BuiltinType::UShort:     return 'S';
7777     case BuiltinType::Char32:
7778     case BuiltinType::UInt:       return 'I';
7779     case BuiltinType::ULong:
7780         return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
7781     case BuiltinType::UInt128:    return 'T';
7782     case BuiltinType::ULongLong:  return 'Q';
7783     case BuiltinType::Char_S:
7784     case BuiltinType::SChar:      return 'c';
7785     case BuiltinType::Short:      return 's';
7786     case BuiltinType::WChar_S:
7787     case BuiltinType::WChar_U:
7788     case BuiltinType::Int:        return 'i';
7789     case BuiltinType::Long:
7790       return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
7791     case BuiltinType::LongLong:   return 'q';
7792     case BuiltinType::Int128:     return 't';
7793     case BuiltinType::Float:      return 'f';
7794     case BuiltinType::Double:     return 'd';
7795     case BuiltinType::LongDouble: return 'D';
7796     case BuiltinType::NullPtr:    return '*'; // like char*
7797 
7798     case BuiltinType::BFloat16:
7799     case BuiltinType::Float16:
7800     case BuiltinType::Float128:
7801     case BuiltinType::Ibm128:
7802     case BuiltinType::Half:
7803     case BuiltinType::ShortAccum:
7804     case BuiltinType::Accum:
7805     case BuiltinType::LongAccum:
7806     case BuiltinType::UShortAccum:
7807     case BuiltinType::UAccum:
7808     case BuiltinType::ULongAccum:
7809     case BuiltinType::ShortFract:
7810     case BuiltinType::Fract:
7811     case BuiltinType::LongFract:
7812     case BuiltinType::UShortFract:
7813     case BuiltinType::UFract:
7814     case BuiltinType::ULongFract:
7815     case BuiltinType::SatShortAccum:
7816     case BuiltinType::SatAccum:
7817     case BuiltinType::SatLongAccum:
7818     case BuiltinType::SatUShortAccum:
7819     case BuiltinType::SatUAccum:
7820     case BuiltinType::SatULongAccum:
7821     case BuiltinType::SatShortFract:
7822     case BuiltinType::SatFract:
7823     case BuiltinType::SatLongFract:
7824     case BuiltinType::SatUShortFract:
7825     case BuiltinType::SatUFract:
7826     case BuiltinType::SatULongFract:
7827       // FIXME: potentially need @encodes for these!
7828       return ' ';
7829 
7830 #define SVE_TYPE(Name, Id, SingletonId) \
7831     case BuiltinType::Id:
7832 #include "clang/Basic/AArch64SVEACLETypes.def"
7833 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
7834 #include "clang/Basic/RISCVVTypes.def"
7835       {
7836         DiagnosticsEngine &Diags = C->getDiagnostics();
7837         unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
7838                                                 "cannot yet @encode type %0");
7839         Diags.Report(DiagID) << BT->getName(C->getPrintingPolicy());
7840         return ' ';
7841       }
7842 
7843     case BuiltinType::ObjCId:
7844     case BuiltinType::ObjCClass:
7845     case BuiltinType::ObjCSel:
7846       llvm_unreachable("@encoding ObjC primitive type");
7847 
7848     // OpenCL and placeholder types don't need @encodings.
7849 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7850     case BuiltinType::Id:
7851 #include "clang/Basic/OpenCLImageTypes.def"
7852 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
7853     case BuiltinType::Id:
7854 #include "clang/Basic/OpenCLExtensionTypes.def"
7855     case BuiltinType::OCLEvent:
7856     case BuiltinType::OCLClkEvent:
7857     case BuiltinType::OCLQueue:
7858     case BuiltinType::OCLReserveID:
7859     case BuiltinType::OCLSampler:
7860     case BuiltinType::Dependent:
7861 #define PPC_VECTOR_TYPE(Name, Id, Size) \
7862     case BuiltinType::Id:
7863 #include "clang/Basic/PPCTypes.def"
7864 #define BUILTIN_TYPE(KIND, ID)
7865 #define PLACEHOLDER_TYPE(KIND, ID) \
7866     case BuiltinType::KIND:
7867 #include "clang/AST/BuiltinTypes.def"
7868       llvm_unreachable("invalid builtin type for @encode");
7869     }
7870     llvm_unreachable("invalid BuiltinType::Kind value");
7871 }
7872 
7873 static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
7874   EnumDecl *Enum = ET->getDecl();
7875 
7876   // The encoding of an non-fixed enum type is always 'i', regardless of size.
7877   if (!Enum->isFixed())
7878     return 'i';
7879 
7880   // The encoding of a fixed enum type matches its fixed underlying type.
7881   const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
7882   return getObjCEncodingForPrimitiveType(C, BT);
7883 }
7884 
7885 static void EncodeBitField(const ASTContext *Ctx, std::string& S,
7886                            QualType T, const FieldDecl *FD) {
7887   assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
7888   S += 'b';
7889   // The NeXT runtime encodes bit fields as b followed by the number of bits.
7890   // The GNU runtime requires more information; bitfields are encoded as b,
7891   // then the offset (in bits) of the first element, then the type of the
7892   // bitfield, then the size in bits.  For example, in this structure:
7893   //
7894   // struct
7895   // {
7896   //    int integer;
7897   //    int flags:2;
7898   // };
7899   // On a 32-bit system, the encoding for flags would be b2 for the NeXT
7900   // runtime, but b32i2 for the GNU runtime.  The reason for this extra
7901   // information is not especially sensible, but we're stuck with it for
7902   // compatibility with GCC, although providing it breaks anything that
7903   // actually uses runtime introspection and wants to work on both runtimes...
7904   if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
7905     uint64_t Offset;
7906 
7907     if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
7908       Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), nullptr,
7909                                          IVD);
7910     } else {
7911       const RecordDecl *RD = FD->getParent();
7912       const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
7913       Offset = RL.getFieldOffset(FD->getFieldIndex());
7914     }
7915 
7916     S += llvm::utostr(Offset);
7917 
7918     if (const auto *ET = T->getAs<EnumType>())
7919       S += ObjCEncodingForEnumType(Ctx, ET);
7920     else {
7921       const auto *BT = T->castAs<BuiltinType>();
7922       S += getObjCEncodingForPrimitiveType(Ctx, BT);
7923     }
7924   }
7925   S += llvm::utostr(FD->getBitWidthValue(*Ctx));
7926 }
7927 
7928 // Helper function for determining whether the encoded type string would include
7929 // a template specialization type.
7930 static bool hasTemplateSpecializationInEncodedString(const Type *T,
7931                                                      bool VisitBasesAndFields) {
7932   T = T->getBaseElementTypeUnsafe();
7933 
7934   if (auto *PT = T->getAs<PointerType>())
7935     return hasTemplateSpecializationInEncodedString(
7936         PT->getPointeeType().getTypePtr(), false);
7937 
7938   auto *CXXRD = T->getAsCXXRecordDecl();
7939 
7940   if (!CXXRD)
7941     return false;
7942 
7943   if (isa<ClassTemplateSpecializationDecl>(CXXRD))
7944     return true;
7945 
7946   if (!CXXRD->hasDefinition() || !VisitBasesAndFields)
7947     return false;
7948 
7949   for (auto B : CXXRD->bases())
7950     if (hasTemplateSpecializationInEncodedString(B.getType().getTypePtr(),
7951                                                  true))
7952       return true;
7953 
7954   for (auto *FD : CXXRD->fields())
7955     if (hasTemplateSpecializationInEncodedString(FD->getType().getTypePtr(),
7956                                                  true))
7957       return true;
7958 
7959   return false;
7960 }
7961 
7962 // FIXME: Use SmallString for accumulating string.
7963 void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
7964                                             const ObjCEncOptions Options,
7965                                             const FieldDecl *FD,
7966                                             QualType *NotEncodedT) const {
7967   CanQualType CT = getCanonicalType(T);
7968   switch (CT->getTypeClass()) {
7969   case Type::Builtin:
7970   case Type::Enum:
7971     if (FD && FD->isBitField())
7972       return EncodeBitField(this, S, T, FD);
7973     if (const auto *BT = dyn_cast<BuiltinType>(CT))
7974       S += getObjCEncodingForPrimitiveType(this, BT);
7975     else
7976       S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
7977     return;
7978 
7979   case Type::Complex:
7980     S += 'j';
7981     getObjCEncodingForTypeImpl(T->castAs<ComplexType>()->getElementType(), S,
7982                                ObjCEncOptions(),
7983                                /*Field=*/nullptr);
7984     return;
7985 
7986   case Type::Atomic:
7987     S += 'A';
7988     getObjCEncodingForTypeImpl(T->castAs<AtomicType>()->getValueType(), S,
7989                                ObjCEncOptions(),
7990                                /*Field=*/nullptr);
7991     return;
7992 
7993   // encoding for pointer or reference types.
7994   case Type::Pointer:
7995   case Type::LValueReference:
7996   case Type::RValueReference: {
7997     QualType PointeeTy;
7998     if (isa<PointerType>(CT)) {
7999       const auto *PT = T->castAs<PointerType>();
8000       if (PT->isObjCSelType()) {
8001         S += ':';
8002         return;
8003       }
8004       PointeeTy = PT->getPointeeType();
8005     } else {
8006       PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
8007     }
8008 
8009     bool isReadOnly = false;
8010     // For historical/compatibility reasons, the read-only qualifier of the
8011     // pointee gets emitted _before_ the '^'.  The read-only qualifier of
8012     // the pointer itself gets ignored, _unless_ we are looking at a typedef!
8013     // Also, do not emit the 'r' for anything but the outermost type!
8014     if (isa<TypedefType>(T.getTypePtr())) {
8015       if (Options.IsOutermostType() && T.isConstQualified()) {
8016         isReadOnly = true;
8017         S += 'r';
8018       }
8019     } else if (Options.IsOutermostType()) {
8020       QualType P = PointeeTy;
8021       while (auto PT = P->getAs<PointerType>())
8022         P = PT->getPointeeType();
8023       if (P.isConstQualified()) {
8024         isReadOnly = true;
8025         S += 'r';
8026       }
8027     }
8028     if (isReadOnly) {
8029       // Another legacy compatibility encoding. Some ObjC qualifier and type
8030       // combinations need to be rearranged.
8031       // Rewrite "in const" from "nr" to "rn"
8032       if (StringRef(S).endswith("nr"))
8033         S.replace(S.end()-2, S.end(), "rn");
8034     }
8035 
8036     if (PointeeTy->isCharType()) {
8037       // char pointer types should be encoded as '*' unless it is a
8038       // type that has been typedef'd to 'BOOL'.
8039       if (!isTypeTypedefedAsBOOL(PointeeTy)) {
8040         S += '*';
8041         return;
8042       }
8043     } else if (const auto *RTy = PointeeTy->getAs<RecordType>()) {
8044       // GCC binary compat: Need to convert "struct objc_class *" to "#".
8045       if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
8046         S += '#';
8047         return;
8048       }
8049       // GCC binary compat: Need to convert "struct objc_object *" to "@".
8050       if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
8051         S += '@';
8052         return;
8053       }
8054       // If the encoded string for the class includes template names, just emit
8055       // "^v" for pointers to the class.
8056       if (getLangOpts().CPlusPlus &&
8057           (!getLangOpts().EncodeCXXClassTemplateSpec &&
8058            hasTemplateSpecializationInEncodedString(
8059                RTy, Options.ExpandPointedToStructures()))) {
8060         S += "^v";
8061         return;
8062       }
8063       // fall through...
8064     }
8065     S += '^';
8066     getLegacyIntegralTypeEncoding(PointeeTy);
8067 
8068     ObjCEncOptions NewOptions;
8069     if (Options.ExpandPointedToStructures())
8070       NewOptions.setExpandStructures();
8071     getObjCEncodingForTypeImpl(PointeeTy, S, NewOptions,
8072                                /*Field=*/nullptr, NotEncodedT);
8073     return;
8074   }
8075 
8076   case Type::ConstantArray:
8077   case Type::IncompleteArray:
8078   case Type::VariableArray: {
8079     const auto *AT = cast<ArrayType>(CT);
8080 
8081     if (isa<IncompleteArrayType>(AT) && !Options.IsStructField()) {
8082       // Incomplete arrays are encoded as a pointer to the array element.
8083       S += '^';
8084 
8085       getObjCEncodingForTypeImpl(
8086           AT->getElementType(), S,
8087           Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD);
8088     } else {
8089       S += '[';
8090 
8091       if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
8092         S += llvm::utostr(CAT->getSize().getZExtValue());
8093       else {
8094         //Variable length arrays are encoded as a regular array with 0 elements.
8095         assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
8096                "Unknown array type!");
8097         S += '0';
8098       }
8099 
8100       getObjCEncodingForTypeImpl(
8101           AT->getElementType(), S,
8102           Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD,
8103           NotEncodedT);
8104       S += ']';
8105     }
8106     return;
8107   }
8108 
8109   case Type::FunctionNoProto:
8110   case Type::FunctionProto:
8111     S += '?';
8112     return;
8113 
8114   case Type::Record: {
8115     RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
8116     S += RDecl->isUnion() ? '(' : '{';
8117     // Anonymous structures print as '?'
8118     if (const IdentifierInfo *II = RDecl->getIdentifier()) {
8119       S += II->getName();
8120       if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
8121         const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
8122         llvm::raw_string_ostream OS(S);
8123         printTemplateArgumentList(OS, TemplateArgs.asArray(),
8124                                   getPrintingPolicy());
8125       }
8126     } else {
8127       S += '?';
8128     }
8129     if (Options.ExpandStructures()) {
8130       S += '=';
8131       if (!RDecl->isUnion()) {
8132         getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
8133       } else {
8134         for (const auto *Field : RDecl->fields()) {
8135           if (FD) {
8136             S += '"';
8137             S += Field->getNameAsString();
8138             S += '"';
8139           }
8140 
8141           // Special case bit-fields.
8142           if (Field->isBitField()) {
8143             getObjCEncodingForTypeImpl(Field->getType(), S,
8144                                        ObjCEncOptions().setExpandStructures(),
8145                                        Field);
8146           } else {
8147             QualType qt = Field->getType();
8148             getLegacyIntegralTypeEncoding(qt);
8149             getObjCEncodingForTypeImpl(
8150                 qt, S,
8151                 ObjCEncOptions().setExpandStructures().setIsStructField(), FD,
8152                 NotEncodedT);
8153           }
8154         }
8155       }
8156     }
8157     S += RDecl->isUnion() ? ')' : '}';
8158     return;
8159   }
8160 
8161   case Type::BlockPointer: {
8162     const auto *BT = T->castAs<BlockPointerType>();
8163     S += "@?"; // Unlike a pointer-to-function, which is "^?".
8164     if (Options.EncodeBlockParameters()) {
8165       const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
8166 
8167       S += '<';
8168       // Block return type
8169       getObjCEncodingForTypeImpl(FT->getReturnType(), S,
8170                                  Options.forComponentType(), FD, NotEncodedT);
8171       // Block self
8172       S += "@?";
8173       // Block parameters
8174       if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) {
8175         for (const auto &I : FPT->param_types())
8176           getObjCEncodingForTypeImpl(I, S, Options.forComponentType(), FD,
8177                                      NotEncodedT);
8178       }
8179       S += '>';
8180     }
8181     return;
8182   }
8183 
8184   case Type::ObjCObject: {
8185     // hack to match legacy encoding of *id and *Class
8186     QualType Ty = getObjCObjectPointerType(CT);
8187     if (Ty->isObjCIdType()) {
8188       S += "{objc_object=}";
8189       return;
8190     }
8191     else if (Ty->isObjCClassType()) {
8192       S += "{objc_class=}";
8193       return;
8194     }
8195     // TODO: Double check to make sure this intentionally falls through.
8196     LLVM_FALLTHROUGH;
8197   }
8198 
8199   case Type::ObjCInterface: {
8200     // Ignore protocol qualifiers when mangling at this level.
8201     // @encode(class_name)
8202     ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
8203     S += '{';
8204     S += OI->getObjCRuntimeNameAsString();
8205     if (Options.ExpandStructures()) {
8206       S += '=';
8207       SmallVector<const ObjCIvarDecl*, 32> Ivars;
8208       DeepCollectObjCIvars(OI, true, Ivars);
8209       for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
8210         const FieldDecl *Field = Ivars[i];
8211         if (Field->isBitField())
8212           getObjCEncodingForTypeImpl(Field->getType(), S,
8213                                      ObjCEncOptions().setExpandStructures(),
8214                                      Field);
8215         else
8216           getObjCEncodingForTypeImpl(Field->getType(), S,
8217                                      ObjCEncOptions().setExpandStructures(), FD,
8218                                      NotEncodedT);
8219       }
8220     }
8221     S += '}';
8222     return;
8223   }
8224 
8225   case Type::ObjCObjectPointer: {
8226     const auto *OPT = T->castAs<ObjCObjectPointerType>();
8227     if (OPT->isObjCIdType()) {
8228       S += '@';
8229       return;
8230     }
8231 
8232     if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
8233       // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
8234       // Since this is a binary compatibility issue, need to consult with
8235       // runtime folks. Fortunately, this is a *very* obscure construct.
8236       S += '#';
8237       return;
8238     }
8239 
8240     if (OPT->isObjCQualifiedIdType()) {
8241       getObjCEncodingForTypeImpl(
8242           getObjCIdType(), S,
8243           Options.keepingOnly(ObjCEncOptions()
8244                                   .setExpandPointedToStructures()
8245                                   .setExpandStructures()),
8246           FD);
8247       if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) {
8248         // Note that we do extended encoding of protocol qualifier list
8249         // Only when doing ivar or property encoding.
8250         S += '"';
8251         for (const auto *I : OPT->quals()) {
8252           S += '<';
8253           S += I->getObjCRuntimeNameAsString();
8254           S += '>';
8255         }
8256         S += '"';
8257       }
8258       return;
8259     }
8260 
8261     S += '@';
8262     if (OPT->getInterfaceDecl() &&
8263         (FD || Options.EncodingProperty() || Options.EncodeClassNames())) {
8264       S += '"';
8265       S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
8266       for (const auto *I : OPT->quals()) {
8267         S += '<';
8268         S += I->getObjCRuntimeNameAsString();
8269         S += '>';
8270       }
8271       S += '"';
8272     }
8273     return;
8274   }
8275 
8276   // gcc just blithely ignores member pointers.
8277   // FIXME: we should do better than that.  'M' is available.
8278   case Type::MemberPointer:
8279   // This matches gcc's encoding, even though technically it is insufficient.
8280   //FIXME. We should do a better job than gcc.
8281   case Type::Vector:
8282   case Type::ExtVector:
8283   // Until we have a coherent encoding of these three types, issue warning.
8284     if (NotEncodedT)
8285       *NotEncodedT = T;
8286     return;
8287 
8288   case Type::ConstantMatrix:
8289     if (NotEncodedT)
8290       *NotEncodedT = T;
8291     return;
8292 
8293   case Type::BitInt:
8294     if (NotEncodedT)
8295       *NotEncodedT = T;
8296     return;
8297 
8298   // We could see an undeduced auto type here during error recovery.
8299   // Just ignore it.
8300   case Type::Auto:
8301   case Type::DeducedTemplateSpecialization:
8302     return;
8303 
8304   case Type::Pipe:
8305 #define ABSTRACT_TYPE(KIND, BASE)
8306 #define TYPE(KIND, BASE)
8307 #define DEPENDENT_TYPE(KIND, BASE) \
8308   case Type::KIND:
8309 #define NON_CANONICAL_TYPE(KIND, BASE) \
8310   case Type::KIND:
8311 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
8312   case Type::KIND:
8313 #include "clang/AST/TypeNodes.inc"
8314     llvm_unreachable("@encode for dependent type!");
8315   }
8316   llvm_unreachable("bad type kind!");
8317 }
8318 
8319 void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
8320                                                  std::string &S,
8321                                                  const FieldDecl *FD,
8322                                                  bool includeVBases,
8323                                                  QualType *NotEncodedT) const {
8324   assert(RDecl && "Expected non-null RecordDecl");
8325   assert(!RDecl->isUnion() && "Should not be called for unions");
8326   if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
8327     return;
8328 
8329   const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
8330   std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
8331   const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
8332 
8333   if (CXXRec) {
8334     for (const auto &BI : CXXRec->bases()) {
8335       if (!BI.isVirtual()) {
8336         CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
8337         if (base->isEmpty())
8338           continue;
8339         uint64_t offs = toBits(layout.getBaseClassOffset(base));
8340         FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
8341                                   std::make_pair(offs, base));
8342       }
8343     }
8344   }
8345 
8346   unsigned i = 0;
8347   for (FieldDecl *Field : RDecl->fields()) {
8348     if (!Field->isZeroLengthBitField(*this) && Field->isZeroSize(*this))
8349       continue;
8350     uint64_t offs = layout.getFieldOffset(i);
8351     FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
8352                               std::make_pair(offs, Field));
8353     ++i;
8354   }
8355 
8356   if (CXXRec && includeVBases) {
8357     for (const auto &BI : CXXRec->vbases()) {
8358       CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
8359       if (base->isEmpty())
8360         continue;
8361       uint64_t offs = toBits(layout.getVBaseClassOffset(base));
8362       if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
8363           FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
8364         FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
8365                                   std::make_pair(offs, base));
8366     }
8367   }
8368 
8369   CharUnits size;
8370   if (CXXRec) {
8371     size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
8372   } else {
8373     size = layout.getSize();
8374   }
8375 
8376 #ifndef NDEBUG
8377   uint64_t CurOffs = 0;
8378 #endif
8379   std::multimap<uint64_t, NamedDecl *>::iterator
8380     CurLayObj = FieldOrBaseOffsets.begin();
8381 
8382   if (CXXRec && CXXRec->isDynamicClass() &&
8383       (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
8384     if (FD) {
8385       S += "\"_vptr$";
8386       std::string recname = CXXRec->getNameAsString();
8387       if (recname.empty()) recname = "?";
8388       S += recname;
8389       S += '"';
8390     }
8391     S += "^^?";
8392 #ifndef NDEBUG
8393     CurOffs += getTypeSize(VoidPtrTy);
8394 #endif
8395   }
8396 
8397   if (!RDecl->hasFlexibleArrayMember()) {
8398     // Mark the end of the structure.
8399     uint64_t offs = toBits(size);
8400     FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
8401                               std::make_pair(offs, nullptr));
8402   }
8403 
8404   for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
8405 #ifndef NDEBUG
8406     assert(CurOffs <= CurLayObj->first);
8407     if (CurOffs < CurLayObj->first) {
8408       uint64_t padding = CurLayObj->first - CurOffs;
8409       // FIXME: There doesn't seem to be a way to indicate in the encoding that
8410       // packing/alignment of members is different that normal, in which case
8411       // the encoding will be out-of-sync with the real layout.
8412       // If the runtime switches to just consider the size of types without
8413       // taking into account alignment, we could make padding explicit in the
8414       // encoding (e.g. using arrays of chars). The encoding strings would be
8415       // longer then though.
8416       CurOffs += padding;
8417     }
8418 #endif
8419 
8420     NamedDecl *dcl = CurLayObj->second;
8421     if (!dcl)
8422       break; // reached end of structure.
8423 
8424     if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) {
8425       // We expand the bases without their virtual bases since those are going
8426       // in the initial structure. Note that this differs from gcc which
8427       // expands virtual bases each time one is encountered in the hierarchy,
8428       // making the encoding type bigger than it really is.
8429       getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
8430                                       NotEncodedT);
8431       assert(!base->isEmpty());
8432 #ifndef NDEBUG
8433       CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
8434 #endif
8435     } else {
8436       const auto *field = cast<FieldDecl>(dcl);
8437       if (FD) {
8438         S += '"';
8439         S += field->getNameAsString();
8440         S += '"';
8441       }
8442 
8443       if (field->isBitField()) {
8444         EncodeBitField(this, S, field->getType(), field);
8445 #ifndef NDEBUG
8446         CurOffs += field->getBitWidthValue(*this);
8447 #endif
8448       } else {
8449         QualType qt = field->getType();
8450         getLegacyIntegralTypeEncoding(qt);
8451         getObjCEncodingForTypeImpl(
8452             qt, S, ObjCEncOptions().setExpandStructures().setIsStructField(),
8453             FD, NotEncodedT);
8454 #ifndef NDEBUG
8455         CurOffs += getTypeSize(field->getType());
8456 #endif
8457       }
8458     }
8459   }
8460 }
8461 
8462 void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
8463                                                  std::string& S) const {
8464   if (QT & Decl::OBJC_TQ_In)
8465     S += 'n';
8466   if (QT & Decl::OBJC_TQ_Inout)
8467     S += 'N';
8468   if (QT & Decl::OBJC_TQ_Out)
8469     S += 'o';
8470   if (QT & Decl::OBJC_TQ_Bycopy)
8471     S += 'O';
8472   if (QT & Decl::OBJC_TQ_Byref)
8473     S += 'R';
8474   if (QT & Decl::OBJC_TQ_Oneway)
8475     S += 'V';
8476 }
8477 
8478 TypedefDecl *ASTContext::getObjCIdDecl() const {
8479   if (!ObjCIdDecl) {
8480     QualType T = getObjCObjectType(ObjCBuiltinIdTy, {}, {});
8481     T = getObjCObjectPointerType(T);
8482     ObjCIdDecl = buildImplicitTypedef(T, "id");
8483   }
8484   return ObjCIdDecl;
8485 }
8486 
8487 TypedefDecl *ASTContext::getObjCSelDecl() const {
8488   if (!ObjCSelDecl) {
8489     QualType T = getPointerType(ObjCBuiltinSelTy);
8490     ObjCSelDecl = buildImplicitTypedef(T, "SEL");
8491   }
8492   return ObjCSelDecl;
8493 }
8494 
8495 TypedefDecl *ASTContext::getObjCClassDecl() const {
8496   if (!ObjCClassDecl) {
8497     QualType T = getObjCObjectType(ObjCBuiltinClassTy, {}, {});
8498     T = getObjCObjectPointerType(T);
8499     ObjCClassDecl = buildImplicitTypedef(T, "Class");
8500   }
8501   return ObjCClassDecl;
8502 }
8503 
8504 ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
8505   if (!ObjCProtocolClassDecl) {
8506     ObjCProtocolClassDecl
8507       = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
8508                                   SourceLocation(),
8509                                   &Idents.get("Protocol"),
8510                                   /*typeParamList=*/nullptr,
8511                                   /*PrevDecl=*/nullptr,
8512                                   SourceLocation(), true);
8513   }
8514 
8515   return ObjCProtocolClassDecl;
8516 }
8517 
8518 //===----------------------------------------------------------------------===//
8519 // __builtin_va_list Construction Functions
8520 //===----------------------------------------------------------------------===//
8521 
8522 static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
8523                                                  StringRef Name) {
8524   // typedef char* __builtin[_ms]_va_list;
8525   QualType T = Context->getPointerType(Context->CharTy);
8526   return Context->buildImplicitTypedef(T, Name);
8527 }
8528 
8529 static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
8530   return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
8531 }
8532 
8533 static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
8534   return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
8535 }
8536 
8537 static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
8538   // typedef void* __builtin_va_list;
8539   QualType T = Context->getPointerType(Context->VoidTy);
8540   return Context->buildImplicitTypedef(T, "__builtin_va_list");
8541 }
8542 
8543 static TypedefDecl *
8544 CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
8545   // struct __va_list
8546   RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
8547   if (Context->getLangOpts().CPlusPlus) {
8548     // namespace std { struct __va_list {
8549     auto *NS = NamespaceDecl::Create(
8550         const_cast<ASTContext &>(*Context), Context->getTranslationUnitDecl(),
8551         /*Inline*/ false, SourceLocation(), SourceLocation(),
8552         &Context->Idents.get("std"),
8553         /*PrevDecl*/ nullptr);
8554     NS->setImplicit();
8555     VaListTagDecl->setDeclContext(NS);
8556   }
8557 
8558   VaListTagDecl->startDefinition();
8559 
8560   const size_t NumFields = 5;
8561   QualType FieldTypes[NumFields];
8562   const char *FieldNames[NumFields];
8563 
8564   // void *__stack;
8565   FieldTypes[0] = Context->getPointerType(Context->VoidTy);
8566   FieldNames[0] = "__stack";
8567 
8568   // void *__gr_top;
8569   FieldTypes[1] = Context->getPointerType(Context->VoidTy);
8570   FieldNames[1] = "__gr_top";
8571 
8572   // void *__vr_top;
8573   FieldTypes[2] = Context->getPointerType(Context->VoidTy);
8574   FieldNames[2] = "__vr_top";
8575 
8576   // int __gr_offs;
8577   FieldTypes[3] = Context->IntTy;
8578   FieldNames[3] = "__gr_offs";
8579 
8580   // int __vr_offs;
8581   FieldTypes[4] = Context->IntTy;
8582   FieldNames[4] = "__vr_offs";
8583 
8584   // Create fields
8585   for (unsigned i = 0; i < NumFields; ++i) {
8586     FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
8587                                          VaListTagDecl,
8588                                          SourceLocation(),
8589                                          SourceLocation(),
8590                                          &Context->Idents.get(FieldNames[i]),
8591                                          FieldTypes[i], /*TInfo=*/nullptr,
8592                                          /*BitWidth=*/nullptr,
8593                                          /*Mutable=*/false,
8594                                          ICIS_NoInit);
8595     Field->setAccess(AS_public);
8596     VaListTagDecl->addDecl(Field);
8597   }
8598   VaListTagDecl->completeDefinition();
8599   Context->VaListTagDecl = VaListTagDecl;
8600   QualType VaListTagType = Context->getRecordType(VaListTagDecl);
8601 
8602   // } __builtin_va_list;
8603   return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
8604 }
8605 
8606 static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
8607   // typedef struct __va_list_tag {
8608   RecordDecl *VaListTagDecl;
8609 
8610   VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
8611   VaListTagDecl->startDefinition();
8612 
8613   const size_t NumFields = 5;
8614   QualType FieldTypes[NumFields];
8615   const char *FieldNames[NumFields];
8616 
8617   //   unsigned char gpr;
8618   FieldTypes[0] = Context->UnsignedCharTy;
8619   FieldNames[0] = "gpr";
8620 
8621   //   unsigned char fpr;
8622   FieldTypes[1] = Context->UnsignedCharTy;
8623   FieldNames[1] = "fpr";
8624 
8625   //   unsigned short reserved;
8626   FieldTypes[2] = Context->UnsignedShortTy;
8627   FieldNames[2] = "reserved";
8628 
8629   //   void* overflow_arg_area;
8630   FieldTypes[3] = Context->getPointerType(Context->VoidTy);
8631   FieldNames[3] = "overflow_arg_area";
8632 
8633   //   void* reg_save_area;
8634   FieldTypes[4] = Context->getPointerType(Context->VoidTy);
8635   FieldNames[4] = "reg_save_area";
8636 
8637   // Create fields
8638   for (unsigned i = 0; i < NumFields; ++i) {
8639     FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
8640                                          SourceLocation(),
8641                                          SourceLocation(),
8642                                          &Context->Idents.get(FieldNames[i]),
8643                                          FieldTypes[i], /*TInfo=*/nullptr,
8644                                          /*BitWidth=*/nullptr,
8645                                          /*Mutable=*/false,
8646                                          ICIS_NoInit);
8647     Field->setAccess(AS_public);
8648     VaListTagDecl->addDecl(Field);
8649   }
8650   VaListTagDecl->completeDefinition();
8651   Context->VaListTagDecl = VaListTagDecl;
8652   QualType VaListTagType = Context->getRecordType(VaListTagDecl);
8653 
8654   // } __va_list_tag;
8655   TypedefDecl *VaListTagTypedefDecl =
8656       Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
8657 
8658   QualType VaListTagTypedefType =
8659     Context->getTypedefType(VaListTagTypedefDecl);
8660 
8661   // typedef __va_list_tag __builtin_va_list[1];
8662   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
8663   QualType VaListTagArrayType
8664     = Context->getConstantArrayType(VaListTagTypedefType,
8665                                     Size, nullptr, ArrayType::Normal, 0);
8666   return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
8667 }
8668 
8669 static TypedefDecl *
8670 CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
8671   // struct __va_list_tag {
8672   RecordDecl *VaListTagDecl;
8673   VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
8674   VaListTagDecl->startDefinition();
8675 
8676   const size_t NumFields = 4;
8677   QualType FieldTypes[NumFields];
8678   const char *FieldNames[NumFields];
8679 
8680   //   unsigned gp_offset;
8681   FieldTypes[0] = Context->UnsignedIntTy;
8682   FieldNames[0] = "gp_offset";
8683 
8684   //   unsigned fp_offset;
8685   FieldTypes[1] = Context->UnsignedIntTy;
8686   FieldNames[1] = "fp_offset";
8687 
8688   //   void* overflow_arg_area;
8689   FieldTypes[2] = Context->getPointerType(Context->VoidTy);
8690   FieldNames[2] = "overflow_arg_area";
8691 
8692   //   void* reg_save_area;
8693   FieldTypes[3] = Context->getPointerType(Context->VoidTy);
8694   FieldNames[3] = "reg_save_area";
8695 
8696   // Create fields
8697   for (unsigned i = 0; i < NumFields; ++i) {
8698     FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
8699                                          VaListTagDecl,
8700                                          SourceLocation(),
8701                                          SourceLocation(),
8702                                          &Context->Idents.get(FieldNames[i]),
8703                                          FieldTypes[i], /*TInfo=*/nullptr,
8704                                          /*BitWidth=*/nullptr,
8705                                          /*Mutable=*/false,
8706                                          ICIS_NoInit);
8707     Field->setAccess(AS_public);
8708     VaListTagDecl->addDecl(Field);
8709   }
8710   VaListTagDecl->completeDefinition();
8711   Context->VaListTagDecl = VaListTagDecl;
8712   QualType VaListTagType = Context->getRecordType(VaListTagDecl);
8713 
8714   // };
8715 
8716   // typedef struct __va_list_tag __builtin_va_list[1];
8717   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
8718   QualType VaListTagArrayType = Context->getConstantArrayType(
8719       VaListTagType, Size, nullptr, ArrayType::Normal, 0);
8720   return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
8721 }
8722 
8723 static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
8724   // typedef int __builtin_va_list[4];
8725   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
8726   QualType IntArrayType = Context->getConstantArrayType(
8727       Context->IntTy, Size, nullptr, ArrayType::Normal, 0);
8728   return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
8729 }
8730 
8731 static TypedefDecl *
8732 CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
8733   // struct __va_list
8734   RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
8735   if (Context->getLangOpts().CPlusPlus) {
8736     // namespace std { struct __va_list {
8737     NamespaceDecl *NS;
8738     NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
8739                                Context->getTranslationUnitDecl(),
8740                                /*Inline*/false, SourceLocation(),
8741                                SourceLocation(), &Context->Idents.get("std"),
8742                                /*PrevDecl*/ nullptr);
8743     NS->setImplicit();
8744     VaListDecl->setDeclContext(NS);
8745   }
8746 
8747   VaListDecl->startDefinition();
8748 
8749   // void * __ap;
8750   FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
8751                                        VaListDecl,
8752                                        SourceLocation(),
8753                                        SourceLocation(),
8754                                        &Context->Idents.get("__ap"),
8755                                        Context->getPointerType(Context->VoidTy),
8756                                        /*TInfo=*/nullptr,
8757                                        /*BitWidth=*/nullptr,
8758                                        /*Mutable=*/false,
8759                                        ICIS_NoInit);
8760   Field->setAccess(AS_public);
8761   VaListDecl->addDecl(Field);
8762 
8763   // };
8764   VaListDecl->completeDefinition();
8765   Context->VaListTagDecl = VaListDecl;
8766 
8767   // typedef struct __va_list __builtin_va_list;
8768   QualType T = Context->getRecordType(VaListDecl);
8769   return Context->buildImplicitTypedef(T, "__builtin_va_list");
8770 }
8771 
8772 static TypedefDecl *
8773 CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
8774   // struct __va_list_tag {
8775   RecordDecl *VaListTagDecl;
8776   VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
8777   VaListTagDecl->startDefinition();
8778 
8779   const size_t NumFields = 4;
8780   QualType FieldTypes[NumFields];
8781   const char *FieldNames[NumFields];
8782 
8783   //   long __gpr;
8784   FieldTypes[0] = Context->LongTy;
8785   FieldNames[0] = "__gpr";
8786 
8787   //   long __fpr;
8788   FieldTypes[1] = Context->LongTy;
8789   FieldNames[1] = "__fpr";
8790 
8791   //   void *__overflow_arg_area;
8792   FieldTypes[2] = Context->getPointerType(Context->VoidTy);
8793   FieldNames[2] = "__overflow_arg_area";
8794 
8795   //   void *__reg_save_area;
8796   FieldTypes[3] = Context->getPointerType(Context->VoidTy);
8797   FieldNames[3] = "__reg_save_area";
8798 
8799   // Create fields
8800   for (unsigned i = 0; i < NumFields; ++i) {
8801     FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
8802                                          VaListTagDecl,
8803                                          SourceLocation(),
8804                                          SourceLocation(),
8805                                          &Context->Idents.get(FieldNames[i]),
8806                                          FieldTypes[i], /*TInfo=*/nullptr,
8807                                          /*BitWidth=*/nullptr,
8808                                          /*Mutable=*/false,
8809                                          ICIS_NoInit);
8810     Field->setAccess(AS_public);
8811     VaListTagDecl->addDecl(Field);
8812   }
8813   VaListTagDecl->completeDefinition();
8814   Context->VaListTagDecl = VaListTagDecl;
8815   QualType VaListTagType = Context->getRecordType(VaListTagDecl);
8816 
8817   // };
8818 
8819   // typedef __va_list_tag __builtin_va_list[1];
8820   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
8821   QualType VaListTagArrayType = Context->getConstantArrayType(
8822       VaListTagType, Size, nullptr, ArrayType::Normal, 0);
8823 
8824   return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
8825 }
8826 
8827 static TypedefDecl *CreateHexagonBuiltinVaListDecl(const ASTContext *Context) {
8828   // typedef struct __va_list_tag {
8829   RecordDecl *VaListTagDecl;
8830   VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
8831   VaListTagDecl->startDefinition();
8832 
8833   const size_t NumFields = 3;
8834   QualType FieldTypes[NumFields];
8835   const char *FieldNames[NumFields];
8836 
8837   //   void *CurrentSavedRegisterArea;
8838   FieldTypes[0] = Context->getPointerType(Context->VoidTy);
8839   FieldNames[0] = "__current_saved_reg_area_pointer";
8840 
8841   //   void *SavedRegAreaEnd;
8842   FieldTypes[1] = Context->getPointerType(Context->VoidTy);
8843   FieldNames[1] = "__saved_reg_area_end_pointer";
8844 
8845   //   void *OverflowArea;
8846   FieldTypes[2] = Context->getPointerType(Context->VoidTy);
8847   FieldNames[2] = "__overflow_area_pointer";
8848 
8849   // Create fields
8850   for (unsigned i = 0; i < NumFields; ++i) {
8851     FieldDecl *Field = FieldDecl::Create(
8852         const_cast<ASTContext &>(*Context), VaListTagDecl, SourceLocation(),
8853         SourceLocation(), &Context->Idents.get(FieldNames[i]), FieldTypes[i],
8854         /*TInfo=*/nullptr,
8855         /*BitWidth=*/nullptr,
8856         /*Mutable=*/false, ICIS_NoInit);
8857     Field->setAccess(AS_public);
8858     VaListTagDecl->addDecl(Field);
8859   }
8860   VaListTagDecl->completeDefinition();
8861   Context->VaListTagDecl = VaListTagDecl;
8862   QualType VaListTagType = Context->getRecordType(VaListTagDecl);
8863 
8864   // } __va_list_tag;
8865   TypedefDecl *VaListTagTypedefDecl =
8866       Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
8867 
8868   QualType VaListTagTypedefType = Context->getTypedefType(VaListTagTypedefDecl);
8869 
8870   // typedef __va_list_tag __builtin_va_list[1];
8871   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
8872   QualType VaListTagArrayType = Context->getConstantArrayType(
8873       VaListTagTypedefType, Size, nullptr, ArrayType::Normal, 0);
8874 
8875   return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
8876 }
8877 
8878 static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
8879                                      TargetInfo::BuiltinVaListKind Kind) {
8880   switch (Kind) {
8881   case TargetInfo::CharPtrBuiltinVaList:
8882     return CreateCharPtrBuiltinVaListDecl(Context);
8883   case TargetInfo::VoidPtrBuiltinVaList:
8884     return CreateVoidPtrBuiltinVaListDecl(Context);
8885   case TargetInfo::AArch64ABIBuiltinVaList:
8886     return CreateAArch64ABIBuiltinVaListDecl(Context);
8887   case TargetInfo::PowerABIBuiltinVaList:
8888     return CreatePowerABIBuiltinVaListDecl(Context);
8889   case TargetInfo::X86_64ABIBuiltinVaList:
8890     return CreateX86_64ABIBuiltinVaListDecl(Context);
8891   case TargetInfo::PNaClABIBuiltinVaList:
8892     return CreatePNaClABIBuiltinVaListDecl(Context);
8893   case TargetInfo::AAPCSABIBuiltinVaList:
8894     return CreateAAPCSABIBuiltinVaListDecl(Context);
8895   case TargetInfo::SystemZBuiltinVaList:
8896     return CreateSystemZBuiltinVaListDecl(Context);
8897   case TargetInfo::HexagonBuiltinVaList:
8898     return CreateHexagonBuiltinVaListDecl(Context);
8899   }
8900 
8901   llvm_unreachable("Unhandled __builtin_va_list type kind");
8902 }
8903 
8904 TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
8905   if (!BuiltinVaListDecl) {
8906     BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
8907     assert(BuiltinVaListDecl->isImplicit());
8908   }
8909 
8910   return BuiltinVaListDecl;
8911 }
8912 
8913 Decl *ASTContext::getVaListTagDecl() const {
8914   // Force the creation of VaListTagDecl by building the __builtin_va_list
8915   // declaration.
8916   if (!VaListTagDecl)
8917     (void)getBuiltinVaListDecl();
8918 
8919   return VaListTagDecl;
8920 }
8921 
8922 TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
8923   if (!BuiltinMSVaListDecl)
8924     BuiltinMSVaListDecl = CreateMSVaListDecl(this);
8925 
8926   return BuiltinMSVaListDecl;
8927 }
8928 
8929 bool ASTContext::canBuiltinBeRedeclared(const FunctionDecl *FD) const {
8930   return BuiltinInfo.canBeRedeclared(FD->getBuiltinID());
8931 }
8932 
8933 void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
8934   assert(ObjCConstantStringType.isNull() &&
8935          "'NSConstantString' type already set!");
8936 
8937   ObjCConstantStringType = getObjCInterfaceType(Decl);
8938 }
8939 
8940 /// Retrieve the template name that corresponds to a non-empty
8941 /// lookup.
8942 TemplateName
8943 ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
8944                                       UnresolvedSetIterator End) const {
8945   unsigned size = End - Begin;
8946   assert(size > 1 && "set is not overloaded!");
8947 
8948   void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
8949                           size * sizeof(FunctionTemplateDecl*));
8950   auto *OT = new (memory) OverloadedTemplateStorage(size);
8951 
8952   NamedDecl **Storage = OT->getStorage();
8953   for (UnresolvedSetIterator I = Begin; I != End; ++I) {
8954     NamedDecl *D = *I;
8955     assert(isa<FunctionTemplateDecl>(D) ||
8956            isa<UnresolvedUsingValueDecl>(D) ||
8957            (isa<UsingShadowDecl>(D) &&
8958             isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
8959     *Storage++ = D;
8960   }
8961 
8962   return TemplateName(OT);
8963 }
8964 
8965 /// Retrieve a template name representing an unqualified-id that has been
8966 /// assumed to name a template for ADL purposes.
8967 TemplateName ASTContext::getAssumedTemplateName(DeclarationName Name) const {
8968   auto *OT = new (*this) AssumedTemplateStorage(Name);
8969   return TemplateName(OT);
8970 }
8971 
8972 /// Retrieve the template name that represents a qualified
8973 /// template name such as \c std::vector.
8974 TemplateName
8975 ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
8976                                      bool TemplateKeyword,
8977                                      TemplateDecl *Template) const {
8978   assert(NNS && "Missing nested-name-specifier in qualified template name");
8979 
8980   // FIXME: Canonicalization?
8981   llvm::FoldingSetNodeID ID;
8982   QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
8983 
8984   void *InsertPos = nullptr;
8985   QualifiedTemplateName *QTN =
8986     QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
8987   if (!QTN) {
8988     QTN = new (*this, alignof(QualifiedTemplateName))
8989         QualifiedTemplateName(NNS, TemplateKeyword, Template);
8990     QualifiedTemplateNames.InsertNode(QTN, InsertPos);
8991   }
8992 
8993   return TemplateName(QTN);
8994 }
8995 
8996 /// Retrieve the template name that represents a dependent
8997 /// template name such as \c MetaFun::template apply.
8998 TemplateName
8999 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
9000                                      const IdentifierInfo *Name) const {
9001   assert((!NNS || NNS->isDependent()) &&
9002          "Nested name specifier must be dependent");
9003 
9004   llvm::FoldingSetNodeID ID;
9005   DependentTemplateName::Profile(ID, NNS, Name);
9006 
9007   void *InsertPos = nullptr;
9008   DependentTemplateName *QTN =
9009     DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
9010 
9011   if (QTN)
9012     return TemplateName(QTN);
9013 
9014   NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
9015   if (CanonNNS == NNS) {
9016     QTN = new (*this, alignof(DependentTemplateName))
9017         DependentTemplateName(NNS, Name);
9018   } else {
9019     TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
9020     QTN = new (*this, alignof(DependentTemplateName))
9021         DependentTemplateName(NNS, Name, Canon);
9022     DependentTemplateName *CheckQTN =
9023       DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
9024     assert(!CheckQTN && "Dependent type name canonicalization broken");
9025     (void)CheckQTN;
9026   }
9027 
9028   DependentTemplateNames.InsertNode(QTN, InsertPos);
9029   return TemplateName(QTN);
9030 }
9031 
9032 /// Retrieve the template name that represents a dependent
9033 /// template name such as \c MetaFun::template operator+.
9034 TemplateName
9035 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
9036                                      OverloadedOperatorKind Operator) const {
9037   assert((!NNS || NNS->isDependent()) &&
9038          "Nested name specifier must be dependent");
9039 
9040   llvm::FoldingSetNodeID ID;
9041   DependentTemplateName::Profile(ID, NNS, Operator);
9042 
9043   void *InsertPos = nullptr;
9044   DependentTemplateName *QTN
9045     = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
9046 
9047   if (QTN)
9048     return TemplateName(QTN);
9049 
9050   NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
9051   if (CanonNNS == NNS) {
9052     QTN = new (*this, alignof(DependentTemplateName))
9053         DependentTemplateName(NNS, Operator);
9054   } else {
9055     TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
9056     QTN = new (*this, alignof(DependentTemplateName))
9057         DependentTemplateName(NNS, Operator, Canon);
9058 
9059     DependentTemplateName *CheckQTN
9060       = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
9061     assert(!CheckQTN && "Dependent template name canonicalization broken");
9062     (void)CheckQTN;
9063   }
9064 
9065   DependentTemplateNames.InsertNode(QTN, InsertPos);
9066   return TemplateName(QTN);
9067 }
9068 
9069 TemplateName
9070 ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
9071                                          TemplateName replacement) const {
9072   llvm::FoldingSetNodeID ID;
9073   SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
9074 
9075   void *insertPos = nullptr;
9076   SubstTemplateTemplateParmStorage *subst
9077     = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
9078 
9079   if (!subst) {
9080     subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
9081     SubstTemplateTemplateParms.InsertNode(subst, insertPos);
9082   }
9083 
9084   return TemplateName(subst);
9085 }
9086 
9087 TemplateName
9088 ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
9089                                        const TemplateArgument &ArgPack) const {
9090   auto &Self = const_cast<ASTContext &>(*this);
9091   llvm::FoldingSetNodeID ID;
9092   SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
9093 
9094   void *InsertPos = nullptr;
9095   SubstTemplateTemplateParmPackStorage *Subst
9096     = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
9097 
9098   if (!Subst) {
9099     Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
9100                                                            ArgPack.pack_size(),
9101                                                          ArgPack.pack_begin());
9102     SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
9103   }
9104 
9105   return TemplateName(Subst);
9106 }
9107 
9108 /// getFromTargetType - Given one of the integer types provided by
9109 /// TargetInfo, produce the corresponding type. The unsigned @p Type
9110 /// is actually a value of type @c TargetInfo::IntType.
9111 CanQualType ASTContext::getFromTargetType(unsigned Type) const {
9112   switch (Type) {
9113   case TargetInfo::NoInt: return {};
9114   case TargetInfo::SignedChar: return SignedCharTy;
9115   case TargetInfo::UnsignedChar: return UnsignedCharTy;
9116   case TargetInfo::SignedShort: return ShortTy;
9117   case TargetInfo::UnsignedShort: return UnsignedShortTy;
9118   case TargetInfo::SignedInt: return IntTy;
9119   case TargetInfo::UnsignedInt: return UnsignedIntTy;
9120   case TargetInfo::SignedLong: return LongTy;
9121   case TargetInfo::UnsignedLong: return UnsignedLongTy;
9122   case TargetInfo::SignedLongLong: return LongLongTy;
9123   case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
9124   }
9125 
9126   llvm_unreachable("Unhandled TargetInfo::IntType value");
9127 }
9128 
9129 //===----------------------------------------------------------------------===//
9130 //                        Type Predicates.
9131 //===----------------------------------------------------------------------===//
9132 
9133 /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
9134 /// garbage collection attribute.
9135 ///
9136 Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
9137   if (getLangOpts().getGC() == LangOptions::NonGC)
9138     return Qualifiers::GCNone;
9139 
9140   assert(getLangOpts().ObjC);
9141   Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
9142 
9143   // Default behaviour under objective-C's gc is for ObjC pointers
9144   // (or pointers to them) be treated as though they were declared
9145   // as __strong.
9146   if (GCAttrs == Qualifiers::GCNone) {
9147     if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
9148       return Qualifiers::Strong;
9149     else if (Ty->isPointerType())
9150       return getObjCGCAttrKind(Ty->castAs<PointerType>()->getPointeeType());
9151   } else {
9152     // It's not valid to set GC attributes on anything that isn't a
9153     // pointer.
9154 #ifndef NDEBUG
9155     QualType CT = Ty->getCanonicalTypeInternal();
9156     while (const auto *AT = dyn_cast<ArrayType>(CT))
9157       CT = AT->getElementType();
9158     assert(CT->isAnyPointerType() || CT->isBlockPointerType());
9159 #endif
9160   }
9161   return GCAttrs;
9162 }
9163 
9164 //===----------------------------------------------------------------------===//
9165 //                        Type Compatibility Testing
9166 //===----------------------------------------------------------------------===//
9167 
9168 /// areCompatVectorTypes - Return true if the two specified vector types are
9169 /// compatible.
9170 static bool areCompatVectorTypes(const VectorType *LHS,
9171                                  const VectorType *RHS) {
9172   assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
9173   return LHS->getElementType() == RHS->getElementType() &&
9174          LHS->getNumElements() == RHS->getNumElements();
9175 }
9176 
9177 /// areCompatMatrixTypes - Return true if the two specified matrix types are
9178 /// compatible.
9179 static bool areCompatMatrixTypes(const ConstantMatrixType *LHS,
9180                                  const ConstantMatrixType *RHS) {
9181   assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
9182   return LHS->getElementType() == RHS->getElementType() &&
9183          LHS->getNumRows() == RHS->getNumRows() &&
9184          LHS->getNumColumns() == RHS->getNumColumns();
9185 }
9186 
9187 bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
9188                                           QualType SecondVec) {
9189   assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
9190   assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
9191 
9192   if (hasSameUnqualifiedType(FirstVec, SecondVec))
9193     return true;
9194 
9195   // Treat Neon vector types and most AltiVec vector types as if they are the
9196   // equivalent GCC vector types.
9197   const auto *First = FirstVec->castAs<VectorType>();
9198   const auto *Second = SecondVec->castAs<VectorType>();
9199   if (First->getNumElements() == Second->getNumElements() &&
9200       hasSameType(First->getElementType(), Second->getElementType()) &&
9201       First->getVectorKind() != VectorType::AltiVecPixel &&
9202       First->getVectorKind() != VectorType::AltiVecBool &&
9203       Second->getVectorKind() != VectorType::AltiVecPixel &&
9204       Second->getVectorKind() != VectorType::AltiVecBool &&
9205       First->getVectorKind() != VectorType::SveFixedLengthDataVector &&
9206       First->getVectorKind() != VectorType::SveFixedLengthPredicateVector &&
9207       Second->getVectorKind() != VectorType::SveFixedLengthDataVector &&
9208       Second->getVectorKind() != VectorType::SveFixedLengthPredicateVector)
9209     return true;
9210 
9211   return false;
9212 }
9213 
9214 /// getSVETypeSize - Return SVE vector or predicate register size.
9215 static uint64_t getSVETypeSize(ASTContext &Context, const BuiltinType *Ty) {
9216   assert(Ty->isVLSTBuiltinType() && "Invalid SVE Type");
9217   return Ty->getKind() == BuiltinType::SveBool
9218              ? (Context.getLangOpts().VScaleMin * 128) / Context.getCharWidth()
9219              : Context.getLangOpts().VScaleMin * 128;
9220 }
9221 
9222 bool ASTContext::areCompatibleSveTypes(QualType FirstType,
9223                                        QualType SecondType) {
9224   assert(((FirstType->isSizelessBuiltinType() && SecondType->isVectorType()) ||
9225           (FirstType->isVectorType() && SecondType->isSizelessBuiltinType())) &&
9226          "Expected SVE builtin type and vector type!");
9227 
9228   auto IsValidCast = [this](QualType FirstType, QualType SecondType) {
9229     if (const auto *BT = FirstType->getAs<BuiltinType>()) {
9230       if (const auto *VT = SecondType->getAs<VectorType>()) {
9231         // Predicates have the same representation as uint8 so we also have to
9232         // check the kind to make these types incompatible.
9233         if (VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector)
9234           return BT->getKind() == BuiltinType::SveBool;
9235         else if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector)
9236           return VT->getElementType().getCanonicalType() ==
9237                  FirstType->getSveEltType(*this);
9238         else if (VT->getVectorKind() == VectorType::GenericVector)
9239           return getTypeSize(SecondType) == getSVETypeSize(*this, BT) &&
9240                  hasSameType(VT->getElementType(),
9241                              getBuiltinVectorTypeInfo(BT).ElementType);
9242       }
9243     }
9244     return false;
9245   };
9246 
9247   return IsValidCast(FirstType, SecondType) ||
9248          IsValidCast(SecondType, FirstType);
9249 }
9250 
9251 bool ASTContext::areLaxCompatibleSveTypes(QualType FirstType,
9252                                           QualType SecondType) {
9253   assert(((FirstType->isSizelessBuiltinType() && SecondType->isVectorType()) ||
9254           (FirstType->isVectorType() && SecondType->isSizelessBuiltinType())) &&
9255          "Expected SVE builtin type and vector type!");
9256 
9257   auto IsLaxCompatible = [this](QualType FirstType, QualType SecondType) {
9258     const auto *BT = FirstType->getAs<BuiltinType>();
9259     if (!BT)
9260       return false;
9261 
9262     const auto *VecTy = SecondType->getAs<VectorType>();
9263     if (VecTy &&
9264         (VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector ||
9265          VecTy->getVectorKind() == VectorType::GenericVector)) {
9266       const LangOptions::LaxVectorConversionKind LVCKind =
9267           getLangOpts().getLaxVectorConversions();
9268 
9269       // Can not convert between sve predicates and sve vectors because of
9270       // different size.
9271       if (BT->getKind() == BuiltinType::SveBool &&
9272           VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector)
9273         return false;
9274 
9275       // If __ARM_FEATURE_SVE_BITS != N do not allow GNU vector lax conversion.
9276       // "Whenever __ARM_FEATURE_SVE_BITS==N, GNUT implicitly
9277       // converts to VLAT and VLAT implicitly converts to GNUT."
9278       // ACLE Spec Version 00bet6, 3.7.3.2. Behavior common to vectors and
9279       // predicates.
9280       if (VecTy->getVectorKind() == VectorType::GenericVector &&
9281           getTypeSize(SecondType) != getSVETypeSize(*this, BT))
9282         return false;
9283 
9284       // If -flax-vector-conversions=all is specified, the types are
9285       // certainly compatible.
9286       if (LVCKind == LangOptions::LaxVectorConversionKind::All)
9287         return true;
9288 
9289       // If -flax-vector-conversions=integer is specified, the types are
9290       // compatible if the elements are integer types.
9291       if (LVCKind == LangOptions::LaxVectorConversionKind::Integer)
9292         return VecTy->getElementType().getCanonicalType()->isIntegerType() &&
9293                FirstType->getSveEltType(*this)->isIntegerType();
9294     }
9295 
9296     return false;
9297   };
9298 
9299   return IsLaxCompatible(FirstType, SecondType) ||
9300          IsLaxCompatible(SecondType, FirstType);
9301 }
9302 
9303 bool ASTContext::hasDirectOwnershipQualifier(QualType Ty) const {
9304   while (true) {
9305     // __strong id
9306     if (const AttributedType *Attr = dyn_cast<AttributedType>(Ty)) {
9307       if (Attr->getAttrKind() == attr::ObjCOwnership)
9308         return true;
9309 
9310       Ty = Attr->getModifiedType();
9311 
9312     // X *__strong (...)
9313     } else if (const ParenType *Paren = dyn_cast<ParenType>(Ty)) {
9314       Ty = Paren->getInnerType();
9315 
9316     // We do not want to look through typedefs, typeof(expr),
9317     // typeof(type), or any other way that the type is somehow
9318     // abstracted.
9319     } else {
9320       return false;
9321     }
9322   }
9323 }
9324 
9325 //===----------------------------------------------------------------------===//
9326 // ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
9327 //===----------------------------------------------------------------------===//
9328 
9329 /// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
9330 /// inheritance hierarchy of 'rProto'.
9331 bool
9332 ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
9333                                            ObjCProtocolDecl *rProto) const {
9334   if (declaresSameEntity(lProto, rProto))
9335     return true;
9336   for (auto *PI : rProto->protocols())
9337     if (ProtocolCompatibleWithProtocol(lProto, PI))
9338       return true;
9339   return false;
9340 }
9341 
9342 /// ObjCQualifiedClassTypesAreCompatible - compare  Class<pr,...> and
9343 /// Class<pr1, ...>.
9344 bool ASTContext::ObjCQualifiedClassTypesAreCompatible(
9345     const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs) {
9346   for (auto *lhsProto : lhs->quals()) {
9347     bool match = false;
9348     for (auto *rhsProto : rhs->quals()) {
9349       if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
9350         match = true;
9351         break;
9352       }
9353     }
9354     if (!match)
9355       return false;
9356   }
9357   return true;
9358 }
9359 
9360 /// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
9361 /// ObjCQualifiedIDType.
9362 bool ASTContext::ObjCQualifiedIdTypesAreCompatible(
9363     const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs,
9364     bool compare) {
9365   // Allow id<P..> and an 'id' in all cases.
9366   if (lhs->isObjCIdType() || rhs->isObjCIdType())
9367     return true;
9368 
9369   // Don't allow id<P..> to convert to Class or Class<P..> in either direction.
9370   if (lhs->isObjCClassType() || lhs->isObjCQualifiedClassType() ||
9371       rhs->isObjCClassType() || rhs->isObjCQualifiedClassType())
9372     return false;
9373 
9374   if (lhs->isObjCQualifiedIdType()) {
9375     if (rhs->qual_empty()) {
9376       // If the RHS is a unqualified interface pointer "NSString*",
9377       // make sure we check the class hierarchy.
9378       if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
9379         for (auto *I : lhs->quals()) {
9380           // when comparing an id<P> on lhs with a static type on rhs,
9381           // see if static class implements all of id's protocols, directly or
9382           // through its super class and categories.
9383           if (!rhsID->ClassImplementsProtocol(I, true))
9384             return false;
9385         }
9386       }
9387       // If there are no qualifiers and no interface, we have an 'id'.
9388       return true;
9389     }
9390     // Both the right and left sides have qualifiers.
9391     for (auto *lhsProto : lhs->quals()) {
9392       bool match = false;
9393 
9394       // when comparing an id<P> on lhs with a static type on rhs,
9395       // see if static class implements all of id's protocols, directly or
9396       // through its super class and categories.
9397       for (auto *rhsProto : rhs->quals()) {
9398         if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
9399             (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
9400           match = true;
9401           break;
9402         }
9403       }
9404       // If the RHS is a qualified interface pointer "NSString<P>*",
9405       // make sure we check the class hierarchy.
9406       if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
9407         for (auto *I : lhs->quals()) {
9408           // when comparing an id<P> on lhs with a static type on rhs,
9409           // see if static class implements all of id's protocols, directly or
9410           // through its super class and categories.
9411           if (rhsID->ClassImplementsProtocol(I, true)) {
9412             match = true;
9413             break;
9414           }
9415         }
9416       }
9417       if (!match)
9418         return false;
9419     }
9420 
9421     return true;
9422   }
9423 
9424   assert(rhs->isObjCQualifiedIdType() && "One of the LHS/RHS should be id<x>");
9425 
9426   if (lhs->getInterfaceType()) {
9427     // If both the right and left sides have qualifiers.
9428     for (auto *lhsProto : lhs->quals()) {
9429       bool match = false;
9430 
9431       // when comparing an id<P> on rhs with a static type on lhs,
9432       // see if static class implements all of id's protocols, directly or
9433       // through its super class and categories.
9434       // First, lhs protocols in the qualifier list must be found, direct
9435       // or indirect in rhs's qualifier list or it is a mismatch.
9436       for (auto *rhsProto : rhs->quals()) {
9437         if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
9438             (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
9439           match = true;
9440           break;
9441         }
9442       }
9443       if (!match)
9444         return false;
9445     }
9446 
9447     // Static class's protocols, or its super class or category protocols
9448     // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
9449     if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) {
9450       llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
9451       CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
9452       // This is rather dubious but matches gcc's behavior. If lhs has
9453       // no type qualifier and its class has no static protocol(s)
9454       // assume that it is mismatch.
9455       if (LHSInheritedProtocols.empty() && lhs->qual_empty())
9456         return false;
9457       for (auto *lhsProto : LHSInheritedProtocols) {
9458         bool match = false;
9459         for (auto *rhsProto : rhs->quals()) {
9460           if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
9461               (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
9462             match = true;
9463             break;
9464           }
9465         }
9466         if (!match)
9467           return false;
9468       }
9469     }
9470     return true;
9471   }
9472   return false;
9473 }
9474 
9475 /// canAssignObjCInterfaces - Return true if the two interface types are
9476 /// compatible for assignment from RHS to LHS.  This handles validation of any
9477 /// protocol qualifiers on the LHS or RHS.
9478 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
9479                                          const ObjCObjectPointerType *RHSOPT) {
9480   const ObjCObjectType* LHS = LHSOPT->getObjectType();
9481   const ObjCObjectType* RHS = RHSOPT->getObjectType();
9482 
9483   // If either type represents the built-in 'id' type, return true.
9484   if (LHS->isObjCUnqualifiedId() || RHS->isObjCUnqualifiedId())
9485     return true;
9486 
9487   // Function object that propagates a successful result or handles
9488   // __kindof types.
9489   auto finish = [&](bool succeeded) -> bool {
9490     if (succeeded)
9491       return true;
9492 
9493     if (!RHS->isKindOfType())
9494       return false;
9495 
9496     // Strip off __kindof and protocol qualifiers, then check whether
9497     // we can assign the other way.
9498     return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
9499                                    LHSOPT->stripObjCKindOfTypeAndQuals(*this));
9500   };
9501 
9502   // Casts from or to id<P> are allowed when the other side has compatible
9503   // protocols.
9504   if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
9505     return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false));
9506   }
9507 
9508   // Verify protocol compatibility for casts from Class<P1> to Class<P2>.
9509   if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
9510     return finish(ObjCQualifiedClassTypesAreCompatible(LHSOPT, RHSOPT));
9511   }
9512 
9513   // Casts from Class to Class<Foo>, or vice-versa, are allowed.
9514   if (LHS->isObjCClass() && RHS->isObjCClass()) {
9515     return true;
9516   }
9517 
9518   // If we have 2 user-defined types, fall into that path.
9519   if (LHS->getInterface() && RHS->getInterface()) {
9520     return finish(canAssignObjCInterfaces(LHS, RHS));
9521   }
9522 
9523   return false;
9524 }
9525 
9526 /// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
9527 /// for providing type-safety for objective-c pointers used to pass/return
9528 /// arguments in block literals. When passed as arguments, passing 'A*' where
9529 /// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
9530 /// not OK. For the return type, the opposite is not OK.
9531 bool ASTContext::canAssignObjCInterfacesInBlockPointer(
9532                                          const ObjCObjectPointerType *LHSOPT,
9533                                          const ObjCObjectPointerType *RHSOPT,
9534                                          bool BlockReturnType) {
9535 
9536   // Function object that propagates a successful result or handles
9537   // __kindof types.
9538   auto finish = [&](bool succeeded) -> bool {
9539     if (succeeded)
9540       return true;
9541 
9542     const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
9543     if (!Expected->isKindOfType())
9544       return false;
9545 
9546     // Strip off __kindof and protocol qualifiers, then check whether
9547     // we can assign the other way.
9548     return canAssignObjCInterfacesInBlockPointer(
9549              RHSOPT->stripObjCKindOfTypeAndQuals(*this),
9550              LHSOPT->stripObjCKindOfTypeAndQuals(*this),
9551              BlockReturnType);
9552   };
9553 
9554   if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
9555     return true;
9556 
9557   if (LHSOPT->isObjCBuiltinType()) {
9558     return finish(RHSOPT->isObjCBuiltinType() ||
9559                   RHSOPT->isObjCQualifiedIdType());
9560   }
9561 
9562   if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) {
9563     if (getLangOpts().CompatibilityQualifiedIdBlockParamTypeChecking)
9564       // Use for block parameters previous type checking for compatibility.
9565       return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false) ||
9566                     // Or corrected type checking as in non-compat mode.
9567                     (!BlockReturnType &&
9568                      ObjCQualifiedIdTypesAreCompatible(RHSOPT, LHSOPT, false)));
9569     else
9570       return finish(ObjCQualifiedIdTypesAreCompatible(
9571           (BlockReturnType ? LHSOPT : RHSOPT),
9572           (BlockReturnType ? RHSOPT : LHSOPT), false));
9573   }
9574 
9575   const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
9576   const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
9577   if (LHS && RHS)  { // We have 2 user-defined types.
9578     if (LHS != RHS) {
9579       if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
9580         return finish(BlockReturnType);
9581       if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
9582         return finish(!BlockReturnType);
9583     }
9584     else
9585       return true;
9586   }
9587   return false;
9588 }
9589 
9590 /// Comparison routine for Objective-C protocols to be used with
9591 /// llvm::array_pod_sort.
9592 static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
9593                                       ObjCProtocolDecl * const *rhs) {
9594   return (*lhs)->getName().compare((*rhs)->getName());
9595 }
9596 
9597 /// getIntersectionOfProtocols - This routine finds the intersection of set
9598 /// of protocols inherited from two distinct objective-c pointer objects with
9599 /// the given common base.
9600 /// It is used to build composite qualifier list of the composite type of
9601 /// the conditional expression involving two objective-c pointer objects.
9602 static
9603 void getIntersectionOfProtocols(ASTContext &Context,
9604                                 const ObjCInterfaceDecl *CommonBase,
9605                                 const ObjCObjectPointerType *LHSOPT,
9606                                 const ObjCObjectPointerType *RHSOPT,
9607       SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
9608 
9609   const ObjCObjectType* LHS = LHSOPT->getObjectType();
9610   const ObjCObjectType* RHS = RHSOPT->getObjectType();
9611   assert(LHS->getInterface() && "LHS must have an interface base");
9612   assert(RHS->getInterface() && "RHS must have an interface base");
9613 
9614   // Add all of the protocols for the LHS.
9615   llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
9616 
9617   // Start with the protocol qualifiers.
9618   for (auto proto : LHS->quals()) {
9619     Context.CollectInheritedProtocols(proto, LHSProtocolSet);
9620   }
9621 
9622   // Also add the protocols associated with the LHS interface.
9623   Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
9624 
9625   // Add all of the protocols for the RHS.
9626   llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
9627 
9628   // Start with the protocol qualifiers.
9629   for (auto proto : RHS->quals()) {
9630     Context.CollectInheritedProtocols(proto, RHSProtocolSet);
9631   }
9632 
9633   // Also add the protocols associated with the RHS interface.
9634   Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
9635 
9636   // Compute the intersection of the collected protocol sets.
9637   for (auto proto : LHSProtocolSet) {
9638     if (RHSProtocolSet.count(proto))
9639       IntersectionSet.push_back(proto);
9640   }
9641 
9642   // Compute the set of protocols that is implied by either the common type or
9643   // the protocols within the intersection.
9644   llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
9645   Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
9646 
9647   // Remove any implied protocols from the list of inherited protocols.
9648   if (!ImpliedProtocols.empty()) {
9649     llvm::erase_if(IntersectionSet, [&](ObjCProtocolDecl *proto) -> bool {
9650       return ImpliedProtocols.contains(proto);
9651     });
9652   }
9653 
9654   // Sort the remaining protocols by name.
9655   llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
9656                        compareObjCProtocolsByName);
9657 }
9658 
9659 /// Determine whether the first type is a subtype of the second.
9660 static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
9661                                      QualType rhs) {
9662   // Common case: two object pointers.
9663   const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
9664   const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
9665   if (lhsOPT && rhsOPT)
9666     return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
9667 
9668   // Two block pointers.
9669   const auto *lhsBlock = lhs->getAs<BlockPointerType>();
9670   const auto *rhsBlock = rhs->getAs<BlockPointerType>();
9671   if (lhsBlock && rhsBlock)
9672     return ctx.typesAreBlockPointerCompatible(lhs, rhs);
9673 
9674   // If either is an unqualified 'id' and the other is a block, it's
9675   // acceptable.
9676   if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
9677       (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
9678     return true;
9679 
9680   return false;
9681 }
9682 
9683 // Check that the given Objective-C type argument lists are equivalent.
9684 static bool sameObjCTypeArgs(ASTContext &ctx,
9685                              const ObjCInterfaceDecl *iface,
9686                              ArrayRef<QualType> lhsArgs,
9687                              ArrayRef<QualType> rhsArgs,
9688                              bool stripKindOf) {
9689   if (lhsArgs.size() != rhsArgs.size())
9690     return false;
9691 
9692   ObjCTypeParamList *typeParams = iface->getTypeParamList();
9693   for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
9694     if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
9695       continue;
9696 
9697     switch (typeParams->begin()[i]->getVariance()) {
9698     case ObjCTypeParamVariance::Invariant:
9699       if (!stripKindOf ||
9700           !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
9701                            rhsArgs[i].stripObjCKindOfType(ctx))) {
9702         return false;
9703       }
9704       break;
9705 
9706     case ObjCTypeParamVariance::Covariant:
9707       if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
9708         return false;
9709       break;
9710 
9711     case ObjCTypeParamVariance::Contravariant:
9712       if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
9713         return false;
9714       break;
9715     }
9716   }
9717 
9718   return true;
9719 }
9720 
9721 QualType ASTContext::areCommonBaseCompatible(
9722            const ObjCObjectPointerType *Lptr,
9723            const ObjCObjectPointerType *Rptr) {
9724   const ObjCObjectType *LHS = Lptr->getObjectType();
9725   const ObjCObjectType *RHS = Rptr->getObjectType();
9726   const ObjCInterfaceDecl* LDecl = LHS->getInterface();
9727   const ObjCInterfaceDecl* RDecl = RHS->getInterface();
9728 
9729   if (!LDecl || !RDecl)
9730     return {};
9731 
9732   // When either LHS or RHS is a kindof type, we should return a kindof type.
9733   // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
9734   // kindof(A).
9735   bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
9736 
9737   // Follow the left-hand side up the class hierarchy until we either hit a
9738   // root or find the RHS. Record the ancestors in case we don't find it.
9739   llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
9740     LHSAncestors;
9741   while (true) {
9742     // Record this ancestor. We'll need this if the common type isn't in the
9743     // path from the LHS to the root.
9744     LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
9745 
9746     if (declaresSameEntity(LHS->getInterface(), RDecl)) {
9747       // Get the type arguments.
9748       ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
9749       bool anyChanges = false;
9750       if (LHS->isSpecialized() && RHS->isSpecialized()) {
9751         // Both have type arguments, compare them.
9752         if (!sameObjCTypeArgs(*this, LHS->getInterface(),
9753                               LHS->getTypeArgs(), RHS->getTypeArgs(),
9754                               /*stripKindOf=*/true))
9755           return {};
9756       } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
9757         // If only one has type arguments, the result will not have type
9758         // arguments.
9759         LHSTypeArgs = {};
9760         anyChanges = true;
9761       }
9762 
9763       // Compute the intersection of protocols.
9764       SmallVector<ObjCProtocolDecl *, 8> Protocols;
9765       getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
9766                                  Protocols);
9767       if (!Protocols.empty())
9768         anyChanges = true;
9769 
9770       // If anything in the LHS will have changed, build a new result type.
9771       // If we need to return a kindof type but LHS is not a kindof type, we
9772       // build a new result type.
9773       if (anyChanges || LHS->isKindOfType() != anyKindOf) {
9774         QualType Result = getObjCInterfaceType(LHS->getInterface());
9775         Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
9776                                    anyKindOf || LHS->isKindOfType());
9777         return getObjCObjectPointerType(Result);
9778       }
9779 
9780       return getObjCObjectPointerType(QualType(LHS, 0));
9781     }
9782 
9783     // Find the superclass.
9784     QualType LHSSuperType = LHS->getSuperClassType();
9785     if (LHSSuperType.isNull())
9786       break;
9787 
9788     LHS = LHSSuperType->castAs<ObjCObjectType>();
9789   }
9790 
9791   // We didn't find anything by following the LHS to its root; now check
9792   // the RHS against the cached set of ancestors.
9793   while (true) {
9794     auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
9795     if (KnownLHS != LHSAncestors.end()) {
9796       LHS = KnownLHS->second;
9797 
9798       // Get the type arguments.
9799       ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
9800       bool anyChanges = false;
9801       if (LHS->isSpecialized() && RHS->isSpecialized()) {
9802         // Both have type arguments, compare them.
9803         if (!sameObjCTypeArgs(*this, LHS->getInterface(),
9804                               LHS->getTypeArgs(), RHS->getTypeArgs(),
9805                               /*stripKindOf=*/true))
9806           return {};
9807       } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
9808         // If only one has type arguments, the result will not have type
9809         // arguments.
9810         RHSTypeArgs = {};
9811         anyChanges = true;
9812       }
9813 
9814       // Compute the intersection of protocols.
9815       SmallVector<ObjCProtocolDecl *, 8> Protocols;
9816       getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
9817                                  Protocols);
9818       if (!Protocols.empty())
9819         anyChanges = true;
9820 
9821       // If we need to return a kindof type but RHS is not a kindof type, we
9822       // build a new result type.
9823       if (anyChanges || RHS->isKindOfType() != anyKindOf) {
9824         QualType Result = getObjCInterfaceType(RHS->getInterface());
9825         Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
9826                                    anyKindOf || RHS->isKindOfType());
9827         return getObjCObjectPointerType(Result);
9828       }
9829 
9830       return getObjCObjectPointerType(QualType(RHS, 0));
9831     }
9832 
9833     // Find the superclass of the RHS.
9834     QualType RHSSuperType = RHS->getSuperClassType();
9835     if (RHSSuperType.isNull())
9836       break;
9837 
9838     RHS = RHSSuperType->castAs<ObjCObjectType>();
9839   }
9840 
9841   return {};
9842 }
9843 
9844 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
9845                                          const ObjCObjectType *RHS) {
9846   assert(LHS->getInterface() && "LHS is not an interface type");
9847   assert(RHS->getInterface() && "RHS is not an interface type");
9848 
9849   // Verify that the base decls are compatible: the RHS must be a subclass of
9850   // the LHS.
9851   ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
9852   bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
9853   if (!IsSuperClass)
9854     return false;
9855 
9856   // If the LHS has protocol qualifiers, determine whether all of them are
9857   // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
9858   // LHS).
9859   if (LHS->getNumProtocols() > 0) {
9860     // OK if conversion of LHS to SuperClass results in narrowing of types
9861     // ; i.e., SuperClass may implement at least one of the protocols
9862     // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
9863     // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
9864     llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
9865     CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
9866     // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
9867     // qualifiers.
9868     for (auto *RHSPI : RHS->quals())
9869       CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
9870     // If there is no protocols associated with RHS, it is not a match.
9871     if (SuperClassInheritedProtocols.empty())
9872       return false;
9873 
9874     for (const auto *LHSProto : LHS->quals()) {
9875       bool SuperImplementsProtocol = false;
9876       for (auto *SuperClassProto : SuperClassInheritedProtocols)
9877         if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
9878           SuperImplementsProtocol = true;
9879           break;
9880         }
9881       if (!SuperImplementsProtocol)
9882         return false;
9883     }
9884   }
9885 
9886   // If the LHS is specialized, we may need to check type arguments.
9887   if (LHS->isSpecialized()) {
9888     // Follow the superclass chain until we've matched the LHS class in the
9889     // hierarchy. This substitutes type arguments through.
9890     const ObjCObjectType *RHSSuper = RHS;
9891     while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
9892       RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
9893 
9894     // If the RHS is specializd, compare type arguments.
9895     if (RHSSuper->isSpecialized() &&
9896         !sameObjCTypeArgs(*this, LHS->getInterface(),
9897                           LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
9898                           /*stripKindOf=*/true)) {
9899       return false;
9900     }
9901   }
9902 
9903   return true;
9904 }
9905 
9906 bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
9907   // get the "pointed to" types
9908   const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
9909   const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
9910 
9911   if (!LHSOPT || !RHSOPT)
9912     return false;
9913 
9914   return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
9915          canAssignObjCInterfaces(RHSOPT, LHSOPT);
9916 }
9917 
9918 bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
9919   return canAssignObjCInterfaces(
9920       getObjCObjectPointerType(To)->castAs<ObjCObjectPointerType>(),
9921       getObjCObjectPointerType(From)->castAs<ObjCObjectPointerType>());
9922 }
9923 
9924 /// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
9925 /// both shall have the identically qualified version of a compatible type.
9926 /// C99 6.2.7p1: Two types have compatible types if their types are the
9927 /// same. See 6.7.[2,3,5] for additional rules.
9928 bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
9929                                     bool CompareUnqualified) {
9930   if (getLangOpts().CPlusPlus)
9931     return hasSameType(LHS, RHS);
9932 
9933   return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
9934 }
9935 
9936 bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
9937   return typesAreCompatible(LHS, RHS);
9938 }
9939 
9940 bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
9941   return !mergeTypes(LHS, RHS, true).isNull();
9942 }
9943 
9944 /// mergeTransparentUnionType - if T is a transparent union type and a member
9945 /// of T is compatible with SubType, return the merged type, else return
9946 /// QualType()
9947 QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
9948                                                bool OfBlockPointer,
9949                                                bool Unqualified) {
9950   if (const RecordType *UT = T->getAsUnionType()) {
9951     RecordDecl *UD = UT->getDecl();
9952     if (UD->hasAttr<TransparentUnionAttr>()) {
9953       for (const auto *I : UD->fields()) {
9954         QualType ET = I->getType().getUnqualifiedType();
9955         QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
9956         if (!MT.isNull())
9957           return MT;
9958       }
9959     }
9960   }
9961 
9962   return {};
9963 }
9964 
9965 /// mergeFunctionParameterTypes - merge two types which appear as function
9966 /// parameter types
9967 QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
9968                                                  bool OfBlockPointer,
9969                                                  bool Unqualified) {
9970   // GNU extension: two types are compatible if they appear as a function
9971   // argument, one of the types is a transparent union type and the other
9972   // type is compatible with a union member
9973   QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
9974                                               Unqualified);
9975   if (!lmerge.isNull())
9976     return lmerge;
9977 
9978   QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
9979                                               Unqualified);
9980   if (!rmerge.isNull())
9981     return rmerge;
9982 
9983   return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
9984 }
9985 
9986 QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
9987                                         bool OfBlockPointer, bool Unqualified,
9988                                         bool AllowCXX) {
9989   const auto *lbase = lhs->castAs<FunctionType>();
9990   const auto *rbase = rhs->castAs<FunctionType>();
9991   const auto *lproto = dyn_cast<FunctionProtoType>(lbase);
9992   const auto *rproto = dyn_cast<FunctionProtoType>(rbase);
9993   bool allLTypes = true;
9994   bool allRTypes = true;
9995 
9996   // Check return type
9997   QualType retType;
9998   if (OfBlockPointer) {
9999     QualType RHS = rbase->getReturnType();
10000     QualType LHS = lbase->getReturnType();
10001     bool UnqualifiedResult = Unqualified;
10002     if (!UnqualifiedResult)
10003       UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
10004     retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
10005   }
10006   else
10007     retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
10008                          Unqualified);
10009   if (retType.isNull())
10010     return {};
10011 
10012   if (Unqualified)
10013     retType = retType.getUnqualifiedType();
10014 
10015   CanQualType LRetType = getCanonicalType(lbase->getReturnType());
10016   CanQualType RRetType = getCanonicalType(rbase->getReturnType());
10017   if (Unqualified) {
10018     LRetType = LRetType.getUnqualifiedType();
10019     RRetType = RRetType.getUnqualifiedType();
10020   }
10021 
10022   if (getCanonicalType(retType) != LRetType)
10023     allLTypes = false;
10024   if (getCanonicalType(retType) != RRetType)
10025     allRTypes = false;
10026 
10027   // FIXME: double check this
10028   // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
10029   //                           rbase->getRegParmAttr() != 0 &&
10030   //                           lbase->getRegParmAttr() != rbase->getRegParmAttr()?
10031   FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
10032   FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
10033 
10034   // Compatible functions must have compatible calling conventions
10035   if (lbaseInfo.getCC() != rbaseInfo.getCC())
10036     return {};
10037 
10038   // Regparm is part of the calling convention.
10039   if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
10040     return {};
10041   if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
10042     return {};
10043 
10044   if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
10045     return {};
10046   if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
10047     return {};
10048   if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
10049     return {};
10050 
10051   // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
10052   bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
10053 
10054   if (lbaseInfo.getNoReturn() != NoReturn)
10055     allLTypes = false;
10056   if (rbaseInfo.getNoReturn() != NoReturn)
10057     allRTypes = false;
10058 
10059   FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
10060 
10061   if (lproto && rproto) { // two C99 style function prototypes
10062     assert((AllowCXX ||
10063             (!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec())) &&
10064            "C++ shouldn't be here");
10065     // Compatible functions must have the same number of parameters
10066     if (lproto->getNumParams() != rproto->getNumParams())
10067       return {};
10068 
10069     // Variadic and non-variadic functions aren't compatible
10070     if (lproto->isVariadic() != rproto->isVariadic())
10071       return {};
10072 
10073     if (lproto->getMethodQuals() != rproto->getMethodQuals())
10074       return {};
10075 
10076     SmallVector<FunctionProtoType::ExtParameterInfo, 4> newParamInfos;
10077     bool canUseLeft, canUseRight;
10078     if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight,
10079                                newParamInfos))
10080       return {};
10081 
10082     if (!canUseLeft)
10083       allLTypes = false;
10084     if (!canUseRight)
10085       allRTypes = false;
10086 
10087     // Check parameter type compatibility
10088     SmallVector<QualType, 10> types;
10089     for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
10090       QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
10091       QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
10092       QualType paramType = mergeFunctionParameterTypes(
10093           lParamType, rParamType, OfBlockPointer, Unqualified);
10094       if (paramType.isNull())
10095         return {};
10096 
10097       if (Unqualified)
10098         paramType = paramType.getUnqualifiedType();
10099 
10100       types.push_back(paramType);
10101       if (Unqualified) {
10102         lParamType = lParamType.getUnqualifiedType();
10103         rParamType = rParamType.getUnqualifiedType();
10104       }
10105 
10106       if (getCanonicalType(paramType) != getCanonicalType(lParamType))
10107         allLTypes = false;
10108       if (getCanonicalType(paramType) != getCanonicalType(rParamType))
10109         allRTypes = false;
10110     }
10111 
10112     if (allLTypes) return lhs;
10113     if (allRTypes) return rhs;
10114 
10115     FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
10116     EPI.ExtInfo = einfo;
10117     EPI.ExtParameterInfos =
10118         newParamInfos.empty() ? nullptr : newParamInfos.data();
10119     return getFunctionType(retType, types, EPI);
10120   }
10121 
10122   if (lproto) allRTypes = false;
10123   if (rproto) allLTypes = false;
10124 
10125   const FunctionProtoType *proto = lproto ? lproto : rproto;
10126   if (proto) {
10127     assert((AllowCXX || !proto->hasExceptionSpec()) && "C++ shouldn't be here");
10128     if (proto->isVariadic())
10129       return {};
10130     // Check that the types are compatible with the types that
10131     // would result from default argument promotions (C99 6.7.5.3p15).
10132     // The only types actually affected are promotable integer
10133     // types and floats, which would be passed as a different
10134     // type depending on whether the prototype is visible.
10135     for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
10136       QualType paramTy = proto->getParamType(i);
10137 
10138       // Look at the converted type of enum types, since that is the type used
10139       // to pass enum values.
10140       if (const auto *Enum = paramTy->getAs<EnumType>()) {
10141         paramTy = Enum->getDecl()->getIntegerType();
10142         if (paramTy.isNull())
10143           return {};
10144       }
10145 
10146       if (paramTy->isPromotableIntegerType() ||
10147           getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
10148         return {};
10149     }
10150 
10151     if (allLTypes) return lhs;
10152     if (allRTypes) return rhs;
10153 
10154     FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
10155     EPI.ExtInfo = einfo;
10156     return getFunctionType(retType, proto->getParamTypes(), EPI);
10157   }
10158 
10159   if (allLTypes) return lhs;
10160   if (allRTypes) return rhs;
10161   return getFunctionNoProtoType(retType, einfo);
10162 }
10163 
10164 /// Given that we have an enum type and a non-enum type, try to merge them.
10165 static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
10166                                      QualType other, bool isBlockReturnType) {
10167   // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
10168   // a signed integer type, or an unsigned integer type.
10169   // Compatibility is based on the underlying type, not the promotion
10170   // type.
10171   QualType underlyingType = ET->getDecl()->getIntegerType();
10172   if (underlyingType.isNull())
10173     return {};
10174   if (Context.hasSameType(underlyingType, other))
10175     return other;
10176 
10177   // In block return types, we're more permissive and accept any
10178   // integral type of the same size.
10179   if (isBlockReturnType && other->isIntegerType() &&
10180       Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
10181     return other;
10182 
10183   return {};
10184 }
10185 
10186 QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
10187                                 bool OfBlockPointer,
10188                                 bool Unqualified, bool BlockReturnType) {
10189   // For C++ we will not reach this code with reference types (see below),
10190   // for OpenMP variant call overloading we might.
10191   //
10192   // C++ [expr]: If an expression initially has the type "reference to T", the
10193   // type is adjusted to "T" prior to any further analysis, the expression
10194   // designates the object or function denoted by the reference, and the
10195   // expression is an lvalue unless the reference is an rvalue reference and
10196   // the expression is a function call (possibly inside parentheses).
10197   auto *LHSRefTy = LHS->getAs<ReferenceType>();
10198   auto *RHSRefTy = RHS->getAs<ReferenceType>();
10199   if (LangOpts.OpenMP && LHSRefTy && RHSRefTy &&
10200       LHS->getTypeClass() == RHS->getTypeClass())
10201     return mergeTypes(LHSRefTy->getPointeeType(), RHSRefTy->getPointeeType(),
10202                       OfBlockPointer, Unqualified, BlockReturnType);
10203   if (LHSRefTy || RHSRefTy)
10204     return {};
10205 
10206   if (Unqualified) {
10207     LHS = LHS.getUnqualifiedType();
10208     RHS = RHS.getUnqualifiedType();
10209   }
10210 
10211   QualType LHSCan = getCanonicalType(LHS),
10212            RHSCan = getCanonicalType(RHS);
10213 
10214   // If two types are identical, they are compatible.
10215   if (LHSCan == RHSCan)
10216     return LHS;
10217 
10218   // If the qualifiers are different, the types aren't compatible... mostly.
10219   Qualifiers LQuals = LHSCan.getLocalQualifiers();
10220   Qualifiers RQuals = RHSCan.getLocalQualifiers();
10221   if (LQuals != RQuals) {
10222     // If any of these qualifiers are different, we have a type
10223     // mismatch.
10224     if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
10225         LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
10226         LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
10227         LQuals.hasUnaligned() != RQuals.hasUnaligned())
10228       return {};
10229 
10230     // Exactly one GC qualifier difference is allowed: __strong is
10231     // okay if the other type has no GC qualifier but is an Objective
10232     // C object pointer (i.e. implicitly strong by default).  We fix
10233     // this by pretending that the unqualified type was actually
10234     // qualified __strong.
10235     Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
10236     Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
10237     assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
10238 
10239     if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
10240       return {};
10241 
10242     if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
10243       return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
10244     }
10245     if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
10246       return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
10247     }
10248     return {};
10249   }
10250 
10251   // Okay, qualifiers are equal.
10252 
10253   Type::TypeClass LHSClass = LHSCan->getTypeClass();
10254   Type::TypeClass RHSClass = RHSCan->getTypeClass();
10255 
10256   // We want to consider the two function types to be the same for these
10257   // comparisons, just force one to the other.
10258   if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
10259   if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
10260 
10261   // Same as above for arrays
10262   if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
10263     LHSClass = Type::ConstantArray;
10264   if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
10265     RHSClass = Type::ConstantArray;
10266 
10267   // ObjCInterfaces are just specialized ObjCObjects.
10268   if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
10269   if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
10270 
10271   // Canonicalize ExtVector -> Vector.
10272   if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
10273   if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
10274 
10275   // If the canonical type classes don't match.
10276   if (LHSClass != RHSClass) {
10277     // Note that we only have special rules for turning block enum
10278     // returns into block int returns, not vice-versa.
10279     if (const auto *ETy = LHS->getAs<EnumType>()) {
10280       return mergeEnumWithInteger(*this, ETy, RHS, false);
10281     }
10282     if (const EnumType* ETy = RHS->getAs<EnumType>()) {
10283       return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
10284     }
10285     // allow block pointer type to match an 'id' type.
10286     if (OfBlockPointer && !BlockReturnType) {
10287        if (LHS->isObjCIdType() && RHS->isBlockPointerType())
10288          return LHS;
10289       if (RHS->isObjCIdType() && LHS->isBlockPointerType())
10290         return RHS;
10291     }
10292     // Allow __auto_type to match anything; it merges to the type with more
10293     // information.
10294     if (const auto *AT = LHS->getAs<AutoType>()) {
10295       if (AT->isGNUAutoType())
10296         return RHS;
10297     }
10298     if (const auto *AT = RHS->getAs<AutoType>()) {
10299       if (AT->isGNUAutoType())
10300         return LHS;
10301     }
10302     return {};
10303   }
10304 
10305   // The canonical type classes match.
10306   switch (LHSClass) {
10307 #define TYPE(Class, Base)
10308 #define ABSTRACT_TYPE(Class, Base)
10309 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
10310 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
10311 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
10312 #include "clang/AST/TypeNodes.inc"
10313     llvm_unreachable("Non-canonical and dependent types shouldn't get here");
10314 
10315   case Type::Auto:
10316   case Type::DeducedTemplateSpecialization:
10317   case Type::LValueReference:
10318   case Type::RValueReference:
10319   case Type::MemberPointer:
10320     llvm_unreachable("C++ should never be in mergeTypes");
10321 
10322   case Type::ObjCInterface:
10323   case Type::IncompleteArray:
10324   case Type::VariableArray:
10325   case Type::FunctionProto:
10326   case Type::ExtVector:
10327     llvm_unreachable("Types are eliminated above");
10328 
10329   case Type::Pointer:
10330   {
10331     // Merge two pointer types, while trying to preserve typedef info
10332     QualType LHSPointee = LHS->castAs<PointerType>()->getPointeeType();
10333     QualType RHSPointee = RHS->castAs<PointerType>()->getPointeeType();
10334     if (Unqualified) {
10335       LHSPointee = LHSPointee.getUnqualifiedType();
10336       RHSPointee = RHSPointee.getUnqualifiedType();
10337     }
10338     QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
10339                                      Unqualified);
10340     if (ResultType.isNull())
10341       return {};
10342     if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
10343       return LHS;
10344     if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
10345       return RHS;
10346     return getPointerType(ResultType);
10347   }
10348   case Type::BlockPointer:
10349   {
10350     // Merge two block pointer types, while trying to preserve typedef info
10351     QualType LHSPointee = LHS->castAs<BlockPointerType>()->getPointeeType();
10352     QualType RHSPointee = RHS->castAs<BlockPointerType>()->getPointeeType();
10353     if (Unqualified) {
10354       LHSPointee = LHSPointee.getUnqualifiedType();
10355       RHSPointee = RHSPointee.getUnqualifiedType();
10356     }
10357     if (getLangOpts().OpenCL) {
10358       Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
10359       Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
10360       // Blocks can't be an expression in a ternary operator (OpenCL v2.0
10361       // 6.12.5) thus the following check is asymmetric.
10362       if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual))
10363         return {};
10364       LHSPteeQual.removeAddressSpace();
10365       RHSPteeQual.removeAddressSpace();
10366       LHSPointee =
10367           QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
10368       RHSPointee =
10369           QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
10370     }
10371     QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
10372                                      Unqualified);
10373     if (ResultType.isNull())
10374       return {};
10375     if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
10376       return LHS;
10377     if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
10378       return RHS;
10379     return getBlockPointerType(ResultType);
10380   }
10381   case Type::Atomic:
10382   {
10383     // Merge two pointer types, while trying to preserve typedef info
10384     QualType LHSValue = LHS->castAs<AtomicType>()->getValueType();
10385     QualType RHSValue = RHS->castAs<AtomicType>()->getValueType();
10386     if (Unqualified) {
10387       LHSValue = LHSValue.getUnqualifiedType();
10388       RHSValue = RHSValue.getUnqualifiedType();
10389     }
10390     QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
10391                                      Unqualified);
10392     if (ResultType.isNull())
10393       return {};
10394     if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
10395       return LHS;
10396     if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
10397       return RHS;
10398     return getAtomicType(ResultType);
10399   }
10400   case Type::ConstantArray:
10401   {
10402     const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
10403     const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
10404     if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
10405       return {};
10406 
10407     QualType LHSElem = getAsArrayType(LHS)->getElementType();
10408     QualType RHSElem = getAsArrayType(RHS)->getElementType();
10409     if (Unqualified) {
10410       LHSElem = LHSElem.getUnqualifiedType();
10411       RHSElem = RHSElem.getUnqualifiedType();
10412     }
10413 
10414     QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
10415     if (ResultType.isNull())
10416       return {};
10417 
10418     const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
10419     const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
10420 
10421     // If either side is a variable array, and both are complete, check whether
10422     // the current dimension is definite.
10423     if (LVAT || RVAT) {
10424       auto SizeFetch = [this](const VariableArrayType* VAT,
10425           const ConstantArrayType* CAT)
10426           -> std::pair<bool,llvm::APInt> {
10427         if (VAT) {
10428           Optional<llvm::APSInt> TheInt;
10429           Expr *E = VAT->getSizeExpr();
10430           if (E && (TheInt = E->getIntegerConstantExpr(*this)))
10431             return std::make_pair(true, *TheInt);
10432           return std::make_pair(false, llvm::APSInt());
10433         }
10434         if (CAT)
10435           return std::make_pair(true, CAT->getSize());
10436         return std::make_pair(false, llvm::APInt());
10437       };
10438 
10439       bool HaveLSize, HaveRSize;
10440       llvm::APInt LSize, RSize;
10441       std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT);
10442       std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT);
10443       if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize))
10444         return {}; // Definite, but unequal, array dimension
10445     }
10446 
10447     if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
10448       return LHS;
10449     if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
10450       return RHS;
10451     if (LCAT)
10452       return getConstantArrayType(ResultType, LCAT->getSize(),
10453                                   LCAT->getSizeExpr(),
10454                                   ArrayType::ArraySizeModifier(), 0);
10455     if (RCAT)
10456       return getConstantArrayType(ResultType, RCAT->getSize(),
10457                                   RCAT->getSizeExpr(),
10458                                   ArrayType::ArraySizeModifier(), 0);
10459     if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
10460       return LHS;
10461     if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
10462       return RHS;
10463     if (LVAT) {
10464       // FIXME: This isn't correct! But tricky to implement because
10465       // the array's size has to be the size of LHS, but the type
10466       // has to be different.
10467       return LHS;
10468     }
10469     if (RVAT) {
10470       // FIXME: This isn't correct! But tricky to implement because
10471       // the array's size has to be the size of RHS, but the type
10472       // has to be different.
10473       return RHS;
10474     }
10475     if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
10476     if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
10477     return getIncompleteArrayType(ResultType,
10478                                   ArrayType::ArraySizeModifier(), 0);
10479   }
10480   case Type::FunctionNoProto:
10481     return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
10482   case Type::Record:
10483   case Type::Enum:
10484     return {};
10485   case Type::Builtin:
10486     // Only exactly equal builtin types are compatible, which is tested above.
10487     return {};
10488   case Type::Complex:
10489     // Distinct complex types are incompatible.
10490     return {};
10491   case Type::Vector:
10492     // FIXME: The merged type should be an ExtVector!
10493     if (areCompatVectorTypes(LHSCan->castAs<VectorType>(),
10494                              RHSCan->castAs<VectorType>()))
10495       return LHS;
10496     return {};
10497   case Type::ConstantMatrix:
10498     if (areCompatMatrixTypes(LHSCan->castAs<ConstantMatrixType>(),
10499                              RHSCan->castAs<ConstantMatrixType>()))
10500       return LHS;
10501     return {};
10502   case Type::ObjCObject: {
10503     // Check if the types are assignment compatible.
10504     // FIXME: This should be type compatibility, e.g. whether
10505     // "LHS x; RHS x;" at global scope is legal.
10506     if (canAssignObjCInterfaces(LHS->castAs<ObjCObjectType>(),
10507                                 RHS->castAs<ObjCObjectType>()))
10508       return LHS;
10509     return {};
10510   }
10511   case Type::ObjCObjectPointer:
10512     if (OfBlockPointer) {
10513       if (canAssignObjCInterfacesInBlockPointer(
10514               LHS->castAs<ObjCObjectPointerType>(),
10515               RHS->castAs<ObjCObjectPointerType>(), BlockReturnType))
10516         return LHS;
10517       return {};
10518     }
10519     if (canAssignObjCInterfaces(LHS->castAs<ObjCObjectPointerType>(),
10520                                 RHS->castAs<ObjCObjectPointerType>()))
10521       return LHS;
10522     return {};
10523   case Type::Pipe:
10524     assert(LHS != RHS &&
10525            "Equivalent pipe types should have already been handled!");
10526     return {};
10527   case Type::BitInt: {
10528     // Merge two bit-precise int types, while trying to preserve typedef info.
10529     bool LHSUnsigned = LHS->castAs<BitIntType>()->isUnsigned();
10530     bool RHSUnsigned = RHS->castAs<BitIntType>()->isUnsigned();
10531     unsigned LHSBits = LHS->castAs<BitIntType>()->getNumBits();
10532     unsigned RHSBits = RHS->castAs<BitIntType>()->getNumBits();
10533 
10534     // Like unsigned/int, shouldn't have a type if they don't match.
10535     if (LHSUnsigned != RHSUnsigned)
10536       return {};
10537 
10538     if (LHSBits != RHSBits)
10539       return {};
10540     return LHS;
10541   }
10542   }
10543 
10544   llvm_unreachable("Invalid Type::Class!");
10545 }
10546 
10547 bool ASTContext::mergeExtParameterInfo(
10548     const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
10549     bool &CanUseFirst, bool &CanUseSecond,
10550     SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos) {
10551   assert(NewParamInfos.empty() && "param info list not empty");
10552   CanUseFirst = CanUseSecond = true;
10553   bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
10554   bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
10555 
10556   // Fast path: if the first type doesn't have ext parameter infos,
10557   // we match if and only if the second type also doesn't have them.
10558   if (!FirstHasInfo && !SecondHasInfo)
10559     return true;
10560 
10561   bool NeedParamInfo = false;
10562   size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
10563                           : SecondFnType->getExtParameterInfos().size();
10564 
10565   for (size_t I = 0; I < E; ++I) {
10566     FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
10567     if (FirstHasInfo)
10568       FirstParam = FirstFnType->getExtParameterInfo(I);
10569     if (SecondHasInfo)
10570       SecondParam = SecondFnType->getExtParameterInfo(I);
10571 
10572     // Cannot merge unless everything except the noescape flag matches.
10573     if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false))
10574       return false;
10575 
10576     bool FirstNoEscape = FirstParam.isNoEscape();
10577     bool SecondNoEscape = SecondParam.isNoEscape();
10578     bool IsNoEscape = FirstNoEscape && SecondNoEscape;
10579     NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape));
10580     if (NewParamInfos.back().getOpaqueValue())
10581       NeedParamInfo = true;
10582     if (FirstNoEscape != IsNoEscape)
10583       CanUseFirst = false;
10584     if (SecondNoEscape != IsNoEscape)
10585       CanUseSecond = false;
10586   }
10587 
10588   if (!NeedParamInfo)
10589     NewParamInfos.clear();
10590 
10591   return true;
10592 }
10593 
10594 void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) {
10595   ObjCLayouts[CD] = nullptr;
10596 }
10597 
10598 /// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
10599 /// 'RHS' attributes and returns the merged version; including for function
10600 /// return types.
10601 QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
10602   QualType LHSCan = getCanonicalType(LHS),
10603   RHSCan = getCanonicalType(RHS);
10604   // If two types are identical, they are compatible.
10605   if (LHSCan == RHSCan)
10606     return LHS;
10607   if (RHSCan->isFunctionType()) {
10608     if (!LHSCan->isFunctionType())
10609       return {};
10610     QualType OldReturnType =
10611         cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
10612     QualType NewReturnType =
10613         cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
10614     QualType ResReturnType =
10615       mergeObjCGCQualifiers(NewReturnType, OldReturnType);
10616     if (ResReturnType.isNull())
10617       return {};
10618     if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
10619       // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
10620       // In either case, use OldReturnType to build the new function type.
10621       const auto *F = LHS->castAs<FunctionType>();
10622       if (const auto *FPT = cast<FunctionProtoType>(F)) {
10623         FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10624         EPI.ExtInfo = getFunctionExtInfo(LHS);
10625         QualType ResultType =
10626             getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
10627         return ResultType;
10628       }
10629     }
10630     return {};
10631   }
10632 
10633   // If the qualifiers are different, the types can still be merged.
10634   Qualifiers LQuals = LHSCan.getLocalQualifiers();
10635   Qualifiers RQuals = RHSCan.getLocalQualifiers();
10636   if (LQuals != RQuals) {
10637     // If any of these qualifiers are different, we have a type mismatch.
10638     if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
10639         LQuals.getAddressSpace() != RQuals.getAddressSpace())
10640       return {};
10641 
10642     // Exactly one GC qualifier difference is allowed: __strong is
10643     // okay if the other type has no GC qualifier but is an Objective
10644     // C object pointer (i.e. implicitly strong by default).  We fix
10645     // this by pretending that the unqualified type was actually
10646     // qualified __strong.
10647     Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
10648     Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
10649     assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
10650 
10651     if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
10652       return {};
10653 
10654     if (GC_L == Qualifiers::Strong)
10655       return LHS;
10656     if (GC_R == Qualifiers::Strong)
10657       return RHS;
10658     return {};
10659   }
10660 
10661   if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
10662     QualType LHSBaseQT = LHS->castAs<ObjCObjectPointerType>()->getPointeeType();
10663     QualType RHSBaseQT = RHS->castAs<ObjCObjectPointerType>()->getPointeeType();
10664     QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
10665     if (ResQT == LHSBaseQT)
10666       return LHS;
10667     if (ResQT == RHSBaseQT)
10668       return RHS;
10669   }
10670   return {};
10671 }
10672 
10673 //===----------------------------------------------------------------------===//
10674 //                         Integer Predicates
10675 //===----------------------------------------------------------------------===//
10676 
10677 unsigned ASTContext::getIntWidth(QualType T) const {
10678   if (const auto *ET = T->getAs<EnumType>())
10679     T = ET->getDecl()->getIntegerType();
10680   if (T->isBooleanType())
10681     return 1;
10682   if (const auto *EIT = T->getAs<BitIntType>())
10683     return EIT->getNumBits();
10684   // For builtin types, just use the standard type sizing method
10685   return (unsigned)getTypeSize(T);
10686 }
10687 
10688 QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
10689   assert((T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) &&
10690          "Unexpected type");
10691 
10692   // Turn <4 x signed int> -> <4 x unsigned int>
10693   if (const auto *VTy = T->getAs<VectorType>())
10694     return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
10695                          VTy->getNumElements(), VTy->getVectorKind());
10696 
10697   // For _BitInt, return an unsigned _BitInt with same width.
10698   if (const auto *EITy = T->getAs<BitIntType>())
10699     return getBitIntType(/*Unsigned=*/true, EITy->getNumBits());
10700 
10701   // For enums, get the underlying integer type of the enum, and let the general
10702   // integer type signchanging code handle it.
10703   if (const auto *ETy = T->getAs<EnumType>())
10704     T = ETy->getDecl()->getIntegerType();
10705 
10706   switch (T->castAs<BuiltinType>()->getKind()) {
10707   case BuiltinType::Char_S:
10708   case BuiltinType::SChar:
10709     return UnsignedCharTy;
10710   case BuiltinType::Short:
10711     return UnsignedShortTy;
10712   case BuiltinType::Int:
10713     return UnsignedIntTy;
10714   case BuiltinType::Long:
10715     return UnsignedLongTy;
10716   case BuiltinType::LongLong:
10717     return UnsignedLongLongTy;
10718   case BuiltinType::Int128:
10719     return UnsignedInt128Ty;
10720   // wchar_t is special. It is either signed or not, but when it's signed,
10721   // there's no matching "unsigned wchar_t". Therefore we return the unsigned
10722   // version of it's underlying type instead.
10723   case BuiltinType::WChar_S:
10724     return getUnsignedWCharType();
10725 
10726   case BuiltinType::ShortAccum:
10727     return UnsignedShortAccumTy;
10728   case BuiltinType::Accum:
10729     return UnsignedAccumTy;
10730   case BuiltinType::LongAccum:
10731     return UnsignedLongAccumTy;
10732   case BuiltinType::SatShortAccum:
10733     return SatUnsignedShortAccumTy;
10734   case BuiltinType::SatAccum:
10735     return SatUnsignedAccumTy;
10736   case BuiltinType::SatLongAccum:
10737     return SatUnsignedLongAccumTy;
10738   case BuiltinType::ShortFract:
10739     return UnsignedShortFractTy;
10740   case BuiltinType::Fract:
10741     return UnsignedFractTy;
10742   case BuiltinType::LongFract:
10743     return UnsignedLongFractTy;
10744   case BuiltinType::SatShortFract:
10745     return SatUnsignedShortFractTy;
10746   case BuiltinType::SatFract:
10747     return SatUnsignedFractTy;
10748   case BuiltinType::SatLongFract:
10749     return SatUnsignedLongFractTy;
10750   default:
10751     llvm_unreachable("Unexpected signed integer or fixed point type");
10752   }
10753 }
10754 
10755 QualType ASTContext::getCorrespondingSignedType(QualType T) const {
10756   assert((T->hasUnsignedIntegerRepresentation() ||
10757           T->isUnsignedFixedPointType()) &&
10758          "Unexpected type");
10759 
10760   // Turn <4 x unsigned int> -> <4 x signed int>
10761   if (const auto *VTy = T->getAs<VectorType>())
10762     return getVectorType(getCorrespondingSignedType(VTy->getElementType()),
10763                          VTy->getNumElements(), VTy->getVectorKind());
10764 
10765   // For _BitInt, return a signed _BitInt with same width.
10766   if (const auto *EITy = T->getAs<BitIntType>())
10767     return getBitIntType(/*Unsigned=*/false, EITy->getNumBits());
10768 
10769   // For enums, get the underlying integer type of the enum, and let the general
10770   // integer type signchanging code handle it.
10771   if (const auto *ETy = T->getAs<EnumType>())
10772     T = ETy->getDecl()->getIntegerType();
10773 
10774   switch (T->castAs<BuiltinType>()->getKind()) {
10775   case BuiltinType::Char_U:
10776   case BuiltinType::UChar:
10777     return SignedCharTy;
10778   case BuiltinType::UShort:
10779     return ShortTy;
10780   case BuiltinType::UInt:
10781     return IntTy;
10782   case BuiltinType::ULong:
10783     return LongTy;
10784   case BuiltinType::ULongLong:
10785     return LongLongTy;
10786   case BuiltinType::UInt128:
10787     return Int128Ty;
10788   // wchar_t is special. It is either unsigned or not, but when it's unsigned,
10789   // there's no matching "signed wchar_t". Therefore we return the signed
10790   // version of it's underlying type instead.
10791   case BuiltinType::WChar_U:
10792     return getSignedWCharType();
10793 
10794   case BuiltinType::UShortAccum:
10795     return ShortAccumTy;
10796   case BuiltinType::UAccum:
10797     return AccumTy;
10798   case BuiltinType::ULongAccum:
10799     return LongAccumTy;
10800   case BuiltinType::SatUShortAccum:
10801     return SatShortAccumTy;
10802   case BuiltinType::SatUAccum:
10803     return SatAccumTy;
10804   case BuiltinType::SatULongAccum:
10805     return SatLongAccumTy;
10806   case BuiltinType::UShortFract:
10807     return ShortFractTy;
10808   case BuiltinType::UFract:
10809     return FractTy;
10810   case BuiltinType::ULongFract:
10811     return LongFractTy;
10812   case BuiltinType::SatUShortFract:
10813     return SatShortFractTy;
10814   case BuiltinType::SatUFract:
10815     return SatFractTy;
10816   case BuiltinType::SatULongFract:
10817     return SatLongFractTy;
10818   default:
10819     llvm_unreachable("Unexpected unsigned integer or fixed point type");
10820   }
10821 }
10822 
10823 ASTMutationListener::~ASTMutationListener() = default;
10824 
10825 void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
10826                                             QualType ReturnType) {}
10827 
10828 //===----------------------------------------------------------------------===//
10829 //                          Builtin Type Computation
10830 //===----------------------------------------------------------------------===//
10831 
10832 /// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
10833 /// pointer over the consumed characters.  This returns the resultant type.  If
10834 /// AllowTypeModifiers is false then modifier like * are not parsed, just basic
10835 /// types.  This allows "v2i*" to be parsed as a pointer to a v2i instead of
10836 /// a vector of "i*".
10837 ///
10838 /// RequiresICE is filled in on return to indicate whether the value is required
10839 /// to be an Integer Constant Expression.
10840 static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
10841                                   ASTContext::GetBuiltinTypeError &Error,
10842                                   bool &RequiresICE,
10843                                   bool AllowTypeModifiers) {
10844   // Modifiers.
10845   int HowLong = 0;
10846   bool Signed = false, Unsigned = false;
10847   RequiresICE = false;
10848 
10849   // Read the prefixed modifiers first.
10850   bool Done = false;
10851   #ifndef NDEBUG
10852   bool IsSpecial = false;
10853   #endif
10854   while (!Done) {
10855     switch (*Str++) {
10856     default: Done = true; --Str; break;
10857     case 'I':
10858       RequiresICE = true;
10859       break;
10860     case 'S':
10861       assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
10862       assert(!Signed && "Can't use 'S' modifier multiple times!");
10863       Signed = true;
10864       break;
10865     case 'U':
10866       assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
10867       assert(!Unsigned && "Can't use 'U' modifier multiple times!");
10868       Unsigned = true;
10869       break;
10870     case 'L':
10871       assert(!IsSpecial && "Can't use 'L' with 'W', 'N', 'Z' or 'O' modifiers");
10872       assert(HowLong <= 2 && "Can't have LLLL modifier");
10873       ++HowLong;
10874       break;
10875     case 'N':
10876       // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
10877       assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
10878       assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
10879       #ifndef NDEBUG
10880       IsSpecial = true;
10881       #endif
10882       if (Context.getTargetInfo().getLongWidth() == 32)
10883         ++HowLong;
10884       break;
10885     case 'W':
10886       // This modifier represents int64 type.
10887       assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
10888       assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
10889       #ifndef NDEBUG
10890       IsSpecial = true;
10891       #endif
10892       switch (Context.getTargetInfo().getInt64Type()) {
10893       default:
10894         llvm_unreachable("Unexpected integer type");
10895       case TargetInfo::SignedLong:
10896         HowLong = 1;
10897         break;
10898       case TargetInfo::SignedLongLong:
10899         HowLong = 2;
10900         break;
10901       }
10902       break;
10903     case 'Z':
10904       // This modifier represents int32 type.
10905       assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
10906       assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!");
10907       #ifndef NDEBUG
10908       IsSpecial = true;
10909       #endif
10910       switch (Context.getTargetInfo().getIntTypeByWidth(32, true)) {
10911       default:
10912         llvm_unreachable("Unexpected integer type");
10913       case TargetInfo::SignedInt:
10914         HowLong = 0;
10915         break;
10916       case TargetInfo::SignedLong:
10917         HowLong = 1;
10918         break;
10919       case TargetInfo::SignedLongLong:
10920         HowLong = 2;
10921         break;
10922       }
10923       break;
10924     case 'O':
10925       assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
10926       assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!");
10927       #ifndef NDEBUG
10928       IsSpecial = true;
10929       #endif
10930       if (Context.getLangOpts().OpenCL)
10931         HowLong = 1;
10932       else
10933         HowLong = 2;
10934       break;
10935     }
10936   }
10937 
10938   QualType Type;
10939 
10940   // Read the base type.
10941   switch (*Str++) {
10942   default: llvm_unreachable("Unknown builtin type letter!");
10943   case 'x':
10944     assert(HowLong == 0 && !Signed && !Unsigned &&
10945            "Bad modifiers used with 'x'!");
10946     Type = Context.Float16Ty;
10947     break;
10948   case 'y':
10949     assert(HowLong == 0 && !Signed && !Unsigned &&
10950            "Bad modifiers used with 'y'!");
10951     Type = Context.BFloat16Ty;
10952     break;
10953   case 'v':
10954     assert(HowLong == 0 && !Signed && !Unsigned &&
10955            "Bad modifiers used with 'v'!");
10956     Type = Context.VoidTy;
10957     break;
10958   case 'h':
10959     assert(HowLong == 0 && !Signed && !Unsigned &&
10960            "Bad modifiers used with 'h'!");
10961     Type = Context.HalfTy;
10962     break;
10963   case 'f':
10964     assert(HowLong == 0 && !Signed && !Unsigned &&
10965            "Bad modifiers used with 'f'!");
10966     Type = Context.FloatTy;
10967     break;
10968   case 'd':
10969     assert(HowLong < 3 && !Signed && !Unsigned &&
10970            "Bad modifiers used with 'd'!");
10971     if (HowLong == 1)
10972       Type = Context.LongDoubleTy;
10973     else if (HowLong == 2)
10974       Type = Context.Float128Ty;
10975     else
10976       Type = Context.DoubleTy;
10977     break;
10978   case 's':
10979     assert(HowLong == 0 && "Bad modifiers used with 's'!");
10980     if (Unsigned)
10981       Type = Context.UnsignedShortTy;
10982     else
10983       Type = Context.ShortTy;
10984     break;
10985   case 'i':
10986     if (HowLong == 3)
10987       Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
10988     else if (HowLong == 2)
10989       Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
10990     else if (HowLong == 1)
10991       Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
10992     else
10993       Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
10994     break;
10995   case 'c':
10996     assert(HowLong == 0 && "Bad modifiers used with 'c'!");
10997     if (Signed)
10998       Type = Context.SignedCharTy;
10999     else if (Unsigned)
11000       Type = Context.UnsignedCharTy;
11001     else
11002       Type = Context.CharTy;
11003     break;
11004   case 'b': // boolean
11005     assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
11006     Type = Context.BoolTy;
11007     break;
11008   case 'z':  // size_t.
11009     assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
11010     Type = Context.getSizeType();
11011     break;
11012   case 'w':  // wchar_t.
11013     assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
11014     Type = Context.getWideCharType();
11015     break;
11016   case 'F':
11017     Type = Context.getCFConstantStringType();
11018     break;
11019   case 'G':
11020     Type = Context.getObjCIdType();
11021     break;
11022   case 'H':
11023     Type = Context.getObjCSelType();
11024     break;
11025   case 'M':
11026     Type = Context.getObjCSuperType();
11027     break;
11028   case 'a':
11029     Type = Context.getBuiltinVaListType();
11030     assert(!Type.isNull() && "builtin va list type not initialized!");
11031     break;
11032   case 'A':
11033     // This is a "reference" to a va_list; however, what exactly
11034     // this means depends on how va_list is defined. There are two
11035     // different kinds of va_list: ones passed by value, and ones
11036     // passed by reference.  An example of a by-value va_list is
11037     // x86, where va_list is a char*. An example of by-ref va_list
11038     // is x86-64, where va_list is a __va_list_tag[1]. For x86,
11039     // we want this argument to be a char*&; for x86-64, we want
11040     // it to be a __va_list_tag*.
11041     Type = Context.getBuiltinVaListType();
11042     assert(!Type.isNull() && "builtin va list type not initialized!");
11043     if (Type->isArrayType())
11044       Type = Context.getArrayDecayedType(Type);
11045     else
11046       Type = Context.getLValueReferenceType(Type);
11047     break;
11048   case 'q': {
11049     char *End;
11050     unsigned NumElements = strtoul(Str, &End, 10);
11051     assert(End != Str && "Missing vector size");
11052     Str = End;
11053 
11054     QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
11055                                              RequiresICE, false);
11056     assert(!RequiresICE && "Can't require vector ICE");
11057 
11058     Type = Context.getScalableVectorType(ElementType, NumElements);
11059     break;
11060   }
11061   case 'V': {
11062     char *End;
11063     unsigned NumElements = strtoul(Str, &End, 10);
11064     assert(End != Str && "Missing vector size");
11065     Str = End;
11066 
11067     QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
11068                                              RequiresICE, false);
11069     assert(!RequiresICE && "Can't require vector ICE");
11070 
11071     // TODO: No way to make AltiVec vectors in builtins yet.
11072     Type = Context.getVectorType(ElementType, NumElements,
11073                                  VectorType::GenericVector);
11074     break;
11075   }
11076   case 'E': {
11077     char *End;
11078 
11079     unsigned NumElements = strtoul(Str, &End, 10);
11080     assert(End != Str && "Missing vector size");
11081 
11082     Str = End;
11083 
11084     QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
11085                                              false);
11086     Type = Context.getExtVectorType(ElementType, NumElements);
11087     break;
11088   }
11089   case 'X': {
11090     QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
11091                                              false);
11092     assert(!RequiresICE && "Can't require complex ICE");
11093     Type = Context.getComplexType(ElementType);
11094     break;
11095   }
11096   case 'Y':
11097     Type = Context.getPointerDiffType();
11098     break;
11099   case 'P':
11100     Type = Context.getFILEType();
11101     if (Type.isNull()) {
11102       Error = ASTContext::GE_Missing_stdio;
11103       return {};
11104     }
11105     break;
11106   case 'J':
11107     if (Signed)
11108       Type = Context.getsigjmp_bufType();
11109     else
11110       Type = Context.getjmp_bufType();
11111 
11112     if (Type.isNull()) {
11113       Error = ASTContext::GE_Missing_setjmp;
11114       return {};
11115     }
11116     break;
11117   case 'K':
11118     assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
11119     Type = Context.getucontext_tType();
11120 
11121     if (Type.isNull()) {
11122       Error = ASTContext::GE_Missing_ucontext;
11123       return {};
11124     }
11125     break;
11126   case 'p':
11127     Type = Context.getProcessIDType();
11128     break;
11129   }
11130 
11131   // If there are modifiers and if we're allowed to parse them, go for it.
11132   Done = !AllowTypeModifiers;
11133   while (!Done) {
11134     switch (char c = *Str++) {
11135     default: Done = true; --Str; break;
11136     case '*':
11137     case '&': {
11138       // Both pointers and references can have their pointee types
11139       // qualified with an address space.
11140       char *End;
11141       unsigned AddrSpace = strtoul(Str, &End, 10);
11142       if (End != Str) {
11143         // Note AddrSpace == 0 is not the same as an unspecified address space.
11144         Type = Context.getAddrSpaceQualType(
11145           Type,
11146           Context.getLangASForBuiltinAddressSpace(AddrSpace));
11147         Str = End;
11148       }
11149       if (c == '*')
11150         Type = Context.getPointerType(Type);
11151       else
11152         Type = Context.getLValueReferenceType(Type);
11153       break;
11154     }
11155     // FIXME: There's no way to have a built-in with an rvalue ref arg.
11156     case 'C':
11157       Type = Type.withConst();
11158       break;
11159     case 'D':
11160       Type = Context.getVolatileType(Type);
11161       break;
11162     case 'R':
11163       Type = Type.withRestrict();
11164       break;
11165     }
11166   }
11167 
11168   assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
11169          "Integer constant 'I' type must be an integer");
11170 
11171   return Type;
11172 }
11173 
11174 // On some targets such as PowerPC, some of the builtins are defined with custom
11175 // type descriptors for target-dependent types. These descriptors are decoded in
11176 // other functions, but it may be useful to be able to fall back to default
11177 // descriptor decoding to define builtins mixing target-dependent and target-
11178 // independent types. This function allows decoding one type descriptor with
11179 // default decoding.
11180 QualType ASTContext::DecodeTypeStr(const char *&Str, const ASTContext &Context,
11181                                    GetBuiltinTypeError &Error, bool &RequireICE,
11182                                    bool AllowTypeModifiers) const {
11183   return DecodeTypeFromStr(Str, Context, Error, RequireICE, AllowTypeModifiers);
11184 }
11185 
11186 /// GetBuiltinType - Return the type for the specified builtin.
11187 QualType ASTContext::GetBuiltinType(unsigned Id,
11188                                     GetBuiltinTypeError &Error,
11189                                     unsigned *IntegerConstantArgs) const {
11190   const char *TypeStr = BuiltinInfo.getTypeString(Id);
11191   if (TypeStr[0] == '\0') {
11192     Error = GE_Missing_type;
11193     return {};
11194   }
11195 
11196   SmallVector<QualType, 8> ArgTypes;
11197 
11198   bool RequiresICE = false;
11199   Error = GE_None;
11200   QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
11201                                        RequiresICE, true);
11202   if (Error != GE_None)
11203     return {};
11204 
11205   assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
11206 
11207   while (TypeStr[0] && TypeStr[0] != '.') {
11208     QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
11209     if (Error != GE_None)
11210       return {};
11211 
11212     // If this argument is required to be an IntegerConstantExpression and the
11213     // caller cares, fill in the bitmask we return.
11214     if (RequiresICE && IntegerConstantArgs)
11215       *IntegerConstantArgs |= 1 << ArgTypes.size();
11216 
11217     // Do array -> pointer decay.  The builtin should use the decayed type.
11218     if (Ty->isArrayType())
11219       Ty = getArrayDecayedType(Ty);
11220 
11221     ArgTypes.push_back(Ty);
11222   }
11223 
11224   if (Id == Builtin::BI__GetExceptionInfo)
11225     return {};
11226 
11227   assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
11228          "'.' should only occur at end of builtin type list!");
11229 
11230   bool Variadic = (TypeStr[0] == '.');
11231 
11232   FunctionType::ExtInfo EI(getDefaultCallingConvention(
11233       Variadic, /*IsCXXMethod=*/false, /*IsBuiltin=*/true));
11234   if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
11235 
11236 
11237   // We really shouldn't be making a no-proto type here.
11238   if (ArgTypes.empty() && Variadic && !getLangOpts().CPlusPlus)
11239     return getFunctionNoProtoType(ResType, EI);
11240 
11241   FunctionProtoType::ExtProtoInfo EPI;
11242   EPI.ExtInfo = EI;
11243   EPI.Variadic = Variadic;
11244   if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id))
11245     EPI.ExceptionSpec.Type =
11246         getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
11247 
11248   return getFunctionType(ResType, ArgTypes, EPI);
11249 }
11250 
11251 static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
11252                                              const FunctionDecl *FD) {
11253   if (!FD->isExternallyVisible())
11254     return GVA_Internal;
11255 
11256   // Non-user-provided functions get emitted as weak definitions with every
11257   // use, no matter whether they've been explicitly instantiated etc.
11258   if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
11259     if (!MD->isUserProvided())
11260       return GVA_DiscardableODR;
11261 
11262   GVALinkage External;
11263   switch (FD->getTemplateSpecializationKind()) {
11264   case TSK_Undeclared:
11265   case TSK_ExplicitSpecialization:
11266     External = GVA_StrongExternal;
11267     break;
11268 
11269   case TSK_ExplicitInstantiationDefinition:
11270     return GVA_StrongODR;
11271 
11272   // C++11 [temp.explicit]p10:
11273   //   [ Note: The intent is that an inline function that is the subject of
11274   //   an explicit instantiation declaration will still be implicitly
11275   //   instantiated when used so that the body can be considered for
11276   //   inlining, but that no out-of-line copy of the inline function would be
11277   //   generated in the translation unit. -- end note ]
11278   case TSK_ExplicitInstantiationDeclaration:
11279     return GVA_AvailableExternally;
11280 
11281   case TSK_ImplicitInstantiation:
11282     External = GVA_DiscardableODR;
11283     break;
11284   }
11285 
11286   if (!FD->isInlined())
11287     return External;
11288 
11289   if ((!Context.getLangOpts().CPlusPlus &&
11290        !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
11291        !FD->hasAttr<DLLExportAttr>()) ||
11292       FD->hasAttr<GNUInlineAttr>()) {
11293     // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
11294 
11295     // GNU or C99 inline semantics. Determine whether this symbol should be
11296     // externally visible.
11297     if (FD->isInlineDefinitionExternallyVisible())
11298       return External;
11299 
11300     // C99 inline semantics, where the symbol is not externally visible.
11301     return GVA_AvailableExternally;
11302   }
11303 
11304   // Functions specified with extern and inline in -fms-compatibility mode
11305   // forcibly get emitted.  While the body of the function cannot be later
11306   // replaced, the function definition cannot be discarded.
11307   if (FD->isMSExternInline())
11308     return GVA_StrongODR;
11309 
11310   return GVA_DiscardableODR;
11311 }
11312 
11313 static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context,
11314                                                 const Decl *D, GVALinkage L) {
11315   // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
11316   // dllexport/dllimport on inline functions.
11317   if (D->hasAttr<DLLImportAttr>()) {
11318     if (L == GVA_DiscardableODR || L == GVA_StrongODR)
11319       return GVA_AvailableExternally;
11320   } else if (D->hasAttr<DLLExportAttr>()) {
11321     if (L == GVA_DiscardableODR)
11322       return GVA_StrongODR;
11323   } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice) {
11324     // Device-side functions with __global__ attribute must always be
11325     // visible externally so they can be launched from host.
11326     if (D->hasAttr<CUDAGlobalAttr>() &&
11327         (L == GVA_DiscardableODR || L == GVA_Internal))
11328       return GVA_StrongODR;
11329     // Single source offloading languages like CUDA/HIP need to be able to
11330     // access static device variables from host code of the same compilation
11331     // unit. This is done by externalizing the static variable with a shared
11332     // name between the host and device compilation which is the same for the
11333     // same compilation unit whereas different among different compilation
11334     // units.
11335     if (Context.shouldExternalize(D))
11336       return GVA_StrongExternal;
11337   }
11338   return L;
11339 }
11340 
11341 /// Adjust the GVALinkage for a declaration based on what an external AST source
11342 /// knows about whether there can be other definitions of this declaration.
11343 static GVALinkage
11344 adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D,
11345                                           GVALinkage L) {
11346   ExternalASTSource *Source = Ctx.getExternalSource();
11347   if (!Source)
11348     return L;
11349 
11350   switch (Source->hasExternalDefinitions(D)) {
11351   case ExternalASTSource::EK_Never:
11352     // Other translation units rely on us to provide the definition.
11353     if (L == GVA_DiscardableODR)
11354       return GVA_StrongODR;
11355     break;
11356 
11357   case ExternalASTSource::EK_Always:
11358     return GVA_AvailableExternally;
11359 
11360   case ExternalASTSource::EK_ReplyHazy:
11361     break;
11362   }
11363   return L;
11364 }
11365 
11366 GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
11367   return adjustGVALinkageForExternalDefinitionKind(*this, FD,
11368            adjustGVALinkageForAttributes(*this, FD,
11369              basicGVALinkageForFunction(*this, FD)));
11370 }
11371 
11372 static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
11373                                              const VarDecl *VD) {
11374   if (!VD->isExternallyVisible())
11375     return GVA_Internal;
11376 
11377   if (VD->isStaticLocal()) {
11378     const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
11379     while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
11380       LexicalContext = LexicalContext->getLexicalParent();
11381 
11382     // ObjC Blocks can create local variables that don't have a FunctionDecl
11383     // LexicalContext.
11384     if (!LexicalContext)
11385       return GVA_DiscardableODR;
11386 
11387     // Otherwise, let the static local variable inherit its linkage from the
11388     // nearest enclosing function.
11389     auto StaticLocalLinkage =
11390         Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
11391 
11392     // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
11393     // be emitted in any object with references to the symbol for the object it
11394     // contains, whether inline or out-of-line."
11395     // Similar behavior is observed with MSVC. An alternative ABI could use
11396     // StrongODR/AvailableExternally to match the function, but none are
11397     // known/supported currently.
11398     if (StaticLocalLinkage == GVA_StrongODR ||
11399         StaticLocalLinkage == GVA_AvailableExternally)
11400       return GVA_DiscardableODR;
11401     return StaticLocalLinkage;
11402   }
11403 
11404   // MSVC treats in-class initialized static data members as definitions.
11405   // By giving them non-strong linkage, out-of-line definitions won't
11406   // cause link errors.
11407   if (Context.isMSStaticDataMemberInlineDefinition(VD))
11408     return GVA_DiscardableODR;
11409 
11410   // Most non-template variables have strong linkage; inline variables are
11411   // linkonce_odr or (occasionally, for compatibility) weak_odr.
11412   GVALinkage StrongLinkage;
11413   switch (Context.getInlineVariableDefinitionKind(VD)) {
11414   case ASTContext::InlineVariableDefinitionKind::None:
11415     StrongLinkage = GVA_StrongExternal;
11416     break;
11417   case ASTContext::InlineVariableDefinitionKind::Weak:
11418   case ASTContext::InlineVariableDefinitionKind::WeakUnknown:
11419     StrongLinkage = GVA_DiscardableODR;
11420     break;
11421   case ASTContext::InlineVariableDefinitionKind::Strong:
11422     StrongLinkage = GVA_StrongODR;
11423     break;
11424   }
11425 
11426   switch (VD->getTemplateSpecializationKind()) {
11427   case TSK_Undeclared:
11428     return StrongLinkage;
11429 
11430   case TSK_ExplicitSpecialization:
11431     return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
11432                    VD->isStaticDataMember()
11433                ? GVA_StrongODR
11434                : StrongLinkage;
11435 
11436   case TSK_ExplicitInstantiationDefinition:
11437     return GVA_StrongODR;
11438 
11439   case TSK_ExplicitInstantiationDeclaration:
11440     return GVA_AvailableExternally;
11441 
11442   case TSK_ImplicitInstantiation:
11443     return GVA_DiscardableODR;
11444   }
11445 
11446   llvm_unreachable("Invalid Linkage!");
11447 }
11448 
11449 GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
11450   return adjustGVALinkageForExternalDefinitionKind(*this, VD,
11451            adjustGVALinkageForAttributes(*this, VD,
11452              basicGVALinkageForVariable(*this, VD)));
11453 }
11454 
11455 bool ASTContext::DeclMustBeEmitted(const Decl *D) {
11456   if (const auto *VD = dyn_cast<VarDecl>(D)) {
11457     if (!VD->isFileVarDecl())
11458       return false;
11459     // Global named register variables (GNU extension) are never emitted.
11460     if (VD->getStorageClass() == SC_Register)
11461       return false;
11462     if (VD->getDescribedVarTemplate() ||
11463         isa<VarTemplatePartialSpecializationDecl>(VD))
11464       return false;
11465   } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
11466     // We never need to emit an uninstantiated function template.
11467     if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
11468       return false;
11469   } else if (isa<PragmaCommentDecl>(D))
11470     return true;
11471   else if (isa<PragmaDetectMismatchDecl>(D))
11472     return true;
11473   else if (isa<OMPRequiresDecl>(D))
11474     return true;
11475   else if (isa<OMPThreadPrivateDecl>(D))
11476     return !D->getDeclContext()->isDependentContext();
11477   else if (isa<OMPAllocateDecl>(D))
11478     return !D->getDeclContext()->isDependentContext();
11479   else if (isa<OMPDeclareReductionDecl>(D) || isa<OMPDeclareMapperDecl>(D))
11480     return !D->getDeclContext()->isDependentContext();
11481   else if (isa<ImportDecl>(D))
11482     return true;
11483   else
11484     return false;
11485 
11486   // If this is a member of a class template, we do not need to emit it.
11487   if (D->getDeclContext()->isDependentContext())
11488     return false;
11489 
11490   // Weak references don't produce any output by themselves.
11491   if (D->hasAttr<WeakRefAttr>())
11492     return false;
11493 
11494   // Aliases and used decls are required.
11495   if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
11496     return true;
11497 
11498   if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
11499     // Forward declarations aren't required.
11500     if (!FD->doesThisDeclarationHaveABody())
11501       return FD->doesDeclarationForceExternallyVisibleDefinition();
11502 
11503     // Constructors and destructors are required.
11504     if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
11505       return true;
11506 
11507     // The key function for a class is required.  This rule only comes
11508     // into play when inline functions can be key functions, though.
11509     if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
11510       if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
11511         const CXXRecordDecl *RD = MD->getParent();
11512         if (MD->isOutOfLine() && RD->isDynamicClass()) {
11513           const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
11514           if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
11515             return true;
11516         }
11517       }
11518     }
11519 
11520     GVALinkage Linkage = GetGVALinkageForFunction(FD);
11521 
11522     // static, static inline, always_inline, and extern inline functions can
11523     // always be deferred.  Normal inline functions can be deferred in C99/C++.
11524     // Implicit template instantiations can also be deferred in C++.
11525     return !isDiscardableGVALinkage(Linkage);
11526   }
11527 
11528   const auto *VD = cast<VarDecl>(D);
11529   assert(VD->isFileVarDecl() && "Expected file scoped var");
11530 
11531   // If the decl is marked as `declare target to`, it should be emitted for the
11532   // host and for the device.
11533   if (LangOpts.OpenMP &&
11534       OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
11535     return true;
11536 
11537   if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
11538       !isMSStaticDataMemberInlineDefinition(VD))
11539     return false;
11540 
11541   // Variables that can be needed in other TUs are required.
11542   auto Linkage = GetGVALinkageForVariable(VD);
11543   if (!isDiscardableGVALinkage(Linkage))
11544     return true;
11545 
11546   // We never need to emit a variable that is available in another TU.
11547   if (Linkage == GVA_AvailableExternally)
11548     return false;
11549 
11550   // Variables that have destruction with side-effects are required.
11551   if (VD->needsDestruction(*this))
11552     return true;
11553 
11554   // Variables that have initialization with side-effects are required.
11555   if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
11556       // We can get a value-dependent initializer during error recovery.
11557       (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
11558     return true;
11559 
11560   // Likewise, variables with tuple-like bindings are required if their
11561   // bindings have side-effects.
11562   if (const auto *DD = dyn_cast<DecompositionDecl>(VD))
11563     for (const auto *BD : DD->bindings())
11564       if (const auto *BindingVD = BD->getHoldingVar())
11565         if (DeclMustBeEmitted(BindingVD))
11566           return true;
11567 
11568   return false;
11569 }
11570 
11571 void ASTContext::forEachMultiversionedFunctionVersion(
11572     const FunctionDecl *FD,
11573     llvm::function_ref<void(FunctionDecl *)> Pred) const {
11574   assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
11575   llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
11576   FD = FD->getMostRecentDecl();
11577   // FIXME: The order of traversal here matters and depends on the order of
11578   // lookup results, which happens to be (mostly) oldest-to-newest, but we
11579   // shouldn't rely on that.
11580   for (auto *CurDecl :
11581        FD->getDeclContext()->getRedeclContext()->lookup(FD->getDeclName())) {
11582     FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl();
11583     if (CurFD && hasSameType(CurFD->getType(), FD->getType()) &&
11584         std::end(SeenDecls) == llvm::find(SeenDecls, CurFD)) {
11585       SeenDecls.insert(CurFD);
11586       Pred(CurFD);
11587     }
11588   }
11589 }
11590 
11591 CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
11592                                                     bool IsCXXMethod,
11593                                                     bool IsBuiltin) const {
11594   // Pass through to the C++ ABI object
11595   if (IsCXXMethod)
11596     return ABI->getDefaultMethodCallConv(IsVariadic);
11597 
11598   // Builtins ignore user-specified default calling convention and remain the
11599   // Target's default calling convention.
11600   if (!IsBuiltin) {
11601     switch (LangOpts.getDefaultCallingConv()) {
11602     case LangOptions::DCC_None:
11603       break;
11604     case LangOptions::DCC_CDecl:
11605       return CC_C;
11606     case LangOptions::DCC_FastCall:
11607       if (getTargetInfo().hasFeature("sse2") && !IsVariadic)
11608         return CC_X86FastCall;
11609       break;
11610     case LangOptions::DCC_StdCall:
11611       if (!IsVariadic)
11612         return CC_X86StdCall;
11613       break;
11614     case LangOptions::DCC_VectorCall:
11615       // __vectorcall cannot be applied to variadic functions.
11616       if (!IsVariadic)
11617         return CC_X86VectorCall;
11618       break;
11619     case LangOptions::DCC_RegCall:
11620       // __regcall cannot be applied to variadic functions.
11621       if (!IsVariadic)
11622         return CC_X86RegCall;
11623       break;
11624     }
11625   }
11626   return Target->getDefaultCallingConv();
11627 }
11628 
11629 bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
11630   // Pass through to the C++ ABI object
11631   return ABI->isNearlyEmpty(RD);
11632 }
11633 
11634 VTableContextBase *ASTContext::getVTableContext() {
11635   if (!VTContext.get()) {
11636     auto ABI = Target->getCXXABI();
11637     if (ABI.isMicrosoft())
11638       VTContext.reset(new MicrosoftVTableContext(*this));
11639     else {
11640       auto ComponentLayout = getLangOpts().RelativeCXXABIVTables
11641                                  ? ItaniumVTableContext::Relative
11642                                  : ItaniumVTableContext::Pointer;
11643       VTContext.reset(new ItaniumVTableContext(*this, ComponentLayout));
11644     }
11645   }
11646   return VTContext.get();
11647 }
11648 
11649 MangleContext *ASTContext::createMangleContext(const TargetInfo *T) {
11650   if (!T)
11651     T = Target;
11652   switch (T->getCXXABI().getKind()) {
11653   case TargetCXXABI::AppleARM64:
11654   case TargetCXXABI::Fuchsia:
11655   case TargetCXXABI::GenericAArch64:
11656   case TargetCXXABI::GenericItanium:
11657   case TargetCXXABI::GenericARM:
11658   case TargetCXXABI::GenericMIPS:
11659   case TargetCXXABI::iOS:
11660   case TargetCXXABI::WebAssembly:
11661   case TargetCXXABI::WatchOS:
11662   case TargetCXXABI::XL:
11663     return ItaniumMangleContext::create(*this, getDiagnostics());
11664   case TargetCXXABI::Microsoft:
11665     return MicrosoftMangleContext::create(*this, getDiagnostics());
11666   }
11667   llvm_unreachable("Unsupported ABI");
11668 }
11669 
11670 MangleContext *ASTContext::createDeviceMangleContext(const TargetInfo &T) {
11671   assert(T.getCXXABI().getKind() != TargetCXXABI::Microsoft &&
11672          "Device mangle context does not support Microsoft mangling.");
11673   switch (T.getCXXABI().getKind()) {
11674   case TargetCXXABI::AppleARM64:
11675   case TargetCXXABI::Fuchsia:
11676   case TargetCXXABI::GenericAArch64:
11677   case TargetCXXABI::GenericItanium:
11678   case TargetCXXABI::GenericARM:
11679   case TargetCXXABI::GenericMIPS:
11680   case TargetCXXABI::iOS:
11681   case TargetCXXABI::WebAssembly:
11682   case TargetCXXABI::WatchOS:
11683   case TargetCXXABI::XL:
11684     return ItaniumMangleContext::create(
11685         *this, getDiagnostics(),
11686         [](ASTContext &, const NamedDecl *ND) -> llvm::Optional<unsigned> {
11687           if (const auto *RD = dyn_cast<CXXRecordDecl>(ND))
11688             return RD->getDeviceLambdaManglingNumber();
11689           return llvm::None;
11690         });
11691   case TargetCXXABI::Microsoft:
11692     return MicrosoftMangleContext::create(*this, getDiagnostics());
11693   }
11694   llvm_unreachable("Unsupported ABI");
11695 }
11696 
11697 CXXABI::~CXXABI() = default;
11698 
11699 size_t ASTContext::getSideTableAllocatedMemory() const {
11700   return ASTRecordLayouts.getMemorySize() +
11701          llvm::capacity_in_bytes(ObjCLayouts) +
11702          llvm::capacity_in_bytes(KeyFunctions) +
11703          llvm::capacity_in_bytes(ObjCImpls) +
11704          llvm::capacity_in_bytes(BlockVarCopyInits) +
11705          llvm::capacity_in_bytes(DeclAttrs) +
11706          llvm::capacity_in_bytes(TemplateOrInstantiation) +
11707          llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
11708          llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
11709          llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
11710          llvm::capacity_in_bytes(OverriddenMethods) +
11711          llvm::capacity_in_bytes(Types) +
11712          llvm::capacity_in_bytes(VariableArrayTypes);
11713 }
11714 
11715 /// getIntTypeForBitwidth -
11716 /// sets integer QualTy according to specified details:
11717 /// bitwidth, signed/unsigned.
11718 /// Returns empty type if there is no appropriate target types.
11719 QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
11720                                            unsigned Signed) const {
11721   TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
11722   CanQualType QualTy = getFromTargetType(Ty);
11723   if (!QualTy && DestWidth == 128)
11724     return Signed ? Int128Ty : UnsignedInt128Ty;
11725   return QualTy;
11726 }
11727 
11728 /// getRealTypeForBitwidth -
11729 /// sets floating point QualTy according to specified bitwidth.
11730 /// Returns empty type if there is no appropriate target types.
11731 QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth,
11732                                             FloatModeKind ExplicitType) const {
11733   FloatModeKind Ty =
11734       getTargetInfo().getRealTypeByWidth(DestWidth, ExplicitType);
11735   switch (Ty) {
11736   case FloatModeKind::Float:
11737     return FloatTy;
11738   case FloatModeKind::Double:
11739     return DoubleTy;
11740   case FloatModeKind::LongDouble:
11741     return LongDoubleTy;
11742   case FloatModeKind::Float128:
11743     return Float128Ty;
11744   case FloatModeKind::Ibm128:
11745     return Ibm128Ty;
11746   case FloatModeKind::NoFloat:
11747     return {};
11748   }
11749 
11750   llvm_unreachable("Unhandled TargetInfo::RealType value");
11751 }
11752 
11753 void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
11754   if (Number > 1)
11755     MangleNumbers[ND] = Number;
11756 }
11757 
11758 unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
11759   auto I = MangleNumbers.find(ND);
11760   return I != MangleNumbers.end() ? I->second : 1;
11761 }
11762 
11763 void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
11764   if (Number > 1)
11765     StaticLocalNumbers[VD] = Number;
11766 }
11767 
11768 unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
11769   auto I = StaticLocalNumbers.find(VD);
11770   return I != StaticLocalNumbers.end() ? I->second : 1;
11771 }
11772 
11773 MangleNumberingContext &
11774 ASTContext::getManglingNumberContext(const DeclContext *DC) {
11775   assert(LangOpts.CPlusPlus);  // We don't need mangling numbers for plain C.
11776   std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
11777   if (!MCtx)
11778     MCtx = createMangleNumberingContext();
11779   return *MCtx;
11780 }
11781 
11782 MangleNumberingContext &
11783 ASTContext::getManglingNumberContext(NeedExtraManglingDecl_t, const Decl *D) {
11784   assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
11785   std::unique_ptr<MangleNumberingContext> &MCtx =
11786       ExtraMangleNumberingContexts[D];
11787   if (!MCtx)
11788     MCtx = createMangleNumberingContext();
11789   return *MCtx;
11790 }
11791 
11792 std::unique_ptr<MangleNumberingContext>
11793 ASTContext::createMangleNumberingContext() const {
11794   return ABI->createMangleNumberingContext();
11795 }
11796 
11797 const CXXConstructorDecl *
11798 ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
11799   return ABI->getCopyConstructorForExceptionObject(
11800       cast<CXXRecordDecl>(RD->getFirstDecl()));
11801 }
11802 
11803 void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
11804                                                       CXXConstructorDecl *CD) {
11805   return ABI->addCopyConstructorForExceptionObject(
11806       cast<CXXRecordDecl>(RD->getFirstDecl()),
11807       cast<CXXConstructorDecl>(CD->getFirstDecl()));
11808 }
11809 
11810 void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
11811                                                  TypedefNameDecl *DD) {
11812   return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
11813 }
11814 
11815 TypedefNameDecl *
11816 ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
11817   return ABI->getTypedefNameForUnnamedTagDecl(TD);
11818 }
11819 
11820 void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
11821                                                 DeclaratorDecl *DD) {
11822   return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
11823 }
11824 
11825 DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
11826   return ABI->getDeclaratorForUnnamedTagDecl(TD);
11827 }
11828 
11829 void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
11830   ParamIndices[D] = index;
11831 }
11832 
11833 unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
11834   ParameterIndexTable::const_iterator I = ParamIndices.find(D);
11835   assert(I != ParamIndices.end() &&
11836          "ParmIndices lacks entry set by ParmVarDecl");
11837   return I->second;
11838 }
11839 
11840 QualType ASTContext::getStringLiteralArrayType(QualType EltTy,
11841                                                unsigned Length) const {
11842   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
11843   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
11844     EltTy = EltTy.withConst();
11845 
11846   EltTy = adjustStringLiteralBaseType(EltTy);
11847 
11848   // Get an array type for the string, according to C99 6.4.5. This includes
11849   // the null terminator character.
11850   return getConstantArrayType(EltTy, llvm::APInt(32, Length + 1), nullptr,
11851                               ArrayType::Normal, /*IndexTypeQuals*/ 0);
11852 }
11853 
11854 StringLiteral *
11855 ASTContext::getPredefinedStringLiteralFromCache(StringRef Key) const {
11856   StringLiteral *&Result = StringLiteralCache[Key];
11857   if (!Result)
11858     Result = StringLiteral::Create(
11859         *this, Key, StringLiteral::Ascii,
11860         /*Pascal*/ false, getStringLiteralArrayType(CharTy, Key.size()),
11861         SourceLocation());
11862   return Result;
11863 }
11864 
11865 MSGuidDecl *
11866 ASTContext::getMSGuidDecl(MSGuidDecl::Parts Parts) const {
11867   assert(MSGuidTagDecl && "building MS GUID without MS extensions?");
11868 
11869   llvm::FoldingSetNodeID ID;
11870   MSGuidDecl::Profile(ID, Parts);
11871 
11872   void *InsertPos;
11873   if (MSGuidDecl *Existing = MSGuidDecls.FindNodeOrInsertPos(ID, InsertPos))
11874     return Existing;
11875 
11876   QualType GUIDType = getMSGuidType().withConst();
11877   MSGuidDecl *New = MSGuidDecl::Create(*this, GUIDType, Parts);
11878   MSGuidDecls.InsertNode(New, InsertPos);
11879   return New;
11880 }
11881 
11882 UnnamedGlobalConstantDecl *
11883 ASTContext::getUnnamedGlobalConstantDecl(QualType Ty,
11884                                          const APValue &APVal) const {
11885   llvm::FoldingSetNodeID ID;
11886   UnnamedGlobalConstantDecl::Profile(ID, Ty, APVal);
11887 
11888   void *InsertPos;
11889   if (UnnamedGlobalConstantDecl *Existing =
11890           UnnamedGlobalConstantDecls.FindNodeOrInsertPos(ID, InsertPos))
11891     return Existing;
11892 
11893   UnnamedGlobalConstantDecl *New =
11894       UnnamedGlobalConstantDecl::Create(*this, Ty, APVal);
11895   UnnamedGlobalConstantDecls.InsertNode(New, InsertPos);
11896   return New;
11897 }
11898 
11899 TemplateParamObjectDecl *
11900 ASTContext::getTemplateParamObjectDecl(QualType T, const APValue &V) const {
11901   assert(T->isRecordType() && "template param object of unexpected type");
11902 
11903   // C++ [temp.param]p8:
11904   //   [...] a static storage duration object of type 'const T' [...]
11905   T.addConst();
11906 
11907   llvm::FoldingSetNodeID ID;
11908   TemplateParamObjectDecl::Profile(ID, T, V);
11909 
11910   void *InsertPos;
11911   if (TemplateParamObjectDecl *Existing =
11912           TemplateParamObjectDecls.FindNodeOrInsertPos(ID, InsertPos))
11913     return Existing;
11914 
11915   TemplateParamObjectDecl *New = TemplateParamObjectDecl::Create(*this, T, V);
11916   TemplateParamObjectDecls.InsertNode(New, InsertPos);
11917   return New;
11918 }
11919 
11920 bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
11921   const llvm::Triple &T = getTargetInfo().getTriple();
11922   if (!T.isOSDarwin())
11923     return false;
11924 
11925   if (!(T.isiOS() && T.isOSVersionLT(7)) &&
11926       !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
11927     return false;
11928 
11929   QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
11930   CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
11931   uint64_t Size = sizeChars.getQuantity();
11932   CharUnits alignChars = getTypeAlignInChars(AtomicTy);
11933   unsigned Align = alignChars.getQuantity();
11934   unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
11935   return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
11936 }
11937 
11938 bool
11939 ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
11940                                 const ObjCMethodDecl *MethodImpl) {
11941   // No point trying to match an unavailable/deprecated mothod.
11942   if (MethodDecl->hasAttr<UnavailableAttr>()
11943       || MethodDecl->hasAttr<DeprecatedAttr>())
11944     return false;
11945   if (MethodDecl->getObjCDeclQualifier() !=
11946       MethodImpl->getObjCDeclQualifier())
11947     return false;
11948   if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
11949     return false;
11950 
11951   if (MethodDecl->param_size() != MethodImpl->param_size())
11952     return false;
11953 
11954   for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
11955        IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
11956        EF = MethodDecl->param_end();
11957        IM != EM && IF != EF; ++IM, ++IF) {
11958     const ParmVarDecl *DeclVar = (*IF);
11959     const ParmVarDecl *ImplVar = (*IM);
11960     if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
11961       return false;
11962     if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
11963       return false;
11964   }
11965 
11966   return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
11967 }
11968 
11969 uint64_t ASTContext::getTargetNullPointerValue(QualType QT) const {
11970   LangAS AS;
11971   if (QT->getUnqualifiedDesugaredType()->isNullPtrType())
11972     AS = LangAS::Default;
11973   else
11974     AS = QT->getPointeeType().getAddressSpace();
11975 
11976   return getTargetInfo().getNullPointerValue(AS);
11977 }
11978 
11979 unsigned ASTContext::getTargetAddressSpace(QualType T) const {
11980   // Return the address space for the type. If the type is a
11981   // function type without an address space qualifier, the
11982   // program address space is used. Otherwise, the target picks
11983   // the best address space based on the type information
11984   return T->isFunctionType() && !T.hasAddressSpace()
11985              ? getTargetInfo().getProgramAddressSpace()
11986              : getTargetAddressSpace(T.getQualifiers());
11987 }
11988 
11989 unsigned ASTContext::getTargetAddressSpace(Qualifiers Q) const {
11990   return getTargetAddressSpace(Q.getAddressSpace());
11991 }
11992 
11993 unsigned ASTContext::getTargetAddressSpace(LangAS AS) const {
11994   if (isTargetAddressSpace(AS))
11995     return toTargetAddressSpace(AS);
11996   else
11997     return (*AddrSpaceMap)[(unsigned)AS];
11998 }
11999 
12000 QualType ASTContext::getCorrespondingSaturatedType(QualType Ty) const {
12001   assert(Ty->isFixedPointType());
12002 
12003   if (Ty->isSaturatedFixedPointType()) return Ty;
12004 
12005   switch (Ty->castAs<BuiltinType>()->getKind()) {
12006     default:
12007       llvm_unreachable("Not a fixed point type!");
12008     case BuiltinType::ShortAccum:
12009       return SatShortAccumTy;
12010     case BuiltinType::Accum:
12011       return SatAccumTy;
12012     case BuiltinType::LongAccum:
12013       return SatLongAccumTy;
12014     case BuiltinType::UShortAccum:
12015       return SatUnsignedShortAccumTy;
12016     case BuiltinType::UAccum:
12017       return SatUnsignedAccumTy;
12018     case BuiltinType::ULongAccum:
12019       return SatUnsignedLongAccumTy;
12020     case BuiltinType::ShortFract:
12021       return SatShortFractTy;
12022     case BuiltinType::Fract:
12023       return SatFractTy;
12024     case BuiltinType::LongFract:
12025       return SatLongFractTy;
12026     case BuiltinType::UShortFract:
12027       return SatUnsignedShortFractTy;
12028     case BuiltinType::UFract:
12029       return SatUnsignedFractTy;
12030     case BuiltinType::ULongFract:
12031       return SatUnsignedLongFractTy;
12032   }
12033 }
12034 
12035 LangAS ASTContext::getLangASForBuiltinAddressSpace(unsigned AS) const {
12036   if (LangOpts.OpenCL)
12037     return getTargetInfo().getOpenCLBuiltinAddressSpace(AS);
12038 
12039   if (LangOpts.CUDA)
12040     return getTargetInfo().getCUDABuiltinAddressSpace(AS);
12041 
12042   return getLangASFromTargetAS(AS);
12043 }
12044 
12045 // Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
12046 // doesn't include ASTContext.h
12047 template
12048 clang::LazyGenerationalUpdatePtr<
12049     const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
12050 clang::LazyGenerationalUpdatePtr<
12051     const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
12052         const clang::ASTContext &Ctx, Decl *Value);
12053 
12054 unsigned char ASTContext::getFixedPointScale(QualType Ty) const {
12055   assert(Ty->isFixedPointType());
12056 
12057   const TargetInfo &Target = getTargetInfo();
12058   switch (Ty->castAs<BuiltinType>()->getKind()) {
12059     default:
12060       llvm_unreachable("Not a fixed point type!");
12061     case BuiltinType::ShortAccum:
12062     case BuiltinType::SatShortAccum:
12063       return Target.getShortAccumScale();
12064     case BuiltinType::Accum:
12065     case BuiltinType::SatAccum:
12066       return Target.getAccumScale();
12067     case BuiltinType::LongAccum:
12068     case BuiltinType::SatLongAccum:
12069       return Target.getLongAccumScale();
12070     case BuiltinType::UShortAccum:
12071     case BuiltinType::SatUShortAccum:
12072       return Target.getUnsignedShortAccumScale();
12073     case BuiltinType::UAccum:
12074     case BuiltinType::SatUAccum:
12075       return Target.getUnsignedAccumScale();
12076     case BuiltinType::ULongAccum:
12077     case BuiltinType::SatULongAccum:
12078       return Target.getUnsignedLongAccumScale();
12079     case BuiltinType::ShortFract:
12080     case BuiltinType::SatShortFract:
12081       return Target.getShortFractScale();
12082     case BuiltinType::Fract:
12083     case BuiltinType::SatFract:
12084       return Target.getFractScale();
12085     case BuiltinType::LongFract:
12086     case BuiltinType::SatLongFract:
12087       return Target.getLongFractScale();
12088     case BuiltinType::UShortFract:
12089     case BuiltinType::SatUShortFract:
12090       return Target.getUnsignedShortFractScale();
12091     case BuiltinType::UFract:
12092     case BuiltinType::SatUFract:
12093       return Target.getUnsignedFractScale();
12094     case BuiltinType::ULongFract:
12095     case BuiltinType::SatULongFract:
12096       return Target.getUnsignedLongFractScale();
12097   }
12098 }
12099 
12100 unsigned char ASTContext::getFixedPointIBits(QualType Ty) const {
12101   assert(Ty->isFixedPointType());
12102 
12103   const TargetInfo &Target = getTargetInfo();
12104   switch (Ty->castAs<BuiltinType>()->getKind()) {
12105     default:
12106       llvm_unreachable("Not a fixed point type!");
12107     case BuiltinType::ShortAccum:
12108     case BuiltinType::SatShortAccum:
12109       return Target.getShortAccumIBits();
12110     case BuiltinType::Accum:
12111     case BuiltinType::SatAccum:
12112       return Target.getAccumIBits();
12113     case BuiltinType::LongAccum:
12114     case BuiltinType::SatLongAccum:
12115       return Target.getLongAccumIBits();
12116     case BuiltinType::UShortAccum:
12117     case BuiltinType::SatUShortAccum:
12118       return Target.getUnsignedShortAccumIBits();
12119     case BuiltinType::UAccum:
12120     case BuiltinType::SatUAccum:
12121       return Target.getUnsignedAccumIBits();
12122     case BuiltinType::ULongAccum:
12123     case BuiltinType::SatULongAccum:
12124       return Target.getUnsignedLongAccumIBits();
12125     case BuiltinType::ShortFract:
12126     case BuiltinType::SatShortFract:
12127     case BuiltinType::Fract:
12128     case BuiltinType::SatFract:
12129     case BuiltinType::LongFract:
12130     case BuiltinType::SatLongFract:
12131     case BuiltinType::UShortFract:
12132     case BuiltinType::SatUShortFract:
12133     case BuiltinType::UFract:
12134     case BuiltinType::SatUFract:
12135     case BuiltinType::ULongFract:
12136     case BuiltinType::SatULongFract:
12137       return 0;
12138   }
12139 }
12140 
12141 llvm::FixedPointSemantics
12142 ASTContext::getFixedPointSemantics(QualType Ty) const {
12143   assert((Ty->isFixedPointType() || Ty->isIntegerType()) &&
12144          "Can only get the fixed point semantics for a "
12145          "fixed point or integer type.");
12146   if (Ty->isIntegerType())
12147     return llvm::FixedPointSemantics::GetIntegerSemantics(
12148         getIntWidth(Ty), Ty->isSignedIntegerType());
12149 
12150   bool isSigned = Ty->isSignedFixedPointType();
12151   return llvm::FixedPointSemantics(
12152       static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned,
12153       Ty->isSaturatedFixedPointType(),
12154       !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding());
12155 }
12156 
12157 llvm::APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const {
12158   assert(Ty->isFixedPointType());
12159   return llvm::APFixedPoint::getMax(getFixedPointSemantics(Ty));
12160 }
12161 
12162 llvm::APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const {
12163   assert(Ty->isFixedPointType());
12164   return llvm::APFixedPoint::getMin(getFixedPointSemantics(Ty));
12165 }
12166 
12167 QualType ASTContext::getCorrespondingSignedFixedPointType(QualType Ty) const {
12168   assert(Ty->isUnsignedFixedPointType() &&
12169          "Expected unsigned fixed point type");
12170 
12171   switch (Ty->castAs<BuiltinType>()->getKind()) {
12172   case BuiltinType::UShortAccum:
12173     return ShortAccumTy;
12174   case BuiltinType::UAccum:
12175     return AccumTy;
12176   case BuiltinType::ULongAccum:
12177     return LongAccumTy;
12178   case BuiltinType::SatUShortAccum:
12179     return SatShortAccumTy;
12180   case BuiltinType::SatUAccum:
12181     return SatAccumTy;
12182   case BuiltinType::SatULongAccum:
12183     return SatLongAccumTy;
12184   case BuiltinType::UShortFract:
12185     return ShortFractTy;
12186   case BuiltinType::UFract:
12187     return FractTy;
12188   case BuiltinType::ULongFract:
12189     return LongFractTy;
12190   case BuiltinType::SatUShortFract:
12191     return SatShortFractTy;
12192   case BuiltinType::SatUFract:
12193     return SatFractTy;
12194   case BuiltinType::SatULongFract:
12195     return SatLongFractTy;
12196   default:
12197     llvm_unreachable("Unexpected unsigned fixed point type");
12198   }
12199 }
12200 
12201 ParsedTargetAttr
12202 ASTContext::filterFunctionTargetAttrs(const TargetAttr *TD) const {
12203   assert(TD != nullptr);
12204   ParsedTargetAttr ParsedAttr = TD->parse();
12205 
12206   llvm::erase_if(ParsedAttr.Features, [&](const std::string &Feat) {
12207     return !Target->isValidFeatureName(StringRef{Feat}.substr(1));
12208   });
12209   return ParsedAttr;
12210 }
12211 
12212 void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
12213                                        const FunctionDecl *FD) const {
12214   if (FD)
12215     getFunctionFeatureMap(FeatureMap, GlobalDecl().getWithDecl(FD));
12216   else
12217     Target->initFeatureMap(FeatureMap, getDiagnostics(),
12218                            Target->getTargetOpts().CPU,
12219                            Target->getTargetOpts().Features);
12220 }
12221 
12222 // Fills in the supplied string map with the set of target features for the
12223 // passed in function.
12224 void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
12225                                        GlobalDecl GD) const {
12226   StringRef TargetCPU = Target->getTargetOpts().CPU;
12227   const FunctionDecl *FD = GD.getDecl()->getAsFunction();
12228   if (const auto *TD = FD->getAttr<TargetAttr>()) {
12229     ParsedTargetAttr ParsedAttr = filterFunctionTargetAttrs(TD);
12230 
12231     // Make a copy of the features as passed on the command line into the
12232     // beginning of the additional features from the function to override.
12233     ParsedAttr.Features.insert(
12234         ParsedAttr.Features.begin(),
12235         Target->getTargetOpts().FeaturesAsWritten.begin(),
12236         Target->getTargetOpts().FeaturesAsWritten.end());
12237 
12238     if (ParsedAttr.Architecture != "" &&
12239         Target->isValidCPUName(ParsedAttr.Architecture))
12240       TargetCPU = ParsedAttr.Architecture;
12241 
12242     // Now populate the feature map, first with the TargetCPU which is either
12243     // the default or a new one from the target attribute string. Then we'll use
12244     // the passed in features (FeaturesAsWritten) along with the new ones from
12245     // the attribute.
12246     Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU,
12247                            ParsedAttr.Features);
12248   } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) {
12249     llvm::SmallVector<StringRef, 32> FeaturesTmp;
12250     Target->getCPUSpecificCPUDispatchFeatures(
12251         SD->getCPUName(GD.getMultiVersionIndex())->getName(), FeaturesTmp);
12252     std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end());
12253     Features.insert(Features.begin(),
12254                     Target->getTargetOpts().FeaturesAsWritten.begin(),
12255                     Target->getTargetOpts().FeaturesAsWritten.end());
12256     Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
12257   } else if (const auto *TC = FD->getAttr<TargetClonesAttr>()) {
12258     std::vector<std::string> Features;
12259     StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
12260     if (VersionStr.startswith("arch="))
12261       TargetCPU = VersionStr.drop_front(sizeof("arch=") - 1);
12262     else if (VersionStr != "default")
12263       Features.push_back((StringRef{"+"} + VersionStr).str());
12264 
12265     Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
12266   } else {
12267     FeatureMap = Target->getTargetOpts().FeatureMap;
12268   }
12269 }
12270 
12271 OMPTraitInfo &ASTContext::getNewOMPTraitInfo() {
12272   OMPTraitInfoVector.emplace_back(new OMPTraitInfo());
12273   return *OMPTraitInfoVector.back();
12274 }
12275 
12276 const StreamingDiagnostic &clang::
12277 operator<<(const StreamingDiagnostic &DB,
12278            const ASTContext::SectionInfo &Section) {
12279   if (Section.Decl)
12280     return DB << Section.Decl;
12281   return DB << "a prior #pragma section";
12282 }
12283 
12284 bool ASTContext::mayExternalize(const Decl *D) const {
12285   bool IsStaticVar =
12286       isa<VarDecl>(D) && cast<VarDecl>(D)->getStorageClass() == SC_Static;
12287   bool IsExplicitDeviceVar = (D->hasAttr<CUDADeviceAttr>() &&
12288                               !D->getAttr<CUDADeviceAttr>()->isImplicit()) ||
12289                              (D->hasAttr<CUDAConstantAttr>() &&
12290                               !D->getAttr<CUDAConstantAttr>()->isImplicit());
12291   // CUDA/HIP: static managed variables need to be externalized since it is
12292   // a declaration in IR, therefore cannot have internal linkage. Kernels in
12293   // anonymous name space needs to be externalized to avoid duplicate symbols.
12294   return (IsStaticVar &&
12295           (D->hasAttr<HIPManagedAttr>() || IsExplicitDeviceVar)) ||
12296          (D->hasAttr<CUDAGlobalAttr>() && D->isInAnonymousNamespace());
12297 }
12298 
12299 bool ASTContext::shouldExternalize(const Decl *D) const {
12300   return mayExternalize(D) &&
12301          (D->hasAttr<HIPManagedAttr>() || D->hasAttr<CUDAGlobalAttr>() ||
12302           CUDADeviceVarODRUsedByHost.count(cast<VarDecl>(D)));
12303 }
12304 
12305 StringRef ASTContext::getCUIDHash() const {
12306   if (!CUIDHash.empty())
12307     return CUIDHash;
12308   if (LangOpts.CUID.empty())
12309     return StringRef();
12310   CUIDHash = llvm::utohexstr(llvm::MD5Hash(LangOpts.CUID), /*LowerCase=*/true);
12311   return CUIDHash;
12312 }
12313