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