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