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