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