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