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