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