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