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     QualType T =
4874         NTTP->getType().getNonPackExpansionType().getNonLValueExprType(*this);
4875     // For class NTTPs, ensure we include the 'const' so the type matches that
4876     // of a real template argument.
4877     // FIXME: It would be more faithful to model this as something like an
4878     // lvalue-to-rvalue conversion applied to a const-qualified lvalue.
4879     if (T->isRecordType())
4880       T.addConst();
4881     Expr *E = new (*this) DeclRefExpr(
4882         *this, NTTP, /*enclosing*/ false, T,
4883         Expr::getValueKindForType(NTTP->getType()), NTTP->getLocation());
4884 
4885     if (NTTP->isParameterPack())
4886       E = new (*this) PackExpansionExpr(DependentTy, E, NTTP->getLocation(),
4887                                         None);
4888     Arg = TemplateArgument(E);
4889   } else {
4890     auto *TTP = cast<TemplateTemplateParmDecl>(Param);
4891     if (TTP->isParameterPack())
4892       Arg = TemplateArgument(TemplateName(TTP), Optional<unsigned>());
4893     else
4894       Arg = TemplateArgument(TemplateName(TTP));
4895   }
4896 
4897   if (Param->isTemplateParameterPack())
4898     Arg = TemplateArgument::CreatePackCopy(*this, Arg);
4899 
4900   return Arg;
4901 }
4902 
4903 void
4904 ASTContext::getInjectedTemplateArgs(const TemplateParameterList *Params,
4905                                     SmallVectorImpl<TemplateArgument> &Args) {
4906   Args.reserve(Args.size() + Params->size());
4907 
4908   for (NamedDecl *Param : *Params)
4909     Args.push_back(getInjectedTemplateArg(Param));
4910 }
4911 
4912 QualType ASTContext::getPackExpansionType(QualType Pattern,
4913                                           Optional<unsigned> NumExpansions,
4914                                           bool ExpectPackInType) {
4915   assert((!ExpectPackInType || Pattern->containsUnexpandedParameterPack()) &&
4916          "Pack expansions must expand one or more parameter packs");
4917 
4918   llvm::FoldingSetNodeID ID;
4919   PackExpansionType::Profile(ID, Pattern, NumExpansions);
4920 
4921   void *InsertPos = nullptr;
4922   PackExpansionType *T = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
4923   if (T)
4924     return QualType(T, 0);
4925 
4926   QualType Canon;
4927   if (!Pattern.isCanonical()) {
4928     Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions,
4929                                  /*ExpectPackInType=*/false);
4930 
4931     // Find the insert position again, in case we inserted an element into
4932     // PackExpansionTypes and invalidated our insert position.
4933     PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
4934   }
4935 
4936   T = new (*this, TypeAlignment)
4937       PackExpansionType(Pattern, Canon, NumExpansions);
4938   Types.push_back(T);
4939   PackExpansionTypes.InsertNode(T, InsertPos);
4940   return QualType(T, 0);
4941 }
4942 
4943 /// CmpProtocolNames - Comparison predicate for sorting protocols
4944 /// alphabetically.
4945 static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
4946                             ObjCProtocolDecl *const *RHS) {
4947   return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
4948 }
4949 
4950 static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) {
4951   if (Protocols.empty()) return true;
4952 
4953   if (Protocols[0]->getCanonicalDecl() != Protocols[0])
4954     return false;
4955 
4956   for (unsigned i = 1; i != Protocols.size(); ++i)
4957     if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
4958         Protocols[i]->getCanonicalDecl() != Protocols[i])
4959       return false;
4960   return true;
4961 }
4962 
4963 static void
4964 SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
4965   // Sort protocols, keyed by name.
4966   llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
4967 
4968   // Canonicalize.
4969   for (ObjCProtocolDecl *&P : Protocols)
4970     P = P->getCanonicalDecl();
4971 
4972   // Remove duplicates.
4973   auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
4974   Protocols.erase(ProtocolsEnd, Protocols.end());
4975 }
4976 
4977 QualType ASTContext::getObjCObjectType(QualType BaseType,
4978                                        ObjCProtocolDecl * const *Protocols,
4979                                        unsigned NumProtocols) const {
4980   return getObjCObjectType(BaseType, {},
4981                            llvm::makeArrayRef(Protocols, NumProtocols),
4982                            /*isKindOf=*/false);
4983 }
4984 
4985 QualType ASTContext::getObjCObjectType(
4986            QualType baseType,
4987            ArrayRef<QualType> typeArgs,
4988            ArrayRef<ObjCProtocolDecl *> protocols,
4989            bool isKindOf) const {
4990   // If the base type is an interface and there aren't any protocols or
4991   // type arguments to add, then the interface type will do just fine.
4992   if (typeArgs.empty() && protocols.empty() && !isKindOf &&
4993       isa<ObjCInterfaceType>(baseType))
4994     return baseType;
4995 
4996   // Look in the folding set for an existing type.
4997   llvm::FoldingSetNodeID ID;
4998   ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
4999   void *InsertPos = nullptr;
5000   if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
5001     return QualType(QT, 0);
5002 
5003   // Determine the type arguments to be used for canonicalization,
5004   // which may be explicitly specified here or written on the base
5005   // type.
5006   ArrayRef<QualType> effectiveTypeArgs = typeArgs;
5007   if (effectiveTypeArgs.empty()) {
5008     if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
5009       effectiveTypeArgs = baseObject->getTypeArgs();
5010   }
5011 
5012   // Build the canonical type, which has the canonical base type and a
5013   // sorted-and-uniqued list of protocols and the type arguments
5014   // canonicalized.
5015   QualType canonical;
5016   bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(),
5017                                           effectiveTypeArgs.end(),
5018                                           [&](QualType type) {
5019                                             return type.isCanonical();
5020                                           });
5021   bool protocolsSorted = areSortedAndUniqued(protocols);
5022   if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
5023     // Determine the canonical type arguments.
5024     ArrayRef<QualType> canonTypeArgs;
5025     SmallVector<QualType, 4> canonTypeArgsVec;
5026     if (!typeArgsAreCanonical) {
5027       canonTypeArgsVec.reserve(effectiveTypeArgs.size());
5028       for (auto typeArg : effectiveTypeArgs)
5029         canonTypeArgsVec.push_back(getCanonicalType(typeArg));
5030       canonTypeArgs = canonTypeArgsVec;
5031     } else {
5032       canonTypeArgs = effectiveTypeArgs;
5033     }
5034 
5035     ArrayRef<ObjCProtocolDecl *> canonProtocols;
5036     SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
5037     if (!protocolsSorted) {
5038       canonProtocolsVec.append(protocols.begin(), protocols.end());
5039       SortAndUniqueProtocols(canonProtocolsVec);
5040       canonProtocols = canonProtocolsVec;
5041     } else {
5042       canonProtocols = protocols;
5043     }
5044 
5045     canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
5046                                   canonProtocols, isKindOf);
5047 
5048     // Regenerate InsertPos.
5049     ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
5050   }
5051 
5052   unsigned size = sizeof(ObjCObjectTypeImpl);
5053   size += typeArgs.size() * sizeof(QualType);
5054   size += protocols.size() * sizeof(ObjCProtocolDecl *);
5055   void *mem = Allocate(size, TypeAlignment);
5056   auto *T =
5057     new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
5058                                  isKindOf);
5059 
5060   Types.push_back(T);
5061   ObjCObjectTypes.InsertNode(T, InsertPos);
5062   return QualType(T, 0);
5063 }
5064 
5065 /// Apply Objective-C protocol qualifiers to the given type.
5066 /// If this is for the canonical type of a type parameter, we can apply
5067 /// protocol qualifiers on the ObjCObjectPointerType.
5068 QualType
5069 ASTContext::applyObjCProtocolQualifiers(QualType type,
5070                   ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
5071                   bool allowOnPointerType) const {
5072   hasError = false;
5073 
5074   if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
5075     return getObjCTypeParamType(objT->getDecl(), protocols);
5076   }
5077 
5078   // Apply protocol qualifiers to ObjCObjectPointerType.
5079   if (allowOnPointerType) {
5080     if (const auto *objPtr =
5081             dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
5082       const ObjCObjectType *objT = objPtr->getObjectType();
5083       // Merge protocol lists and construct ObjCObjectType.
5084       SmallVector<ObjCProtocolDecl*, 8> protocolsVec;
5085       protocolsVec.append(objT->qual_begin(),
5086                           objT->qual_end());
5087       protocolsVec.append(protocols.begin(), protocols.end());
5088       ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
5089       type = getObjCObjectType(
5090              objT->getBaseType(),
5091              objT->getTypeArgsAsWritten(),
5092              protocols,
5093              objT->isKindOfTypeAsWritten());
5094       return getObjCObjectPointerType(type);
5095     }
5096   }
5097 
5098   // Apply protocol qualifiers to ObjCObjectType.
5099   if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
5100     // FIXME: Check for protocols to which the class type is already
5101     // known to conform.
5102 
5103     return getObjCObjectType(objT->getBaseType(),
5104                              objT->getTypeArgsAsWritten(),
5105                              protocols,
5106                              objT->isKindOfTypeAsWritten());
5107   }
5108 
5109   // If the canonical type is ObjCObjectType, ...
5110   if (type->isObjCObjectType()) {
5111     // Silently overwrite any existing protocol qualifiers.
5112     // TODO: determine whether that's the right thing to do.
5113 
5114     // FIXME: Check for protocols to which the class type is already
5115     // known to conform.
5116     return getObjCObjectType(type, {}, protocols, false);
5117   }
5118 
5119   // id<protocol-list>
5120   if (type->isObjCIdType()) {
5121     const auto *objPtr = type->castAs<ObjCObjectPointerType>();
5122     type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols,
5123                                  objPtr->isKindOfType());
5124     return getObjCObjectPointerType(type);
5125   }
5126 
5127   // Class<protocol-list>
5128   if (type->isObjCClassType()) {
5129     const auto *objPtr = type->castAs<ObjCObjectPointerType>();
5130     type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols,
5131                                  objPtr->isKindOfType());
5132     return getObjCObjectPointerType(type);
5133   }
5134 
5135   hasError = true;
5136   return type;
5137 }
5138 
5139 QualType
5140 ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
5141                                  ArrayRef<ObjCProtocolDecl *> protocols) const {
5142   // Look in the folding set for an existing type.
5143   llvm::FoldingSetNodeID ID;
5144   ObjCTypeParamType::Profile(ID, Decl, Decl->getUnderlyingType(), protocols);
5145   void *InsertPos = nullptr;
5146   if (ObjCTypeParamType *TypeParam =
5147       ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
5148     return QualType(TypeParam, 0);
5149 
5150   // We canonicalize to the underlying type.
5151   QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
5152   if (!protocols.empty()) {
5153     // Apply the protocol qualifers.
5154     bool hasError;
5155     Canonical = getCanonicalType(applyObjCProtocolQualifiers(
5156         Canonical, protocols, hasError, true /*allowOnPointerType*/));
5157     assert(!hasError && "Error when apply protocol qualifier to bound type");
5158   }
5159 
5160   unsigned size = sizeof(ObjCTypeParamType);
5161   size += protocols.size() * sizeof(ObjCProtocolDecl *);
5162   void *mem = Allocate(size, TypeAlignment);
5163   auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
5164 
5165   Types.push_back(newType);
5166   ObjCTypeParamTypes.InsertNode(newType, InsertPos);
5167   return QualType(newType, 0);
5168 }
5169 
5170 void ASTContext::adjustObjCTypeParamBoundType(const ObjCTypeParamDecl *Orig,
5171                                               ObjCTypeParamDecl *New) const {
5172   New->setTypeSourceInfo(getTrivialTypeSourceInfo(Orig->getUnderlyingType()));
5173   // Update TypeForDecl after updating TypeSourceInfo.
5174   auto NewTypeParamTy = cast<ObjCTypeParamType>(New->getTypeForDecl());
5175   SmallVector<ObjCProtocolDecl *, 8> protocols;
5176   protocols.append(NewTypeParamTy->qual_begin(), NewTypeParamTy->qual_end());
5177   QualType UpdatedTy = getObjCTypeParamType(New, protocols);
5178   New->setTypeForDecl(UpdatedTy.getTypePtr());
5179 }
5180 
5181 /// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
5182 /// protocol list adopt all protocols in QT's qualified-id protocol
5183 /// list.
5184 bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
5185                                                 ObjCInterfaceDecl *IC) {
5186   if (!QT->isObjCQualifiedIdType())
5187     return false;
5188 
5189   if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
5190     // If both the right and left sides have qualifiers.
5191     for (auto *Proto : OPT->quals()) {
5192       if (!IC->ClassImplementsProtocol(Proto, false))
5193         return false;
5194     }
5195     return true;
5196   }
5197   return false;
5198 }
5199 
5200 /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
5201 /// QT's qualified-id protocol list adopt all protocols in IDecl's list
5202 /// of protocols.
5203 bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
5204                                                 ObjCInterfaceDecl *IDecl) {
5205   if (!QT->isObjCQualifiedIdType())
5206     return false;
5207   const auto *OPT = QT->getAs<ObjCObjectPointerType>();
5208   if (!OPT)
5209     return false;
5210   if (!IDecl->hasDefinition())
5211     return false;
5212   llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
5213   CollectInheritedProtocols(IDecl, InheritedProtocols);
5214   if (InheritedProtocols.empty())
5215     return false;
5216   // Check that if every protocol in list of id<plist> conforms to a protocol
5217   // of IDecl's, then bridge casting is ok.
5218   bool Conforms = false;
5219   for (auto *Proto : OPT->quals()) {
5220     Conforms = false;
5221     for (auto *PI : InheritedProtocols) {
5222       if (ProtocolCompatibleWithProtocol(Proto, PI)) {
5223         Conforms = true;
5224         break;
5225       }
5226     }
5227     if (!Conforms)
5228       break;
5229   }
5230   if (Conforms)
5231     return true;
5232 
5233   for (auto *PI : InheritedProtocols) {
5234     // If both the right and left sides have qualifiers.
5235     bool Adopts = false;
5236     for (auto *Proto : OPT->quals()) {
5237       // return 'true' if 'PI' is in the inheritance hierarchy of Proto
5238       if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
5239         break;
5240     }
5241     if (!Adopts)
5242       return false;
5243   }
5244   return true;
5245 }
5246 
5247 /// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
5248 /// the given object type.
5249 QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
5250   llvm::FoldingSetNodeID ID;
5251   ObjCObjectPointerType::Profile(ID, ObjectT);
5252 
5253   void *InsertPos = nullptr;
5254   if (ObjCObjectPointerType *QT =
5255               ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
5256     return QualType(QT, 0);
5257 
5258   // Find the canonical object type.
5259   QualType Canonical;
5260   if (!ObjectT.isCanonical()) {
5261     Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
5262 
5263     // Regenerate InsertPos.
5264     ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
5265   }
5266 
5267   // No match.
5268   void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
5269   auto *QType =
5270     new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
5271 
5272   Types.push_back(QType);
5273   ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
5274   return QualType(QType, 0);
5275 }
5276 
5277 /// getObjCInterfaceType - Return the unique reference to the type for the
5278 /// specified ObjC interface decl. The list of protocols is optional.
5279 QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
5280                                           ObjCInterfaceDecl *PrevDecl) const {
5281   if (Decl->TypeForDecl)
5282     return QualType(Decl->TypeForDecl, 0);
5283 
5284   if (PrevDecl) {
5285     assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
5286     Decl->TypeForDecl = PrevDecl->TypeForDecl;
5287     return QualType(PrevDecl->TypeForDecl, 0);
5288   }
5289 
5290   // Prefer the definition, if there is one.
5291   if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
5292     Decl = Def;
5293 
5294   void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
5295   auto *T = new (Mem) ObjCInterfaceType(Decl);
5296   Decl->TypeForDecl = T;
5297   Types.push_back(T);
5298   return QualType(T, 0);
5299 }
5300 
5301 /// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
5302 /// TypeOfExprType AST's (since expression's are never shared). For example,
5303 /// multiple declarations that refer to "typeof(x)" all contain different
5304 /// DeclRefExpr's. This doesn't effect the type checker, since it operates
5305 /// on canonical type's (which are always unique).
5306 QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
5307   TypeOfExprType *toe;
5308   if (tofExpr->isTypeDependent()) {
5309     llvm::FoldingSetNodeID ID;
5310     DependentTypeOfExprType::Profile(ID, *this, tofExpr);
5311 
5312     void *InsertPos = nullptr;
5313     DependentTypeOfExprType *Canon
5314       = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
5315     if (Canon) {
5316       // We already have a "canonical" version of an identical, dependent
5317       // typeof(expr) type. Use that as our canonical type.
5318       toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
5319                                           QualType((TypeOfExprType*)Canon, 0));
5320     } else {
5321       // Build a new, canonical typeof(expr) type.
5322       Canon
5323         = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
5324       DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
5325       toe = Canon;
5326     }
5327   } else {
5328     QualType Canonical = getCanonicalType(tofExpr->getType());
5329     toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
5330   }
5331   Types.push_back(toe);
5332   return QualType(toe, 0);
5333 }
5334 
5335 /// getTypeOfType -  Unlike many "get<Type>" functions, we don't unique
5336 /// TypeOfType nodes. The only motivation to unique these nodes would be
5337 /// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
5338 /// an issue. This doesn't affect the type checker, since it operates
5339 /// on canonical types (which are always unique).
5340 QualType ASTContext::getTypeOfType(QualType tofType) const {
5341   QualType Canonical = getCanonicalType(tofType);
5342   auto *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
5343   Types.push_back(tot);
5344   return QualType(tot, 0);
5345 }
5346 
5347 /// Unlike many "get<Type>" functions, we don't unique DecltypeType
5348 /// nodes. This would never be helpful, since each such type has its own
5349 /// expression, and would not give a significant memory saving, since there
5350 /// is an Expr tree under each such type.
5351 QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
5352   DecltypeType *dt;
5353 
5354   // C++11 [temp.type]p2:
5355   //   If an expression e involves a template parameter, decltype(e) denotes a
5356   //   unique dependent type. Two such decltype-specifiers refer to the same
5357   //   type only if their expressions are equivalent (14.5.6.1).
5358   if (e->isInstantiationDependent()) {
5359     llvm::FoldingSetNodeID ID;
5360     DependentDecltypeType::Profile(ID, *this, e);
5361 
5362     void *InsertPos = nullptr;
5363     DependentDecltypeType *Canon
5364       = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
5365     if (!Canon) {
5366       // Build a new, canonical decltype(expr) type.
5367       Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
5368       DependentDecltypeTypes.InsertNode(Canon, InsertPos);
5369     }
5370     dt = new (*this, TypeAlignment)
5371         DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
5372   } else {
5373     dt = new (*this, TypeAlignment)
5374         DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
5375   }
5376   Types.push_back(dt);
5377   return QualType(dt, 0);
5378 }
5379 
5380 /// getUnaryTransformationType - We don't unique these, since the memory
5381 /// savings are minimal and these are rare.
5382 QualType ASTContext::getUnaryTransformType(QualType BaseType,
5383                                            QualType UnderlyingType,
5384                                            UnaryTransformType::UTTKind Kind)
5385     const {
5386   UnaryTransformType *ut = nullptr;
5387 
5388   if (BaseType->isDependentType()) {
5389     // Look in the folding set for an existing type.
5390     llvm::FoldingSetNodeID ID;
5391     DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind);
5392 
5393     void *InsertPos = nullptr;
5394     DependentUnaryTransformType *Canon
5395       = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
5396 
5397     if (!Canon) {
5398       // Build a new, canonical __underlying_type(type) type.
5399       Canon = new (*this, TypeAlignment)
5400              DependentUnaryTransformType(*this, getCanonicalType(BaseType),
5401                                          Kind);
5402       DependentUnaryTransformTypes.InsertNode(Canon, InsertPos);
5403     }
5404     ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
5405                                                         QualType(), Kind,
5406                                                         QualType(Canon, 0));
5407   } else {
5408     QualType CanonType = getCanonicalType(UnderlyingType);
5409     ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
5410                                                         UnderlyingType, Kind,
5411                                                         CanonType);
5412   }
5413   Types.push_back(ut);
5414   return QualType(ut, 0);
5415 }
5416 
5417 /// getAutoType - Return the uniqued reference to the 'auto' type which has been
5418 /// deduced to the given type, or to the canonical undeduced 'auto' type, or the
5419 /// canonical deduced-but-dependent 'auto' type.
5420 QualType
5421 ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
5422                         bool IsDependent, bool IsPack,
5423                         ConceptDecl *TypeConstraintConcept,
5424                         ArrayRef<TemplateArgument> TypeConstraintArgs) const {
5425   assert((!IsPack || IsDependent) && "only use IsPack for a dependent pack");
5426   if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto &&
5427       !TypeConstraintConcept && !IsDependent)
5428     return getAutoDeductType();
5429 
5430   // Look in the folding set for an existing type.
5431   void *InsertPos = nullptr;
5432   llvm::FoldingSetNodeID ID;
5433   AutoType::Profile(ID, *this, DeducedType, Keyword, IsDependent,
5434                     TypeConstraintConcept, TypeConstraintArgs);
5435   if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
5436     return QualType(AT, 0);
5437 
5438   void *Mem = Allocate(sizeof(AutoType) +
5439                        sizeof(TemplateArgument) * TypeConstraintArgs.size(),
5440                        TypeAlignment);
5441   auto *AT = new (Mem) AutoType(
5442       DeducedType, Keyword,
5443       (IsDependent ? TypeDependence::DependentInstantiation
5444                    : TypeDependence::None) |
5445           (IsPack ? TypeDependence::UnexpandedPack : TypeDependence::None),
5446       TypeConstraintConcept, TypeConstraintArgs);
5447   Types.push_back(AT);
5448   if (InsertPos)
5449     AutoTypes.InsertNode(AT, InsertPos);
5450   return QualType(AT, 0);
5451 }
5452 
5453 /// Return the uniqued reference to the deduced template specialization type
5454 /// which has been deduced to the given type, or to the canonical undeduced
5455 /// such type, or the canonical deduced-but-dependent such type.
5456 QualType ASTContext::getDeducedTemplateSpecializationType(
5457     TemplateName Template, QualType DeducedType, bool IsDependent) const {
5458   // Look in the folding set for an existing type.
5459   void *InsertPos = nullptr;
5460   llvm::FoldingSetNodeID ID;
5461   DeducedTemplateSpecializationType::Profile(ID, Template, DeducedType,
5462                                              IsDependent);
5463   if (DeducedTemplateSpecializationType *DTST =
5464           DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
5465     return QualType(DTST, 0);
5466 
5467   auto *DTST = new (*this, TypeAlignment)
5468       DeducedTemplateSpecializationType(Template, DeducedType, IsDependent);
5469   Types.push_back(DTST);
5470   if (InsertPos)
5471     DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
5472   return QualType(DTST, 0);
5473 }
5474 
5475 /// getAtomicType - Return the uniqued reference to the atomic type for
5476 /// the given value type.
5477 QualType ASTContext::getAtomicType(QualType T) const {
5478   // Unique pointers, to guarantee there is only one pointer of a particular
5479   // structure.
5480   llvm::FoldingSetNodeID ID;
5481   AtomicType::Profile(ID, T);
5482 
5483   void *InsertPos = nullptr;
5484   if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
5485     return QualType(AT, 0);
5486 
5487   // If the atomic value type isn't canonical, this won't be a canonical type
5488   // either, so fill in the canonical type field.
5489   QualType Canonical;
5490   if (!T.isCanonical()) {
5491     Canonical = getAtomicType(getCanonicalType(T));
5492 
5493     // Get the new insert position for the node we care about.
5494     AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
5495     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
5496   }
5497   auto *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
5498   Types.push_back(New);
5499   AtomicTypes.InsertNode(New, InsertPos);
5500   return QualType(New, 0);
5501 }
5502 
5503 /// getAutoDeductType - Get type pattern for deducing against 'auto'.
5504 QualType ASTContext::getAutoDeductType() const {
5505   if (AutoDeductTy.isNull())
5506     AutoDeductTy = QualType(new (*this, TypeAlignment)
5507                                 AutoType(QualType(), AutoTypeKeyword::Auto,
5508                                          TypeDependence::None,
5509                                          /*concept*/ nullptr, /*args*/ {}),
5510                             0);
5511   return AutoDeductTy;
5512 }
5513 
5514 /// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
5515 QualType ASTContext::getAutoRRefDeductType() const {
5516   if (AutoRRefDeductTy.isNull())
5517     AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
5518   assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
5519   return AutoRRefDeductTy;
5520 }
5521 
5522 /// getTagDeclType - Return the unique reference to the type for the
5523 /// specified TagDecl (struct/union/class/enum) decl.
5524 QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
5525   assert(Decl);
5526   // FIXME: What is the design on getTagDeclType when it requires casting
5527   // away const?  mutable?
5528   return getTypeDeclType(const_cast<TagDecl*>(Decl));
5529 }
5530 
5531 /// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
5532 /// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
5533 /// needs to agree with the definition in <stddef.h>.
5534 CanQualType ASTContext::getSizeType() const {
5535   return getFromTargetType(Target->getSizeType());
5536 }
5537 
5538 /// Return the unique signed counterpart of the integer type
5539 /// corresponding to size_t.
5540 CanQualType ASTContext::getSignedSizeType() const {
5541   return getFromTargetType(Target->getSignedSizeType());
5542 }
5543 
5544 /// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
5545 CanQualType ASTContext::getIntMaxType() const {
5546   return getFromTargetType(Target->getIntMaxType());
5547 }
5548 
5549 /// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
5550 CanQualType ASTContext::getUIntMaxType() const {
5551   return getFromTargetType(Target->getUIntMaxType());
5552 }
5553 
5554 /// getSignedWCharType - Return the type of "signed wchar_t".
5555 /// Used when in C++, as a GCC extension.
5556 QualType ASTContext::getSignedWCharType() const {
5557   // FIXME: derive from "Target" ?
5558   return WCharTy;
5559 }
5560 
5561 /// getUnsignedWCharType - Return the type of "unsigned wchar_t".
5562 /// Used when in C++, as a GCC extension.
5563 QualType ASTContext::getUnsignedWCharType() const {
5564   // FIXME: derive from "Target" ?
5565   return UnsignedIntTy;
5566 }
5567 
5568 QualType ASTContext::getIntPtrType() const {
5569   return getFromTargetType(Target->getIntPtrType());
5570 }
5571 
5572 QualType ASTContext::getUIntPtrType() const {
5573   return getCorrespondingUnsignedType(getIntPtrType());
5574 }
5575 
5576 /// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
5577 /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
5578 QualType ASTContext::getPointerDiffType() const {
5579   return getFromTargetType(Target->getPtrDiffType(0));
5580 }
5581 
5582 /// Return the unique unsigned counterpart of "ptrdiff_t"
5583 /// integer type. The standard (C11 7.21.6.1p7) refers to this type
5584 /// in the definition of %tu format specifier.
5585 QualType ASTContext::getUnsignedPointerDiffType() const {
5586   return getFromTargetType(Target->getUnsignedPtrDiffType(0));
5587 }
5588 
5589 /// Return the unique type for "pid_t" defined in
5590 /// <sys/types.h>. We need this to compute the correct type for vfork().
5591 QualType ASTContext::getProcessIDType() const {
5592   return getFromTargetType(Target->getProcessIDType());
5593 }
5594 
5595 //===----------------------------------------------------------------------===//
5596 //                              Type Operators
5597 //===----------------------------------------------------------------------===//
5598 
5599 CanQualType ASTContext::getCanonicalParamType(QualType T) const {
5600   // Push qualifiers into arrays, and then discard any remaining
5601   // qualifiers.
5602   T = getCanonicalType(T);
5603   T = getVariableArrayDecayedType(T);
5604   const Type *Ty = T.getTypePtr();
5605   QualType Result;
5606   if (isa<ArrayType>(Ty)) {
5607     Result = getArrayDecayedType(QualType(Ty,0));
5608   } else if (isa<FunctionType>(Ty)) {
5609     Result = getPointerType(QualType(Ty, 0));
5610   } else {
5611     Result = QualType(Ty, 0);
5612   }
5613 
5614   return CanQualType::CreateUnsafe(Result);
5615 }
5616 
5617 QualType ASTContext::getUnqualifiedArrayType(QualType type,
5618                                              Qualifiers &quals) {
5619   SplitQualType splitType = type.getSplitUnqualifiedType();
5620 
5621   // FIXME: getSplitUnqualifiedType() actually walks all the way to
5622   // the unqualified desugared type and then drops it on the floor.
5623   // We then have to strip that sugar back off with
5624   // getUnqualifiedDesugaredType(), which is silly.
5625   const auto *AT =
5626       dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
5627 
5628   // If we don't have an array, just use the results in splitType.
5629   if (!AT) {
5630     quals = splitType.Quals;
5631     return QualType(splitType.Ty, 0);
5632   }
5633 
5634   // Otherwise, recurse on the array's element type.
5635   QualType elementType = AT->getElementType();
5636   QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
5637 
5638   // If that didn't change the element type, AT has no qualifiers, so we
5639   // can just use the results in splitType.
5640   if (elementType == unqualElementType) {
5641     assert(quals.empty()); // from the recursive call
5642     quals = splitType.Quals;
5643     return QualType(splitType.Ty, 0);
5644   }
5645 
5646   // Otherwise, add in the qualifiers from the outermost type, then
5647   // build the type back up.
5648   quals.addConsistentQualifiers(splitType.Quals);
5649 
5650   if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
5651     return getConstantArrayType(unqualElementType, CAT->getSize(),
5652                                 CAT->getSizeExpr(), CAT->getSizeModifier(), 0);
5653   }
5654 
5655   if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) {
5656     return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
5657   }
5658 
5659   if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) {
5660     return getVariableArrayType(unqualElementType,
5661                                 VAT->getSizeExpr(),
5662                                 VAT->getSizeModifier(),
5663                                 VAT->getIndexTypeCVRQualifiers(),
5664                                 VAT->getBracketsRange());
5665   }
5666 
5667   const auto *DSAT = cast<DependentSizedArrayType>(AT);
5668   return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
5669                                     DSAT->getSizeModifier(), 0,
5670                                     SourceRange());
5671 }
5672 
5673 /// Attempt to unwrap two types that may both be array types with the same bound
5674 /// (or both be array types of unknown bound) for the purpose of comparing the
5675 /// cv-decomposition of two types per C++ [conv.qual].
5676 bool ASTContext::UnwrapSimilarArrayTypes(QualType &T1, QualType &T2) {
5677   bool UnwrappedAny = false;
5678   while (true) {
5679     auto *AT1 = getAsArrayType(T1);
5680     if (!AT1) return UnwrappedAny;
5681 
5682     auto *AT2 = getAsArrayType(T2);
5683     if (!AT2) return UnwrappedAny;
5684 
5685     // If we don't have two array types with the same constant bound nor two
5686     // incomplete array types, we've unwrapped everything we can.
5687     if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) {
5688       auto *CAT2 = dyn_cast<ConstantArrayType>(AT2);
5689       if (!CAT2 || CAT1->getSize() != CAT2->getSize())
5690         return UnwrappedAny;
5691     } else if (!isa<IncompleteArrayType>(AT1) ||
5692                !isa<IncompleteArrayType>(AT2)) {
5693       return UnwrappedAny;
5694     }
5695 
5696     T1 = AT1->getElementType();
5697     T2 = AT2->getElementType();
5698     UnwrappedAny = true;
5699   }
5700 }
5701 
5702 /// Attempt to unwrap two types that may be similar (C++ [conv.qual]).
5703 ///
5704 /// If T1 and T2 are both pointer types of the same kind, or both array types
5705 /// with the same bound, unwraps layers from T1 and T2 until a pointer type is
5706 /// unwrapped. Top-level qualifiers on T1 and T2 are ignored.
5707 ///
5708 /// This function will typically be called in a loop that successively
5709 /// "unwraps" pointer and pointer-to-member types to compare them at each
5710 /// level.
5711 ///
5712 /// \return \c true if a pointer type was unwrapped, \c false if we reached a
5713 /// pair of types that can't be unwrapped further.
5714 bool ASTContext::UnwrapSimilarTypes(QualType &T1, QualType &T2) {
5715   UnwrapSimilarArrayTypes(T1, T2);
5716 
5717   const auto *T1PtrType = T1->getAs<PointerType>();
5718   const auto *T2PtrType = T2->getAs<PointerType>();
5719   if (T1PtrType && T2PtrType) {
5720     T1 = T1PtrType->getPointeeType();
5721     T2 = T2PtrType->getPointeeType();
5722     return true;
5723   }
5724 
5725   const auto *T1MPType = T1->getAs<MemberPointerType>();
5726   const auto *T2MPType = T2->getAs<MemberPointerType>();
5727   if (T1MPType && T2MPType &&
5728       hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
5729                              QualType(T2MPType->getClass(), 0))) {
5730     T1 = T1MPType->getPointeeType();
5731     T2 = T2MPType->getPointeeType();
5732     return true;
5733   }
5734 
5735   if (getLangOpts().ObjC) {
5736     const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
5737     const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
5738     if (T1OPType && T2OPType) {
5739       T1 = T1OPType->getPointeeType();
5740       T2 = T2OPType->getPointeeType();
5741       return true;
5742     }
5743   }
5744 
5745   // FIXME: Block pointers, too?
5746 
5747   return false;
5748 }
5749 
5750 bool ASTContext::hasSimilarType(QualType T1, QualType T2) {
5751   while (true) {
5752     Qualifiers Quals;
5753     T1 = getUnqualifiedArrayType(T1, Quals);
5754     T2 = getUnqualifiedArrayType(T2, Quals);
5755     if (hasSameType(T1, T2))
5756       return true;
5757     if (!UnwrapSimilarTypes(T1, T2))
5758       return false;
5759   }
5760 }
5761 
5762 bool ASTContext::hasCvrSimilarType(QualType T1, QualType T2) {
5763   while (true) {
5764     Qualifiers Quals1, Quals2;
5765     T1 = getUnqualifiedArrayType(T1, Quals1);
5766     T2 = getUnqualifiedArrayType(T2, Quals2);
5767 
5768     Quals1.removeCVRQualifiers();
5769     Quals2.removeCVRQualifiers();
5770     if (Quals1 != Quals2)
5771       return false;
5772 
5773     if (hasSameType(T1, T2))
5774       return true;
5775 
5776     if (!UnwrapSimilarTypes(T1, T2))
5777       return false;
5778   }
5779 }
5780 
5781 DeclarationNameInfo
5782 ASTContext::getNameForTemplate(TemplateName Name,
5783                                SourceLocation NameLoc) const {
5784   switch (Name.getKind()) {
5785   case TemplateName::QualifiedTemplate:
5786   case TemplateName::Template:
5787     // DNInfo work in progress: CHECKME: what about DNLoc?
5788     return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
5789                                NameLoc);
5790 
5791   case TemplateName::OverloadedTemplate: {
5792     OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
5793     // DNInfo work in progress: CHECKME: what about DNLoc?
5794     return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
5795   }
5796 
5797   case TemplateName::AssumedTemplate: {
5798     AssumedTemplateStorage *Storage = Name.getAsAssumedTemplateName();
5799     return DeclarationNameInfo(Storage->getDeclName(), NameLoc);
5800   }
5801 
5802   case TemplateName::DependentTemplate: {
5803     DependentTemplateName *DTN = Name.getAsDependentTemplateName();
5804     DeclarationName DName;
5805     if (DTN->isIdentifier()) {
5806       DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
5807       return DeclarationNameInfo(DName, NameLoc);
5808     } else {
5809       DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
5810       // DNInfo work in progress: FIXME: source locations?
5811       DeclarationNameLoc DNLoc;
5812       DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
5813       DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
5814       return DeclarationNameInfo(DName, NameLoc, DNLoc);
5815     }
5816   }
5817 
5818   case TemplateName::SubstTemplateTemplateParm: {
5819     SubstTemplateTemplateParmStorage *subst
5820       = Name.getAsSubstTemplateTemplateParm();
5821     return DeclarationNameInfo(subst->getParameter()->getDeclName(),
5822                                NameLoc);
5823   }
5824 
5825   case TemplateName::SubstTemplateTemplateParmPack: {
5826     SubstTemplateTemplateParmPackStorage *subst
5827       = Name.getAsSubstTemplateTemplateParmPack();
5828     return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
5829                                NameLoc);
5830   }
5831   }
5832 
5833   llvm_unreachable("bad template name kind!");
5834 }
5835 
5836 TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
5837   switch (Name.getKind()) {
5838   case TemplateName::QualifiedTemplate:
5839   case TemplateName::Template: {
5840     TemplateDecl *Template = Name.getAsTemplateDecl();
5841     if (auto *TTP  = dyn_cast<TemplateTemplateParmDecl>(Template))
5842       Template = getCanonicalTemplateTemplateParmDecl(TTP);
5843 
5844     // The canonical template name is the canonical template declaration.
5845     return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
5846   }
5847 
5848   case TemplateName::OverloadedTemplate:
5849   case TemplateName::AssumedTemplate:
5850     llvm_unreachable("cannot canonicalize unresolved template");
5851 
5852   case TemplateName::DependentTemplate: {
5853     DependentTemplateName *DTN = Name.getAsDependentTemplateName();
5854     assert(DTN && "Non-dependent template names must refer to template decls.");
5855     return DTN->CanonicalTemplateName;
5856   }
5857 
5858   case TemplateName::SubstTemplateTemplateParm: {
5859     SubstTemplateTemplateParmStorage *subst
5860       = Name.getAsSubstTemplateTemplateParm();
5861     return getCanonicalTemplateName(subst->getReplacement());
5862   }
5863 
5864   case TemplateName::SubstTemplateTemplateParmPack: {
5865     SubstTemplateTemplateParmPackStorage *subst
5866                                   = Name.getAsSubstTemplateTemplateParmPack();
5867     TemplateTemplateParmDecl *canonParameter
5868       = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
5869     TemplateArgument canonArgPack
5870       = getCanonicalTemplateArgument(subst->getArgumentPack());
5871     return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
5872   }
5873   }
5874 
5875   llvm_unreachable("bad template name!");
5876 }
5877 
5878 bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
5879   X = getCanonicalTemplateName(X);
5880   Y = getCanonicalTemplateName(Y);
5881   return X.getAsVoidPointer() == Y.getAsVoidPointer();
5882 }
5883 
5884 TemplateArgument
5885 ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
5886   switch (Arg.getKind()) {
5887     case TemplateArgument::Null:
5888       return Arg;
5889 
5890     case TemplateArgument::Expression:
5891       return Arg;
5892 
5893     case TemplateArgument::Declaration: {
5894       auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
5895       return TemplateArgument(D, Arg.getParamTypeForDecl());
5896     }
5897 
5898     case TemplateArgument::NullPtr:
5899       return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
5900                               /*isNullPtr*/true);
5901 
5902     case TemplateArgument::Template:
5903       return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
5904 
5905     case TemplateArgument::TemplateExpansion:
5906       return TemplateArgument(getCanonicalTemplateName(
5907                                          Arg.getAsTemplateOrTemplatePattern()),
5908                               Arg.getNumTemplateExpansions());
5909 
5910     case TemplateArgument::Integral:
5911       return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
5912 
5913     case TemplateArgument::Type:
5914       return TemplateArgument(getCanonicalType(Arg.getAsType()));
5915 
5916     case TemplateArgument::Pack: {
5917       if (Arg.pack_size() == 0)
5918         return Arg;
5919 
5920       auto *CanonArgs = new (*this) TemplateArgument[Arg.pack_size()];
5921       unsigned Idx = 0;
5922       for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
5923                                         AEnd = Arg.pack_end();
5924            A != AEnd; (void)++A, ++Idx)
5925         CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
5926 
5927       return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
5928     }
5929   }
5930 
5931   // Silence GCC warning
5932   llvm_unreachable("Unhandled template argument kind");
5933 }
5934 
5935 NestedNameSpecifier *
5936 ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
5937   if (!NNS)
5938     return nullptr;
5939 
5940   switch (NNS->getKind()) {
5941   case NestedNameSpecifier::Identifier:
5942     // Canonicalize the prefix but keep the identifier the same.
5943     return NestedNameSpecifier::Create(*this,
5944                          getCanonicalNestedNameSpecifier(NNS->getPrefix()),
5945                                        NNS->getAsIdentifier());
5946 
5947   case NestedNameSpecifier::Namespace:
5948     // A namespace is canonical; build a nested-name-specifier with
5949     // this namespace and no prefix.
5950     return NestedNameSpecifier::Create(*this, nullptr,
5951                                  NNS->getAsNamespace()->getOriginalNamespace());
5952 
5953   case NestedNameSpecifier::NamespaceAlias:
5954     // A namespace is canonical; build a nested-name-specifier with
5955     // this namespace and no prefix.
5956     return NestedNameSpecifier::Create(*this, nullptr,
5957                                     NNS->getAsNamespaceAlias()->getNamespace()
5958                                                       ->getOriginalNamespace());
5959 
5960   case NestedNameSpecifier::TypeSpec:
5961   case NestedNameSpecifier::TypeSpecWithTemplate: {
5962     QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
5963 
5964     // If we have some kind of dependent-named type (e.g., "typename T::type"),
5965     // break it apart into its prefix and identifier, then reconsititute those
5966     // as the canonical nested-name-specifier. This is required to canonicalize
5967     // a dependent nested-name-specifier involving typedefs of dependent-name
5968     // types, e.g.,
5969     //   typedef typename T::type T1;
5970     //   typedef typename T1::type T2;
5971     if (const auto *DNT = T->getAs<DependentNameType>())
5972       return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
5973                            const_cast<IdentifierInfo *>(DNT->getIdentifier()));
5974 
5975     // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
5976     // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
5977     // first place?
5978     return NestedNameSpecifier::Create(*this, nullptr, false,
5979                                        const_cast<Type *>(T.getTypePtr()));
5980   }
5981 
5982   case NestedNameSpecifier::Global:
5983   case NestedNameSpecifier::Super:
5984     // The global specifier and __super specifer are canonical and unique.
5985     return NNS;
5986   }
5987 
5988   llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
5989 }
5990 
5991 const ArrayType *ASTContext::getAsArrayType(QualType T) const {
5992   // Handle the non-qualified case efficiently.
5993   if (!T.hasLocalQualifiers()) {
5994     // Handle the common positive case fast.
5995     if (const auto *AT = dyn_cast<ArrayType>(T))
5996       return AT;
5997   }
5998 
5999   // Handle the common negative case fast.
6000   if (!isa<ArrayType>(T.getCanonicalType()))
6001     return nullptr;
6002 
6003   // Apply any qualifiers from the array type to the element type.  This
6004   // implements C99 6.7.3p8: "If the specification of an array type includes
6005   // any type qualifiers, the element type is so qualified, not the array type."
6006 
6007   // If we get here, we either have type qualifiers on the type, or we have
6008   // sugar such as a typedef in the way.  If we have type qualifiers on the type
6009   // we must propagate them down into the element type.
6010 
6011   SplitQualType split = T.getSplitDesugaredType();
6012   Qualifiers qs = split.Quals;
6013 
6014   // If we have a simple case, just return now.
6015   const auto *ATy = dyn_cast<ArrayType>(split.Ty);
6016   if (!ATy || qs.empty())
6017     return ATy;
6018 
6019   // Otherwise, we have an array and we have qualifiers on it.  Push the
6020   // qualifiers into the array element type and return a new array type.
6021   QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
6022 
6023   if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy))
6024     return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
6025                                                 CAT->getSizeExpr(),
6026                                                 CAT->getSizeModifier(),
6027                                            CAT->getIndexTypeCVRQualifiers()));
6028   if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy))
6029     return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
6030                                                   IAT->getSizeModifier(),
6031                                            IAT->getIndexTypeCVRQualifiers()));
6032 
6033   if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy))
6034     return cast<ArrayType>(
6035                      getDependentSizedArrayType(NewEltTy,
6036                                                 DSAT->getSizeExpr(),
6037                                                 DSAT->getSizeModifier(),
6038                                               DSAT->getIndexTypeCVRQualifiers(),
6039                                                 DSAT->getBracketsRange()));
6040 
6041   const auto *VAT = cast<VariableArrayType>(ATy);
6042   return cast<ArrayType>(getVariableArrayType(NewEltTy,
6043                                               VAT->getSizeExpr(),
6044                                               VAT->getSizeModifier(),
6045                                               VAT->getIndexTypeCVRQualifiers(),
6046                                               VAT->getBracketsRange()));
6047 }
6048 
6049 QualType ASTContext::getAdjustedParameterType(QualType T) const {
6050   if (T->isArrayType() || T->isFunctionType())
6051     return getDecayedType(T);
6052   return T;
6053 }
6054 
6055 QualType ASTContext::getSignatureParameterType(QualType T) const {
6056   T = getVariableArrayDecayedType(T);
6057   T = getAdjustedParameterType(T);
6058   return T.getUnqualifiedType();
6059 }
6060 
6061 QualType ASTContext::getExceptionObjectType(QualType T) const {
6062   // C++ [except.throw]p3:
6063   //   A throw-expression initializes a temporary object, called the exception
6064   //   object, the type of which is determined by removing any top-level
6065   //   cv-qualifiers from the static type of the operand of throw and adjusting
6066   //   the type from "array of T" or "function returning T" to "pointer to T"
6067   //   or "pointer to function returning T", [...]
6068   T = getVariableArrayDecayedType(T);
6069   if (T->isArrayType() || T->isFunctionType())
6070     T = getDecayedType(T);
6071   return T.getUnqualifiedType();
6072 }
6073 
6074 /// getArrayDecayedType - Return the properly qualified result of decaying the
6075 /// specified array type to a pointer.  This operation is non-trivial when
6076 /// handling typedefs etc.  The canonical type of "T" must be an array type,
6077 /// this returns a pointer to a properly qualified element of the array.
6078 ///
6079 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
6080 QualType ASTContext::getArrayDecayedType(QualType Ty) const {
6081   // Get the element type with 'getAsArrayType' so that we don't lose any
6082   // typedefs in the element type of the array.  This also handles propagation
6083   // of type qualifiers from the array type into the element type if present
6084   // (C99 6.7.3p8).
6085   const ArrayType *PrettyArrayType = getAsArrayType(Ty);
6086   assert(PrettyArrayType && "Not an array type!");
6087 
6088   QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
6089 
6090   // int x[restrict 4] ->  int *restrict
6091   QualType Result = getQualifiedType(PtrTy,
6092                                      PrettyArrayType->getIndexTypeQualifiers());
6093 
6094   // int x[_Nullable] -> int * _Nullable
6095   if (auto Nullability = Ty->getNullability(*this)) {
6096     Result = const_cast<ASTContext *>(this)->getAttributedType(
6097         AttributedType::getNullabilityAttrKind(*Nullability), Result, Result);
6098   }
6099   return Result;
6100 }
6101 
6102 QualType ASTContext::getBaseElementType(const ArrayType *array) const {
6103   return getBaseElementType(array->getElementType());
6104 }
6105 
6106 QualType ASTContext::getBaseElementType(QualType type) const {
6107   Qualifiers qs;
6108   while (true) {
6109     SplitQualType split = type.getSplitDesugaredType();
6110     const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
6111     if (!array) break;
6112 
6113     type = array->getElementType();
6114     qs.addConsistentQualifiers(split.Quals);
6115   }
6116 
6117   return getQualifiedType(type, qs);
6118 }
6119 
6120 /// getConstantArrayElementCount - Returns number of constant array elements.
6121 uint64_t
6122 ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA)  const {
6123   uint64_t ElementCount = 1;
6124   do {
6125     ElementCount *= CA->getSize().getZExtValue();
6126     CA = dyn_cast_or_null<ConstantArrayType>(
6127       CA->getElementType()->getAsArrayTypeUnsafe());
6128   } while (CA);
6129   return ElementCount;
6130 }
6131 
6132 /// getFloatingRank - Return a relative rank for floating point types.
6133 /// This routine will assert if passed a built-in type that isn't a float.
6134 static FloatingRank getFloatingRank(QualType T) {
6135   if (const auto *CT = T->getAs<ComplexType>())
6136     return getFloatingRank(CT->getElementType());
6137 
6138   switch (T->castAs<BuiltinType>()->getKind()) {
6139   default: llvm_unreachable("getFloatingRank(): not a floating type");
6140   case BuiltinType::Float16:    return Float16Rank;
6141   case BuiltinType::Half:       return HalfRank;
6142   case BuiltinType::Float:      return FloatRank;
6143   case BuiltinType::Double:     return DoubleRank;
6144   case BuiltinType::LongDouble: return LongDoubleRank;
6145   case BuiltinType::Float128:   return Float128Rank;
6146   case BuiltinType::BFloat16:   return BFloat16Rank;
6147   }
6148 }
6149 
6150 /// getFloatingTypeOfSizeWithinDomain - Returns a real floating
6151 /// point or a complex type (based on typeDomain/typeSize).
6152 /// 'typeDomain' is a real floating point or complex type.
6153 /// 'typeSize' is a real floating point or complex type.
6154 QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
6155                                                        QualType Domain) const {
6156   FloatingRank EltRank = getFloatingRank(Size);
6157   if (Domain->isComplexType()) {
6158     switch (EltRank) {
6159     case BFloat16Rank: llvm_unreachable("Complex bfloat16 is not supported");
6160     case Float16Rank:
6161     case HalfRank: llvm_unreachable("Complex half is not supported");
6162     case FloatRank:      return FloatComplexTy;
6163     case DoubleRank:     return DoubleComplexTy;
6164     case LongDoubleRank: return LongDoubleComplexTy;
6165     case Float128Rank:   return Float128ComplexTy;
6166     }
6167   }
6168 
6169   assert(Domain->isRealFloatingType() && "Unknown domain!");
6170   switch (EltRank) {
6171   case Float16Rank:    return HalfTy;
6172   case BFloat16Rank:   return BFloat16Ty;
6173   case HalfRank:       return HalfTy;
6174   case FloatRank:      return FloatTy;
6175   case DoubleRank:     return DoubleTy;
6176   case LongDoubleRank: return LongDoubleTy;
6177   case Float128Rank:   return Float128Ty;
6178   }
6179   llvm_unreachable("getFloatingRank(): illegal value for rank");
6180 }
6181 
6182 /// getFloatingTypeOrder - Compare the rank of the two specified floating
6183 /// point types, ignoring the domain of the type (i.e. 'double' ==
6184 /// '_Complex double').  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
6185 /// LHS < RHS, return -1.
6186 int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
6187   FloatingRank LHSR = getFloatingRank(LHS);
6188   FloatingRank RHSR = getFloatingRank(RHS);
6189 
6190   if (LHSR == RHSR)
6191     return 0;
6192   if (LHSR > RHSR)
6193     return 1;
6194   return -1;
6195 }
6196 
6197 int ASTContext::getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const {
6198   if (&getFloatTypeSemantics(LHS) == &getFloatTypeSemantics(RHS))
6199     return 0;
6200   return getFloatingTypeOrder(LHS, RHS);
6201 }
6202 
6203 /// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
6204 /// routine will assert if passed a built-in type that isn't an integer or enum,
6205 /// or if it is not canonicalized.
6206 unsigned ASTContext::getIntegerRank(const Type *T) const {
6207   assert(T->isCanonicalUnqualified() && "T should be canonicalized");
6208 
6209   // Results in this 'losing' to any type of the same size, but winning if
6210   // larger.
6211   if (const auto *EIT = dyn_cast<ExtIntType>(T))
6212     return 0 + (EIT->getNumBits() << 3);
6213 
6214   switch (cast<BuiltinType>(T)->getKind()) {
6215   default: llvm_unreachable("getIntegerRank(): not a built-in integer");
6216   case BuiltinType::Bool:
6217     return 1 + (getIntWidth(BoolTy) << 3);
6218   case BuiltinType::Char_S:
6219   case BuiltinType::Char_U:
6220   case BuiltinType::SChar:
6221   case BuiltinType::UChar:
6222     return 2 + (getIntWidth(CharTy) << 3);
6223   case BuiltinType::Short:
6224   case BuiltinType::UShort:
6225     return 3 + (getIntWidth(ShortTy) << 3);
6226   case BuiltinType::Int:
6227   case BuiltinType::UInt:
6228     return 4 + (getIntWidth(IntTy) << 3);
6229   case BuiltinType::Long:
6230   case BuiltinType::ULong:
6231     return 5 + (getIntWidth(LongTy) << 3);
6232   case BuiltinType::LongLong:
6233   case BuiltinType::ULongLong:
6234     return 6 + (getIntWidth(LongLongTy) << 3);
6235   case BuiltinType::Int128:
6236   case BuiltinType::UInt128:
6237     return 7 + (getIntWidth(Int128Ty) << 3);
6238   }
6239 }
6240 
6241 /// Whether this is a promotable bitfield reference according
6242 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
6243 ///
6244 /// \returns the type this bit-field will promote to, or NULL if no
6245 /// promotion occurs.
6246 QualType ASTContext::isPromotableBitField(Expr *E) const {
6247   if (E->isTypeDependent() || E->isValueDependent())
6248     return {};
6249 
6250   // C++ [conv.prom]p5:
6251   //    If the bit-field has an enumerated type, it is treated as any other
6252   //    value of that type for promotion purposes.
6253   if (getLangOpts().CPlusPlus && E->getType()->isEnumeralType())
6254     return {};
6255 
6256   // FIXME: We should not do this unless E->refersToBitField() is true. This
6257   // matters in C where getSourceBitField() will find bit-fields for various
6258   // cases where the source expression is not a bit-field designator.
6259 
6260   FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
6261   if (!Field)
6262     return {};
6263 
6264   QualType FT = Field->getType();
6265 
6266   uint64_t BitWidth = Field->getBitWidthValue(*this);
6267   uint64_t IntSize = getTypeSize(IntTy);
6268   // C++ [conv.prom]p5:
6269   //   A prvalue for an integral bit-field can be converted to a prvalue of type
6270   //   int if int can represent all the values of the bit-field; otherwise, it
6271   //   can be converted to unsigned int if unsigned int can represent all the
6272   //   values of the bit-field. If the bit-field is larger yet, no integral
6273   //   promotion applies to it.
6274   // C11 6.3.1.1/2:
6275   //   [For a bit-field of type _Bool, int, signed int, or unsigned int:]
6276   //   If an int can represent all values of the original type (as restricted by
6277   //   the width, for a bit-field), the value is converted to an int; otherwise,
6278   //   it is converted to an unsigned int.
6279   //
6280   // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
6281   //        We perform that promotion here to match GCC and C++.
6282   // FIXME: C does not permit promotion of an enum bit-field whose rank is
6283   //        greater than that of 'int'. We perform that promotion to match GCC.
6284   if (BitWidth < IntSize)
6285     return IntTy;
6286 
6287   if (BitWidth == IntSize)
6288     return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
6289 
6290   // Bit-fields wider than int are not subject to promotions, and therefore act
6291   // like the base type. GCC has some weird bugs in this area that we
6292   // deliberately do not follow (GCC follows a pre-standard resolution to
6293   // C's DR315 which treats bit-width as being part of the type, and this leaks
6294   // into their semantics in some cases).
6295   return {};
6296 }
6297 
6298 /// getPromotedIntegerType - Returns the type that Promotable will
6299 /// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
6300 /// integer type.
6301 QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
6302   assert(!Promotable.isNull());
6303   assert(Promotable->isPromotableIntegerType());
6304   if (const auto *ET = Promotable->getAs<EnumType>())
6305     return ET->getDecl()->getPromotionType();
6306 
6307   if (const auto *BT = Promotable->getAs<BuiltinType>()) {
6308     // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
6309     // (3.9.1) can be converted to a prvalue of the first of the following
6310     // types that can represent all the values of its underlying type:
6311     // int, unsigned int, long int, unsigned long int, long long int, or
6312     // unsigned long long int [...]
6313     // FIXME: Is there some better way to compute this?
6314     if (BT->getKind() == BuiltinType::WChar_S ||
6315         BT->getKind() == BuiltinType::WChar_U ||
6316         BT->getKind() == BuiltinType::Char8 ||
6317         BT->getKind() == BuiltinType::Char16 ||
6318         BT->getKind() == BuiltinType::Char32) {
6319       bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
6320       uint64_t FromSize = getTypeSize(BT);
6321       QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
6322                                   LongLongTy, UnsignedLongLongTy };
6323       for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
6324         uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
6325         if (FromSize < ToSize ||
6326             (FromSize == ToSize &&
6327              FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
6328           return PromoteTypes[Idx];
6329       }
6330       llvm_unreachable("char type should fit into long long");
6331     }
6332   }
6333 
6334   // At this point, we should have a signed or unsigned integer type.
6335   if (Promotable->isSignedIntegerType())
6336     return IntTy;
6337   uint64_t PromotableSize = getIntWidth(Promotable);
6338   uint64_t IntSize = getIntWidth(IntTy);
6339   assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
6340   return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
6341 }
6342 
6343 /// Recurses in pointer/array types until it finds an objc retainable
6344 /// type and returns its ownership.
6345 Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
6346   while (!T.isNull()) {
6347     if (T.getObjCLifetime() != Qualifiers::OCL_None)
6348       return T.getObjCLifetime();
6349     if (T->isArrayType())
6350       T = getBaseElementType(T);
6351     else if (const auto *PT = T->getAs<PointerType>())
6352       T = PT->getPointeeType();
6353     else if (const auto *RT = T->getAs<ReferenceType>())
6354       T = RT->getPointeeType();
6355     else
6356       break;
6357   }
6358 
6359   return Qualifiers::OCL_None;
6360 }
6361 
6362 static const Type *getIntegerTypeForEnum(const EnumType *ET) {
6363   // Incomplete enum types are not treated as integer types.
6364   // FIXME: In C++, enum types are never integer types.
6365   if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
6366     return ET->getDecl()->getIntegerType().getTypePtr();
6367   return nullptr;
6368 }
6369 
6370 /// getIntegerTypeOrder - Returns the highest ranked integer type:
6371 /// C99 6.3.1.8p1.  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
6372 /// LHS < RHS, return -1.
6373 int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
6374   const Type *LHSC = getCanonicalType(LHS).getTypePtr();
6375   const Type *RHSC = getCanonicalType(RHS).getTypePtr();
6376 
6377   // Unwrap enums to their underlying type.
6378   if (const auto *ET = dyn_cast<EnumType>(LHSC))
6379     LHSC = getIntegerTypeForEnum(ET);
6380   if (const auto *ET = dyn_cast<EnumType>(RHSC))
6381     RHSC = getIntegerTypeForEnum(ET);
6382 
6383   if (LHSC == RHSC) return 0;
6384 
6385   bool LHSUnsigned = LHSC->isUnsignedIntegerType();
6386   bool RHSUnsigned = RHSC->isUnsignedIntegerType();
6387 
6388   unsigned LHSRank = getIntegerRank(LHSC);
6389   unsigned RHSRank = getIntegerRank(RHSC);
6390 
6391   if (LHSUnsigned == RHSUnsigned) {  // Both signed or both unsigned.
6392     if (LHSRank == RHSRank) return 0;
6393     return LHSRank > RHSRank ? 1 : -1;
6394   }
6395 
6396   // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
6397   if (LHSUnsigned) {
6398     // If the unsigned [LHS] type is larger, return it.
6399     if (LHSRank >= RHSRank)
6400       return 1;
6401 
6402     // If the signed type can represent all values of the unsigned type, it
6403     // wins.  Because we are dealing with 2's complement and types that are
6404     // powers of two larger than each other, this is always safe.
6405     return -1;
6406   }
6407 
6408   // If the unsigned [RHS] type is larger, return it.
6409   if (RHSRank >= LHSRank)
6410     return -1;
6411 
6412   // If the signed type can represent all values of the unsigned type, it
6413   // wins.  Because we are dealing with 2's complement and types that are
6414   // powers of two larger than each other, this is always safe.
6415   return 1;
6416 }
6417 
6418 TypedefDecl *ASTContext::getCFConstantStringDecl() const {
6419   if (CFConstantStringTypeDecl)
6420     return CFConstantStringTypeDecl;
6421 
6422   assert(!CFConstantStringTagDecl &&
6423          "tag and typedef should be initialized together");
6424   CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
6425   CFConstantStringTagDecl->startDefinition();
6426 
6427   struct {
6428     QualType Type;
6429     const char *Name;
6430   } Fields[5];
6431   unsigned Count = 0;
6432 
6433   /// Objective-C ABI
6434   ///
6435   ///    typedef struct __NSConstantString_tag {
6436   ///      const int *isa;
6437   ///      int flags;
6438   ///      const char *str;
6439   ///      long length;
6440   ///    } __NSConstantString;
6441   ///
6442   /// Swift ABI (4.1, 4.2)
6443   ///
6444   ///    typedef struct __NSConstantString_tag {
6445   ///      uintptr_t _cfisa;
6446   ///      uintptr_t _swift_rc;
6447   ///      _Atomic(uint64_t) _cfinfoa;
6448   ///      const char *_ptr;
6449   ///      uint32_t _length;
6450   ///    } __NSConstantString;
6451   ///
6452   /// Swift ABI (5.0)
6453   ///
6454   ///    typedef struct __NSConstantString_tag {
6455   ///      uintptr_t _cfisa;
6456   ///      uintptr_t _swift_rc;
6457   ///      _Atomic(uint64_t) _cfinfoa;
6458   ///      const char *_ptr;
6459   ///      uintptr_t _length;
6460   ///    } __NSConstantString;
6461 
6462   const auto CFRuntime = getLangOpts().CFRuntime;
6463   if (static_cast<unsigned>(CFRuntime) <
6464       static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) {
6465     Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" };
6466     Fields[Count++] = { IntTy, "flags" };
6467     Fields[Count++] = { getPointerType(CharTy.withConst()), "str" };
6468     Fields[Count++] = { LongTy, "length" };
6469   } else {
6470     Fields[Count++] = { getUIntPtrType(), "_cfisa" };
6471     Fields[Count++] = { getUIntPtrType(), "_swift_rc" };
6472     Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" };
6473     Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" };
6474     if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
6475         CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
6476       Fields[Count++] = { IntTy, "_ptr" };
6477     else
6478       Fields[Count++] = { getUIntPtrType(), "_ptr" };
6479   }
6480 
6481   // Create fields
6482   for (unsigned i = 0; i < Count; ++i) {
6483     FieldDecl *Field =
6484         FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(),
6485                           SourceLocation(), &Idents.get(Fields[i].Name),
6486                           Fields[i].Type, /*TInfo=*/nullptr,
6487                           /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
6488     Field->setAccess(AS_public);
6489     CFConstantStringTagDecl->addDecl(Field);
6490   }
6491 
6492   CFConstantStringTagDecl->completeDefinition();
6493   // This type is designed to be compatible with NSConstantString, but cannot
6494   // use the same name, since NSConstantString is an interface.
6495   auto tagType = getTagDeclType(CFConstantStringTagDecl);
6496   CFConstantStringTypeDecl =
6497       buildImplicitTypedef(tagType, "__NSConstantString");
6498 
6499   return CFConstantStringTypeDecl;
6500 }
6501 
6502 RecordDecl *ASTContext::getCFConstantStringTagDecl() const {
6503   if (!CFConstantStringTagDecl)
6504     getCFConstantStringDecl(); // Build the tag and the typedef.
6505   return CFConstantStringTagDecl;
6506 }
6507 
6508 // getCFConstantStringType - Return the type used for constant CFStrings.
6509 QualType ASTContext::getCFConstantStringType() const {
6510   return getTypedefType(getCFConstantStringDecl());
6511 }
6512 
6513 QualType ASTContext::getObjCSuperType() const {
6514   if (ObjCSuperType.isNull()) {
6515     RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
6516     TUDecl->addDecl(ObjCSuperTypeDecl);
6517     ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
6518   }
6519   return ObjCSuperType;
6520 }
6521 
6522 void ASTContext::setCFConstantStringType(QualType T) {
6523   const auto *TD = T->castAs<TypedefType>();
6524   CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl());
6525   const auto *TagType =
6526       CFConstantStringTypeDecl->getUnderlyingType()->castAs<RecordType>();
6527   CFConstantStringTagDecl = TagType->getDecl();
6528 }
6529 
6530 QualType ASTContext::getBlockDescriptorType() const {
6531   if (BlockDescriptorType)
6532     return getTagDeclType(BlockDescriptorType);
6533 
6534   RecordDecl *RD;
6535   // FIXME: Needs the FlagAppleBlock bit.
6536   RD = buildImplicitRecord("__block_descriptor");
6537   RD->startDefinition();
6538 
6539   QualType FieldTypes[] = {
6540     UnsignedLongTy,
6541     UnsignedLongTy,
6542   };
6543 
6544   static const char *const FieldNames[] = {
6545     "reserved",
6546     "Size"
6547   };
6548 
6549   for (size_t i = 0; i < 2; ++i) {
6550     FieldDecl *Field = FieldDecl::Create(
6551         *this, RD, SourceLocation(), SourceLocation(),
6552         &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
6553         /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
6554     Field->setAccess(AS_public);
6555     RD->addDecl(Field);
6556   }
6557 
6558   RD->completeDefinition();
6559 
6560   BlockDescriptorType = RD;
6561 
6562   return getTagDeclType(BlockDescriptorType);
6563 }
6564 
6565 QualType ASTContext::getBlockDescriptorExtendedType() const {
6566   if (BlockDescriptorExtendedType)
6567     return getTagDeclType(BlockDescriptorExtendedType);
6568 
6569   RecordDecl *RD;
6570   // FIXME: Needs the FlagAppleBlock bit.
6571   RD = buildImplicitRecord("__block_descriptor_withcopydispose");
6572   RD->startDefinition();
6573 
6574   QualType FieldTypes[] = {
6575     UnsignedLongTy,
6576     UnsignedLongTy,
6577     getPointerType(VoidPtrTy),
6578     getPointerType(VoidPtrTy)
6579   };
6580 
6581   static const char *const FieldNames[] = {
6582     "reserved",
6583     "Size",
6584     "CopyFuncPtr",
6585     "DestroyFuncPtr"
6586   };
6587 
6588   for (size_t i = 0; i < 4; ++i) {
6589     FieldDecl *Field = FieldDecl::Create(
6590         *this, RD, SourceLocation(), SourceLocation(),
6591         &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
6592         /*BitWidth=*/nullptr,
6593         /*Mutable=*/false, ICIS_NoInit);
6594     Field->setAccess(AS_public);
6595     RD->addDecl(Field);
6596   }
6597 
6598   RD->completeDefinition();
6599 
6600   BlockDescriptorExtendedType = RD;
6601   return getTagDeclType(BlockDescriptorExtendedType);
6602 }
6603 
6604 OpenCLTypeKind ASTContext::getOpenCLTypeKind(const Type *T) const {
6605   const auto *BT = dyn_cast<BuiltinType>(T);
6606 
6607   if (!BT) {
6608     if (isa<PipeType>(T))
6609       return OCLTK_Pipe;
6610 
6611     return OCLTK_Default;
6612   }
6613 
6614   switch (BT->getKind()) {
6615 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix)                   \
6616   case BuiltinType::Id:                                                        \
6617     return OCLTK_Image;
6618 #include "clang/Basic/OpenCLImageTypes.def"
6619 
6620   case BuiltinType::OCLClkEvent:
6621     return OCLTK_ClkEvent;
6622 
6623   case BuiltinType::OCLEvent:
6624     return OCLTK_Event;
6625 
6626   case BuiltinType::OCLQueue:
6627     return OCLTK_Queue;
6628 
6629   case BuiltinType::OCLReserveID:
6630     return OCLTK_ReserveID;
6631 
6632   case BuiltinType::OCLSampler:
6633     return OCLTK_Sampler;
6634 
6635   default:
6636     return OCLTK_Default;
6637   }
6638 }
6639 
6640 LangAS ASTContext::getOpenCLTypeAddrSpace(const Type *T) const {
6641   return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
6642 }
6643 
6644 /// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
6645 /// requires copy/dispose. Note that this must match the logic
6646 /// in buildByrefHelpers.
6647 bool ASTContext::BlockRequiresCopying(QualType Ty,
6648                                       const VarDecl *D) {
6649   if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
6650     const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr();
6651     if (!copyExpr && record->hasTrivialDestructor()) return false;
6652 
6653     return true;
6654   }
6655 
6656   // The block needs copy/destroy helpers if Ty is non-trivial to destructively
6657   // move or destroy.
6658   if (Ty.isNonTrivialToPrimitiveDestructiveMove() || Ty.isDestructedType())
6659     return true;
6660 
6661   if (!Ty->isObjCRetainableType()) return false;
6662 
6663   Qualifiers qs = Ty.getQualifiers();
6664 
6665   // If we have lifetime, that dominates.
6666   if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
6667     switch (lifetime) {
6668       case Qualifiers::OCL_None: llvm_unreachable("impossible");
6669 
6670       // These are just bits as far as the runtime is concerned.
6671       case Qualifiers::OCL_ExplicitNone:
6672       case Qualifiers::OCL_Autoreleasing:
6673         return false;
6674 
6675       // These cases should have been taken care of when checking the type's
6676       // non-triviality.
6677       case Qualifiers::OCL_Weak:
6678       case Qualifiers::OCL_Strong:
6679         llvm_unreachable("impossible");
6680     }
6681     llvm_unreachable("fell out of lifetime switch!");
6682   }
6683   return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
6684           Ty->isObjCObjectPointerType());
6685 }
6686 
6687 bool ASTContext::getByrefLifetime(QualType Ty,
6688                               Qualifiers::ObjCLifetime &LifeTime,
6689                               bool &HasByrefExtendedLayout) const {
6690   if (!getLangOpts().ObjC ||
6691       getLangOpts().getGC() != LangOptions::NonGC)
6692     return false;
6693 
6694   HasByrefExtendedLayout = false;
6695   if (Ty->isRecordType()) {
6696     HasByrefExtendedLayout = true;
6697     LifeTime = Qualifiers::OCL_None;
6698   } else if ((LifeTime = Ty.getObjCLifetime())) {
6699     // Honor the ARC qualifiers.
6700   } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
6701     // The MRR rule.
6702     LifeTime = Qualifiers::OCL_ExplicitNone;
6703   } else {
6704     LifeTime = Qualifiers::OCL_None;
6705   }
6706   return true;
6707 }
6708 
6709 CanQualType ASTContext::getNSUIntegerType() const {
6710   assert(Target && "Expected target to be initialized");
6711   const llvm::Triple &T = Target->getTriple();
6712   // Windows is LLP64 rather than LP64
6713   if (T.isOSWindows() && T.isArch64Bit())
6714     return UnsignedLongLongTy;
6715   return UnsignedLongTy;
6716 }
6717 
6718 CanQualType ASTContext::getNSIntegerType() const {
6719   assert(Target && "Expected target to be initialized");
6720   const llvm::Triple &T = Target->getTriple();
6721   // Windows is LLP64 rather than LP64
6722   if (T.isOSWindows() && T.isArch64Bit())
6723     return LongLongTy;
6724   return LongTy;
6725 }
6726 
6727 TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
6728   if (!ObjCInstanceTypeDecl)
6729     ObjCInstanceTypeDecl =
6730         buildImplicitTypedef(getObjCIdType(), "instancetype");
6731   return ObjCInstanceTypeDecl;
6732 }
6733 
6734 // This returns true if a type has been typedefed to BOOL:
6735 // typedef <type> BOOL;
6736 static bool isTypeTypedefedAsBOOL(QualType T) {
6737   if (const auto *TT = dyn_cast<TypedefType>(T))
6738     if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
6739       return II->isStr("BOOL");
6740 
6741   return false;
6742 }
6743 
6744 /// getObjCEncodingTypeSize returns size of type for objective-c encoding
6745 /// purpose.
6746 CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
6747   if (!type->isIncompleteArrayType() && type->isIncompleteType())
6748     return CharUnits::Zero();
6749 
6750   CharUnits sz = getTypeSizeInChars(type);
6751 
6752   // Make all integer and enum types at least as large as an int
6753   if (sz.isPositive() && type->isIntegralOrEnumerationType())
6754     sz = std::max(sz, getTypeSizeInChars(IntTy));
6755   // Treat arrays as pointers, since that's how they're passed in.
6756   else if (type->isArrayType())
6757     sz = getTypeSizeInChars(VoidPtrTy);
6758   return sz;
6759 }
6760 
6761 bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
6762   return getTargetInfo().getCXXABI().isMicrosoft() &&
6763          VD->isStaticDataMember() &&
6764          VD->getType()->isIntegralOrEnumerationType() &&
6765          !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
6766 }
6767 
6768 ASTContext::InlineVariableDefinitionKind
6769 ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const {
6770   if (!VD->isInline())
6771     return InlineVariableDefinitionKind::None;
6772 
6773   // In almost all cases, it's a weak definition.
6774   auto *First = VD->getFirstDecl();
6775   if (First->isInlineSpecified() || !First->isStaticDataMember())
6776     return InlineVariableDefinitionKind::Weak;
6777 
6778   // If there's a file-context declaration in this translation unit, it's a
6779   // non-discardable definition.
6780   for (auto *D : VD->redecls())
6781     if (D->getLexicalDeclContext()->isFileContext() &&
6782         !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
6783       return InlineVariableDefinitionKind::Strong;
6784 
6785   // If we've not seen one yet, we don't know.
6786   return InlineVariableDefinitionKind::WeakUnknown;
6787 }
6788 
6789 static std::string charUnitsToString(const CharUnits &CU) {
6790   return llvm::itostr(CU.getQuantity());
6791 }
6792 
6793 /// getObjCEncodingForBlock - Return the encoded type for this block
6794 /// declaration.
6795 std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
6796   std::string S;
6797 
6798   const BlockDecl *Decl = Expr->getBlockDecl();
6799   QualType BlockTy =
6800       Expr->getType()->castAs<BlockPointerType>()->getPointeeType();
6801   QualType BlockReturnTy = BlockTy->castAs<FunctionType>()->getReturnType();
6802   // Encode result type.
6803   if (getLangOpts().EncodeExtendedBlockSig)
6804     getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, BlockReturnTy, S,
6805                                       true /*Extended*/);
6806   else
6807     getObjCEncodingForType(BlockReturnTy, S);
6808   // Compute size of all parameters.
6809   // Start with computing size of a pointer in number of bytes.
6810   // FIXME: There might(should) be a better way of doing this computation!
6811   CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
6812   CharUnits ParmOffset = PtrSize;
6813   for (auto PI : Decl->parameters()) {
6814     QualType PType = PI->getType();
6815     CharUnits sz = getObjCEncodingTypeSize(PType);
6816     if (sz.isZero())
6817       continue;
6818     assert(sz.isPositive() && "BlockExpr - Incomplete param type");
6819     ParmOffset += sz;
6820   }
6821   // Size of the argument frame
6822   S += charUnitsToString(ParmOffset);
6823   // Block pointer and offset.
6824   S += "@?0";
6825 
6826   // Argument types.
6827   ParmOffset = PtrSize;
6828   for (auto PVDecl : Decl->parameters()) {
6829     QualType PType = PVDecl->getOriginalType();
6830     if (const auto *AT =
6831             dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
6832       // Use array's original type only if it has known number of
6833       // elements.
6834       if (!isa<ConstantArrayType>(AT))
6835         PType = PVDecl->getType();
6836     } else if (PType->isFunctionType())
6837       PType = PVDecl->getType();
6838     if (getLangOpts().EncodeExtendedBlockSig)
6839       getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
6840                                       S, true /*Extended*/);
6841     else
6842       getObjCEncodingForType(PType, S);
6843     S += charUnitsToString(ParmOffset);
6844     ParmOffset += getObjCEncodingTypeSize(PType);
6845   }
6846 
6847   return S;
6848 }
6849 
6850 std::string
6851 ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const {
6852   std::string S;
6853   // Encode result type.
6854   getObjCEncodingForType(Decl->getReturnType(), S);
6855   CharUnits ParmOffset;
6856   // Compute size of all parameters.
6857   for (auto PI : Decl->parameters()) {
6858     QualType PType = PI->getType();
6859     CharUnits sz = getObjCEncodingTypeSize(PType);
6860     if (sz.isZero())
6861       continue;
6862 
6863     assert(sz.isPositive() &&
6864            "getObjCEncodingForFunctionDecl - Incomplete param type");
6865     ParmOffset += sz;
6866   }
6867   S += charUnitsToString(ParmOffset);
6868   ParmOffset = CharUnits::Zero();
6869 
6870   // Argument types.
6871   for (auto PVDecl : Decl->parameters()) {
6872     QualType PType = PVDecl->getOriginalType();
6873     if (const auto *AT =
6874             dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
6875       // Use array's original type only if it has known number of
6876       // elements.
6877       if (!isa<ConstantArrayType>(AT))
6878         PType = PVDecl->getType();
6879     } else if (PType->isFunctionType())
6880       PType = PVDecl->getType();
6881     getObjCEncodingForType(PType, S);
6882     S += charUnitsToString(ParmOffset);
6883     ParmOffset += getObjCEncodingTypeSize(PType);
6884   }
6885 
6886   return S;
6887 }
6888 
6889 /// getObjCEncodingForMethodParameter - Return the encoded type for a single
6890 /// method parameter or return type. If Extended, include class names and
6891 /// block object types.
6892 void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
6893                                                    QualType T, std::string& S,
6894                                                    bool Extended) const {
6895   // Encode type qualifer, 'in', 'inout', etc. for the parameter.
6896   getObjCEncodingForTypeQualifier(QT, S);
6897   // Encode parameter type.
6898   ObjCEncOptions Options = ObjCEncOptions()
6899                                .setExpandPointedToStructures()
6900                                .setExpandStructures()
6901                                .setIsOutermostType();
6902   if (Extended)
6903     Options.setEncodeBlockParameters().setEncodeClassNames();
6904   getObjCEncodingForTypeImpl(T, S, Options, /*Field=*/nullptr);
6905 }
6906 
6907 /// getObjCEncodingForMethodDecl - Return the encoded type for this method
6908 /// declaration.
6909 std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
6910                                                      bool Extended) const {
6911   // FIXME: This is not very efficient.
6912   // Encode return type.
6913   std::string S;
6914   getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
6915                                     Decl->getReturnType(), S, Extended);
6916   // Compute size of all parameters.
6917   // Start with computing size of a pointer in number of bytes.
6918   // FIXME: There might(should) be a better way of doing this computation!
6919   CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
6920   // The first two arguments (self and _cmd) are pointers; account for
6921   // their size.
6922   CharUnits ParmOffset = 2 * PtrSize;
6923   for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
6924        E = Decl->sel_param_end(); PI != E; ++PI) {
6925     QualType PType = (*PI)->getType();
6926     CharUnits sz = getObjCEncodingTypeSize(PType);
6927     if (sz.isZero())
6928       continue;
6929 
6930     assert(sz.isPositive() &&
6931            "getObjCEncodingForMethodDecl - Incomplete param type");
6932     ParmOffset += sz;
6933   }
6934   S += charUnitsToString(ParmOffset);
6935   S += "@0:";
6936   S += charUnitsToString(PtrSize);
6937 
6938   // Argument types.
6939   ParmOffset = 2 * PtrSize;
6940   for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
6941        E = Decl->sel_param_end(); PI != E; ++PI) {
6942     const ParmVarDecl *PVDecl = *PI;
6943     QualType PType = PVDecl->getOriginalType();
6944     if (const auto *AT =
6945             dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
6946       // Use array's original type only if it has known number of
6947       // elements.
6948       if (!isa<ConstantArrayType>(AT))
6949         PType = PVDecl->getType();
6950     } else if (PType->isFunctionType())
6951       PType = PVDecl->getType();
6952     getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
6953                                       PType, S, Extended);
6954     S += charUnitsToString(ParmOffset);
6955     ParmOffset += getObjCEncodingTypeSize(PType);
6956   }
6957 
6958   return S;
6959 }
6960 
6961 ObjCPropertyImplDecl *
6962 ASTContext::getObjCPropertyImplDeclForPropertyDecl(
6963                                       const ObjCPropertyDecl *PD,
6964                                       const Decl *Container) const {
6965   if (!Container)
6966     return nullptr;
6967   if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) {
6968     for (auto *PID : CID->property_impls())
6969       if (PID->getPropertyDecl() == PD)
6970         return PID;
6971   } else {
6972     const auto *OID = cast<ObjCImplementationDecl>(Container);
6973     for (auto *PID : OID->property_impls())
6974       if (PID->getPropertyDecl() == PD)
6975         return PID;
6976   }
6977   return nullptr;
6978 }
6979 
6980 /// getObjCEncodingForPropertyDecl - Return the encoded type for this
6981 /// property declaration. If non-NULL, Container must be either an
6982 /// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
6983 /// NULL when getting encodings for protocol properties.
6984 /// Property attributes are stored as a comma-delimited C string. The simple
6985 /// attributes readonly and bycopy are encoded as single characters. The
6986 /// parametrized attributes, getter=name, setter=name, and ivar=name, are
6987 /// encoded as single characters, followed by an identifier. Property types
6988 /// are also encoded as a parametrized attribute. The characters used to encode
6989 /// these attributes are defined by the following enumeration:
6990 /// @code
6991 /// enum PropertyAttributes {
6992 /// kPropertyReadOnly = 'R',   // property is read-only.
6993 /// kPropertyBycopy = 'C',     // property is a copy of the value last assigned
6994 /// kPropertyByref = '&',  // property is a reference to the value last assigned
6995 /// kPropertyDynamic = 'D',    // property is dynamic
6996 /// kPropertyGetter = 'G',     // followed by getter selector name
6997 /// kPropertySetter = 'S',     // followed by setter selector name
6998 /// kPropertyInstanceVariable = 'V'  // followed by instance variable  name
6999 /// kPropertyType = 'T'              // followed by old-style type encoding.
7000 /// kPropertyWeak = 'W'              // 'weak' property
7001 /// kPropertyStrong = 'P'            // property GC'able
7002 /// kPropertyNonAtomic = 'N'         // property non-atomic
7003 /// };
7004 /// @endcode
7005 std::string
7006 ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
7007                                            const Decl *Container) const {
7008   // Collect information from the property implementation decl(s).
7009   bool Dynamic = false;
7010   ObjCPropertyImplDecl *SynthesizePID = nullptr;
7011 
7012   if (ObjCPropertyImplDecl *PropertyImpDecl =
7013       getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
7014     if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
7015       Dynamic = true;
7016     else
7017       SynthesizePID = PropertyImpDecl;
7018   }
7019 
7020   // FIXME: This is not very efficient.
7021   std::string S = "T";
7022 
7023   // Encode result type.
7024   // GCC has some special rules regarding encoding of properties which
7025   // closely resembles encoding of ivars.
7026   getObjCEncodingForPropertyType(PD->getType(), S);
7027 
7028   if (PD->isReadOnly()) {
7029     S += ",R";
7030     if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_copy)
7031       S += ",C";
7032     if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_retain)
7033       S += ",&";
7034     if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_weak)
7035       S += ",W";
7036   } else {
7037     switch (PD->getSetterKind()) {
7038     case ObjCPropertyDecl::Assign: break;
7039     case ObjCPropertyDecl::Copy:   S += ",C"; break;
7040     case ObjCPropertyDecl::Retain: S += ",&"; break;
7041     case ObjCPropertyDecl::Weak:   S += ",W"; break;
7042     }
7043   }
7044 
7045   // It really isn't clear at all what this means, since properties
7046   // are "dynamic by default".
7047   if (Dynamic)
7048     S += ",D";
7049 
7050   if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_nonatomic)
7051     S += ",N";
7052 
7053   if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_getter) {
7054     S += ",G";
7055     S += PD->getGetterName().getAsString();
7056   }
7057 
7058   if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_setter) {
7059     S += ",S";
7060     S += PD->getSetterName().getAsString();
7061   }
7062 
7063   if (SynthesizePID) {
7064     const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
7065     S += ",V";
7066     S += OID->getNameAsString();
7067   }
7068 
7069   // FIXME: OBJCGC: weak & strong
7070   return S;
7071 }
7072 
7073 /// getLegacyIntegralTypeEncoding -
7074 /// Another legacy compatibility encoding: 32-bit longs are encoded as
7075 /// 'l' or 'L' , but not always.  For typedefs, we need to use
7076 /// 'i' or 'I' instead if encoding a struct field, or a pointer!
7077 void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
7078   if (isa<TypedefType>(PointeeTy.getTypePtr())) {
7079     if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
7080       if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
7081         PointeeTy = UnsignedIntTy;
7082       else
7083         if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
7084           PointeeTy = IntTy;
7085     }
7086   }
7087 }
7088 
7089 void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
7090                                         const FieldDecl *Field,
7091                                         QualType *NotEncodedT) const {
7092   // We follow the behavior of gcc, expanding structures which are
7093   // directly pointed to, and expanding embedded structures. Note that
7094   // these rules are sufficient to prevent recursive encoding of the
7095   // same type.
7096   getObjCEncodingForTypeImpl(T, S,
7097                              ObjCEncOptions()
7098                                  .setExpandPointedToStructures()
7099                                  .setExpandStructures()
7100                                  .setIsOutermostType(),
7101                              Field, NotEncodedT);
7102 }
7103 
7104 void ASTContext::getObjCEncodingForPropertyType(QualType T,
7105                                                 std::string& S) const {
7106   // Encode result type.
7107   // GCC has some special rules regarding encoding of properties which
7108   // closely resembles encoding of ivars.
7109   getObjCEncodingForTypeImpl(T, S,
7110                              ObjCEncOptions()
7111                                  .setExpandPointedToStructures()
7112                                  .setExpandStructures()
7113                                  .setIsOutermostType()
7114                                  .setEncodingProperty(),
7115                              /*Field=*/nullptr);
7116 }
7117 
7118 static char getObjCEncodingForPrimitiveType(const ASTContext *C,
7119                                             const BuiltinType *BT) {
7120     BuiltinType::Kind kind = BT->getKind();
7121     switch (kind) {
7122     case BuiltinType::Void:       return 'v';
7123     case BuiltinType::Bool:       return 'B';
7124     case BuiltinType::Char8:
7125     case BuiltinType::Char_U:
7126     case BuiltinType::UChar:      return 'C';
7127     case BuiltinType::Char16:
7128     case BuiltinType::UShort:     return 'S';
7129     case BuiltinType::Char32:
7130     case BuiltinType::UInt:       return 'I';
7131     case BuiltinType::ULong:
7132         return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
7133     case BuiltinType::UInt128:    return 'T';
7134     case BuiltinType::ULongLong:  return 'Q';
7135     case BuiltinType::Char_S:
7136     case BuiltinType::SChar:      return 'c';
7137     case BuiltinType::Short:      return 's';
7138     case BuiltinType::WChar_S:
7139     case BuiltinType::WChar_U:
7140     case BuiltinType::Int:        return 'i';
7141     case BuiltinType::Long:
7142       return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
7143     case BuiltinType::LongLong:   return 'q';
7144     case BuiltinType::Int128:     return 't';
7145     case BuiltinType::Float:      return 'f';
7146     case BuiltinType::Double:     return 'd';
7147     case BuiltinType::LongDouble: return 'D';
7148     case BuiltinType::NullPtr:    return '*'; // like char*
7149 
7150     case BuiltinType::BFloat16:
7151     case BuiltinType::Float16:
7152     case BuiltinType::Float128:
7153     case BuiltinType::Half:
7154     case BuiltinType::ShortAccum:
7155     case BuiltinType::Accum:
7156     case BuiltinType::LongAccum:
7157     case BuiltinType::UShortAccum:
7158     case BuiltinType::UAccum:
7159     case BuiltinType::ULongAccum:
7160     case BuiltinType::ShortFract:
7161     case BuiltinType::Fract:
7162     case BuiltinType::LongFract:
7163     case BuiltinType::UShortFract:
7164     case BuiltinType::UFract:
7165     case BuiltinType::ULongFract:
7166     case BuiltinType::SatShortAccum:
7167     case BuiltinType::SatAccum:
7168     case BuiltinType::SatLongAccum:
7169     case BuiltinType::SatUShortAccum:
7170     case BuiltinType::SatUAccum:
7171     case BuiltinType::SatULongAccum:
7172     case BuiltinType::SatShortFract:
7173     case BuiltinType::SatFract:
7174     case BuiltinType::SatLongFract:
7175     case BuiltinType::SatUShortFract:
7176     case BuiltinType::SatUFract:
7177     case BuiltinType::SatULongFract:
7178       // FIXME: potentially need @encodes for these!
7179       return ' ';
7180 
7181 #define SVE_TYPE(Name, Id, SingletonId) \
7182     case BuiltinType::Id:
7183 #include "clang/Basic/AArch64SVEACLETypes.def"
7184     {
7185       DiagnosticsEngine &Diags = C->getDiagnostics();
7186       unsigned DiagID = Diags.getCustomDiagID(
7187           DiagnosticsEngine::Error, "cannot yet @encode type %0");
7188       Diags.Report(DiagID) << BT->getName(C->getPrintingPolicy());
7189       return ' ';
7190     }
7191 
7192     case BuiltinType::ObjCId:
7193     case BuiltinType::ObjCClass:
7194     case BuiltinType::ObjCSel:
7195       llvm_unreachable("@encoding ObjC primitive type");
7196 
7197     // OpenCL and placeholder types don't need @encodings.
7198 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7199     case BuiltinType::Id:
7200 #include "clang/Basic/OpenCLImageTypes.def"
7201 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
7202     case BuiltinType::Id:
7203 #include "clang/Basic/OpenCLExtensionTypes.def"
7204     case BuiltinType::OCLEvent:
7205     case BuiltinType::OCLClkEvent:
7206     case BuiltinType::OCLQueue:
7207     case BuiltinType::OCLReserveID:
7208     case BuiltinType::OCLSampler:
7209     case BuiltinType::Dependent:
7210 #define BUILTIN_TYPE(KIND, ID)
7211 #define PLACEHOLDER_TYPE(KIND, ID) \
7212     case BuiltinType::KIND:
7213 #include "clang/AST/BuiltinTypes.def"
7214       llvm_unreachable("invalid builtin type for @encode");
7215     }
7216     llvm_unreachable("invalid BuiltinType::Kind value");
7217 }
7218 
7219 static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
7220   EnumDecl *Enum = ET->getDecl();
7221 
7222   // The encoding of an non-fixed enum type is always 'i', regardless of size.
7223   if (!Enum->isFixed())
7224     return 'i';
7225 
7226   // The encoding of a fixed enum type matches its fixed underlying type.
7227   const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
7228   return getObjCEncodingForPrimitiveType(C, BT);
7229 }
7230 
7231 static void EncodeBitField(const ASTContext *Ctx, std::string& S,
7232                            QualType T, const FieldDecl *FD) {
7233   assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
7234   S += 'b';
7235   // The NeXT runtime encodes bit fields as b followed by the number of bits.
7236   // The GNU runtime requires more information; bitfields are encoded as b,
7237   // then the offset (in bits) of the first element, then the type of the
7238   // bitfield, then the size in bits.  For example, in this structure:
7239   //
7240   // struct
7241   // {
7242   //    int integer;
7243   //    int flags:2;
7244   // };
7245   // On a 32-bit system, the encoding for flags would be b2 for the NeXT
7246   // runtime, but b32i2 for the GNU runtime.  The reason for this extra
7247   // information is not especially sensible, but we're stuck with it for
7248   // compatibility with GCC, although providing it breaks anything that
7249   // actually uses runtime introspection and wants to work on both runtimes...
7250   if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
7251     uint64_t Offset;
7252 
7253     if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
7254       Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), nullptr,
7255                                          IVD);
7256     } else {
7257       const RecordDecl *RD = FD->getParent();
7258       const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
7259       Offset = RL.getFieldOffset(FD->getFieldIndex());
7260     }
7261 
7262     S += llvm::utostr(Offset);
7263 
7264     if (const auto *ET = T->getAs<EnumType>())
7265       S += ObjCEncodingForEnumType(Ctx, ET);
7266     else {
7267       const auto *BT = T->castAs<BuiltinType>();
7268       S += getObjCEncodingForPrimitiveType(Ctx, BT);
7269     }
7270   }
7271   S += llvm::utostr(FD->getBitWidthValue(*Ctx));
7272 }
7273 
7274 // FIXME: Use SmallString for accumulating string.
7275 void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
7276                                             const ObjCEncOptions Options,
7277                                             const FieldDecl *FD,
7278                                             QualType *NotEncodedT) const {
7279   CanQualType CT = getCanonicalType(T);
7280   switch (CT->getTypeClass()) {
7281   case Type::Builtin:
7282   case Type::Enum:
7283     if (FD && FD->isBitField())
7284       return EncodeBitField(this, S, T, FD);
7285     if (const auto *BT = dyn_cast<BuiltinType>(CT))
7286       S += getObjCEncodingForPrimitiveType(this, BT);
7287     else
7288       S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
7289     return;
7290 
7291   case Type::Complex:
7292     S += 'j';
7293     getObjCEncodingForTypeImpl(T->castAs<ComplexType>()->getElementType(), S,
7294                                ObjCEncOptions(),
7295                                /*Field=*/nullptr);
7296     return;
7297 
7298   case Type::Atomic:
7299     S += 'A';
7300     getObjCEncodingForTypeImpl(T->castAs<AtomicType>()->getValueType(), S,
7301                                ObjCEncOptions(),
7302                                /*Field=*/nullptr);
7303     return;
7304 
7305   // encoding for pointer or reference types.
7306   case Type::Pointer:
7307   case Type::LValueReference:
7308   case Type::RValueReference: {
7309     QualType PointeeTy;
7310     if (isa<PointerType>(CT)) {
7311       const auto *PT = T->castAs<PointerType>();
7312       if (PT->isObjCSelType()) {
7313         S += ':';
7314         return;
7315       }
7316       PointeeTy = PT->getPointeeType();
7317     } else {
7318       PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
7319     }
7320 
7321     bool isReadOnly = false;
7322     // For historical/compatibility reasons, the read-only qualifier of the
7323     // pointee gets emitted _before_ the '^'.  The read-only qualifier of
7324     // the pointer itself gets ignored, _unless_ we are looking at a typedef!
7325     // Also, do not emit the 'r' for anything but the outermost type!
7326     if (isa<TypedefType>(T.getTypePtr())) {
7327       if (Options.IsOutermostType() && T.isConstQualified()) {
7328         isReadOnly = true;
7329         S += 'r';
7330       }
7331     } else if (Options.IsOutermostType()) {
7332       QualType P = PointeeTy;
7333       while (auto PT = P->getAs<PointerType>())
7334         P = PT->getPointeeType();
7335       if (P.isConstQualified()) {
7336         isReadOnly = true;
7337         S += 'r';
7338       }
7339     }
7340     if (isReadOnly) {
7341       // Another legacy compatibility encoding. Some ObjC qualifier and type
7342       // combinations need to be rearranged.
7343       // Rewrite "in const" from "nr" to "rn"
7344       if (StringRef(S).endswith("nr"))
7345         S.replace(S.end()-2, S.end(), "rn");
7346     }
7347 
7348     if (PointeeTy->isCharType()) {
7349       // char pointer types should be encoded as '*' unless it is a
7350       // type that has been typedef'd to 'BOOL'.
7351       if (!isTypeTypedefedAsBOOL(PointeeTy)) {
7352         S += '*';
7353         return;
7354       }
7355     } else if (const auto *RTy = PointeeTy->getAs<RecordType>()) {
7356       // GCC binary compat: Need to convert "struct objc_class *" to "#".
7357       if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
7358         S += '#';
7359         return;
7360       }
7361       // GCC binary compat: Need to convert "struct objc_object *" to "@".
7362       if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
7363         S += '@';
7364         return;
7365       }
7366       // fall through...
7367     }
7368     S += '^';
7369     getLegacyIntegralTypeEncoding(PointeeTy);
7370 
7371     ObjCEncOptions NewOptions;
7372     if (Options.ExpandPointedToStructures())
7373       NewOptions.setExpandStructures();
7374     getObjCEncodingForTypeImpl(PointeeTy, S, NewOptions,
7375                                /*Field=*/nullptr, NotEncodedT);
7376     return;
7377   }
7378 
7379   case Type::ConstantArray:
7380   case Type::IncompleteArray:
7381   case Type::VariableArray: {
7382     const auto *AT = cast<ArrayType>(CT);
7383 
7384     if (isa<IncompleteArrayType>(AT) && !Options.IsStructField()) {
7385       // Incomplete arrays are encoded as a pointer to the array element.
7386       S += '^';
7387 
7388       getObjCEncodingForTypeImpl(
7389           AT->getElementType(), S,
7390           Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD);
7391     } else {
7392       S += '[';
7393 
7394       if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
7395         S += llvm::utostr(CAT->getSize().getZExtValue());
7396       else {
7397         //Variable length arrays are encoded as a regular array with 0 elements.
7398         assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
7399                "Unknown array type!");
7400         S += '0';
7401       }
7402 
7403       getObjCEncodingForTypeImpl(
7404           AT->getElementType(), S,
7405           Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD,
7406           NotEncodedT);
7407       S += ']';
7408     }
7409     return;
7410   }
7411 
7412   case Type::FunctionNoProto:
7413   case Type::FunctionProto:
7414     S += '?';
7415     return;
7416 
7417   case Type::Record: {
7418     RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
7419     S += RDecl->isUnion() ? '(' : '{';
7420     // Anonymous structures print as '?'
7421     if (const IdentifierInfo *II = RDecl->getIdentifier()) {
7422       S += II->getName();
7423       if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
7424         const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
7425         llvm::raw_string_ostream OS(S);
7426         printTemplateArgumentList(OS, TemplateArgs.asArray(),
7427                                   getPrintingPolicy());
7428       }
7429     } else {
7430       S += '?';
7431     }
7432     if (Options.ExpandStructures()) {
7433       S += '=';
7434       if (!RDecl->isUnion()) {
7435         getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
7436       } else {
7437         for (const auto *Field : RDecl->fields()) {
7438           if (FD) {
7439             S += '"';
7440             S += Field->getNameAsString();
7441             S += '"';
7442           }
7443 
7444           // Special case bit-fields.
7445           if (Field->isBitField()) {
7446             getObjCEncodingForTypeImpl(Field->getType(), S,
7447                                        ObjCEncOptions().setExpandStructures(),
7448                                        Field);
7449           } else {
7450             QualType qt = Field->getType();
7451             getLegacyIntegralTypeEncoding(qt);
7452             getObjCEncodingForTypeImpl(
7453                 qt, S,
7454                 ObjCEncOptions().setExpandStructures().setIsStructField(), FD,
7455                 NotEncodedT);
7456           }
7457         }
7458       }
7459     }
7460     S += RDecl->isUnion() ? ')' : '}';
7461     return;
7462   }
7463 
7464   case Type::BlockPointer: {
7465     const auto *BT = T->castAs<BlockPointerType>();
7466     S += "@?"; // Unlike a pointer-to-function, which is "^?".
7467     if (Options.EncodeBlockParameters()) {
7468       const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
7469 
7470       S += '<';
7471       // Block return type
7472       getObjCEncodingForTypeImpl(FT->getReturnType(), S,
7473                                  Options.forComponentType(), FD, NotEncodedT);
7474       // Block self
7475       S += "@?";
7476       // Block parameters
7477       if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) {
7478         for (const auto &I : FPT->param_types())
7479           getObjCEncodingForTypeImpl(I, S, Options.forComponentType(), FD,
7480                                      NotEncodedT);
7481       }
7482       S += '>';
7483     }
7484     return;
7485   }
7486 
7487   case Type::ObjCObject: {
7488     // hack to match legacy encoding of *id and *Class
7489     QualType Ty = getObjCObjectPointerType(CT);
7490     if (Ty->isObjCIdType()) {
7491       S += "{objc_object=}";
7492       return;
7493     }
7494     else if (Ty->isObjCClassType()) {
7495       S += "{objc_class=}";
7496       return;
7497     }
7498     // TODO: Double check to make sure this intentionally falls through.
7499     LLVM_FALLTHROUGH;
7500   }
7501 
7502   case Type::ObjCInterface: {
7503     // Ignore protocol qualifiers when mangling at this level.
7504     // @encode(class_name)
7505     ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
7506     S += '{';
7507     S += OI->getObjCRuntimeNameAsString();
7508     if (Options.ExpandStructures()) {
7509       S += '=';
7510       SmallVector<const ObjCIvarDecl*, 32> Ivars;
7511       DeepCollectObjCIvars(OI, true, Ivars);
7512       for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
7513         const FieldDecl *Field = Ivars[i];
7514         if (Field->isBitField())
7515           getObjCEncodingForTypeImpl(Field->getType(), S,
7516                                      ObjCEncOptions().setExpandStructures(),
7517                                      Field);
7518         else
7519           getObjCEncodingForTypeImpl(Field->getType(), S,
7520                                      ObjCEncOptions().setExpandStructures(), FD,
7521                                      NotEncodedT);
7522       }
7523     }
7524     S += '}';
7525     return;
7526   }
7527 
7528   case Type::ObjCObjectPointer: {
7529     const auto *OPT = T->castAs<ObjCObjectPointerType>();
7530     if (OPT->isObjCIdType()) {
7531       S += '@';
7532       return;
7533     }
7534 
7535     if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
7536       // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
7537       // Since this is a binary compatibility issue, need to consult with
7538       // runtime folks. Fortunately, this is a *very* obscure construct.
7539       S += '#';
7540       return;
7541     }
7542 
7543     if (OPT->isObjCQualifiedIdType()) {
7544       getObjCEncodingForTypeImpl(
7545           getObjCIdType(), S,
7546           Options.keepingOnly(ObjCEncOptions()
7547                                   .setExpandPointedToStructures()
7548                                   .setExpandStructures()),
7549           FD);
7550       if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) {
7551         // Note that we do extended encoding of protocol qualifer list
7552         // Only when doing ivar or property encoding.
7553         S += '"';
7554         for (const auto *I : OPT->quals()) {
7555           S += '<';
7556           S += I->getObjCRuntimeNameAsString();
7557           S += '>';
7558         }
7559         S += '"';
7560       }
7561       return;
7562     }
7563 
7564     S += '@';
7565     if (OPT->getInterfaceDecl() &&
7566         (FD || Options.EncodingProperty() || Options.EncodeClassNames())) {
7567       S += '"';
7568       S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
7569       for (const auto *I : OPT->quals()) {
7570         S += '<';
7571         S += I->getObjCRuntimeNameAsString();
7572         S += '>';
7573       }
7574       S += '"';
7575     }
7576     return;
7577   }
7578 
7579   // gcc just blithely ignores member pointers.
7580   // FIXME: we should do better than that.  'M' is available.
7581   case Type::MemberPointer:
7582   // This matches gcc's encoding, even though technically it is insufficient.
7583   //FIXME. We should do a better job than gcc.
7584   case Type::Vector:
7585   case Type::ExtVector:
7586   // Until we have a coherent encoding of these three types, issue warning.
7587     if (NotEncodedT)
7588       *NotEncodedT = T;
7589     return;
7590 
7591   case Type::ConstantMatrix:
7592     if (NotEncodedT)
7593       *NotEncodedT = T;
7594     return;
7595 
7596   // We could see an undeduced auto type here during error recovery.
7597   // Just ignore it.
7598   case Type::Auto:
7599   case Type::DeducedTemplateSpecialization:
7600     return;
7601 
7602   case Type::Pipe:
7603   case Type::ExtInt:
7604 #define ABSTRACT_TYPE(KIND, BASE)
7605 #define TYPE(KIND, BASE)
7606 #define DEPENDENT_TYPE(KIND, BASE) \
7607   case Type::KIND:
7608 #define NON_CANONICAL_TYPE(KIND, BASE) \
7609   case Type::KIND:
7610 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
7611   case Type::KIND:
7612 #include "clang/AST/TypeNodes.inc"
7613     llvm_unreachable("@encode for dependent type!");
7614   }
7615   llvm_unreachable("bad type kind!");
7616 }
7617 
7618 void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
7619                                                  std::string &S,
7620                                                  const FieldDecl *FD,
7621                                                  bool includeVBases,
7622                                                  QualType *NotEncodedT) const {
7623   assert(RDecl && "Expected non-null RecordDecl");
7624   assert(!RDecl->isUnion() && "Should not be called for unions");
7625   if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
7626     return;
7627 
7628   const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
7629   std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
7630   const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
7631 
7632   if (CXXRec) {
7633     for (const auto &BI : CXXRec->bases()) {
7634       if (!BI.isVirtual()) {
7635         CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
7636         if (base->isEmpty())
7637           continue;
7638         uint64_t offs = toBits(layout.getBaseClassOffset(base));
7639         FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
7640                                   std::make_pair(offs, base));
7641       }
7642     }
7643   }
7644 
7645   unsigned i = 0;
7646   for (auto *Field : RDecl->fields()) {
7647     uint64_t offs = layout.getFieldOffset(i);
7648     FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
7649                               std::make_pair(offs, Field));
7650     ++i;
7651   }
7652 
7653   if (CXXRec && includeVBases) {
7654     for (const auto &BI : CXXRec->vbases()) {
7655       CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
7656       if (base->isEmpty())
7657         continue;
7658       uint64_t offs = toBits(layout.getVBaseClassOffset(base));
7659       if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
7660           FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
7661         FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
7662                                   std::make_pair(offs, base));
7663     }
7664   }
7665 
7666   CharUnits size;
7667   if (CXXRec) {
7668     size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
7669   } else {
7670     size = layout.getSize();
7671   }
7672 
7673 #ifndef NDEBUG
7674   uint64_t CurOffs = 0;
7675 #endif
7676   std::multimap<uint64_t, NamedDecl *>::iterator
7677     CurLayObj = FieldOrBaseOffsets.begin();
7678 
7679   if (CXXRec && CXXRec->isDynamicClass() &&
7680       (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
7681     if (FD) {
7682       S += "\"_vptr$";
7683       std::string recname = CXXRec->getNameAsString();
7684       if (recname.empty()) recname = "?";
7685       S += recname;
7686       S += '"';
7687     }
7688     S += "^^?";
7689 #ifndef NDEBUG
7690     CurOffs += getTypeSize(VoidPtrTy);
7691 #endif
7692   }
7693 
7694   if (!RDecl->hasFlexibleArrayMember()) {
7695     // Mark the end of the structure.
7696     uint64_t offs = toBits(size);
7697     FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
7698                               std::make_pair(offs, nullptr));
7699   }
7700 
7701   for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
7702 #ifndef NDEBUG
7703     assert(CurOffs <= CurLayObj->first);
7704     if (CurOffs < CurLayObj->first) {
7705       uint64_t padding = CurLayObj->first - CurOffs;
7706       // FIXME: There doesn't seem to be a way to indicate in the encoding that
7707       // packing/alignment of members is different that normal, in which case
7708       // the encoding will be out-of-sync with the real layout.
7709       // If the runtime switches to just consider the size of types without
7710       // taking into account alignment, we could make padding explicit in the
7711       // encoding (e.g. using arrays of chars). The encoding strings would be
7712       // longer then though.
7713       CurOffs += padding;
7714     }
7715 #endif
7716 
7717     NamedDecl *dcl = CurLayObj->second;
7718     if (!dcl)
7719       break; // reached end of structure.
7720 
7721     if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) {
7722       // We expand the bases without their virtual bases since those are going
7723       // in the initial structure. Note that this differs from gcc which
7724       // expands virtual bases each time one is encountered in the hierarchy,
7725       // making the encoding type bigger than it really is.
7726       getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
7727                                       NotEncodedT);
7728       assert(!base->isEmpty());
7729 #ifndef NDEBUG
7730       CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
7731 #endif
7732     } else {
7733       const auto *field = cast<FieldDecl>(dcl);
7734       if (FD) {
7735         S += '"';
7736         S += field->getNameAsString();
7737         S += '"';
7738       }
7739 
7740       if (field->isBitField()) {
7741         EncodeBitField(this, S, field->getType(), field);
7742 #ifndef NDEBUG
7743         CurOffs += field->getBitWidthValue(*this);
7744 #endif
7745       } else {
7746         QualType qt = field->getType();
7747         getLegacyIntegralTypeEncoding(qt);
7748         getObjCEncodingForTypeImpl(
7749             qt, S, ObjCEncOptions().setExpandStructures().setIsStructField(),
7750             FD, NotEncodedT);
7751 #ifndef NDEBUG
7752         CurOffs += getTypeSize(field->getType());
7753 #endif
7754       }
7755     }
7756   }
7757 }
7758 
7759 void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
7760                                                  std::string& S) const {
7761   if (QT & Decl::OBJC_TQ_In)
7762     S += 'n';
7763   if (QT & Decl::OBJC_TQ_Inout)
7764     S += 'N';
7765   if (QT & Decl::OBJC_TQ_Out)
7766     S += 'o';
7767   if (QT & Decl::OBJC_TQ_Bycopy)
7768     S += 'O';
7769   if (QT & Decl::OBJC_TQ_Byref)
7770     S += 'R';
7771   if (QT & Decl::OBJC_TQ_Oneway)
7772     S += 'V';
7773 }
7774 
7775 TypedefDecl *ASTContext::getObjCIdDecl() const {
7776   if (!ObjCIdDecl) {
7777     QualType T = getObjCObjectType(ObjCBuiltinIdTy, {}, {});
7778     T = getObjCObjectPointerType(T);
7779     ObjCIdDecl = buildImplicitTypedef(T, "id");
7780   }
7781   return ObjCIdDecl;
7782 }
7783 
7784 TypedefDecl *ASTContext::getObjCSelDecl() const {
7785   if (!ObjCSelDecl) {
7786     QualType T = getPointerType(ObjCBuiltinSelTy);
7787     ObjCSelDecl = buildImplicitTypedef(T, "SEL");
7788   }
7789   return ObjCSelDecl;
7790 }
7791 
7792 TypedefDecl *ASTContext::getObjCClassDecl() const {
7793   if (!ObjCClassDecl) {
7794     QualType T = getObjCObjectType(ObjCBuiltinClassTy, {}, {});
7795     T = getObjCObjectPointerType(T);
7796     ObjCClassDecl = buildImplicitTypedef(T, "Class");
7797   }
7798   return ObjCClassDecl;
7799 }
7800 
7801 ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
7802   if (!ObjCProtocolClassDecl) {
7803     ObjCProtocolClassDecl
7804       = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
7805                                   SourceLocation(),
7806                                   &Idents.get("Protocol"),
7807                                   /*typeParamList=*/nullptr,
7808                                   /*PrevDecl=*/nullptr,
7809                                   SourceLocation(), true);
7810   }
7811 
7812   return ObjCProtocolClassDecl;
7813 }
7814 
7815 //===----------------------------------------------------------------------===//
7816 // __builtin_va_list Construction Functions
7817 //===----------------------------------------------------------------------===//
7818 
7819 static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
7820                                                  StringRef Name) {
7821   // typedef char* __builtin[_ms]_va_list;
7822   QualType T = Context->getPointerType(Context->CharTy);
7823   return Context->buildImplicitTypedef(T, Name);
7824 }
7825 
7826 static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
7827   return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
7828 }
7829 
7830 static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
7831   return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
7832 }
7833 
7834 static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
7835   // typedef void* __builtin_va_list;
7836   QualType T = Context->getPointerType(Context->VoidTy);
7837   return Context->buildImplicitTypedef(T, "__builtin_va_list");
7838 }
7839 
7840 static TypedefDecl *
7841 CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
7842   // struct __va_list
7843   RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
7844   if (Context->getLangOpts().CPlusPlus) {
7845     // namespace std { struct __va_list {
7846     NamespaceDecl *NS;
7847     NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
7848                                Context->getTranslationUnitDecl(),
7849                                /*Inline*/ false, SourceLocation(),
7850                                SourceLocation(), &Context->Idents.get("std"),
7851                                /*PrevDecl*/ nullptr);
7852     NS->setImplicit();
7853     VaListTagDecl->setDeclContext(NS);
7854   }
7855 
7856   VaListTagDecl->startDefinition();
7857 
7858   const size_t NumFields = 5;
7859   QualType FieldTypes[NumFields];
7860   const char *FieldNames[NumFields];
7861 
7862   // void *__stack;
7863   FieldTypes[0] = Context->getPointerType(Context->VoidTy);
7864   FieldNames[0] = "__stack";
7865 
7866   // void *__gr_top;
7867   FieldTypes[1] = Context->getPointerType(Context->VoidTy);
7868   FieldNames[1] = "__gr_top";
7869 
7870   // void *__vr_top;
7871   FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7872   FieldNames[2] = "__vr_top";
7873 
7874   // int __gr_offs;
7875   FieldTypes[3] = Context->IntTy;
7876   FieldNames[3] = "__gr_offs";
7877 
7878   // int __vr_offs;
7879   FieldTypes[4] = Context->IntTy;
7880   FieldNames[4] = "__vr_offs";
7881 
7882   // Create fields
7883   for (unsigned i = 0; i < NumFields; ++i) {
7884     FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7885                                          VaListTagDecl,
7886                                          SourceLocation(),
7887                                          SourceLocation(),
7888                                          &Context->Idents.get(FieldNames[i]),
7889                                          FieldTypes[i], /*TInfo=*/nullptr,
7890                                          /*BitWidth=*/nullptr,
7891                                          /*Mutable=*/false,
7892                                          ICIS_NoInit);
7893     Field->setAccess(AS_public);
7894     VaListTagDecl->addDecl(Field);
7895   }
7896   VaListTagDecl->completeDefinition();
7897   Context->VaListTagDecl = VaListTagDecl;
7898   QualType VaListTagType = Context->getRecordType(VaListTagDecl);
7899 
7900   // } __builtin_va_list;
7901   return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
7902 }
7903 
7904 static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
7905   // typedef struct __va_list_tag {
7906   RecordDecl *VaListTagDecl;
7907 
7908   VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
7909   VaListTagDecl->startDefinition();
7910 
7911   const size_t NumFields = 5;
7912   QualType FieldTypes[NumFields];
7913   const char *FieldNames[NumFields];
7914 
7915   //   unsigned char gpr;
7916   FieldTypes[0] = Context->UnsignedCharTy;
7917   FieldNames[0] = "gpr";
7918 
7919   //   unsigned char fpr;
7920   FieldTypes[1] = Context->UnsignedCharTy;
7921   FieldNames[1] = "fpr";
7922 
7923   //   unsigned short reserved;
7924   FieldTypes[2] = Context->UnsignedShortTy;
7925   FieldNames[2] = "reserved";
7926 
7927   //   void* overflow_arg_area;
7928   FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7929   FieldNames[3] = "overflow_arg_area";
7930 
7931   //   void* reg_save_area;
7932   FieldTypes[4] = Context->getPointerType(Context->VoidTy);
7933   FieldNames[4] = "reg_save_area";
7934 
7935   // Create fields
7936   for (unsigned i = 0; i < NumFields; ++i) {
7937     FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
7938                                          SourceLocation(),
7939                                          SourceLocation(),
7940                                          &Context->Idents.get(FieldNames[i]),
7941                                          FieldTypes[i], /*TInfo=*/nullptr,
7942                                          /*BitWidth=*/nullptr,
7943                                          /*Mutable=*/false,
7944                                          ICIS_NoInit);
7945     Field->setAccess(AS_public);
7946     VaListTagDecl->addDecl(Field);
7947   }
7948   VaListTagDecl->completeDefinition();
7949   Context->VaListTagDecl = VaListTagDecl;
7950   QualType VaListTagType = Context->getRecordType(VaListTagDecl);
7951 
7952   // } __va_list_tag;
7953   TypedefDecl *VaListTagTypedefDecl =
7954       Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
7955 
7956   QualType VaListTagTypedefType =
7957     Context->getTypedefType(VaListTagTypedefDecl);
7958 
7959   // typedef __va_list_tag __builtin_va_list[1];
7960   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
7961   QualType VaListTagArrayType
7962     = Context->getConstantArrayType(VaListTagTypedefType,
7963                                     Size, nullptr, ArrayType::Normal, 0);
7964   return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
7965 }
7966 
7967 static TypedefDecl *
7968 CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
7969   // struct __va_list_tag {
7970   RecordDecl *VaListTagDecl;
7971   VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
7972   VaListTagDecl->startDefinition();
7973 
7974   const size_t NumFields = 4;
7975   QualType FieldTypes[NumFields];
7976   const char *FieldNames[NumFields];
7977 
7978   //   unsigned gp_offset;
7979   FieldTypes[0] = Context->UnsignedIntTy;
7980   FieldNames[0] = "gp_offset";
7981 
7982   //   unsigned fp_offset;
7983   FieldTypes[1] = Context->UnsignedIntTy;
7984   FieldNames[1] = "fp_offset";
7985 
7986   //   void* overflow_arg_area;
7987   FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7988   FieldNames[2] = "overflow_arg_area";
7989 
7990   //   void* reg_save_area;
7991   FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7992   FieldNames[3] = "reg_save_area";
7993 
7994   // Create fields
7995   for (unsigned i = 0; i < NumFields; ++i) {
7996     FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7997                                          VaListTagDecl,
7998                                          SourceLocation(),
7999                                          SourceLocation(),
8000                                          &Context->Idents.get(FieldNames[i]),
8001                                          FieldTypes[i], /*TInfo=*/nullptr,
8002                                          /*BitWidth=*/nullptr,
8003                                          /*Mutable=*/false,
8004                                          ICIS_NoInit);
8005     Field->setAccess(AS_public);
8006     VaListTagDecl->addDecl(Field);
8007   }
8008   VaListTagDecl->completeDefinition();
8009   Context->VaListTagDecl = VaListTagDecl;
8010   QualType VaListTagType = Context->getRecordType(VaListTagDecl);
8011 
8012   // };
8013 
8014   // typedef struct __va_list_tag __builtin_va_list[1];
8015   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
8016   QualType VaListTagArrayType = Context->getConstantArrayType(
8017       VaListTagType, Size, nullptr, ArrayType::Normal, 0);
8018   return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
8019 }
8020 
8021 static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
8022   // typedef int __builtin_va_list[4];
8023   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
8024   QualType IntArrayType = Context->getConstantArrayType(
8025       Context->IntTy, Size, nullptr, ArrayType::Normal, 0);
8026   return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
8027 }
8028 
8029 static TypedefDecl *
8030 CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
8031   // struct __va_list
8032   RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
8033   if (Context->getLangOpts().CPlusPlus) {
8034     // namespace std { struct __va_list {
8035     NamespaceDecl *NS;
8036     NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
8037                                Context->getTranslationUnitDecl(),
8038                                /*Inline*/false, SourceLocation(),
8039                                SourceLocation(), &Context->Idents.get("std"),
8040                                /*PrevDecl*/ nullptr);
8041     NS->setImplicit();
8042     VaListDecl->setDeclContext(NS);
8043   }
8044 
8045   VaListDecl->startDefinition();
8046 
8047   // void * __ap;
8048   FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
8049                                        VaListDecl,
8050                                        SourceLocation(),
8051                                        SourceLocation(),
8052                                        &Context->Idents.get("__ap"),
8053                                        Context->getPointerType(Context->VoidTy),
8054                                        /*TInfo=*/nullptr,
8055                                        /*BitWidth=*/nullptr,
8056                                        /*Mutable=*/false,
8057                                        ICIS_NoInit);
8058   Field->setAccess(AS_public);
8059   VaListDecl->addDecl(Field);
8060 
8061   // };
8062   VaListDecl->completeDefinition();
8063   Context->VaListTagDecl = VaListDecl;
8064 
8065   // typedef struct __va_list __builtin_va_list;
8066   QualType T = Context->getRecordType(VaListDecl);
8067   return Context->buildImplicitTypedef(T, "__builtin_va_list");
8068 }
8069 
8070 static TypedefDecl *
8071 CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
8072   // struct __va_list_tag {
8073   RecordDecl *VaListTagDecl;
8074   VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
8075   VaListTagDecl->startDefinition();
8076 
8077   const size_t NumFields = 4;
8078   QualType FieldTypes[NumFields];
8079   const char *FieldNames[NumFields];
8080 
8081   //   long __gpr;
8082   FieldTypes[0] = Context->LongTy;
8083   FieldNames[0] = "__gpr";
8084 
8085   //   long __fpr;
8086   FieldTypes[1] = Context->LongTy;
8087   FieldNames[1] = "__fpr";
8088 
8089   //   void *__overflow_arg_area;
8090   FieldTypes[2] = Context->getPointerType(Context->VoidTy);
8091   FieldNames[2] = "__overflow_arg_area";
8092 
8093   //   void *__reg_save_area;
8094   FieldTypes[3] = Context->getPointerType(Context->VoidTy);
8095   FieldNames[3] = "__reg_save_area";
8096 
8097   // Create fields
8098   for (unsigned i = 0; i < NumFields; ++i) {
8099     FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
8100                                          VaListTagDecl,
8101                                          SourceLocation(),
8102                                          SourceLocation(),
8103                                          &Context->Idents.get(FieldNames[i]),
8104                                          FieldTypes[i], /*TInfo=*/nullptr,
8105                                          /*BitWidth=*/nullptr,
8106                                          /*Mutable=*/false,
8107                                          ICIS_NoInit);
8108     Field->setAccess(AS_public);
8109     VaListTagDecl->addDecl(Field);
8110   }
8111   VaListTagDecl->completeDefinition();
8112   Context->VaListTagDecl = VaListTagDecl;
8113   QualType VaListTagType = Context->getRecordType(VaListTagDecl);
8114 
8115   // };
8116 
8117   // typedef __va_list_tag __builtin_va_list[1];
8118   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
8119   QualType VaListTagArrayType = Context->getConstantArrayType(
8120       VaListTagType, Size, nullptr, ArrayType::Normal, 0);
8121 
8122   return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
8123 }
8124 
8125 static TypedefDecl *CreateHexagonBuiltinVaListDecl(const ASTContext *Context) {
8126   // typedef struct __va_list_tag {
8127   RecordDecl *VaListTagDecl;
8128   VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
8129   VaListTagDecl->startDefinition();
8130 
8131   const size_t NumFields = 3;
8132   QualType FieldTypes[NumFields];
8133   const char *FieldNames[NumFields];
8134 
8135   //   void *CurrentSavedRegisterArea;
8136   FieldTypes[0] = Context->getPointerType(Context->VoidTy);
8137   FieldNames[0] = "__current_saved_reg_area_pointer";
8138 
8139   //   void *SavedRegAreaEnd;
8140   FieldTypes[1] = Context->getPointerType(Context->VoidTy);
8141   FieldNames[1] = "__saved_reg_area_end_pointer";
8142 
8143   //   void *OverflowArea;
8144   FieldTypes[2] = Context->getPointerType(Context->VoidTy);
8145   FieldNames[2] = "__overflow_area_pointer";
8146 
8147   // Create fields
8148   for (unsigned i = 0; i < NumFields; ++i) {
8149     FieldDecl *Field = FieldDecl::Create(
8150         const_cast<ASTContext &>(*Context), VaListTagDecl, SourceLocation(),
8151         SourceLocation(), &Context->Idents.get(FieldNames[i]), FieldTypes[i],
8152         /*TInfo=*/0,
8153         /*BitWidth=*/0,
8154         /*Mutable=*/false, ICIS_NoInit);
8155     Field->setAccess(AS_public);
8156     VaListTagDecl->addDecl(Field);
8157   }
8158   VaListTagDecl->completeDefinition();
8159   Context->VaListTagDecl = VaListTagDecl;
8160   QualType VaListTagType = Context->getRecordType(VaListTagDecl);
8161 
8162   // } __va_list_tag;
8163   TypedefDecl *VaListTagTypedefDecl =
8164       Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
8165 
8166   QualType VaListTagTypedefType = Context->getTypedefType(VaListTagTypedefDecl);
8167 
8168   // typedef __va_list_tag __builtin_va_list[1];
8169   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
8170   QualType VaListTagArrayType = Context->getConstantArrayType(
8171       VaListTagTypedefType, Size, nullptr, ArrayType::Normal, 0);
8172 
8173   return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
8174 }
8175 
8176 static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
8177                                      TargetInfo::BuiltinVaListKind Kind) {
8178   switch (Kind) {
8179   case TargetInfo::CharPtrBuiltinVaList:
8180     return CreateCharPtrBuiltinVaListDecl(Context);
8181   case TargetInfo::VoidPtrBuiltinVaList:
8182     return CreateVoidPtrBuiltinVaListDecl(Context);
8183   case TargetInfo::AArch64ABIBuiltinVaList:
8184     return CreateAArch64ABIBuiltinVaListDecl(Context);
8185   case TargetInfo::PowerABIBuiltinVaList:
8186     return CreatePowerABIBuiltinVaListDecl(Context);
8187   case TargetInfo::X86_64ABIBuiltinVaList:
8188     return CreateX86_64ABIBuiltinVaListDecl(Context);
8189   case TargetInfo::PNaClABIBuiltinVaList:
8190     return CreatePNaClABIBuiltinVaListDecl(Context);
8191   case TargetInfo::AAPCSABIBuiltinVaList:
8192     return CreateAAPCSABIBuiltinVaListDecl(Context);
8193   case TargetInfo::SystemZBuiltinVaList:
8194     return CreateSystemZBuiltinVaListDecl(Context);
8195   case TargetInfo::HexagonBuiltinVaList:
8196     return CreateHexagonBuiltinVaListDecl(Context);
8197   }
8198 
8199   llvm_unreachable("Unhandled __builtin_va_list type kind");
8200 }
8201 
8202 TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
8203   if (!BuiltinVaListDecl) {
8204     BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
8205     assert(BuiltinVaListDecl->isImplicit());
8206   }
8207 
8208   return BuiltinVaListDecl;
8209 }
8210 
8211 Decl *ASTContext::getVaListTagDecl() const {
8212   // Force the creation of VaListTagDecl by building the __builtin_va_list
8213   // declaration.
8214   if (!VaListTagDecl)
8215     (void)getBuiltinVaListDecl();
8216 
8217   return VaListTagDecl;
8218 }
8219 
8220 TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
8221   if (!BuiltinMSVaListDecl)
8222     BuiltinMSVaListDecl = CreateMSVaListDecl(this);
8223 
8224   return BuiltinMSVaListDecl;
8225 }
8226 
8227 bool ASTContext::canBuiltinBeRedeclared(const FunctionDecl *FD) const {
8228   return BuiltinInfo.canBeRedeclared(FD->getBuiltinID());
8229 }
8230 
8231 void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
8232   assert(ObjCConstantStringType.isNull() &&
8233          "'NSConstantString' type already set!");
8234 
8235   ObjCConstantStringType = getObjCInterfaceType(Decl);
8236 }
8237 
8238 /// Retrieve the template name that corresponds to a non-empty
8239 /// lookup.
8240 TemplateName
8241 ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
8242                                       UnresolvedSetIterator End) const {
8243   unsigned size = End - Begin;
8244   assert(size > 1 && "set is not overloaded!");
8245 
8246   void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
8247                           size * sizeof(FunctionTemplateDecl*));
8248   auto *OT = new (memory) OverloadedTemplateStorage(size);
8249 
8250   NamedDecl **Storage = OT->getStorage();
8251   for (UnresolvedSetIterator I = Begin; I != End; ++I) {
8252     NamedDecl *D = *I;
8253     assert(isa<FunctionTemplateDecl>(D) ||
8254            isa<UnresolvedUsingValueDecl>(D) ||
8255            (isa<UsingShadowDecl>(D) &&
8256             isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
8257     *Storage++ = D;
8258   }
8259 
8260   return TemplateName(OT);
8261 }
8262 
8263 /// Retrieve a template name representing an unqualified-id that has been
8264 /// assumed to name a template for ADL purposes.
8265 TemplateName ASTContext::getAssumedTemplateName(DeclarationName Name) const {
8266   auto *OT = new (*this) AssumedTemplateStorage(Name);
8267   return TemplateName(OT);
8268 }
8269 
8270 /// Retrieve the template name that represents a qualified
8271 /// template name such as \c std::vector.
8272 TemplateName
8273 ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
8274                                      bool TemplateKeyword,
8275                                      TemplateDecl *Template) const {
8276   assert(NNS && "Missing nested-name-specifier in qualified template name");
8277 
8278   // FIXME: Canonicalization?
8279   llvm::FoldingSetNodeID ID;
8280   QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
8281 
8282   void *InsertPos = nullptr;
8283   QualifiedTemplateName *QTN =
8284     QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
8285   if (!QTN) {
8286     QTN = new (*this, alignof(QualifiedTemplateName))
8287         QualifiedTemplateName(NNS, TemplateKeyword, Template);
8288     QualifiedTemplateNames.InsertNode(QTN, InsertPos);
8289   }
8290 
8291   return TemplateName(QTN);
8292 }
8293 
8294 /// Retrieve the template name that represents a dependent
8295 /// template name such as \c MetaFun::template apply.
8296 TemplateName
8297 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
8298                                      const IdentifierInfo *Name) const {
8299   assert((!NNS || NNS->isDependent()) &&
8300          "Nested name specifier must be dependent");
8301 
8302   llvm::FoldingSetNodeID ID;
8303   DependentTemplateName::Profile(ID, NNS, Name);
8304 
8305   void *InsertPos = nullptr;
8306   DependentTemplateName *QTN =
8307     DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
8308 
8309   if (QTN)
8310     return TemplateName(QTN);
8311 
8312   NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
8313   if (CanonNNS == NNS) {
8314     QTN = new (*this, alignof(DependentTemplateName))
8315         DependentTemplateName(NNS, Name);
8316   } else {
8317     TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
8318     QTN = new (*this, alignof(DependentTemplateName))
8319         DependentTemplateName(NNS, Name, Canon);
8320     DependentTemplateName *CheckQTN =
8321       DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
8322     assert(!CheckQTN && "Dependent type name canonicalization broken");
8323     (void)CheckQTN;
8324   }
8325 
8326   DependentTemplateNames.InsertNode(QTN, InsertPos);
8327   return TemplateName(QTN);
8328 }
8329 
8330 /// Retrieve the template name that represents a dependent
8331 /// template name such as \c MetaFun::template operator+.
8332 TemplateName
8333 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
8334                                      OverloadedOperatorKind Operator) const {
8335   assert((!NNS || NNS->isDependent()) &&
8336          "Nested name specifier must be dependent");
8337 
8338   llvm::FoldingSetNodeID ID;
8339   DependentTemplateName::Profile(ID, NNS, Operator);
8340 
8341   void *InsertPos = nullptr;
8342   DependentTemplateName *QTN
8343     = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
8344 
8345   if (QTN)
8346     return TemplateName(QTN);
8347 
8348   NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
8349   if (CanonNNS == NNS) {
8350     QTN = new (*this, alignof(DependentTemplateName))
8351         DependentTemplateName(NNS, Operator);
8352   } else {
8353     TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
8354     QTN = new (*this, alignof(DependentTemplateName))
8355         DependentTemplateName(NNS, Operator, Canon);
8356 
8357     DependentTemplateName *CheckQTN
8358       = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
8359     assert(!CheckQTN && "Dependent template name canonicalization broken");
8360     (void)CheckQTN;
8361   }
8362 
8363   DependentTemplateNames.InsertNode(QTN, InsertPos);
8364   return TemplateName(QTN);
8365 }
8366 
8367 TemplateName
8368 ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
8369                                          TemplateName replacement) const {
8370   llvm::FoldingSetNodeID ID;
8371   SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
8372 
8373   void *insertPos = nullptr;
8374   SubstTemplateTemplateParmStorage *subst
8375     = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
8376 
8377   if (!subst) {
8378     subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
8379     SubstTemplateTemplateParms.InsertNode(subst, insertPos);
8380   }
8381 
8382   return TemplateName(subst);
8383 }
8384 
8385 TemplateName
8386 ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
8387                                        const TemplateArgument &ArgPack) const {
8388   auto &Self = const_cast<ASTContext &>(*this);
8389   llvm::FoldingSetNodeID ID;
8390   SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
8391 
8392   void *InsertPos = nullptr;
8393   SubstTemplateTemplateParmPackStorage *Subst
8394     = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
8395 
8396   if (!Subst) {
8397     Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
8398                                                            ArgPack.pack_size(),
8399                                                          ArgPack.pack_begin());
8400     SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
8401   }
8402 
8403   return TemplateName(Subst);
8404 }
8405 
8406 /// getFromTargetType - Given one of the integer types provided by
8407 /// TargetInfo, produce the corresponding type. The unsigned @p Type
8408 /// is actually a value of type @c TargetInfo::IntType.
8409 CanQualType ASTContext::getFromTargetType(unsigned Type) const {
8410   switch (Type) {
8411   case TargetInfo::NoInt: return {};
8412   case TargetInfo::SignedChar: return SignedCharTy;
8413   case TargetInfo::UnsignedChar: return UnsignedCharTy;
8414   case TargetInfo::SignedShort: return ShortTy;
8415   case TargetInfo::UnsignedShort: return UnsignedShortTy;
8416   case TargetInfo::SignedInt: return IntTy;
8417   case TargetInfo::UnsignedInt: return UnsignedIntTy;
8418   case TargetInfo::SignedLong: return LongTy;
8419   case TargetInfo::UnsignedLong: return UnsignedLongTy;
8420   case TargetInfo::SignedLongLong: return LongLongTy;
8421   case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
8422   }
8423 
8424   llvm_unreachable("Unhandled TargetInfo::IntType value");
8425 }
8426 
8427 //===----------------------------------------------------------------------===//
8428 //                        Type Predicates.
8429 //===----------------------------------------------------------------------===//
8430 
8431 /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
8432 /// garbage collection attribute.
8433 ///
8434 Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
8435   if (getLangOpts().getGC() == LangOptions::NonGC)
8436     return Qualifiers::GCNone;
8437 
8438   assert(getLangOpts().ObjC);
8439   Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
8440 
8441   // Default behaviour under objective-C's gc is for ObjC pointers
8442   // (or pointers to them) be treated as though they were declared
8443   // as __strong.
8444   if (GCAttrs == Qualifiers::GCNone) {
8445     if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
8446       return Qualifiers::Strong;
8447     else if (Ty->isPointerType())
8448       return getObjCGCAttrKind(Ty->castAs<PointerType>()->getPointeeType());
8449   } else {
8450     // It's not valid to set GC attributes on anything that isn't a
8451     // pointer.
8452 #ifndef NDEBUG
8453     QualType CT = Ty->getCanonicalTypeInternal();
8454     while (const auto *AT = dyn_cast<ArrayType>(CT))
8455       CT = AT->getElementType();
8456     assert(CT->isAnyPointerType() || CT->isBlockPointerType());
8457 #endif
8458   }
8459   return GCAttrs;
8460 }
8461 
8462 //===----------------------------------------------------------------------===//
8463 //                        Type Compatibility Testing
8464 //===----------------------------------------------------------------------===//
8465 
8466 /// areCompatVectorTypes - Return true if the two specified vector types are
8467 /// compatible.
8468 static bool areCompatVectorTypes(const VectorType *LHS,
8469                                  const VectorType *RHS) {
8470   assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
8471   return LHS->getElementType() == RHS->getElementType() &&
8472          LHS->getNumElements() == RHS->getNumElements();
8473 }
8474 
8475 /// areCompatMatrixTypes - Return true if the two specified matrix types are
8476 /// compatible.
8477 static bool areCompatMatrixTypes(const ConstantMatrixType *LHS,
8478                                  const ConstantMatrixType *RHS) {
8479   assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
8480   return LHS->getElementType() == RHS->getElementType() &&
8481          LHS->getNumRows() == RHS->getNumRows() &&
8482          LHS->getNumColumns() == RHS->getNumColumns();
8483 }
8484 
8485 bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
8486                                           QualType SecondVec) {
8487   assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
8488   assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
8489 
8490   if (hasSameUnqualifiedType(FirstVec, SecondVec))
8491     return true;
8492 
8493   // Treat Neon vector types and most AltiVec vector types as if they are the
8494   // equivalent GCC vector types.
8495   const auto *First = FirstVec->castAs<VectorType>();
8496   const auto *Second = SecondVec->castAs<VectorType>();
8497   if (First->getNumElements() == Second->getNumElements() &&
8498       hasSameType(First->getElementType(), Second->getElementType()) &&
8499       First->getVectorKind() != VectorType::AltiVecPixel &&
8500       First->getVectorKind() != VectorType::AltiVecBool &&
8501       Second->getVectorKind() != VectorType::AltiVecPixel &&
8502       Second->getVectorKind() != VectorType::AltiVecBool)
8503     return true;
8504 
8505   return false;
8506 }
8507 
8508 bool ASTContext::areCompatibleSveTypes(QualType FirstType,
8509                                        QualType SecondType) {
8510   assert(((FirstType->isSizelessBuiltinType() && SecondType->isVectorType()) ||
8511           (FirstType->isVectorType() && SecondType->isSizelessBuiltinType())) &&
8512          "Expected SVE builtin type and vector type!");
8513 
8514   auto IsValidCast = [this](QualType FirstType, QualType SecondType) {
8515     if (const auto *BT = FirstType->getAs<BuiltinType>()) {
8516       if (const auto *VT = SecondType->getAs<VectorType>()) {
8517         // Predicates have the same representation as uint8 so we also have to
8518         // check the kind to make these types incompatible.
8519         if (VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector)
8520           return BT->getKind() == BuiltinType::SveBool;
8521         else if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector)
8522           return VT->getElementType().getCanonicalType() ==
8523                  FirstType->getSveEltType(*this);
8524         else if (VT->getVectorKind() == VectorType::GenericVector)
8525           return getTypeSize(SecondType) == getLangOpts().ArmSveVectorBits &&
8526                  hasSameType(VT->getElementType(),
8527                              getBuiltinVectorTypeInfo(BT).ElementType);
8528       }
8529     }
8530     return false;
8531   };
8532 
8533   return IsValidCast(FirstType, SecondType) ||
8534          IsValidCast(SecondType, FirstType);
8535 }
8536 
8537 bool ASTContext::hasDirectOwnershipQualifier(QualType Ty) const {
8538   while (true) {
8539     // __strong id
8540     if (const AttributedType *Attr = dyn_cast<AttributedType>(Ty)) {
8541       if (Attr->getAttrKind() == attr::ObjCOwnership)
8542         return true;
8543 
8544       Ty = Attr->getModifiedType();
8545 
8546     // X *__strong (...)
8547     } else if (const ParenType *Paren = dyn_cast<ParenType>(Ty)) {
8548       Ty = Paren->getInnerType();
8549 
8550     // We do not want to look through typedefs, typeof(expr),
8551     // typeof(type), or any other way that the type is somehow
8552     // abstracted.
8553     } else {
8554       return false;
8555     }
8556   }
8557 }
8558 
8559 //===----------------------------------------------------------------------===//
8560 // ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
8561 //===----------------------------------------------------------------------===//
8562 
8563 /// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
8564 /// inheritance hierarchy of 'rProto'.
8565 bool
8566 ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
8567                                            ObjCProtocolDecl *rProto) const {
8568   if (declaresSameEntity(lProto, rProto))
8569     return true;
8570   for (auto *PI : rProto->protocols())
8571     if (ProtocolCompatibleWithProtocol(lProto, PI))
8572       return true;
8573   return false;
8574 }
8575 
8576 /// ObjCQualifiedClassTypesAreCompatible - compare  Class<pr,...> and
8577 /// Class<pr1, ...>.
8578 bool ASTContext::ObjCQualifiedClassTypesAreCompatible(
8579     const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs) {
8580   for (auto *lhsProto : lhs->quals()) {
8581     bool match = false;
8582     for (auto *rhsProto : rhs->quals()) {
8583       if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
8584         match = true;
8585         break;
8586       }
8587     }
8588     if (!match)
8589       return false;
8590   }
8591   return true;
8592 }
8593 
8594 /// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
8595 /// ObjCQualifiedIDType.
8596 bool ASTContext::ObjCQualifiedIdTypesAreCompatible(
8597     const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs,
8598     bool compare) {
8599   // Allow id<P..> and an 'id' in all cases.
8600   if (lhs->isObjCIdType() || rhs->isObjCIdType())
8601     return true;
8602 
8603   // Don't allow id<P..> to convert to Class or Class<P..> in either direction.
8604   if (lhs->isObjCClassType() || lhs->isObjCQualifiedClassType() ||
8605       rhs->isObjCClassType() || rhs->isObjCQualifiedClassType())
8606     return false;
8607 
8608   if (lhs->isObjCQualifiedIdType()) {
8609     if (rhs->qual_empty()) {
8610       // If the RHS is a unqualified interface pointer "NSString*",
8611       // make sure we check the class hierarchy.
8612       if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
8613         for (auto *I : lhs->quals()) {
8614           // when comparing an id<P> on lhs with a static type on rhs,
8615           // see if static class implements all of id's protocols, directly or
8616           // through its super class and categories.
8617           if (!rhsID->ClassImplementsProtocol(I, true))
8618             return false;
8619         }
8620       }
8621       // If there are no qualifiers and no interface, we have an 'id'.
8622       return true;
8623     }
8624     // Both the right and left sides have qualifiers.
8625     for (auto *lhsProto : lhs->quals()) {
8626       bool match = false;
8627 
8628       // when comparing an id<P> on lhs with a static type on rhs,
8629       // see if static class implements all of id's protocols, directly or
8630       // through its super class and categories.
8631       for (auto *rhsProto : rhs->quals()) {
8632         if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
8633             (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
8634           match = true;
8635           break;
8636         }
8637       }
8638       // If the RHS is a qualified interface pointer "NSString<P>*",
8639       // make sure we check the class hierarchy.
8640       if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
8641         for (auto *I : lhs->quals()) {
8642           // when comparing an id<P> on lhs with a static type on rhs,
8643           // see if static class implements all of id's protocols, directly or
8644           // through its super class and categories.
8645           if (rhsID->ClassImplementsProtocol(I, true)) {
8646             match = true;
8647             break;
8648           }
8649         }
8650       }
8651       if (!match)
8652         return false;
8653     }
8654 
8655     return true;
8656   }
8657 
8658   assert(rhs->isObjCQualifiedIdType() && "One of the LHS/RHS should be id<x>");
8659 
8660   if (lhs->getInterfaceType()) {
8661     // If both the right and left sides have qualifiers.
8662     for (auto *lhsProto : lhs->quals()) {
8663       bool match = false;
8664 
8665       // when comparing an id<P> on rhs with a static type on lhs,
8666       // see if static class implements all of id's protocols, directly or
8667       // through its super class and categories.
8668       // First, lhs protocols in the qualifier list must be found, direct
8669       // or indirect in rhs's qualifier list or it is a mismatch.
8670       for (auto *rhsProto : rhs->quals()) {
8671         if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
8672             (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
8673           match = true;
8674           break;
8675         }
8676       }
8677       if (!match)
8678         return false;
8679     }
8680 
8681     // Static class's protocols, or its super class or category protocols
8682     // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
8683     if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) {
8684       llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
8685       CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
8686       // This is rather dubious but matches gcc's behavior. If lhs has
8687       // no type qualifier and its class has no static protocol(s)
8688       // assume that it is mismatch.
8689       if (LHSInheritedProtocols.empty() && lhs->qual_empty())
8690         return false;
8691       for (auto *lhsProto : LHSInheritedProtocols) {
8692         bool match = false;
8693         for (auto *rhsProto : rhs->quals()) {
8694           if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
8695               (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
8696             match = true;
8697             break;
8698           }
8699         }
8700         if (!match)
8701           return false;
8702       }
8703     }
8704     return true;
8705   }
8706   return false;
8707 }
8708 
8709 /// canAssignObjCInterfaces - Return true if the two interface types are
8710 /// compatible for assignment from RHS to LHS.  This handles validation of any
8711 /// protocol qualifiers on the LHS or RHS.
8712 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
8713                                          const ObjCObjectPointerType *RHSOPT) {
8714   const ObjCObjectType* LHS = LHSOPT->getObjectType();
8715   const ObjCObjectType* RHS = RHSOPT->getObjectType();
8716 
8717   // If either type represents the built-in 'id' type, return true.
8718   if (LHS->isObjCUnqualifiedId() || RHS->isObjCUnqualifiedId())
8719     return true;
8720 
8721   // Function object that propagates a successful result or handles
8722   // __kindof types.
8723   auto finish = [&](bool succeeded) -> bool {
8724     if (succeeded)
8725       return true;
8726 
8727     if (!RHS->isKindOfType())
8728       return false;
8729 
8730     // Strip off __kindof and protocol qualifiers, then check whether
8731     // we can assign the other way.
8732     return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
8733                                    LHSOPT->stripObjCKindOfTypeAndQuals(*this));
8734   };
8735 
8736   // Casts from or to id<P> are allowed when the other side has compatible
8737   // protocols.
8738   if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
8739     return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false));
8740   }
8741 
8742   // Verify protocol compatibility for casts from Class<P1> to Class<P2>.
8743   if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
8744     return finish(ObjCQualifiedClassTypesAreCompatible(LHSOPT, RHSOPT));
8745   }
8746 
8747   // Casts from Class to Class<Foo>, or vice-versa, are allowed.
8748   if (LHS->isObjCClass() && RHS->isObjCClass()) {
8749     return true;
8750   }
8751 
8752   // If we have 2 user-defined types, fall into that path.
8753   if (LHS->getInterface() && RHS->getInterface()) {
8754     return finish(canAssignObjCInterfaces(LHS, RHS));
8755   }
8756 
8757   return false;
8758 }
8759 
8760 /// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
8761 /// for providing type-safety for objective-c pointers used to pass/return
8762 /// arguments in block literals. When passed as arguments, passing 'A*' where
8763 /// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
8764 /// not OK. For the return type, the opposite is not OK.
8765 bool ASTContext::canAssignObjCInterfacesInBlockPointer(
8766                                          const ObjCObjectPointerType *LHSOPT,
8767                                          const ObjCObjectPointerType *RHSOPT,
8768                                          bool BlockReturnType) {
8769 
8770   // Function object that propagates a successful result or handles
8771   // __kindof types.
8772   auto finish = [&](bool succeeded) -> bool {
8773     if (succeeded)
8774       return true;
8775 
8776     const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
8777     if (!Expected->isKindOfType())
8778       return false;
8779 
8780     // Strip off __kindof and protocol qualifiers, then check whether
8781     // we can assign the other way.
8782     return canAssignObjCInterfacesInBlockPointer(
8783              RHSOPT->stripObjCKindOfTypeAndQuals(*this),
8784              LHSOPT->stripObjCKindOfTypeAndQuals(*this),
8785              BlockReturnType);
8786   };
8787 
8788   if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
8789     return true;
8790 
8791   if (LHSOPT->isObjCBuiltinType()) {
8792     return finish(RHSOPT->isObjCBuiltinType() ||
8793                   RHSOPT->isObjCQualifiedIdType());
8794   }
8795 
8796   if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) {
8797     if (getLangOpts().CompatibilityQualifiedIdBlockParamTypeChecking)
8798       // Use for block parameters previous type checking for compatibility.
8799       return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false) ||
8800                     // Or corrected type checking as in non-compat mode.
8801                     (!BlockReturnType &&
8802                      ObjCQualifiedIdTypesAreCompatible(RHSOPT, LHSOPT, false)));
8803     else
8804       return finish(ObjCQualifiedIdTypesAreCompatible(
8805           (BlockReturnType ? LHSOPT : RHSOPT),
8806           (BlockReturnType ? RHSOPT : LHSOPT), false));
8807   }
8808 
8809   const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
8810   const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
8811   if (LHS && RHS)  { // We have 2 user-defined types.
8812     if (LHS != RHS) {
8813       if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
8814         return finish(BlockReturnType);
8815       if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
8816         return finish(!BlockReturnType);
8817     }
8818     else
8819       return true;
8820   }
8821   return false;
8822 }
8823 
8824 /// Comparison routine for Objective-C protocols to be used with
8825 /// llvm::array_pod_sort.
8826 static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
8827                                       ObjCProtocolDecl * const *rhs) {
8828   return (*lhs)->getName().compare((*rhs)->getName());
8829 }
8830 
8831 /// getIntersectionOfProtocols - This routine finds the intersection of set
8832 /// of protocols inherited from two distinct objective-c pointer objects with
8833 /// the given common base.
8834 /// It is used to build composite qualifier list of the composite type of
8835 /// the conditional expression involving two objective-c pointer objects.
8836 static
8837 void getIntersectionOfProtocols(ASTContext &Context,
8838                                 const ObjCInterfaceDecl *CommonBase,
8839                                 const ObjCObjectPointerType *LHSOPT,
8840                                 const ObjCObjectPointerType *RHSOPT,
8841       SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
8842 
8843   const ObjCObjectType* LHS = LHSOPT->getObjectType();
8844   const ObjCObjectType* RHS = RHSOPT->getObjectType();
8845   assert(LHS->getInterface() && "LHS must have an interface base");
8846   assert(RHS->getInterface() && "RHS must have an interface base");
8847 
8848   // Add all of the protocols for the LHS.
8849   llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
8850 
8851   // Start with the protocol qualifiers.
8852   for (auto proto : LHS->quals()) {
8853     Context.CollectInheritedProtocols(proto, LHSProtocolSet);
8854   }
8855 
8856   // Also add the protocols associated with the LHS interface.
8857   Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
8858 
8859   // Add all of the protocols for the RHS.
8860   llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
8861 
8862   // Start with the protocol qualifiers.
8863   for (auto proto : RHS->quals()) {
8864     Context.CollectInheritedProtocols(proto, RHSProtocolSet);
8865   }
8866 
8867   // Also add the protocols associated with the RHS interface.
8868   Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
8869 
8870   // Compute the intersection of the collected protocol sets.
8871   for (auto proto : LHSProtocolSet) {
8872     if (RHSProtocolSet.count(proto))
8873       IntersectionSet.push_back(proto);
8874   }
8875 
8876   // Compute the set of protocols that is implied by either the common type or
8877   // the protocols within the intersection.
8878   llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
8879   Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
8880 
8881   // Remove any implied protocols from the list of inherited protocols.
8882   if (!ImpliedProtocols.empty()) {
8883     IntersectionSet.erase(
8884       std::remove_if(IntersectionSet.begin(),
8885                      IntersectionSet.end(),
8886                      [&](ObjCProtocolDecl *proto) -> bool {
8887                        return ImpliedProtocols.count(proto) > 0;
8888                      }),
8889       IntersectionSet.end());
8890   }
8891 
8892   // Sort the remaining protocols by name.
8893   llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
8894                        compareObjCProtocolsByName);
8895 }
8896 
8897 /// Determine whether the first type is a subtype of the second.
8898 static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
8899                                      QualType rhs) {
8900   // Common case: two object pointers.
8901   const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
8902   const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
8903   if (lhsOPT && rhsOPT)
8904     return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
8905 
8906   // Two block pointers.
8907   const auto *lhsBlock = lhs->getAs<BlockPointerType>();
8908   const auto *rhsBlock = rhs->getAs<BlockPointerType>();
8909   if (lhsBlock && rhsBlock)
8910     return ctx.typesAreBlockPointerCompatible(lhs, rhs);
8911 
8912   // If either is an unqualified 'id' and the other is a block, it's
8913   // acceptable.
8914   if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
8915       (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
8916     return true;
8917 
8918   return false;
8919 }
8920 
8921 // Check that the given Objective-C type argument lists are equivalent.
8922 static bool sameObjCTypeArgs(ASTContext &ctx,
8923                              const ObjCInterfaceDecl *iface,
8924                              ArrayRef<QualType> lhsArgs,
8925                              ArrayRef<QualType> rhsArgs,
8926                              bool stripKindOf) {
8927   if (lhsArgs.size() != rhsArgs.size())
8928     return false;
8929 
8930   ObjCTypeParamList *typeParams = iface->getTypeParamList();
8931   for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
8932     if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
8933       continue;
8934 
8935     switch (typeParams->begin()[i]->getVariance()) {
8936     case ObjCTypeParamVariance::Invariant:
8937       if (!stripKindOf ||
8938           !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
8939                            rhsArgs[i].stripObjCKindOfType(ctx))) {
8940         return false;
8941       }
8942       break;
8943 
8944     case ObjCTypeParamVariance::Covariant:
8945       if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
8946         return false;
8947       break;
8948 
8949     case ObjCTypeParamVariance::Contravariant:
8950       if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
8951         return false;
8952       break;
8953     }
8954   }
8955 
8956   return true;
8957 }
8958 
8959 QualType ASTContext::areCommonBaseCompatible(
8960            const ObjCObjectPointerType *Lptr,
8961            const ObjCObjectPointerType *Rptr) {
8962   const ObjCObjectType *LHS = Lptr->getObjectType();
8963   const ObjCObjectType *RHS = Rptr->getObjectType();
8964   const ObjCInterfaceDecl* LDecl = LHS->getInterface();
8965   const ObjCInterfaceDecl* RDecl = RHS->getInterface();
8966 
8967   if (!LDecl || !RDecl)
8968     return {};
8969 
8970   // When either LHS or RHS is a kindof type, we should return a kindof type.
8971   // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
8972   // kindof(A).
8973   bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
8974 
8975   // Follow the left-hand side up the class hierarchy until we either hit a
8976   // root or find the RHS. Record the ancestors in case we don't find it.
8977   llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
8978     LHSAncestors;
8979   while (true) {
8980     // Record this ancestor. We'll need this if the common type isn't in the
8981     // path from the LHS to the root.
8982     LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
8983 
8984     if (declaresSameEntity(LHS->getInterface(), RDecl)) {
8985       // Get the type arguments.
8986       ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
8987       bool anyChanges = false;
8988       if (LHS->isSpecialized() && RHS->isSpecialized()) {
8989         // Both have type arguments, compare them.
8990         if (!sameObjCTypeArgs(*this, LHS->getInterface(),
8991                               LHS->getTypeArgs(), RHS->getTypeArgs(),
8992                               /*stripKindOf=*/true))
8993           return {};
8994       } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
8995         // If only one has type arguments, the result will not have type
8996         // arguments.
8997         LHSTypeArgs = {};
8998         anyChanges = true;
8999       }
9000 
9001       // Compute the intersection of protocols.
9002       SmallVector<ObjCProtocolDecl *, 8> Protocols;
9003       getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
9004                                  Protocols);
9005       if (!Protocols.empty())
9006         anyChanges = true;
9007 
9008       // If anything in the LHS will have changed, build a new result type.
9009       // If we need to return a kindof type but LHS is not a kindof type, we
9010       // build a new result type.
9011       if (anyChanges || LHS->isKindOfType() != anyKindOf) {
9012         QualType Result = getObjCInterfaceType(LHS->getInterface());
9013         Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
9014                                    anyKindOf || LHS->isKindOfType());
9015         return getObjCObjectPointerType(Result);
9016       }
9017 
9018       return getObjCObjectPointerType(QualType(LHS, 0));
9019     }
9020 
9021     // Find the superclass.
9022     QualType LHSSuperType = LHS->getSuperClassType();
9023     if (LHSSuperType.isNull())
9024       break;
9025 
9026     LHS = LHSSuperType->castAs<ObjCObjectType>();
9027   }
9028 
9029   // We didn't find anything by following the LHS to its root; now check
9030   // the RHS against the cached set of ancestors.
9031   while (true) {
9032     auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
9033     if (KnownLHS != LHSAncestors.end()) {
9034       LHS = KnownLHS->second;
9035 
9036       // Get the type arguments.
9037       ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
9038       bool anyChanges = false;
9039       if (LHS->isSpecialized() && RHS->isSpecialized()) {
9040         // Both have type arguments, compare them.
9041         if (!sameObjCTypeArgs(*this, LHS->getInterface(),
9042                               LHS->getTypeArgs(), RHS->getTypeArgs(),
9043                               /*stripKindOf=*/true))
9044           return {};
9045       } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
9046         // If only one has type arguments, the result will not have type
9047         // arguments.
9048         RHSTypeArgs = {};
9049         anyChanges = true;
9050       }
9051 
9052       // Compute the intersection of protocols.
9053       SmallVector<ObjCProtocolDecl *, 8> Protocols;
9054       getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
9055                                  Protocols);
9056       if (!Protocols.empty())
9057         anyChanges = true;
9058 
9059       // If we need to return a kindof type but RHS is not a kindof type, we
9060       // build a new result type.
9061       if (anyChanges || RHS->isKindOfType() != anyKindOf) {
9062         QualType Result = getObjCInterfaceType(RHS->getInterface());
9063         Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
9064                                    anyKindOf || RHS->isKindOfType());
9065         return getObjCObjectPointerType(Result);
9066       }
9067 
9068       return getObjCObjectPointerType(QualType(RHS, 0));
9069     }
9070 
9071     // Find the superclass of the RHS.
9072     QualType RHSSuperType = RHS->getSuperClassType();
9073     if (RHSSuperType.isNull())
9074       break;
9075 
9076     RHS = RHSSuperType->castAs<ObjCObjectType>();
9077   }
9078 
9079   return {};
9080 }
9081 
9082 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
9083                                          const ObjCObjectType *RHS) {
9084   assert(LHS->getInterface() && "LHS is not an interface type");
9085   assert(RHS->getInterface() && "RHS is not an interface type");
9086 
9087   // Verify that the base decls are compatible: the RHS must be a subclass of
9088   // the LHS.
9089   ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
9090   bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
9091   if (!IsSuperClass)
9092     return false;
9093 
9094   // If the LHS has protocol qualifiers, determine whether all of them are
9095   // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
9096   // LHS).
9097   if (LHS->getNumProtocols() > 0) {
9098     // OK if conversion of LHS to SuperClass results in narrowing of types
9099     // ; i.e., SuperClass may implement at least one of the protocols
9100     // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
9101     // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
9102     llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
9103     CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
9104     // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
9105     // qualifiers.
9106     for (auto *RHSPI : RHS->quals())
9107       CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
9108     // If there is no protocols associated with RHS, it is not a match.
9109     if (SuperClassInheritedProtocols.empty())
9110       return false;
9111 
9112     for (const auto *LHSProto : LHS->quals()) {
9113       bool SuperImplementsProtocol = false;
9114       for (auto *SuperClassProto : SuperClassInheritedProtocols)
9115         if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
9116           SuperImplementsProtocol = true;
9117           break;
9118         }
9119       if (!SuperImplementsProtocol)
9120         return false;
9121     }
9122   }
9123 
9124   // If the LHS is specialized, we may need to check type arguments.
9125   if (LHS->isSpecialized()) {
9126     // Follow the superclass chain until we've matched the LHS class in the
9127     // hierarchy. This substitutes type arguments through.
9128     const ObjCObjectType *RHSSuper = RHS;
9129     while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
9130       RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
9131 
9132     // If the RHS is specializd, compare type arguments.
9133     if (RHSSuper->isSpecialized() &&
9134         !sameObjCTypeArgs(*this, LHS->getInterface(),
9135                           LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
9136                           /*stripKindOf=*/true)) {
9137       return false;
9138     }
9139   }
9140 
9141   return true;
9142 }
9143 
9144 bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
9145   // get the "pointed to" types
9146   const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
9147   const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
9148 
9149   if (!LHSOPT || !RHSOPT)
9150     return false;
9151 
9152   return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
9153          canAssignObjCInterfaces(RHSOPT, LHSOPT);
9154 }
9155 
9156 bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
9157   return canAssignObjCInterfaces(
9158       getObjCObjectPointerType(To)->castAs<ObjCObjectPointerType>(),
9159       getObjCObjectPointerType(From)->castAs<ObjCObjectPointerType>());
9160 }
9161 
9162 /// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
9163 /// both shall have the identically qualified version of a compatible type.
9164 /// C99 6.2.7p1: Two types have compatible types if their types are the
9165 /// same. See 6.7.[2,3,5] for additional rules.
9166 bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
9167                                     bool CompareUnqualified) {
9168   if (getLangOpts().CPlusPlus)
9169     return hasSameType(LHS, RHS);
9170 
9171   return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
9172 }
9173 
9174 bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
9175   return typesAreCompatible(LHS, RHS);
9176 }
9177 
9178 bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
9179   return !mergeTypes(LHS, RHS, true).isNull();
9180 }
9181 
9182 /// mergeTransparentUnionType - if T is a transparent union type and a member
9183 /// of T is compatible with SubType, return the merged type, else return
9184 /// QualType()
9185 QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
9186                                                bool OfBlockPointer,
9187                                                bool Unqualified) {
9188   if (const RecordType *UT = T->getAsUnionType()) {
9189     RecordDecl *UD = UT->getDecl();
9190     if (UD->hasAttr<TransparentUnionAttr>()) {
9191       for (const auto *I : UD->fields()) {
9192         QualType ET = I->getType().getUnqualifiedType();
9193         QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
9194         if (!MT.isNull())
9195           return MT;
9196       }
9197     }
9198   }
9199 
9200   return {};
9201 }
9202 
9203 /// mergeFunctionParameterTypes - merge two types which appear as function
9204 /// parameter types
9205 QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
9206                                                  bool OfBlockPointer,
9207                                                  bool Unqualified) {
9208   // GNU extension: two types are compatible if they appear as a function
9209   // argument, one of the types is a transparent union type and the other
9210   // type is compatible with a union member
9211   QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
9212                                               Unqualified);
9213   if (!lmerge.isNull())
9214     return lmerge;
9215 
9216   QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
9217                                               Unqualified);
9218   if (!rmerge.isNull())
9219     return rmerge;
9220 
9221   return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
9222 }
9223 
9224 QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
9225                                         bool OfBlockPointer, bool Unqualified,
9226                                         bool AllowCXX) {
9227   const auto *lbase = lhs->castAs<FunctionType>();
9228   const auto *rbase = rhs->castAs<FunctionType>();
9229   const auto *lproto = dyn_cast<FunctionProtoType>(lbase);
9230   const auto *rproto = dyn_cast<FunctionProtoType>(rbase);
9231   bool allLTypes = true;
9232   bool allRTypes = true;
9233 
9234   // Check return type
9235   QualType retType;
9236   if (OfBlockPointer) {
9237     QualType RHS = rbase->getReturnType();
9238     QualType LHS = lbase->getReturnType();
9239     bool UnqualifiedResult = Unqualified;
9240     if (!UnqualifiedResult)
9241       UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
9242     retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
9243   }
9244   else
9245     retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
9246                          Unqualified);
9247   if (retType.isNull())
9248     return {};
9249 
9250   if (Unqualified)
9251     retType = retType.getUnqualifiedType();
9252 
9253   CanQualType LRetType = getCanonicalType(lbase->getReturnType());
9254   CanQualType RRetType = getCanonicalType(rbase->getReturnType());
9255   if (Unqualified) {
9256     LRetType = LRetType.getUnqualifiedType();
9257     RRetType = RRetType.getUnqualifiedType();
9258   }
9259 
9260   if (getCanonicalType(retType) != LRetType)
9261     allLTypes = false;
9262   if (getCanonicalType(retType) != RRetType)
9263     allRTypes = false;
9264 
9265   // FIXME: double check this
9266   // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
9267   //                           rbase->getRegParmAttr() != 0 &&
9268   //                           lbase->getRegParmAttr() != rbase->getRegParmAttr()?
9269   FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
9270   FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
9271 
9272   // Compatible functions must have compatible calling conventions
9273   if (lbaseInfo.getCC() != rbaseInfo.getCC())
9274     return {};
9275 
9276   // Regparm is part of the calling convention.
9277   if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
9278     return {};
9279   if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
9280     return {};
9281 
9282   if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
9283     return {};
9284   if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
9285     return {};
9286   if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
9287     return {};
9288 
9289   // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
9290   bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
9291 
9292   if (lbaseInfo.getNoReturn() != NoReturn)
9293     allLTypes = false;
9294   if (rbaseInfo.getNoReturn() != NoReturn)
9295     allRTypes = false;
9296 
9297   FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
9298 
9299   if (lproto && rproto) { // two C99 style function prototypes
9300     assert((AllowCXX ||
9301             (!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec())) &&
9302            "C++ shouldn't be here");
9303     // Compatible functions must have the same number of parameters
9304     if (lproto->getNumParams() != rproto->getNumParams())
9305       return {};
9306 
9307     // Variadic and non-variadic functions aren't compatible
9308     if (lproto->isVariadic() != rproto->isVariadic())
9309       return {};
9310 
9311     if (lproto->getMethodQuals() != rproto->getMethodQuals())
9312       return {};
9313 
9314     SmallVector<FunctionProtoType::ExtParameterInfo, 4> newParamInfos;
9315     bool canUseLeft, canUseRight;
9316     if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight,
9317                                newParamInfos))
9318       return {};
9319 
9320     if (!canUseLeft)
9321       allLTypes = false;
9322     if (!canUseRight)
9323       allRTypes = false;
9324 
9325     // Check parameter type compatibility
9326     SmallVector<QualType, 10> types;
9327     for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
9328       QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
9329       QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
9330       QualType paramType = mergeFunctionParameterTypes(
9331           lParamType, rParamType, OfBlockPointer, Unqualified);
9332       if (paramType.isNull())
9333         return {};
9334 
9335       if (Unqualified)
9336         paramType = paramType.getUnqualifiedType();
9337 
9338       types.push_back(paramType);
9339       if (Unqualified) {
9340         lParamType = lParamType.getUnqualifiedType();
9341         rParamType = rParamType.getUnqualifiedType();
9342       }
9343 
9344       if (getCanonicalType(paramType) != getCanonicalType(lParamType))
9345         allLTypes = false;
9346       if (getCanonicalType(paramType) != getCanonicalType(rParamType))
9347         allRTypes = false;
9348     }
9349 
9350     if (allLTypes) return lhs;
9351     if (allRTypes) return rhs;
9352 
9353     FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
9354     EPI.ExtInfo = einfo;
9355     EPI.ExtParameterInfos =
9356         newParamInfos.empty() ? nullptr : newParamInfos.data();
9357     return getFunctionType(retType, types, EPI);
9358   }
9359 
9360   if (lproto) allRTypes = false;
9361   if (rproto) allLTypes = false;
9362 
9363   const FunctionProtoType *proto = lproto ? lproto : rproto;
9364   if (proto) {
9365     assert((AllowCXX || !proto->hasExceptionSpec()) && "C++ shouldn't be here");
9366     if (proto->isVariadic())
9367       return {};
9368     // Check that the types are compatible with the types that
9369     // would result from default argument promotions (C99 6.7.5.3p15).
9370     // The only types actually affected are promotable integer
9371     // types and floats, which would be passed as a different
9372     // type depending on whether the prototype is visible.
9373     for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
9374       QualType paramTy = proto->getParamType(i);
9375 
9376       // Look at the converted type of enum types, since that is the type used
9377       // to pass enum values.
9378       if (const auto *Enum = paramTy->getAs<EnumType>()) {
9379         paramTy = Enum->getDecl()->getIntegerType();
9380         if (paramTy.isNull())
9381           return {};
9382       }
9383 
9384       if (paramTy->isPromotableIntegerType() ||
9385           getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
9386         return {};
9387     }
9388 
9389     if (allLTypes) return lhs;
9390     if (allRTypes) return rhs;
9391 
9392     FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
9393     EPI.ExtInfo = einfo;
9394     return getFunctionType(retType, proto->getParamTypes(), EPI);
9395   }
9396 
9397   if (allLTypes) return lhs;
9398   if (allRTypes) return rhs;
9399   return getFunctionNoProtoType(retType, einfo);
9400 }
9401 
9402 /// Given that we have an enum type and a non-enum type, try to merge them.
9403 static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
9404                                      QualType other, bool isBlockReturnType) {
9405   // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
9406   // a signed integer type, or an unsigned integer type.
9407   // Compatibility is based on the underlying type, not the promotion
9408   // type.
9409   QualType underlyingType = ET->getDecl()->getIntegerType();
9410   if (underlyingType.isNull())
9411     return {};
9412   if (Context.hasSameType(underlyingType, other))
9413     return other;
9414 
9415   // In block return types, we're more permissive and accept any
9416   // integral type of the same size.
9417   if (isBlockReturnType && other->isIntegerType() &&
9418       Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
9419     return other;
9420 
9421   return {};
9422 }
9423 
9424 QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
9425                                 bool OfBlockPointer,
9426                                 bool Unqualified, bool BlockReturnType) {
9427   // C++ [expr]: If an expression initially has the type "reference to T", the
9428   // type is adjusted to "T" prior to any further analysis, the expression
9429   // designates the object or function denoted by the reference, and the
9430   // expression is an lvalue unless the reference is an rvalue reference and
9431   // the expression is a function call (possibly inside parentheses).
9432   if (LHS->getAs<ReferenceType>() || RHS->getAs<ReferenceType>())
9433     return {};
9434 
9435   if (Unqualified) {
9436     LHS = LHS.getUnqualifiedType();
9437     RHS = RHS.getUnqualifiedType();
9438   }
9439 
9440   QualType LHSCan = getCanonicalType(LHS),
9441            RHSCan = getCanonicalType(RHS);
9442 
9443   // If two types are identical, they are compatible.
9444   if (LHSCan == RHSCan)
9445     return LHS;
9446 
9447   // If the qualifiers are different, the types aren't compatible... mostly.
9448   Qualifiers LQuals = LHSCan.getLocalQualifiers();
9449   Qualifiers RQuals = RHSCan.getLocalQualifiers();
9450   if (LQuals != RQuals) {
9451     // If any of these qualifiers are different, we have a type
9452     // mismatch.
9453     if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
9454         LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
9455         LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
9456         LQuals.hasUnaligned() != RQuals.hasUnaligned())
9457       return {};
9458 
9459     // Exactly one GC qualifier difference is allowed: __strong is
9460     // okay if the other type has no GC qualifier but is an Objective
9461     // C object pointer (i.e. implicitly strong by default).  We fix
9462     // this by pretending that the unqualified type was actually
9463     // qualified __strong.
9464     Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
9465     Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
9466     assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
9467 
9468     if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
9469       return {};
9470 
9471     if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
9472       return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
9473     }
9474     if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
9475       return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
9476     }
9477     return {};
9478   }
9479 
9480   // Okay, qualifiers are equal.
9481 
9482   Type::TypeClass LHSClass = LHSCan->getTypeClass();
9483   Type::TypeClass RHSClass = RHSCan->getTypeClass();
9484 
9485   // We want to consider the two function types to be the same for these
9486   // comparisons, just force one to the other.
9487   if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
9488   if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
9489 
9490   // Same as above for arrays
9491   if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
9492     LHSClass = Type::ConstantArray;
9493   if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
9494     RHSClass = Type::ConstantArray;
9495 
9496   // ObjCInterfaces are just specialized ObjCObjects.
9497   if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
9498   if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
9499 
9500   // Canonicalize ExtVector -> Vector.
9501   if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
9502   if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
9503 
9504   // If the canonical type classes don't match.
9505   if (LHSClass != RHSClass) {
9506     // Note that we only have special rules for turning block enum
9507     // returns into block int returns, not vice-versa.
9508     if (const auto *ETy = LHS->getAs<EnumType>()) {
9509       return mergeEnumWithInteger(*this, ETy, RHS, false);
9510     }
9511     if (const EnumType* ETy = RHS->getAs<EnumType>()) {
9512       return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
9513     }
9514     // allow block pointer type to match an 'id' type.
9515     if (OfBlockPointer && !BlockReturnType) {
9516        if (LHS->isObjCIdType() && RHS->isBlockPointerType())
9517          return LHS;
9518       if (RHS->isObjCIdType() && LHS->isBlockPointerType())
9519         return RHS;
9520     }
9521 
9522     return {};
9523   }
9524 
9525   // The canonical type classes match.
9526   switch (LHSClass) {
9527 #define TYPE(Class, Base)
9528 #define ABSTRACT_TYPE(Class, Base)
9529 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
9530 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
9531 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
9532 #include "clang/AST/TypeNodes.inc"
9533     llvm_unreachable("Non-canonical and dependent types shouldn't get here");
9534 
9535   case Type::Auto:
9536   case Type::DeducedTemplateSpecialization:
9537   case Type::LValueReference:
9538   case Type::RValueReference:
9539   case Type::MemberPointer:
9540     llvm_unreachable("C++ should never be in mergeTypes");
9541 
9542   case Type::ObjCInterface:
9543   case Type::IncompleteArray:
9544   case Type::VariableArray:
9545   case Type::FunctionProto:
9546   case Type::ExtVector:
9547     llvm_unreachable("Types are eliminated above");
9548 
9549   case Type::Pointer:
9550   {
9551     // Merge two pointer types, while trying to preserve typedef info
9552     QualType LHSPointee = LHS->castAs<PointerType>()->getPointeeType();
9553     QualType RHSPointee = RHS->castAs<PointerType>()->getPointeeType();
9554     if (Unqualified) {
9555       LHSPointee = LHSPointee.getUnqualifiedType();
9556       RHSPointee = RHSPointee.getUnqualifiedType();
9557     }
9558     QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
9559                                      Unqualified);
9560     if (ResultType.isNull())
9561       return {};
9562     if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
9563       return LHS;
9564     if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
9565       return RHS;
9566     return getPointerType(ResultType);
9567   }
9568   case Type::BlockPointer:
9569   {
9570     // Merge two block pointer types, while trying to preserve typedef info
9571     QualType LHSPointee = LHS->castAs<BlockPointerType>()->getPointeeType();
9572     QualType RHSPointee = RHS->castAs<BlockPointerType>()->getPointeeType();
9573     if (Unqualified) {
9574       LHSPointee = LHSPointee.getUnqualifiedType();
9575       RHSPointee = RHSPointee.getUnqualifiedType();
9576     }
9577     if (getLangOpts().OpenCL) {
9578       Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
9579       Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
9580       // Blocks can't be an expression in a ternary operator (OpenCL v2.0
9581       // 6.12.5) thus the following check is asymmetric.
9582       if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual))
9583         return {};
9584       LHSPteeQual.removeAddressSpace();
9585       RHSPteeQual.removeAddressSpace();
9586       LHSPointee =
9587           QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
9588       RHSPointee =
9589           QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
9590     }
9591     QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
9592                                      Unqualified);
9593     if (ResultType.isNull())
9594       return {};
9595     if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
9596       return LHS;
9597     if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
9598       return RHS;
9599     return getBlockPointerType(ResultType);
9600   }
9601   case Type::Atomic:
9602   {
9603     // Merge two pointer types, while trying to preserve typedef info
9604     QualType LHSValue = LHS->castAs<AtomicType>()->getValueType();
9605     QualType RHSValue = RHS->castAs<AtomicType>()->getValueType();
9606     if (Unqualified) {
9607       LHSValue = LHSValue.getUnqualifiedType();
9608       RHSValue = RHSValue.getUnqualifiedType();
9609     }
9610     QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
9611                                      Unqualified);
9612     if (ResultType.isNull())
9613       return {};
9614     if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
9615       return LHS;
9616     if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
9617       return RHS;
9618     return getAtomicType(ResultType);
9619   }
9620   case Type::ConstantArray:
9621   {
9622     const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
9623     const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
9624     if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
9625       return {};
9626 
9627     QualType LHSElem = getAsArrayType(LHS)->getElementType();
9628     QualType RHSElem = getAsArrayType(RHS)->getElementType();
9629     if (Unqualified) {
9630       LHSElem = LHSElem.getUnqualifiedType();
9631       RHSElem = RHSElem.getUnqualifiedType();
9632     }
9633 
9634     QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
9635     if (ResultType.isNull())
9636       return {};
9637 
9638     const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
9639     const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
9640 
9641     // If either side is a variable array, and both are complete, check whether
9642     // the current dimension is definite.
9643     if (LVAT || RVAT) {
9644       auto SizeFetch = [this](const VariableArrayType* VAT,
9645           const ConstantArrayType* CAT)
9646           -> std::pair<bool,llvm::APInt> {
9647         if (VAT) {
9648           Optional<llvm::APSInt> TheInt;
9649           Expr *E = VAT->getSizeExpr();
9650           if (E && (TheInt = E->getIntegerConstantExpr(*this)))
9651             return std::make_pair(true, *TheInt);
9652           return std::make_pair(false, llvm::APSInt());
9653         }
9654         if (CAT)
9655           return std::make_pair(true, CAT->getSize());
9656         return std::make_pair(false, llvm::APInt());
9657       };
9658 
9659       bool HaveLSize, HaveRSize;
9660       llvm::APInt LSize, RSize;
9661       std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT);
9662       std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT);
9663       if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize))
9664         return {}; // Definite, but unequal, array dimension
9665     }
9666 
9667     if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
9668       return LHS;
9669     if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
9670       return RHS;
9671     if (LCAT)
9672       return getConstantArrayType(ResultType, LCAT->getSize(),
9673                                   LCAT->getSizeExpr(),
9674                                   ArrayType::ArraySizeModifier(), 0);
9675     if (RCAT)
9676       return getConstantArrayType(ResultType, RCAT->getSize(),
9677                                   RCAT->getSizeExpr(),
9678                                   ArrayType::ArraySizeModifier(), 0);
9679     if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
9680       return LHS;
9681     if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
9682       return RHS;
9683     if (LVAT) {
9684       // FIXME: This isn't correct! But tricky to implement because
9685       // the array's size has to be the size of LHS, but the type
9686       // has to be different.
9687       return LHS;
9688     }
9689     if (RVAT) {
9690       // FIXME: This isn't correct! But tricky to implement because
9691       // the array's size has to be the size of RHS, but the type
9692       // has to be different.
9693       return RHS;
9694     }
9695     if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
9696     if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
9697     return getIncompleteArrayType(ResultType,
9698                                   ArrayType::ArraySizeModifier(), 0);
9699   }
9700   case Type::FunctionNoProto:
9701     return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
9702   case Type::Record:
9703   case Type::Enum:
9704     return {};
9705   case Type::Builtin:
9706     // Only exactly equal builtin types are compatible, which is tested above.
9707     return {};
9708   case Type::Complex:
9709     // Distinct complex types are incompatible.
9710     return {};
9711   case Type::Vector:
9712     // FIXME: The merged type should be an ExtVector!
9713     if (areCompatVectorTypes(LHSCan->castAs<VectorType>(),
9714                              RHSCan->castAs<VectorType>()))
9715       return LHS;
9716     return {};
9717   case Type::ConstantMatrix:
9718     if (areCompatMatrixTypes(LHSCan->castAs<ConstantMatrixType>(),
9719                              RHSCan->castAs<ConstantMatrixType>()))
9720       return LHS;
9721     return {};
9722   case Type::ObjCObject: {
9723     // Check if the types are assignment compatible.
9724     // FIXME: This should be type compatibility, e.g. whether
9725     // "LHS x; RHS x;" at global scope is legal.
9726     if (canAssignObjCInterfaces(LHS->castAs<ObjCObjectType>(),
9727                                 RHS->castAs<ObjCObjectType>()))
9728       return LHS;
9729     return {};
9730   }
9731   case Type::ObjCObjectPointer:
9732     if (OfBlockPointer) {
9733       if (canAssignObjCInterfacesInBlockPointer(
9734               LHS->castAs<ObjCObjectPointerType>(),
9735               RHS->castAs<ObjCObjectPointerType>(), BlockReturnType))
9736         return LHS;
9737       return {};
9738     }
9739     if (canAssignObjCInterfaces(LHS->castAs<ObjCObjectPointerType>(),
9740                                 RHS->castAs<ObjCObjectPointerType>()))
9741       return LHS;
9742     return {};
9743   case Type::Pipe:
9744     assert(LHS != RHS &&
9745            "Equivalent pipe types should have already been handled!");
9746     return {};
9747   case Type::ExtInt: {
9748     // Merge two ext-int types, while trying to preserve typedef info.
9749     bool LHSUnsigned  = LHS->castAs<ExtIntType>()->isUnsigned();
9750     bool RHSUnsigned = RHS->castAs<ExtIntType>()->isUnsigned();
9751     unsigned LHSBits = LHS->castAs<ExtIntType>()->getNumBits();
9752     unsigned RHSBits = RHS->castAs<ExtIntType>()->getNumBits();
9753 
9754     // Like unsigned/int, shouldn't have a type if they dont match.
9755     if (LHSUnsigned != RHSUnsigned)
9756       return {};
9757 
9758     if (LHSBits != RHSBits)
9759       return {};
9760     return LHS;
9761   }
9762   }
9763 
9764   llvm_unreachable("Invalid Type::Class!");
9765 }
9766 
9767 bool ASTContext::mergeExtParameterInfo(
9768     const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
9769     bool &CanUseFirst, bool &CanUseSecond,
9770     SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos) {
9771   assert(NewParamInfos.empty() && "param info list not empty");
9772   CanUseFirst = CanUseSecond = true;
9773   bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
9774   bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
9775 
9776   // Fast path: if the first type doesn't have ext parameter infos,
9777   // we match if and only if the second type also doesn't have them.
9778   if (!FirstHasInfo && !SecondHasInfo)
9779     return true;
9780 
9781   bool NeedParamInfo = false;
9782   size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
9783                           : SecondFnType->getExtParameterInfos().size();
9784 
9785   for (size_t I = 0; I < E; ++I) {
9786     FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
9787     if (FirstHasInfo)
9788       FirstParam = FirstFnType->getExtParameterInfo(I);
9789     if (SecondHasInfo)
9790       SecondParam = SecondFnType->getExtParameterInfo(I);
9791 
9792     // Cannot merge unless everything except the noescape flag matches.
9793     if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false))
9794       return false;
9795 
9796     bool FirstNoEscape = FirstParam.isNoEscape();
9797     bool SecondNoEscape = SecondParam.isNoEscape();
9798     bool IsNoEscape = FirstNoEscape && SecondNoEscape;
9799     NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape));
9800     if (NewParamInfos.back().getOpaqueValue())
9801       NeedParamInfo = true;
9802     if (FirstNoEscape != IsNoEscape)
9803       CanUseFirst = false;
9804     if (SecondNoEscape != IsNoEscape)
9805       CanUseSecond = false;
9806   }
9807 
9808   if (!NeedParamInfo)
9809     NewParamInfos.clear();
9810 
9811   return true;
9812 }
9813 
9814 void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) {
9815   ObjCLayouts[CD] = nullptr;
9816 }
9817 
9818 /// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
9819 /// 'RHS' attributes and returns the merged version; including for function
9820 /// return types.
9821 QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
9822   QualType LHSCan = getCanonicalType(LHS),
9823   RHSCan = getCanonicalType(RHS);
9824   // If two types are identical, they are compatible.
9825   if (LHSCan == RHSCan)
9826     return LHS;
9827   if (RHSCan->isFunctionType()) {
9828     if (!LHSCan->isFunctionType())
9829       return {};
9830     QualType OldReturnType =
9831         cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
9832     QualType NewReturnType =
9833         cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
9834     QualType ResReturnType =
9835       mergeObjCGCQualifiers(NewReturnType, OldReturnType);
9836     if (ResReturnType.isNull())
9837       return {};
9838     if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
9839       // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
9840       // In either case, use OldReturnType to build the new function type.
9841       const auto *F = LHS->castAs<FunctionType>();
9842       if (const auto *FPT = cast<FunctionProtoType>(F)) {
9843         FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9844         EPI.ExtInfo = getFunctionExtInfo(LHS);
9845         QualType ResultType =
9846             getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
9847         return ResultType;
9848       }
9849     }
9850     return {};
9851   }
9852 
9853   // If the qualifiers are different, the types can still be merged.
9854   Qualifiers LQuals = LHSCan.getLocalQualifiers();
9855   Qualifiers RQuals = RHSCan.getLocalQualifiers();
9856   if (LQuals != RQuals) {
9857     // If any of these qualifiers are different, we have a type mismatch.
9858     if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
9859         LQuals.getAddressSpace() != RQuals.getAddressSpace())
9860       return {};
9861 
9862     // Exactly one GC qualifier difference is allowed: __strong is
9863     // okay if the other type has no GC qualifier but is an Objective
9864     // C object pointer (i.e. implicitly strong by default).  We fix
9865     // this by pretending that the unqualified type was actually
9866     // qualified __strong.
9867     Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
9868     Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
9869     assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
9870 
9871     if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
9872       return {};
9873 
9874     if (GC_L == Qualifiers::Strong)
9875       return LHS;
9876     if (GC_R == Qualifiers::Strong)
9877       return RHS;
9878     return {};
9879   }
9880 
9881   if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
9882     QualType LHSBaseQT = LHS->castAs<ObjCObjectPointerType>()->getPointeeType();
9883     QualType RHSBaseQT = RHS->castAs<ObjCObjectPointerType>()->getPointeeType();
9884     QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
9885     if (ResQT == LHSBaseQT)
9886       return LHS;
9887     if (ResQT == RHSBaseQT)
9888       return RHS;
9889   }
9890   return {};
9891 }
9892 
9893 //===----------------------------------------------------------------------===//
9894 //                         Integer Predicates
9895 //===----------------------------------------------------------------------===//
9896 
9897 unsigned ASTContext::getIntWidth(QualType T) const {
9898   if (const auto *ET = T->getAs<EnumType>())
9899     T = ET->getDecl()->getIntegerType();
9900   if (T->isBooleanType())
9901     return 1;
9902   if(const auto *EIT = T->getAs<ExtIntType>())
9903     return EIT->getNumBits();
9904   // For builtin types, just use the standard type sizing method
9905   return (unsigned)getTypeSize(T);
9906 }
9907 
9908 QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
9909   assert((T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) &&
9910          "Unexpected type");
9911 
9912   // Turn <4 x signed int> -> <4 x unsigned int>
9913   if (const auto *VTy = T->getAs<VectorType>())
9914     return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
9915                          VTy->getNumElements(), VTy->getVectorKind());
9916 
9917   // For enums, we return the unsigned version of the base type.
9918   if (const auto *ETy = T->getAs<EnumType>())
9919     T = ETy->getDecl()->getIntegerType();
9920 
9921   switch (T->castAs<BuiltinType>()->getKind()) {
9922   case BuiltinType::Char_S:
9923   case BuiltinType::SChar:
9924     return UnsignedCharTy;
9925   case BuiltinType::Short:
9926     return UnsignedShortTy;
9927   case BuiltinType::Int:
9928     return UnsignedIntTy;
9929   case BuiltinType::Long:
9930     return UnsignedLongTy;
9931   case BuiltinType::LongLong:
9932     return UnsignedLongLongTy;
9933   case BuiltinType::Int128:
9934     return UnsignedInt128Ty;
9935 
9936   case BuiltinType::ShortAccum:
9937     return UnsignedShortAccumTy;
9938   case BuiltinType::Accum:
9939     return UnsignedAccumTy;
9940   case BuiltinType::LongAccum:
9941     return UnsignedLongAccumTy;
9942   case BuiltinType::SatShortAccum:
9943     return SatUnsignedShortAccumTy;
9944   case BuiltinType::SatAccum:
9945     return SatUnsignedAccumTy;
9946   case BuiltinType::SatLongAccum:
9947     return SatUnsignedLongAccumTy;
9948   case BuiltinType::ShortFract:
9949     return UnsignedShortFractTy;
9950   case BuiltinType::Fract:
9951     return UnsignedFractTy;
9952   case BuiltinType::LongFract:
9953     return UnsignedLongFractTy;
9954   case BuiltinType::SatShortFract:
9955     return SatUnsignedShortFractTy;
9956   case BuiltinType::SatFract:
9957     return SatUnsignedFractTy;
9958   case BuiltinType::SatLongFract:
9959     return SatUnsignedLongFractTy;
9960   default:
9961     llvm_unreachable("Unexpected signed integer or fixed point type");
9962   }
9963 }
9964 
9965 ASTMutationListener::~ASTMutationListener() = default;
9966 
9967 void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
9968                                             QualType ReturnType) {}
9969 
9970 //===----------------------------------------------------------------------===//
9971 //                          Builtin Type Computation
9972 //===----------------------------------------------------------------------===//
9973 
9974 /// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
9975 /// pointer over the consumed characters.  This returns the resultant type.  If
9976 /// AllowTypeModifiers is false then modifier like * are not parsed, just basic
9977 /// types.  This allows "v2i*" to be parsed as a pointer to a v2i instead of
9978 /// a vector of "i*".
9979 ///
9980 /// RequiresICE is filled in on return to indicate whether the value is required
9981 /// to be an Integer Constant Expression.
9982 static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
9983                                   ASTContext::GetBuiltinTypeError &Error,
9984                                   bool &RequiresICE,
9985                                   bool AllowTypeModifiers) {
9986   // Modifiers.
9987   int HowLong = 0;
9988   bool Signed = false, Unsigned = false;
9989   RequiresICE = false;
9990 
9991   // Read the prefixed modifiers first.
9992   bool Done = false;
9993   #ifndef NDEBUG
9994   bool IsSpecial = false;
9995   #endif
9996   while (!Done) {
9997     switch (*Str++) {
9998     default: Done = true; --Str; break;
9999     case 'I':
10000       RequiresICE = true;
10001       break;
10002     case 'S':
10003       assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
10004       assert(!Signed && "Can't use 'S' modifier multiple times!");
10005       Signed = true;
10006       break;
10007     case 'U':
10008       assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
10009       assert(!Unsigned && "Can't use 'U' modifier multiple times!");
10010       Unsigned = true;
10011       break;
10012     case 'L':
10013       assert(!IsSpecial && "Can't use 'L' with 'W', 'N', 'Z' or 'O' modifiers");
10014       assert(HowLong <= 2 && "Can't have LLLL modifier");
10015       ++HowLong;
10016       break;
10017     case 'N':
10018       // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
10019       assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
10020       assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
10021       #ifndef NDEBUG
10022       IsSpecial = true;
10023       #endif
10024       if (Context.getTargetInfo().getLongWidth() == 32)
10025         ++HowLong;
10026       break;
10027     case 'W':
10028       // This modifier represents int64 type.
10029       assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
10030       assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
10031       #ifndef NDEBUG
10032       IsSpecial = true;
10033       #endif
10034       switch (Context.getTargetInfo().getInt64Type()) {
10035       default:
10036         llvm_unreachable("Unexpected integer type");
10037       case TargetInfo::SignedLong:
10038         HowLong = 1;
10039         break;
10040       case TargetInfo::SignedLongLong:
10041         HowLong = 2;
10042         break;
10043       }
10044       break;
10045     case 'Z':
10046       // This modifier represents int32 type.
10047       assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
10048       assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!");
10049       #ifndef NDEBUG
10050       IsSpecial = true;
10051       #endif
10052       switch (Context.getTargetInfo().getIntTypeByWidth(32, true)) {
10053       default:
10054         llvm_unreachable("Unexpected integer type");
10055       case TargetInfo::SignedInt:
10056         HowLong = 0;
10057         break;
10058       case TargetInfo::SignedLong:
10059         HowLong = 1;
10060         break;
10061       case TargetInfo::SignedLongLong:
10062         HowLong = 2;
10063         break;
10064       }
10065       break;
10066     case 'O':
10067       assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
10068       assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!");
10069       #ifndef NDEBUG
10070       IsSpecial = true;
10071       #endif
10072       if (Context.getLangOpts().OpenCL)
10073         HowLong = 1;
10074       else
10075         HowLong = 2;
10076       break;
10077     }
10078   }
10079 
10080   QualType Type;
10081 
10082   // Read the base type.
10083   switch (*Str++) {
10084   default: llvm_unreachable("Unknown builtin type letter!");
10085   case 'y':
10086     assert(HowLong == 0 && !Signed && !Unsigned &&
10087            "Bad modifiers used with 'y'!");
10088     Type = Context.BFloat16Ty;
10089     break;
10090   case 'v':
10091     assert(HowLong == 0 && !Signed && !Unsigned &&
10092            "Bad modifiers used with 'v'!");
10093     Type = Context.VoidTy;
10094     break;
10095   case 'h':
10096     assert(HowLong == 0 && !Signed && !Unsigned &&
10097            "Bad modifiers used with 'h'!");
10098     Type = Context.HalfTy;
10099     break;
10100   case 'f':
10101     assert(HowLong == 0 && !Signed && !Unsigned &&
10102            "Bad modifiers used with 'f'!");
10103     Type = Context.FloatTy;
10104     break;
10105   case 'd':
10106     assert(HowLong < 3 && !Signed && !Unsigned &&
10107            "Bad modifiers used with 'd'!");
10108     if (HowLong == 1)
10109       Type = Context.LongDoubleTy;
10110     else if (HowLong == 2)
10111       Type = Context.Float128Ty;
10112     else
10113       Type = Context.DoubleTy;
10114     break;
10115   case 's':
10116     assert(HowLong == 0 && "Bad modifiers used with 's'!");
10117     if (Unsigned)
10118       Type = Context.UnsignedShortTy;
10119     else
10120       Type = Context.ShortTy;
10121     break;
10122   case 'i':
10123     if (HowLong == 3)
10124       Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
10125     else if (HowLong == 2)
10126       Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
10127     else if (HowLong == 1)
10128       Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
10129     else
10130       Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
10131     break;
10132   case 'c':
10133     assert(HowLong == 0 && "Bad modifiers used with 'c'!");
10134     if (Signed)
10135       Type = Context.SignedCharTy;
10136     else if (Unsigned)
10137       Type = Context.UnsignedCharTy;
10138     else
10139       Type = Context.CharTy;
10140     break;
10141   case 'b': // boolean
10142     assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
10143     Type = Context.BoolTy;
10144     break;
10145   case 'z':  // size_t.
10146     assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
10147     Type = Context.getSizeType();
10148     break;
10149   case 'w':  // wchar_t.
10150     assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
10151     Type = Context.getWideCharType();
10152     break;
10153   case 'F':
10154     Type = Context.getCFConstantStringType();
10155     break;
10156   case 'G':
10157     Type = Context.getObjCIdType();
10158     break;
10159   case 'H':
10160     Type = Context.getObjCSelType();
10161     break;
10162   case 'M':
10163     Type = Context.getObjCSuperType();
10164     break;
10165   case 'a':
10166     Type = Context.getBuiltinVaListType();
10167     assert(!Type.isNull() && "builtin va list type not initialized!");
10168     break;
10169   case 'A':
10170     // This is a "reference" to a va_list; however, what exactly
10171     // this means depends on how va_list is defined. There are two
10172     // different kinds of va_list: ones passed by value, and ones
10173     // passed by reference.  An example of a by-value va_list is
10174     // x86, where va_list is a char*. An example of by-ref va_list
10175     // is x86-64, where va_list is a __va_list_tag[1]. For x86,
10176     // we want this argument to be a char*&; for x86-64, we want
10177     // it to be a __va_list_tag*.
10178     Type = Context.getBuiltinVaListType();
10179     assert(!Type.isNull() && "builtin va list type not initialized!");
10180     if (Type->isArrayType())
10181       Type = Context.getArrayDecayedType(Type);
10182     else
10183       Type = Context.getLValueReferenceType(Type);
10184     break;
10185   case 'q': {
10186     char *End;
10187     unsigned NumElements = strtoul(Str, &End, 10);
10188     assert(End != Str && "Missing vector size");
10189     Str = End;
10190 
10191     QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
10192                                              RequiresICE, false);
10193     assert(!RequiresICE && "Can't require vector ICE");
10194 
10195     Type = Context.getScalableVectorType(ElementType, NumElements);
10196     break;
10197   }
10198   case 'V': {
10199     char *End;
10200     unsigned NumElements = strtoul(Str, &End, 10);
10201     assert(End != Str && "Missing vector size");
10202     Str = End;
10203 
10204     QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
10205                                              RequiresICE, false);
10206     assert(!RequiresICE && "Can't require vector ICE");
10207 
10208     // TODO: No way to make AltiVec vectors in builtins yet.
10209     Type = Context.getVectorType(ElementType, NumElements,
10210                                  VectorType::GenericVector);
10211     break;
10212   }
10213   case 'E': {
10214     char *End;
10215 
10216     unsigned NumElements = strtoul(Str, &End, 10);
10217     assert(End != Str && "Missing vector size");
10218 
10219     Str = End;
10220 
10221     QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
10222                                              false);
10223     Type = Context.getExtVectorType(ElementType, NumElements);
10224     break;
10225   }
10226   case 'X': {
10227     QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
10228                                              false);
10229     assert(!RequiresICE && "Can't require complex ICE");
10230     Type = Context.getComplexType(ElementType);
10231     break;
10232   }
10233   case 'Y':
10234     Type = Context.getPointerDiffType();
10235     break;
10236   case 'P':
10237     Type = Context.getFILEType();
10238     if (Type.isNull()) {
10239       Error = ASTContext::GE_Missing_stdio;
10240       return {};
10241     }
10242     break;
10243   case 'J':
10244     if (Signed)
10245       Type = Context.getsigjmp_bufType();
10246     else
10247       Type = Context.getjmp_bufType();
10248 
10249     if (Type.isNull()) {
10250       Error = ASTContext::GE_Missing_setjmp;
10251       return {};
10252     }
10253     break;
10254   case 'K':
10255     assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
10256     Type = Context.getucontext_tType();
10257 
10258     if (Type.isNull()) {
10259       Error = ASTContext::GE_Missing_ucontext;
10260       return {};
10261     }
10262     break;
10263   case 'p':
10264     Type = Context.getProcessIDType();
10265     break;
10266   }
10267 
10268   // If there are modifiers and if we're allowed to parse them, go for it.
10269   Done = !AllowTypeModifiers;
10270   while (!Done) {
10271     switch (char c = *Str++) {
10272     default: Done = true; --Str; break;
10273     case '*':
10274     case '&': {
10275       // Both pointers and references can have their pointee types
10276       // qualified with an address space.
10277       char *End;
10278       unsigned AddrSpace = strtoul(Str, &End, 10);
10279       if (End != Str) {
10280         // Note AddrSpace == 0 is not the same as an unspecified address space.
10281         Type = Context.getAddrSpaceQualType(
10282           Type,
10283           Context.getLangASForBuiltinAddressSpace(AddrSpace));
10284         Str = End;
10285       }
10286       if (c == '*')
10287         Type = Context.getPointerType(Type);
10288       else
10289         Type = Context.getLValueReferenceType(Type);
10290       break;
10291     }
10292     // FIXME: There's no way to have a built-in with an rvalue ref arg.
10293     case 'C':
10294       Type = Type.withConst();
10295       break;
10296     case 'D':
10297       Type = Context.getVolatileType(Type);
10298       break;
10299     case 'R':
10300       Type = Type.withRestrict();
10301       break;
10302     }
10303   }
10304 
10305   assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
10306          "Integer constant 'I' type must be an integer");
10307 
10308   return Type;
10309 }
10310 
10311 /// GetBuiltinType - Return the type for the specified builtin.
10312 QualType ASTContext::GetBuiltinType(unsigned Id,
10313                                     GetBuiltinTypeError &Error,
10314                                     unsigned *IntegerConstantArgs) const {
10315   const char *TypeStr = BuiltinInfo.getTypeString(Id);
10316   if (TypeStr[0] == '\0') {
10317     Error = GE_Missing_type;
10318     return {};
10319   }
10320 
10321   SmallVector<QualType, 8> ArgTypes;
10322 
10323   bool RequiresICE = false;
10324   Error = GE_None;
10325   QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
10326                                        RequiresICE, true);
10327   if (Error != GE_None)
10328     return {};
10329 
10330   assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
10331 
10332   while (TypeStr[0] && TypeStr[0] != '.') {
10333     QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
10334     if (Error != GE_None)
10335       return {};
10336 
10337     // If this argument is required to be an IntegerConstantExpression and the
10338     // caller cares, fill in the bitmask we return.
10339     if (RequiresICE && IntegerConstantArgs)
10340       *IntegerConstantArgs |= 1 << ArgTypes.size();
10341 
10342     // Do array -> pointer decay.  The builtin should use the decayed type.
10343     if (Ty->isArrayType())
10344       Ty = getArrayDecayedType(Ty);
10345 
10346     ArgTypes.push_back(Ty);
10347   }
10348 
10349   if (Id == Builtin::BI__GetExceptionInfo)
10350     return {};
10351 
10352   assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
10353          "'.' should only occur at end of builtin type list!");
10354 
10355   bool Variadic = (TypeStr[0] == '.');
10356 
10357   FunctionType::ExtInfo EI(getDefaultCallingConvention(
10358       Variadic, /*IsCXXMethod=*/false, /*IsBuiltin=*/true));
10359   if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
10360 
10361 
10362   // We really shouldn't be making a no-proto type here.
10363   if (ArgTypes.empty() && Variadic && !getLangOpts().CPlusPlus)
10364     return getFunctionNoProtoType(ResType, EI);
10365 
10366   FunctionProtoType::ExtProtoInfo EPI;
10367   EPI.ExtInfo = EI;
10368   EPI.Variadic = Variadic;
10369   if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id))
10370     EPI.ExceptionSpec.Type =
10371         getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
10372 
10373   return getFunctionType(ResType, ArgTypes, EPI);
10374 }
10375 
10376 static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
10377                                              const FunctionDecl *FD) {
10378   if (!FD->isExternallyVisible())
10379     return GVA_Internal;
10380 
10381   // Non-user-provided functions get emitted as weak definitions with every
10382   // use, no matter whether they've been explicitly instantiated etc.
10383   if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
10384     if (!MD->isUserProvided())
10385       return GVA_DiscardableODR;
10386 
10387   GVALinkage External;
10388   switch (FD->getTemplateSpecializationKind()) {
10389   case TSK_Undeclared:
10390   case TSK_ExplicitSpecialization:
10391     External = GVA_StrongExternal;
10392     break;
10393 
10394   case TSK_ExplicitInstantiationDefinition:
10395     return GVA_StrongODR;
10396 
10397   // C++11 [temp.explicit]p10:
10398   //   [ Note: The intent is that an inline function that is the subject of
10399   //   an explicit instantiation declaration will still be implicitly
10400   //   instantiated when used so that the body can be considered for
10401   //   inlining, but that no out-of-line copy of the inline function would be
10402   //   generated in the translation unit. -- end note ]
10403   case TSK_ExplicitInstantiationDeclaration:
10404     return GVA_AvailableExternally;
10405 
10406   case TSK_ImplicitInstantiation:
10407     External = GVA_DiscardableODR;
10408     break;
10409   }
10410 
10411   if (!FD->isInlined())
10412     return External;
10413 
10414   if ((!Context.getLangOpts().CPlusPlus &&
10415        !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
10416        !FD->hasAttr<DLLExportAttr>()) ||
10417       FD->hasAttr<GNUInlineAttr>()) {
10418     // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
10419 
10420     // GNU or C99 inline semantics. Determine whether this symbol should be
10421     // externally visible.
10422     if (FD->isInlineDefinitionExternallyVisible())
10423       return External;
10424 
10425     // C99 inline semantics, where the symbol is not externally visible.
10426     return GVA_AvailableExternally;
10427   }
10428 
10429   // Functions specified with extern and inline in -fms-compatibility mode
10430   // forcibly get emitted.  While the body of the function cannot be later
10431   // replaced, the function definition cannot be discarded.
10432   if (FD->isMSExternInline())
10433     return GVA_StrongODR;
10434 
10435   return GVA_DiscardableODR;
10436 }
10437 
10438 static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context,
10439                                                 const Decl *D, GVALinkage L) {
10440   // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
10441   // dllexport/dllimport on inline functions.
10442   if (D->hasAttr<DLLImportAttr>()) {
10443     if (L == GVA_DiscardableODR || L == GVA_StrongODR)
10444       return GVA_AvailableExternally;
10445   } else if (D->hasAttr<DLLExportAttr>()) {
10446     if (L == GVA_DiscardableODR)
10447       return GVA_StrongODR;
10448   } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice) {
10449     // Device-side functions with __global__ attribute must always be
10450     // visible externally so they can be launched from host.
10451     if (D->hasAttr<CUDAGlobalAttr>() &&
10452         (L == GVA_DiscardableODR || L == GVA_Internal))
10453       return GVA_StrongODR;
10454     // Single source offloading languages like CUDA/HIP need to be able to
10455     // access static device variables from host code of the same compilation
10456     // unit. This is done by externalizing the static variable.
10457     if (Context.shouldExternalizeStaticVar(D))
10458       return GVA_StrongExternal;
10459   }
10460   return L;
10461 }
10462 
10463 /// Adjust the GVALinkage for a declaration based on what an external AST source
10464 /// knows about whether there can be other definitions of this declaration.
10465 static GVALinkage
10466 adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D,
10467                                           GVALinkage L) {
10468   ExternalASTSource *Source = Ctx.getExternalSource();
10469   if (!Source)
10470     return L;
10471 
10472   switch (Source->hasExternalDefinitions(D)) {
10473   case ExternalASTSource::EK_Never:
10474     // Other translation units rely on us to provide the definition.
10475     if (L == GVA_DiscardableODR)
10476       return GVA_StrongODR;
10477     break;
10478 
10479   case ExternalASTSource::EK_Always:
10480     return GVA_AvailableExternally;
10481 
10482   case ExternalASTSource::EK_ReplyHazy:
10483     break;
10484   }
10485   return L;
10486 }
10487 
10488 GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
10489   return adjustGVALinkageForExternalDefinitionKind(*this, FD,
10490            adjustGVALinkageForAttributes(*this, FD,
10491              basicGVALinkageForFunction(*this, FD)));
10492 }
10493 
10494 static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
10495                                              const VarDecl *VD) {
10496   if (!VD->isExternallyVisible())
10497     return GVA_Internal;
10498 
10499   if (VD->isStaticLocal()) {
10500     const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
10501     while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
10502       LexicalContext = LexicalContext->getLexicalParent();
10503 
10504     // ObjC Blocks can create local variables that don't have a FunctionDecl
10505     // LexicalContext.
10506     if (!LexicalContext)
10507       return GVA_DiscardableODR;
10508 
10509     // Otherwise, let the static local variable inherit its linkage from the
10510     // nearest enclosing function.
10511     auto StaticLocalLinkage =
10512         Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
10513 
10514     // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
10515     // be emitted in any object with references to the symbol for the object it
10516     // contains, whether inline or out-of-line."
10517     // Similar behavior is observed with MSVC. An alternative ABI could use
10518     // StrongODR/AvailableExternally to match the function, but none are
10519     // known/supported currently.
10520     if (StaticLocalLinkage == GVA_StrongODR ||
10521         StaticLocalLinkage == GVA_AvailableExternally)
10522       return GVA_DiscardableODR;
10523     return StaticLocalLinkage;
10524   }
10525 
10526   // MSVC treats in-class initialized static data members as definitions.
10527   // By giving them non-strong linkage, out-of-line definitions won't
10528   // cause link errors.
10529   if (Context.isMSStaticDataMemberInlineDefinition(VD))
10530     return GVA_DiscardableODR;
10531 
10532   // Most non-template variables have strong linkage; inline variables are
10533   // linkonce_odr or (occasionally, for compatibility) weak_odr.
10534   GVALinkage StrongLinkage;
10535   switch (Context.getInlineVariableDefinitionKind(VD)) {
10536   case ASTContext::InlineVariableDefinitionKind::None:
10537     StrongLinkage = GVA_StrongExternal;
10538     break;
10539   case ASTContext::InlineVariableDefinitionKind::Weak:
10540   case ASTContext::InlineVariableDefinitionKind::WeakUnknown:
10541     StrongLinkage = GVA_DiscardableODR;
10542     break;
10543   case ASTContext::InlineVariableDefinitionKind::Strong:
10544     StrongLinkage = GVA_StrongODR;
10545     break;
10546   }
10547 
10548   switch (VD->getTemplateSpecializationKind()) {
10549   case TSK_Undeclared:
10550     return StrongLinkage;
10551 
10552   case TSK_ExplicitSpecialization:
10553     return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
10554                    VD->isStaticDataMember()
10555                ? GVA_StrongODR
10556                : StrongLinkage;
10557 
10558   case TSK_ExplicitInstantiationDefinition:
10559     return GVA_StrongODR;
10560 
10561   case TSK_ExplicitInstantiationDeclaration:
10562     return GVA_AvailableExternally;
10563 
10564   case TSK_ImplicitInstantiation:
10565     return GVA_DiscardableODR;
10566   }
10567 
10568   llvm_unreachable("Invalid Linkage!");
10569 }
10570 
10571 GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
10572   return adjustGVALinkageForExternalDefinitionKind(*this, VD,
10573            adjustGVALinkageForAttributes(*this, VD,
10574              basicGVALinkageForVariable(*this, VD)));
10575 }
10576 
10577 bool ASTContext::DeclMustBeEmitted(const Decl *D) {
10578   if (const auto *VD = dyn_cast<VarDecl>(D)) {
10579     if (!VD->isFileVarDecl())
10580       return false;
10581     // Global named register variables (GNU extension) are never emitted.
10582     if (VD->getStorageClass() == SC_Register)
10583       return false;
10584     if (VD->getDescribedVarTemplate() ||
10585         isa<VarTemplatePartialSpecializationDecl>(VD))
10586       return false;
10587   } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
10588     // We never need to emit an uninstantiated function template.
10589     if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
10590       return false;
10591   } else if (isa<PragmaCommentDecl>(D))
10592     return true;
10593   else if (isa<PragmaDetectMismatchDecl>(D))
10594     return true;
10595   else if (isa<OMPRequiresDecl>(D))
10596     return true;
10597   else if (isa<OMPThreadPrivateDecl>(D))
10598     return !D->getDeclContext()->isDependentContext();
10599   else if (isa<OMPAllocateDecl>(D))
10600     return !D->getDeclContext()->isDependentContext();
10601   else if (isa<OMPDeclareReductionDecl>(D) || isa<OMPDeclareMapperDecl>(D))
10602     return !D->getDeclContext()->isDependentContext();
10603   else if (isa<ImportDecl>(D))
10604     return true;
10605   else
10606     return false;
10607 
10608   // If this is a member of a class template, we do not need to emit it.
10609   if (D->getDeclContext()->isDependentContext())
10610     return false;
10611 
10612   // Weak references don't produce any output by themselves.
10613   if (D->hasAttr<WeakRefAttr>())
10614     return false;
10615 
10616   // Aliases and used decls are required.
10617   if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
10618     return true;
10619 
10620   if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
10621     // Forward declarations aren't required.
10622     if (!FD->doesThisDeclarationHaveABody())
10623       return FD->doesDeclarationForceExternallyVisibleDefinition();
10624 
10625     // Constructors and destructors are required.
10626     if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
10627       return true;
10628 
10629     // The key function for a class is required.  This rule only comes
10630     // into play when inline functions can be key functions, though.
10631     if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
10632       if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
10633         const CXXRecordDecl *RD = MD->getParent();
10634         if (MD->isOutOfLine() && RD->isDynamicClass()) {
10635           const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
10636           if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
10637             return true;
10638         }
10639       }
10640     }
10641 
10642     GVALinkage Linkage = GetGVALinkageForFunction(FD);
10643 
10644     // static, static inline, always_inline, and extern inline functions can
10645     // always be deferred.  Normal inline functions can be deferred in C99/C++.
10646     // Implicit template instantiations can also be deferred in C++.
10647     return !isDiscardableGVALinkage(Linkage);
10648   }
10649 
10650   const auto *VD = cast<VarDecl>(D);
10651   assert(VD->isFileVarDecl() && "Expected file scoped var");
10652 
10653   // If the decl is marked as `declare target to`, it should be emitted for the
10654   // host and for the device.
10655   if (LangOpts.OpenMP &&
10656       OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
10657     return true;
10658 
10659   if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
10660       !isMSStaticDataMemberInlineDefinition(VD))
10661     return false;
10662 
10663   // Variables that can be needed in other TUs are required.
10664   auto Linkage = GetGVALinkageForVariable(VD);
10665   if (!isDiscardableGVALinkage(Linkage))
10666     return true;
10667 
10668   // We never need to emit a variable that is available in another TU.
10669   if (Linkage == GVA_AvailableExternally)
10670     return false;
10671 
10672   // Variables that have destruction with side-effects are required.
10673   if (VD->needsDestruction(*this))
10674     return true;
10675 
10676   // Variables that have initialization with side-effects are required.
10677   if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
10678       // We can get a value-dependent initializer during error recovery.
10679       (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
10680     return true;
10681 
10682   // Likewise, variables with tuple-like bindings are required if their
10683   // bindings have side-effects.
10684   if (const auto *DD = dyn_cast<DecompositionDecl>(VD))
10685     for (const auto *BD : DD->bindings())
10686       if (const auto *BindingVD = BD->getHoldingVar())
10687         if (DeclMustBeEmitted(BindingVD))
10688           return true;
10689 
10690   return false;
10691 }
10692 
10693 void ASTContext::forEachMultiversionedFunctionVersion(
10694     const FunctionDecl *FD,
10695     llvm::function_ref<void(FunctionDecl *)> Pred) const {
10696   assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
10697   llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
10698   FD = FD->getMostRecentDecl();
10699   for (auto *CurDecl :
10700        FD->getDeclContext()->getRedeclContext()->lookup(FD->getDeclName())) {
10701     FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl();
10702     if (CurFD && hasSameType(CurFD->getType(), FD->getType()) &&
10703         std::end(SeenDecls) == llvm::find(SeenDecls, CurFD)) {
10704       SeenDecls.insert(CurFD);
10705       Pred(CurFD);
10706     }
10707   }
10708 }
10709 
10710 CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
10711                                                     bool IsCXXMethod,
10712                                                     bool IsBuiltin) const {
10713   // Pass through to the C++ ABI object
10714   if (IsCXXMethod)
10715     return ABI->getDefaultMethodCallConv(IsVariadic);
10716 
10717   // Builtins ignore user-specified default calling convention and remain the
10718   // Target's default calling convention.
10719   if (!IsBuiltin) {
10720     switch (LangOpts.getDefaultCallingConv()) {
10721     case LangOptions::DCC_None:
10722       break;
10723     case LangOptions::DCC_CDecl:
10724       return CC_C;
10725     case LangOptions::DCC_FastCall:
10726       if (getTargetInfo().hasFeature("sse2") && !IsVariadic)
10727         return CC_X86FastCall;
10728       break;
10729     case LangOptions::DCC_StdCall:
10730       if (!IsVariadic)
10731         return CC_X86StdCall;
10732       break;
10733     case LangOptions::DCC_VectorCall:
10734       // __vectorcall cannot be applied to variadic functions.
10735       if (!IsVariadic)
10736         return CC_X86VectorCall;
10737       break;
10738     case LangOptions::DCC_RegCall:
10739       // __regcall cannot be applied to variadic functions.
10740       if (!IsVariadic)
10741         return CC_X86RegCall;
10742       break;
10743     }
10744   }
10745   return Target->getDefaultCallingConv();
10746 }
10747 
10748 bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
10749   // Pass through to the C++ ABI object
10750   return ABI->isNearlyEmpty(RD);
10751 }
10752 
10753 VTableContextBase *ASTContext::getVTableContext() {
10754   if (!VTContext.get()) {
10755     auto ABI = Target->getCXXABI();
10756     if (ABI.isMicrosoft())
10757       VTContext.reset(new MicrosoftVTableContext(*this));
10758     else {
10759       auto ComponentLayout = getLangOpts().RelativeCXXABIVTables
10760                                  ? ItaniumVTableContext::Relative
10761                                  : ItaniumVTableContext::Pointer;
10762       VTContext.reset(new ItaniumVTableContext(*this, ComponentLayout));
10763     }
10764   }
10765   return VTContext.get();
10766 }
10767 
10768 MangleContext *ASTContext::createMangleContext(const TargetInfo *T) {
10769   if (!T)
10770     T = Target;
10771   switch (T->getCXXABI().getKind()) {
10772   case TargetCXXABI::Fuchsia:
10773   case TargetCXXABI::GenericAArch64:
10774   case TargetCXXABI::GenericItanium:
10775   case TargetCXXABI::GenericARM:
10776   case TargetCXXABI::GenericMIPS:
10777   case TargetCXXABI::iOS:
10778   case TargetCXXABI::iOS64:
10779   case TargetCXXABI::WebAssembly:
10780   case TargetCXXABI::WatchOS:
10781   case TargetCXXABI::XL:
10782     return ItaniumMangleContext::create(*this, getDiagnostics());
10783   case TargetCXXABI::Microsoft:
10784     return MicrosoftMangleContext::create(*this, getDiagnostics());
10785   }
10786   llvm_unreachable("Unsupported ABI");
10787 }
10788 
10789 CXXABI::~CXXABI() = default;
10790 
10791 size_t ASTContext::getSideTableAllocatedMemory() const {
10792   return ASTRecordLayouts.getMemorySize() +
10793          llvm::capacity_in_bytes(ObjCLayouts) +
10794          llvm::capacity_in_bytes(KeyFunctions) +
10795          llvm::capacity_in_bytes(ObjCImpls) +
10796          llvm::capacity_in_bytes(BlockVarCopyInits) +
10797          llvm::capacity_in_bytes(DeclAttrs) +
10798          llvm::capacity_in_bytes(TemplateOrInstantiation) +
10799          llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
10800          llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
10801          llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
10802          llvm::capacity_in_bytes(OverriddenMethods) +
10803          llvm::capacity_in_bytes(Types) +
10804          llvm::capacity_in_bytes(VariableArrayTypes);
10805 }
10806 
10807 /// getIntTypeForBitwidth -
10808 /// sets integer QualTy according to specified details:
10809 /// bitwidth, signed/unsigned.
10810 /// Returns empty type if there is no appropriate target types.
10811 QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
10812                                            unsigned Signed) const {
10813   TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
10814   CanQualType QualTy = getFromTargetType(Ty);
10815   if (!QualTy && DestWidth == 128)
10816     return Signed ? Int128Ty : UnsignedInt128Ty;
10817   return QualTy;
10818 }
10819 
10820 /// getRealTypeForBitwidth -
10821 /// sets floating point QualTy according to specified bitwidth.
10822 /// Returns empty type if there is no appropriate target types.
10823 QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth,
10824                                             bool ExplicitIEEE) const {
10825   TargetInfo::RealType Ty =
10826       getTargetInfo().getRealTypeByWidth(DestWidth, ExplicitIEEE);
10827   switch (Ty) {
10828   case TargetInfo::Float:
10829     return FloatTy;
10830   case TargetInfo::Double:
10831     return DoubleTy;
10832   case TargetInfo::LongDouble:
10833     return LongDoubleTy;
10834   case TargetInfo::Float128:
10835     return Float128Ty;
10836   case TargetInfo::NoFloat:
10837     return {};
10838   }
10839 
10840   llvm_unreachable("Unhandled TargetInfo::RealType value");
10841 }
10842 
10843 void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
10844   if (Number > 1)
10845     MangleNumbers[ND] = Number;
10846 }
10847 
10848 unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
10849   auto I = MangleNumbers.find(ND);
10850   return I != MangleNumbers.end() ? I->second : 1;
10851 }
10852 
10853 void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
10854   if (Number > 1)
10855     StaticLocalNumbers[VD] = Number;
10856 }
10857 
10858 unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
10859   auto I = StaticLocalNumbers.find(VD);
10860   return I != StaticLocalNumbers.end() ? I->second : 1;
10861 }
10862 
10863 MangleNumberingContext &
10864 ASTContext::getManglingNumberContext(const DeclContext *DC) {
10865   assert(LangOpts.CPlusPlus);  // We don't need mangling numbers for plain C.
10866   std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
10867   if (!MCtx)
10868     MCtx = createMangleNumberingContext();
10869   return *MCtx;
10870 }
10871 
10872 MangleNumberingContext &
10873 ASTContext::getManglingNumberContext(NeedExtraManglingDecl_t, const Decl *D) {
10874   assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
10875   std::unique_ptr<MangleNumberingContext> &MCtx =
10876       ExtraMangleNumberingContexts[D];
10877   if (!MCtx)
10878     MCtx = createMangleNumberingContext();
10879   return *MCtx;
10880 }
10881 
10882 std::unique_ptr<MangleNumberingContext>
10883 ASTContext::createMangleNumberingContext() const {
10884   return ABI->createMangleNumberingContext();
10885 }
10886 
10887 const CXXConstructorDecl *
10888 ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
10889   return ABI->getCopyConstructorForExceptionObject(
10890       cast<CXXRecordDecl>(RD->getFirstDecl()));
10891 }
10892 
10893 void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
10894                                                       CXXConstructorDecl *CD) {
10895   return ABI->addCopyConstructorForExceptionObject(
10896       cast<CXXRecordDecl>(RD->getFirstDecl()),
10897       cast<CXXConstructorDecl>(CD->getFirstDecl()));
10898 }
10899 
10900 void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
10901                                                  TypedefNameDecl *DD) {
10902   return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
10903 }
10904 
10905 TypedefNameDecl *
10906 ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
10907   return ABI->getTypedefNameForUnnamedTagDecl(TD);
10908 }
10909 
10910 void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
10911                                                 DeclaratorDecl *DD) {
10912   return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
10913 }
10914 
10915 DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
10916   return ABI->getDeclaratorForUnnamedTagDecl(TD);
10917 }
10918 
10919 void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
10920   ParamIndices[D] = index;
10921 }
10922 
10923 unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
10924   ParameterIndexTable::const_iterator I = ParamIndices.find(D);
10925   assert(I != ParamIndices.end() &&
10926          "ParmIndices lacks entry set by ParmVarDecl");
10927   return I->second;
10928 }
10929 
10930 QualType ASTContext::getStringLiteralArrayType(QualType EltTy,
10931                                                unsigned Length) const {
10932   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
10933   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
10934     EltTy = EltTy.withConst();
10935 
10936   EltTy = adjustStringLiteralBaseType(EltTy);
10937 
10938   // Get an array type for the string, according to C99 6.4.5. This includes
10939   // the null terminator character.
10940   return getConstantArrayType(EltTy, llvm::APInt(32, Length + 1), nullptr,
10941                               ArrayType::Normal, /*IndexTypeQuals*/ 0);
10942 }
10943 
10944 StringLiteral *
10945 ASTContext::getPredefinedStringLiteralFromCache(StringRef Key) const {
10946   StringLiteral *&Result = StringLiteralCache[Key];
10947   if (!Result)
10948     Result = StringLiteral::Create(
10949         *this, Key, StringLiteral::Ascii,
10950         /*Pascal*/ false, getStringLiteralArrayType(CharTy, Key.size()),
10951         SourceLocation());
10952   return Result;
10953 }
10954 
10955 MSGuidDecl *
10956 ASTContext::getMSGuidDecl(MSGuidDecl::Parts Parts) const {
10957   assert(MSGuidTagDecl && "building MS GUID without MS extensions?");
10958 
10959   llvm::FoldingSetNodeID ID;
10960   MSGuidDecl::Profile(ID, Parts);
10961 
10962   void *InsertPos;
10963   if (MSGuidDecl *Existing = MSGuidDecls.FindNodeOrInsertPos(ID, InsertPos))
10964     return Existing;
10965 
10966   QualType GUIDType = getMSGuidType().withConst();
10967   MSGuidDecl *New = MSGuidDecl::Create(*this, GUIDType, Parts);
10968   MSGuidDecls.InsertNode(New, InsertPos);
10969   return New;
10970 }
10971 
10972 TemplateParamObjectDecl *
10973 ASTContext::getTemplateParamObjectDecl(QualType T, const APValue &V) const {
10974   assert(T->isRecordType() && "template param object of unexpected type");
10975 
10976   // C++ [temp.param]p8:
10977   //   [...] a static storage duration object of type 'const T' [...]
10978   T.addConst();
10979 
10980   llvm::FoldingSetNodeID ID;
10981   TemplateParamObjectDecl::Profile(ID, T, V);
10982 
10983   void *InsertPos;
10984   if (TemplateParamObjectDecl *Existing =
10985           TemplateParamObjectDecls.FindNodeOrInsertPos(ID, InsertPos))
10986     return Existing;
10987 
10988   TemplateParamObjectDecl *New = TemplateParamObjectDecl::Create(*this, T, V);
10989   TemplateParamObjectDecls.InsertNode(New, InsertPos);
10990   return New;
10991 }
10992 
10993 bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
10994   const llvm::Triple &T = getTargetInfo().getTriple();
10995   if (!T.isOSDarwin())
10996     return false;
10997 
10998   if (!(T.isiOS() && T.isOSVersionLT(7)) &&
10999       !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
11000     return false;
11001 
11002   QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
11003   CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
11004   uint64_t Size = sizeChars.getQuantity();
11005   CharUnits alignChars = getTypeAlignInChars(AtomicTy);
11006   unsigned Align = alignChars.getQuantity();
11007   unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
11008   return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
11009 }
11010 
11011 bool
11012 ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
11013                                 const ObjCMethodDecl *MethodImpl) {
11014   // No point trying to match an unavailable/deprecated mothod.
11015   if (MethodDecl->hasAttr<UnavailableAttr>()
11016       || MethodDecl->hasAttr<DeprecatedAttr>())
11017     return false;
11018   if (MethodDecl->getObjCDeclQualifier() !=
11019       MethodImpl->getObjCDeclQualifier())
11020     return false;
11021   if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
11022     return false;
11023 
11024   if (MethodDecl->param_size() != MethodImpl->param_size())
11025     return false;
11026 
11027   for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
11028        IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
11029        EF = MethodDecl->param_end();
11030        IM != EM && IF != EF; ++IM, ++IF) {
11031     const ParmVarDecl *DeclVar = (*IF);
11032     const ParmVarDecl *ImplVar = (*IM);
11033     if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
11034       return false;
11035     if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
11036       return false;
11037   }
11038 
11039   return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
11040 }
11041 
11042 uint64_t ASTContext::getTargetNullPointerValue(QualType QT) const {
11043   LangAS AS;
11044   if (QT->getUnqualifiedDesugaredType()->isNullPtrType())
11045     AS = LangAS::Default;
11046   else
11047     AS = QT->getPointeeType().getAddressSpace();
11048 
11049   return getTargetInfo().getNullPointerValue(AS);
11050 }
11051 
11052 unsigned ASTContext::getTargetAddressSpace(LangAS AS) const {
11053   if (isTargetAddressSpace(AS))
11054     return toTargetAddressSpace(AS);
11055   else
11056     return (*AddrSpaceMap)[(unsigned)AS];
11057 }
11058 
11059 QualType ASTContext::getCorrespondingSaturatedType(QualType Ty) const {
11060   assert(Ty->isFixedPointType());
11061 
11062   if (Ty->isSaturatedFixedPointType()) return Ty;
11063 
11064   switch (Ty->castAs<BuiltinType>()->getKind()) {
11065     default:
11066       llvm_unreachable("Not a fixed point type!");
11067     case BuiltinType::ShortAccum:
11068       return SatShortAccumTy;
11069     case BuiltinType::Accum:
11070       return SatAccumTy;
11071     case BuiltinType::LongAccum:
11072       return SatLongAccumTy;
11073     case BuiltinType::UShortAccum:
11074       return SatUnsignedShortAccumTy;
11075     case BuiltinType::UAccum:
11076       return SatUnsignedAccumTy;
11077     case BuiltinType::ULongAccum:
11078       return SatUnsignedLongAccumTy;
11079     case BuiltinType::ShortFract:
11080       return SatShortFractTy;
11081     case BuiltinType::Fract:
11082       return SatFractTy;
11083     case BuiltinType::LongFract:
11084       return SatLongFractTy;
11085     case BuiltinType::UShortFract:
11086       return SatUnsignedShortFractTy;
11087     case BuiltinType::UFract:
11088       return SatUnsignedFractTy;
11089     case BuiltinType::ULongFract:
11090       return SatUnsignedLongFractTy;
11091   }
11092 }
11093 
11094 LangAS ASTContext::getLangASForBuiltinAddressSpace(unsigned AS) const {
11095   if (LangOpts.OpenCL)
11096     return getTargetInfo().getOpenCLBuiltinAddressSpace(AS);
11097 
11098   if (LangOpts.CUDA)
11099     return getTargetInfo().getCUDABuiltinAddressSpace(AS);
11100 
11101   return getLangASFromTargetAS(AS);
11102 }
11103 
11104 // Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
11105 // doesn't include ASTContext.h
11106 template
11107 clang::LazyGenerationalUpdatePtr<
11108     const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
11109 clang::LazyGenerationalUpdatePtr<
11110     const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
11111         const clang::ASTContext &Ctx, Decl *Value);
11112 
11113 unsigned char ASTContext::getFixedPointScale(QualType Ty) const {
11114   assert(Ty->isFixedPointType());
11115 
11116   const TargetInfo &Target = getTargetInfo();
11117   switch (Ty->castAs<BuiltinType>()->getKind()) {
11118     default:
11119       llvm_unreachable("Not a fixed point type!");
11120     case BuiltinType::ShortAccum:
11121     case BuiltinType::SatShortAccum:
11122       return Target.getShortAccumScale();
11123     case BuiltinType::Accum:
11124     case BuiltinType::SatAccum:
11125       return Target.getAccumScale();
11126     case BuiltinType::LongAccum:
11127     case BuiltinType::SatLongAccum:
11128       return Target.getLongAccumScale();
11129     case BuiltinType::UShortAccum:
11130     case BuiltinType::SatUShortAccum:
11131       return Target.getUnsignedShortAccumScale();
11132     case BuiltinType::UAccum:
11133     case BuiltinType::SatUAccum:
11134       return Target.getUnsignedAccumScale();
11135     case BuiltinType::ULongAccum:
11136     case BuiltinType::SatULongAccum:
11137       return Target.getUnsignedLongAccumScale();
11138     case BuiltinType::ShortFract:
11139     case BuiltinType::SatShortFract:
11140       return Target.getShortFractScale();
11141     case BuiltinType::Fract:
11142     case BuiltinType::SatFract:
11143       return Target.getFractScale();
11144     case BuiltinType::LongFract:
11145     case BuiltinType::SatLongFract:
11146       return Target.getLongFractScale();
11147     case BuiltinType::UShortFract:
11148     case BuiltinType::SatUShortFract:
11149       return Target.getUnsignedShortFractScale();
11150     case BuiltinType::UFract:
11151     case BuiltinType::SatUFract:
11152       return Target.getUnsignedFractScale();
11153     case BuiltinType::ULongFract:
11154     case BuiltinType::SatULongFract:
11155       return Target.getUnsignedLongFractScale();
11156   }
11157 }
11158 
11159 unsigned char ASTContext::getFixedPointIBits(QualType Ty) const {
11160   assert(Ty->isFixedPointType());
11161 
11162   const TargetInfo &Target = getTargetInfo();
11163   switch (Ty->castAs<BuiltinType>()->getKind()) {
11164     default:
11165       llvm_unreachable("Not a fixed point type!");
11166     case BuiltinType::ShortAccum:
11167     case BuiltinType::SatShortAccum:
11168       return Target.getShortAccumIBits();
11169     case BuiltinType::Accum:
11170     case BuiltinType::SatAccum:
11171       return Target.getAccumIBits();
11172     case BuiltinType::LongAccum:
11173     case BuiltinType::SatLongAccum:
11174       return Target.getLongAccumIBits();
11175     case BuiltinType::UShortAccum:
11176     case BuiltinType::SatUShortAccum:
11177       return Target.getUnsignedShortAccumIBits();
11178     case BuiltinType::UAccum:
11179     case BuiltinType::SatUAccum:
11180       return Target.getUnsignedAccumIBits();
11181     case BuiltinType::ULongAccum:
11182     case BuiltinType::SatULongAccum:
11183       return Target.getUnsignedLongAccumIBits();
11184     case BuiltinType::ShortFract:
11185     case BuiltinType::SatShortFract:
11186     case BuiltinType::Fract:
11187     case BuiltinType::SatFract:
11188     case BuiltinType::LongFract:
11189     case BuiltinType::SatLongFract:
11190     case BuiltinType::UShortFract:
11191     case BuiltinType::SatUShortFract:
11192     case BuiltinType::UFract:
11193     case BuiltinType::SatUFract:
11194     case BuiltinType::ULongFract:
11195     case BuiltinType::SatULongFract:
11196       return 0;
11197   }
11198 }
11199 
11200 llvm::FixedPointSemantics
11201 ASTContext::getFixedPointSemantics(QualType Ty) const {
11202   assert((Ty->isFixedPointType() || Ty->isIntegerType()) &&
11203          "Can only get the fixed point semantics for a "
11204          "fixed point or integer type.");
11205   if (Ty->isIntegerType())
11206     return llvm::FixedPointSemantics::GetIntegerSemantics(
11207         getIntWidth(Ty), Ty->isSignedIntegerType());
11208 
11209   bool isSigned = Ty->isSignedFixedPointType();
11210   return llvm::FixedPointSemantics(
11211       static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned,
11212       Ty->isSaturatedFixedPointType(),
11213       !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding());
11214 }
11215 
11216 llvm::APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const {
11217   assert(Ty->isFixedPointType());
11218   return llvm::APFixedPoint::getMax(getFixedPointSemantics(Ty));
11219 }
11220 
11221 llvm::APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const {
11222   assert(Ty->isFixedPointType());
11223   return llvm::APFixedPoint::getMin(getFixedPointSemantics(Ty));
11224 }
11225 
11226 QualType ASTContext::getCorrespondingSignedFixedPointType(QualType Ty) const {
11227   assert(Ty->isUnsignedFixedPointType() &&
11228          "Expected unsigned fixed point type");
11229 
11230   switch (Ty->castAs<BuiltinType>()->getKind()) {
11231   case BuiltinType::UShortAccum:
11232     return ShortAccumTy;
11233   case BuiltinType::UAccum:
11234     return AccumTy;
11235   case BuiltinType::ULongAccum:
11236     return LongAccumTy;
11237   case BuiltinType::SatUShortAccum:
11238     return SatShortAccumTy;
11239   case BuiltinType::SatUAccum:
11240     return SatAccumTy;
11241   case BuiltinType::SatULongAccum:
11242     return SatLongAccumTy;
11243   case BuiltinType::UShortFract:
11244     return ShortFractTy;
11245   case BuiltinType::UFract:
11246     return FractTy;
11247   case BuiltinType::ULongFract:
11248     return LongFractTy;
11249   case BuiltinType::SatUShortFract:
11250     return SatShortFractTy;
11251   case BuiltinType::SatUFract:
11252     return SatFractTy;
11253   case BuiltinType::SatULongFract:
11254     return SatLongFractTy;
11255   default:
11256     llvm_unreachable("Unexpected unsigned fixed point type");
11257   }
11258 }
11259 
11260 ParsedTargetAttr
11261 ASTContext::filterFunctionTargetAttrs(const TargetAttr *TD) const {
11262   assert(TD != nullptr);
11263   ParsedTargetAttr ParsedAttr = TD->parse();
11264 
11265   ParsedAttr.Features.erase(
11266       llvm::remove_if(ParsedAttr.Features,
11267                       [&](const std::string &Feat) {
11268                         return !Target->isValidFeatureName(
11269                             StringRef{Feat}.substr(1));
11270                       }),
11271       ParsedAttr.Features.end());
11272   return ParsedAttr;
11273 }
11274 
11275 void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
11276                                        const FunctionDecl *FD) const {
11277   if (FD)
11278     getFunctionFeatureMap(FeatureMap, GlobalDecl().getWithDecl(FD));
11279   else
11280     Target->initFeatureMap(FeatureMap, getDiagnostics(),
11281                            Target->getTargetOpts().CPU,
11282                            Target->getTargetOpts().Features);
11283 }
11284 
11285 // Fills in the supplied string map with the set of target features for the
11286 // passed in function.
11287 void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
11288                                        GlobalDecl GD) const {
11289   StringRef TargetCPU = Target->getTargetOpts().CPU;
11290   const FunctionDecl *FD = GD.getDecl()->getAsFunction();
11291   if (const auto *TD = FD->getAttr<TargetAttr>()) {
11292     ParsedTargetAttr ParsedAttr = filterFunctionTargetAttrs(TD);
11293 
11294     // Make a copy of the features as passed on the command line into the
11295     // beginning of the additional features from the function to override.
11296     ParsedAttr.Features.insert(
11297         ParsedAttr.Features.begin(),
11298         Target->getTargetOpts().FeaturesAsWritten.begin(),
11299         Target->getTargetOpts().FeaturesAsWritten.end());
11300 
11301     if (ParsedAttr.Architecture != "" &&
11302         Target->isValidCPUName(ParsedAttr.Architecture))
11303       TargetCPU = ParsedAttr.Architecture;
11304 
11305     // Now populate the feature map, first with the TargetCPU which is either
11306     // the default or a new one from the target attribute string. Then we'll use
11307     // the passed in features (FeaturesAsWritten) along with the new ones from
11308     // the attribute.
11309     Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU,
11310                            ParsedAttr.Features);
11311   } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) {
11312     llvm::SmallVector<StringRef, 32> FeaturesTmp;
11313     Target->getCPUSpecificCPUDispatchFeatures(
11314         SD->getCPUName(GD.getMultiVersionIndex())->getName(), FeaturesTmp);
11315     std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end());
11316     Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
11317   } else {
11318     FeatureMap = Target->getTargetOpts().FeatureMap;
11319   }
11320 }
11321 
11322 OMPTraitInfo &ASTContext::getNewOMPTraitInfo() {
11323   OMPTraitInfoVector.emplace_back(new OMPTraitInfo());
11324   return *OMPTraitInfoVector.back();
11325 }
11326 
11327 const StreamingDiagnostic &clang::
11328 operator<<(const StreamingDiagnostic &DB,
11329            const ASTContext::SectionInfo &Section) {
11330   if (Section.Decl)
11331     return DB << Section.Decl;
11332   return DB << "a prior #pragma section";
11333 }
11334 
11335 bool ASTContext::mayExternalizeStaticVar(const Decl *D) const {
11336   return !getLangOpts().GPURelocatableDeviceCode &&
11337          ((D->hasAttr<CUDADeviceAttr>() &&
11338            !D->getAttr<CUDADeviceAttr>()->isImplicit()) ||
11339           (D->hasAttr<CUDAConstantAttr>() &&
11340            !D->getAttr<CUDAConstantAttr>()->isImplicit())) &&
11341          isa<VarDecl>(D) && cast<VarDecl>(D)->isFileVarDecl() &&
11342          cast<VarDecl>(D)->getStorageClass() == SC_Static;
11343 }
11344 
11345 bool ASTContext::shouldExternalizeStaticVar(const Decl *D) const {
11346   return mayExternalizeStaticVar(D) &&
11347          CUDAStaticDeviceVarReferencedByHost.count(cast<VarDecl>(D));
11348 }
11349