Home | History | Annotate | Line # | Download | only in AST
      1 //===- ASTContext.cpp - Context to hold long-lived AST nodes --------------===//
      2 //
      3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
      4 // See https://llvm.org/LICENSE.txt for license information.
      5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
      6 //
      7 //===----------------------------------------------------------------------===//
      8 //
      9 //  This file implements the ASTContext interface.
     10 //
     11 //===----------------------------------------------------------------------===//
     12 
     13 #include "clang/AST/ASTContext.h"
     14 #include "CXXABI.h"
     15 #include "Interp/Context.h"
     16 #include "clang/AST/APValue.h"
     17 #include "clang/AST/ASTConcept.h"
     18 #include "clang/AST/ASTMutationListener.h"
     19 #include "clang/AST/ASTTypeTraits.h"
     20 #include "clang/AST/Attr.h"
     21 #include "clang/AST/AttrIterator.h"
     22 #include "clang/AST/CharUnits.h"
     23 #include "clang/AST/Comment.h"
     24 #include "clang/AST/Decl.h"
     25 #include "clang/AST/DeclBase.h"
     26 #include "clang/AST/DeclCXX.h"
     27 #include "clang/AST/DeclContextInternals.h"
     28 #include "clang/AST/DeclObjC.h"
     29 #include "clang/AST/DeclOpenMP.h"
     30 #include "clang/AST/DeclTemplate.h"
     31 #include "clang/AST/DeclarationName.h"
     32 #include "clang/AST/DependenceFlags.h"
     33 #include "clang/AST/Expr.h"
     34 #include "clang/AST/ExprCXX.h"
     35 #include "clang/AST/ExprConcepts.h"
     36 #include "clang/AST/ExternalASTSource.h"
     37 #include "clang/AST/Mangle.h"
     38 #include "clang/AST/MangleNumberingContext.h"
     39 #include "clang/AST/NestedNameSpecifier.h"
     40 #include "clang/AST/ParentMapContext.h"
     41 #include "clang/AST/RawCommentList.h"
     42 #include "clang/AST/RecordLayout.h"
     43 #include "clang/AST/Stmt.h"
     44 #include "clang/AST/TemplateBase.h"
     45 #include "clang/AST/TemplateName.h"
     46 #include "clang/AST/Type.h"
     47 #include "clang/AST/TypeLoc.h"
     48 #include "clang/AST/UnresolvedSet.h"
     49 #include "clang/AST/VTableBuilder.h"
     50 #include "clang/Basic/AddressSpaces.h"
     51 #include "clang/Basic/Builtins.h"
     52 #include "clang/Basic/CommentOptions.h"
     53 #include "clang/Basic/ExceptionSpecificationType.h"
     54 #include "clang/Basic/IdentifierTable.h"
     55 #include "clang/Basic/LLVM.h"
     56 #include "clang/Basic/LangOptions.h"
     57 #include "clang/Basic/Linkage.h"
     58 #include "clang/Basic/Module.h"
     59 #include "clang/Basic/NoSanitizeList.h"
     60 #include "clang/Basic/ObjCRuntime.h"
     61 #include "clang/Basic/SourceLocation.h"
     62 #include "clang/Basic/SourceManager.h"
     63 #include "clang/Basic/Specifiers.h"
     64 #include "clang/Basic/TargetCXXABI.h"
     65 #include "clang/Basic/TargetInfo.h"
     66 #include "clang/Basic/XRayLists.h"
     67 #include "llvm/ADT/APFixedPoint.h"
     68 #include "llvm/ADT/APInt.h"
     69 #include "llvm/ADT/APSInt.h"
     70 #include "llvm/ADT/ArrayRef.h"
     71 #include "llvm/ADT/DenseMap.h"
     72 #include "llvm/ADT/DenseSet.h"
     73 #include "llvm/ADT/FoldingSet.h"
     74 #include "llvm/ADT/None.h"
     75 #include "llvm/ADT/Optional.h"
     76 #include "llvm/ADT/PointerUnion.h"
     77 #include "llvm/ADT/STLExtras.h"
     78 #include "llvm/ADT/SmallPtrSet.h"
     79 #include "llvm/ADT/SmallVector.h"
     80 #include "llvm/ADT/StringExtras.h"
     81 #include "llvm/ADT/StringRef.h"
     82 #include "llvm/ADT/Triple.h"
     83 #include "llvm/Support/Capacity.h"
     84 #include "llvm/Support/Casting.h"
     85 #include "llvm/Support/Compiler.h"
     86 #include "llvm/Support/ErrorHandling.h"
     87 #include "llvm/Support/MD5.h"
     88 #include "llvm/Support/MathExtras.h"
     89 #include "llvm/Support/raw_ostream.h"
     90 #include <algorithm>
     91 #include <cassert>
     92 #include <cstddef>
     93 #include <cstdint>
     94 #include <cstdlib>
     95 #include <map>
     96 #include <memory>
     97 #include <string>
     98 #include <tuple>
     99 #include <utility>
    100 
    101 using namespace clang;
    102 
    103 enum FloatingRank {
    104   BFloat16Rank, Float16Rank, HalfRank, FloatRank, DoubleRank, LongDoubleRank, Float128Rank
    105 };
    106 
    107 /// \returns location that is relevant when searching for Doc comments related
    108 /// to \p D.
    109 static SourceLocation getDeclLocForCommentSearch(const Decl *D,
    110                                                  SourceManager &SourceMgr) {
    111   assert(D);
    112 
    113   // User can not attach documentation to implicit declarations.
    114   if (D->isImplicit())
    115     return {};
    116 
    117   // User can not attach documentation to implicit instantiations.
    118   if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
    119     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
    120       return {};
    121   }
    122 
    123   if (const auto *VD = dyn_cast<VarDecl>(D)) {
    124     if (VD->isStaticDataMember() &&
    125         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
    126       return {};
    127   }
    128 
    129   if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) {
    130     if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
    131       return {};
    132   }
    133 
    134   if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
    135     TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
    136     if (TSK == TSK_ImplicitInstantiation ||
    137         TSK == TSK_Undeclared)
    138       return {};
    139   }
    140 
    141   if (const auto *ED = dyn_cast<EnumDecl>(D)) {
    142     if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
    143       return {};
    144   }
    145   if (const auto *TD = dyn_cast<TagDecl>(D)) {
    146     // When tag declaration (but not definition!) is part of the
    147     // decl-specifier-seq of some other declaration, it doesn't get comment
    148     if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
    149       return {};
    150   }
    151   // TODO: handle comments for function parameters properly.
    152   if (isa<ParmVarDecl>(D))
    153     return {};
    154 
    155   // TODO: we could look up template parameter documentation in the template
    156   // documentation.
    157   if (isa<TemplateTypeParmDecl>(D) ||
    158       isa<NonTypeTemplateParmDecl>(D) ||
    159       isa<TemplateTemplateParmDecl>(D))
    160     return {};
    161 
    162   // Find declaration location.
    163   // For Objective-C declarations we generally don't expect to have multiple
    164   // declarators, thus use declaration starting location as the "declaration
    165   // location".
    166   // For all other declarations multiple declarators are used quite frequently,
    167   // so we use the location of the identifier as the "declaration location".
    168   if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
    169       isa<ObjCPropertyDecl>(D) ||
    170       isa<RedeclarableTemplateDecl>(D) ||
    171       isa<ClassTemplateSpecializationDecl>(D) ||
    172       // Allow association with Y across {} in `typedef struct X {} Y`.
    173       isa<TypedefDecl>(D))
    174     return D->getBeginLoc();
    175   else {
    176     const SourceLocation DeclLoc = D->getLocation();
    177     if (DeclLoc.isMacroID()) {
    178       if (isa<TypedefDecl>(D)) {
    179         // If location of the typedef name is in a macro, it is because being
    180         // declared via a macro. Try using declaration's starting location as
    181         // the "declaration location".
    182         return D->getBeginLoc();
    183       } else if (const auto *TD = dyn_cast<TagDecl>(D)) {
    184         // If location of the tag decl is inside a macro, but the spelling of
    185         // the tag name comes from a macro argument, it looks like a special
    186         // macro like NS_ENUM is being used to define the tag decl.  In that
    187         // case, adjust the source location to the expansion loc so that we can
    188         // attach the comment to the tag decl.
    189         if (SourceMgr.isMacroArgExpansion(DeclLoc) &&
    190             TD->isCompleteDefinition())
    191           return SourceMgr.getExpansionLoc(DeclLoc);
    192       }
    193     }
    194     return DeclLoc;
    195   }
    196 
    197   return {};
    198 }
    199 
    200 RawComment *ASTContext::getRawCommentForDeclNoCacheImpl(
    201     const Decl *D, const SourceLocation RepresentativeLocForDecl,
    202     const std::map<unsigned, RawComment *> &CommentsInTheFile) const {
    203   // If the declaration doesn't map directly to a location in a file, we
    204   // can't find the comment.
    205   if (RepresentativeLocForDecl.isInvalid() ||
    206       !RepresentativeLocForDecl.isFileID())
    207     return nullptr;
    208 
    209   // If there are no comments anywhere, we won't find anything.
    210   if (CommentsInTheFile.empty())
    211     return nullptr;
    212 
    213   // Decompose the location for the declaration and find the beginning of the
    214   // file buffer.
    215   const std::pair<FileID, unsigned> DeclLocDecomp =
    216       SourceMgr.getDecomposedLoc(RepresentativeLocForDecl);
    217 
    218   // Slow path.
    219   auto OffsetCommentBehindDecl =
    220       CommentsInTheFile.lower_bound(DeclLocDecomp.second);
    221 
    222   // First check whether we have a trailing comment.
    223   if (OffsetCommentBehindDecl != CommentsInTheFile.end()) {
    224     RawComment *CommentBehindDecl = OffsetCommentBehindDecl->second;
    225     if ((CommentBehindDecl->isDocumentation() ||
    226          LangOpts.CommentOpts.ParseAllComments) &&
    227         CommentBehindDecl->isTrailingComment() &&
    228         (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
    229          isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
    230 
    231       // Check that Doxygen trailing comment comes after the declaration, starts
    232       // on the same line and in the same file as the declaration.
    233       if (SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second) ==
    234           Comments.getCommentBeginLine(CommentBehindDecl, DeclLocDecomp.first,
    235                                        OffsetCommentBehindDecl->first)) {
    236         return CommentBehindDecl;
    237       }
    238     }
    239   }
    240 
    241   // The comment just after the declaration was not a trailing comment.
    242   // Let's look at the previous comment.
    243   if (OffsetCommentBehindDecl == CommentsInTheFile.begin())
    244     return nullptr;
    245 
    246   auto OffsetCommentBeforeDecl = --OffsetCommentBehindDecl;
    247   RawComment *CommentBeforeDecl = OffsetCommentBeforeDecl->second;
    248 
    249   // Check that we actually have a non-member Doxygen comment.
    250   if (!(CommentBeforeDecl->isDocumentation() ||
    251         LangOpts.CommentOpts.ParseAllComments) ||
    252       CommentBeforeDecl->isTrailingComment())
    253     return nullptr;
    254 
    255   // Decompose the end of the comment.
    256   const unsigned CommentEndOffset =
    257       Comments.getCommentEndOffset(CommentBeforeDecl);
    258 
    259   // Get the corresponding buffer.
    260   bool Invalid = false;
    261   const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
    262                                                &Invalid).data();
    263   if (Invalid)
    264     return nullptr;
    265 
    266   // Extract text between the comment and declaration.
    267   StringRef Text(Buffer + CommentEndOffset,
    268                  DeclLocDecomp.second - CommentEndOffset);
    269 
    270   // There should be no other declarations or preprocessor directives between
    271   // comment and declaration.
    272   if (Text.find_first_of(";{}#@") != StringRef::npos)
    273     return nullptr;
    274 
    275   return CommentBeforeDecl;
    276 }
    277 
    278 RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
    279   const SourceLocation DeclLoc = getDeclLocForCommentSearch(D, SourceMgr);
    280 
    281   // If the declaration doesn't map directly to a location in a file, we
    282   // can't find the comment.
    283   if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
    284     return nullptr;
    285 
    286   if (ExternalSource && !CommentsLoaded) {
    287     ExternalSource->ReadComments();
    288     CommentsLoaded = true;
    289   }
    290 
    291   if (Comments.empty())
    292     return nullptr;
    293 
    294   const FileID File = SourceMgr.getDecomposedLoc(DeclLoc).first;
    295   const auto CommentsInThisFile = Comments.getCommentsInFile(File);
    296   if (!CommentsInThisFile || CommentsInThisFile->empty())
    297     return nullptr;
    298 
    299   return getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile);
    300 }
    301 
    302 void ASTContext::addComment(const RawComment &RC) {
    303   assert(LangOpts.RetainCommentsFromSystemHeaders ||
    304          !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin()));
    305   Comments.addComment(RC, LangOpts.CommentOpts, BumpAlloc);
    306 }
    307 
    308 /// If we have a 'templated' declaration for a template, adjust 'D' to
    309 /// refer to the actual template.
    310 /// If we have an implicit instantiation, adjust 'D' to refer to template.
    311 static const Decl &adjustDeclToTemplate(const Decl &D) {
    312   if (const auto *FD = dyn_cast<FunctionDecl>(&D)) {
    313     // Is this function declaration part of a function template?
    314     if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
    315       return *FTD;
    316 
    317     // Nothing to do if function is not an implicit instantiation.
    318     if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
    319       return D;
    320 
    321     // Function is an implicit instantiation of a function template?
    322     if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
    323       return *FTD;
    324 
    325     // Function is instantiated from a member definition of a class template?
    326     if (const FunctionDecl *MemberDecl =
    327             FD->getInstantiatedFromMemberFunction())
    328       return *MemberDecl;
    329 
    330     return D;
    331   }
    332   if (const auto *VD = dyn_cast<VarDecl>(&D)) {
    333     // Static data member is instantiated from a member definition of a class
    334     // template?
    335     if (VD->isStaticDataMember())
    336       if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
    337         return *MemberDecl;
    338 
    339     return D;
    340   }
    341   if (const auto *CRD = dyn_cast<CXXRecordDecl>(&D)) {
    342     // Is this class declaration part of a class template?
    343     if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
    344       return *CTD;
    345 
    346     // Class is an implicit instantiation of a class template or partial
    347     // specialization?
    348     if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
    349       if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
    350         return D;
    351       llvm::PointerUnion<ClassTemplateDecl *,
    352                          ClassTemplatePartialSpecializationDecl *>
    353           PU = CTSD->getSpecializedTemplateOrPartial();
    354       return PU.is<ClassTemplateDecl *>()
    355                  ? *static_cast<const Decl *>(PU.get<ClassTemplateDecl *>())
    356                  : *static_cast<const Decl *>(
    357                        PU.get<ClassTemplatePartialSpecializationDecl *>());
    358     }
    359 
    360     // Class is instantiated from a member definition of a class template?
    361     if (const MemberSpecializationInfo *Info =
    362             CRD->getMemberSpecializationInfo())
    363       return *Info->getInstantiatedFrom();
    364 
    365     return D;
    366   }
    367   if (const auto *ED = dyn_cast<EnumDecl>(&D)) {
    368     // Enum is instantiated from a member definition of a class template?
    369     if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
    370       return *MemberDecl;
    371 
    372     return D;
    373   }
    374   // FIXME: Adjust alias templates?
    375   return D;
    376 }
    377 
    378 const RawComment *ASTContext::getRawCommentForAnyRedecl(
    379                                                 const Decl *D,
    380                                                 const Decl **OriginalDecl) const {
    381   if (!D) {
    382     if (OriginalDecl)
    383       OriginalDecl = nullptr;
    384     return nullptr;
    385   }
    386 
    387   D = &adjustDeclToTemplate(*D);
    388 
    389   // Any comment directly attached to D?
    390   {
    391     auto DeclComment = DeclRawComments.find(D);
    392     if (DeclComment != DeclRawComments.end()) {
    393       if (OriginalDecl)
    394         *OriginalDecl = D;
    395       return DeclComment->second;
    396     }
    397   }
    398 
    399   // Any comment attached to any redeclaration of D?
    400   const Decl *CanonicalD = D->getCanonicalDecl();
    401   if (!CanonicalD)
    402     return nullptr;
    403 
    404   {
    405     auto RedeclComment = RedeclChainComments.find(CanonicalD);
    406     if (RedeclComment != RedeclChainComments.end()) {
    407       if (OriginalDecl)
    408         *OriginalDecl = RedeclComment->second;
    409       auto CommentAtRedecl = DeclRawComments.find(RedeclComment->second);
    410       assert(CommentAtRedecl != DeclRawComments.end() &&
    411              "This decl is supposed to have comment attached.");
    412       return CommentAtRedecl->second;
    413     }
    414   }
    415 
    416   // Any redeclarations of D that we haven't checked for comments yet?
    417   // We can't use DenseMap::iterator directly since it'd get invalid.
    418   auto LastCheckedRedecl = [this, CanonicalD]() -> const Decl * {
    419     auto LookupRes = CommentlessRedeclChains.find(CanonicalD);
    420     if (LookupRes != CommentlessRedeclChains.end())
    421       return LookupRes->second;
    422     return nullptr;
    423   }();
    424 
    425   for (const auto Redecl : D->redecls()) {
    426     assert(Redecl);
    427     // Skip all redeclarations that have been checked previously.
    428     if (LastCheckedRedecl) {
    429       if (LastCheckedRedecl == Redecl) {
    430         LastCheckedRedecl = nullptr;
    431       }
    432       continue;
    433     }
    434     const RawComment *RedeclComment = getRawCommentForDeclNoCache(Redecl);
    435     if (RedeclComment) {
    436       cacheRawCommentForDecl(*Redecl, *RedeclComment);
    437       if (OriginalDecl)
    438         *OriginalDecl = Redecl;
    439       return RedeclComment;
    440     }
    441     CommentlessRedeclChains[CanonicalD] = Redecl;
    442   }
    443 
    444   if (OriginalDecl)
    445     *OriginalDecl = nullptr;
    446   return nullptr;
    447 }
    448 
    449 void ASTContext::cacheRawCommentForDecl(const Decl &OriginalD,
    450                                         const RawComment &Comment) const {
    451   assert(Comment.isDocumentation() || LangOpts.CommentOpts.ParseAllComments);
    452   DeclRawComments.try_emplace(&OriginalD, &Comment);
    453   const Decl *const CanonicalDecl = OriginalD.getCanonicalDecl();
    454   RedeclChainComments.try_emplace(CanonicalDecl, &OriginalD);
    455   CommentlessRedeclChains.erase(CanonicalDecl);
    456 }
    457 
    458 static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
    459                    SmallVectorImpl<const NamedDecl *> &Redeclared) {
    460   const DeclContext *DC = ObjCMethod->getDeclContext();
    461   if (const auto *IMD = dyn_cast<ObjCImplDecl>(DC)) {
    462     const ObjCInterfaceDecl *ID = IMD->getClassInterface();
    463     if (!ID)
    464       return;
    465     // Add redeclared method here.
    466     for (const auto *Ext : ID->known_extensions()) {
    467       if (ObjCMethodDecl *RedeclaredMethod =
    468             Ext->getMethod(ObjCMethod->getSelector(),
    469                                   ObjCMethod->isInstanceMethod()))
    470         Redeclared.push_back(RedeclaredMethod);
    471     }
    472   }
    473 }
    474 
    475 void ASTContext::attachCommentsToJustParsedDecls(ArrayRef<Decl *> Decls,
    476                                                  const Preprocessor *PP) {
    477   if (Comments.empty() || Decls.empty())
    478     return;
    479 
    480   FileID File;
    481   for (Decl *D : Decls) {
    482     SourceLocation Loc = D->getLocation();
    483     if (Loc.isValid()) {
    484       // See if there are any new comments that are not attached to a decl.
    485       // The location doesn't have to be precise - we care only about the file.
    486       File = SourceMgr.getDecomposedLoc(Loc).first;
    487       break;
    488     }
    489   }
    490 
    491   if (File.isInvalid())
    492     return;
    493 
    494   auto CommentsInThisFile = Comments.getCommentsInFile(File);
    495   if (!CommentsInThisFile || CommentsInThisFile->empty() ||
    496       CommentsInThisFile->rbegin()->second->isAttached())
    497     return;
    498 
    499   // There is at least one comment not attached to a decl.
    500   // Maybe it should be attached to one of Decls?
    501   //
    502   // Note that this way we pick up not only comments that precede the
    503   // declaration, but also comments that *follow* the declaration -- thanks to
    504   // the lookahead in the lexer: we've consumed the semicolon and looked
    505   // ahead through comments.
    506 
    507   for (const Decl *D : Decls) {
    508     assert(D);
    509     if (D->isInvalidDecl())
    510       continue;
    511 
    512     D = &adjustDeclToTemplate(*D);
    513 
    514     const SourceLocation DeclLoc = getDeclLocForCommentSearch(D, SourceMgr);
    515 
    516     if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
    517       continue;
    518 
    519     if (DeclRawComments.count(D) > 0)
    520       continue;
    521 
    522     if (RawComment *const DocComment =
    523             getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile)) {
    524       cacheRawCommentForDecl(*D, *DocComment);
    525       comments::FullComment *FC = DocComment->parse(*this, PP, D);
    526       ParsedComments[D->getCanonicalDecl()] = FC;
    527     }
    528   }
    529 }
    530 
    531 comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
    532                                                     const Decl *D) const {
    533   auto *ThisDeclInfo = new (*this) comments::DeclInfo;
    534   ThisDeclInfo->CommentDecl = D;
    535   ThisDeclInfo->IsFilled = false;
    536   ThisDeclInfo->fill();
    537   ThisDeclInfo->CommentDecl = FC->getDecl();
    538   if (!ThisDeclInfo->TemplateParameters)
    539     ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
    540   comments::FullComment *CFC =
    541     new (*this) comments::FullComment(FC->getBlocks(),
    542                                       ThisDeclInfo);
    543   return CFC;
    544 }
    545 
    546 comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
    547   const RawComment *RC = getRawCommentForDeclNoCache(D);
    548   return RC ? RC->parse(*this, nullptr, D) : nullptr;
    549 }
    550 
    551 comments::FullComment *ASTContext::getCommentForDecl(
    552                                               const Decl *D,
    553                                               const Preprocessor *PP) const {
    554   if (!D || D->isInvalidDecl())
    555     return nullptr;
    556   D = &adjustDeclToTemplate(*D);
    557 
    558   const Decl *Canonical = D->getCanonicalDecl();
    559   llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
    560       ParsedComments.find(Canonical);
    561 
    562   if (Pos != ParsedComments.end()) {
    563     if (Canonical != D) {
    564       comments::FullComment *FC = Pos->second;
    565       comments::FullComment *CFC = cloneFullComment(FC, D);
    566       return CFC;
    567     }
    568     return Pos->second;
    569   }
    570 
    571   const Decl *OriginalDecl = nullptr;
    572 
    573   const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
    574   if (!RC) {
    575     if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
    576       SmallVector<const NamedDecl*, 8> Overridden;
    577       const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
    578       if (OMD && OMD->isPropertyAccessor())
    579         if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
    580           if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
    581             return cloneFullComment(FC, D);
    582       if (OMD)
    583         addRedeclaredMethods(OMD, Overridden);
    584       getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
    585       for (unsigned i = 0, e = Overridden.size(); i < e; i++)
    586         if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
    587           return cloneFullComment(FC, D);
    588     }
    589     else if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
    590       // Attach any tag type's documentation to its typedef if latter
    591       // does not have one of its own.
    592       QualType QT = TD->getUnderlyingType();
    593       if (const auto *TT = QT->getAs<TagType>())
    594         if (const Decl *TD = TT->getDecl())
    595           if (comments::FullComment *FC = getCommentForDecl(TD, PP))
    596             return cloneFullComment(FC, D);
    597     }
    598     else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
    599       while (IC->getSuperClass()) {
    600         IC = IC->getSuperClass();
    601         if (comments::FullComment *FC = getCommentForDecl(IC, PP))
    602           return cloneFullComment(FC, D);
    603       }
    604     }
    605     else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(D)) {
    606       if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
    607         if (comments::FullComment *FC = getCommentForDecl(IC, PP))
    608           return cloneFullComment(FC, D);
    609     }
    610     else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
    611       if (!(RD = RD->getDefinition()))
    612         return nullptr;
    613       // Check non-virtual bases.
    614       for (const auto &I : RD->bases()) {
    615         if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
    616           continue;
    617         QualType Ty = I.getType();
    618         if (Ty.isNull())
    619           continue;
    620         if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
    621           if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
    622             continue;
    623 
    624           if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
    625             return cloneFullComment(FC, D);
    626         }
    627       }
    628       // Check virtual bases.
    629       for (const auto &I : RD->vbases()) {
    630         if (I.getAccessSpecifier() != AS_public)
    631           continue;
    632         QualType Ty = I.getType();
    633         if (Ty.isNull())
    634           continue;
    635         if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
    636           if (!(VirtualBase= VirtualBase->getDefinition()))
    637             continue;
    638           if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
    639             return cloneFullComment(FC, D);
    640         }
    641       }
    642     }
    643     return nullptr;
    644   }
    645 
    646   // If the RawComment was attached to other redeclaration of this Decl, we
    647   // should parse the comment in context of that other Decl.  This is important
    648   // because comments can contain references to parameter names which can be
    649   // different across redeclarations.
    650   if (D != OriginalDecl && OriginalDecl)
    651     return getCommentForDecl(OriginalDecl, PP);
    652 
    653   comments::FullComment *FC = RC->parse(*this, PP, D);
    654   ParsedComments[Canonical] = FC;
    655   return FC;
    656 }
    657 
    658 void
    659 ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
    660                                                    const ASTContext &C,
    661                                                TemplateTemplateParmDecl *Parm) {
    662   ID.AddInteger(Parm->getDepth());
    663   ID.AddInteger(Parm->getPosition());
    664   ID.AddBoolean(Parm->isParameterPack());
    665 
    666   TemplateParameterList *Params = Parm->getTemplateParameters();
    667   ID.AddInteger(Params->size());
    668   for (TemplateParameterList::const_iterator P = Params->begin(),
    669                                           PEnd = Params->end();
    670        P != PEnd; ++P) {
    671     if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
    672       ID.AddInteger(0);
    673       ID.AddBoolean(TTP->isParameterPack());
    674       const TypeConstraint *TC = TTP->getTypeConstraint();
    675       ID.AddBoolean(TC != nullptr);
    676       if (TC)
    677         TC->getImmediatelyDeclaredConstraint()->Profile(ID, C,
    678                                                         /*Canonical=*/true);
    679       if (TTP->isExpandedParameterPack()) {
    680         ID.AddBoolean(true);
    681         ID.AddInteger(TTP->getNumExpansionParameters());
    682       } else
    683         ID.AddBoolean(false);
    684       continue;
    685     }
    686 
    687     if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
    688       ID.AddInteger(1);
    689       ID.AddBoolean(NTTP->isParameterPack());
    690       ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
    691       if (NTTP->isExpandedParameterPack()) {
    692         ID.AddBoolean(true);
    693         ID.AddInteger(NTTP->getNumExpansionTypes());
    694         for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
    695           QualType T = NTTP->getExpansionType(I);
    696           ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
    697         }
    698       } else
    699         ID.AddBoolean(false);
    700       continue;
    701     }
    702 
    703     auto *TTP = cast<TemplateTemplateParmDecl>(*P);
    704     ID.AddInteger(2);
    705     Profile(ID, C, TTP);
    706   }
    707   Expr *RequiresClause = Parm->getTemplateParameters()->getRequiresClause();
    708   ID.AddBoolean(RequiresClause != nullptr);
    709   if (RequiresClause)
    710     RequiresClause->Profile(ID, C, /*Canonical=*/true);
    711 }
    712 
    713 static Expr *
    714 canonicalizeImmediatelyDeclaredConstraint(const ASTContext &C, Expr *IDC,
    715                                           QualType ConstrainedType) {
    716   // This is a bit ugly - we need to form a new immediately-declared
    717   // constraint that references the new parameter; this would ideally
    718   // require semantic analysis (e.g. template<C T> struct S {}; - the
    719   // converted arguments of C<T> could be an argument pack if C is
    720   // declared as template<typename... T> concept C = ...).
    721   // We don't have semantic analysis here so we dig deep into the
    722   // ready-made constraint expr and change the thing manually.
    723   ConceptSpecializationExpr *CSE;
    724   if (const auto *Fold = dyn_cast<CXXFoldExpr>(IDC))
    725     CSE = cast<ConceptSpecializationExpr>(Fold->getLHS());
    726   else
    727     CSE = cast<ConceptSpecializationExpr>(IDC);
    728   ArrayRef<TemplateArgument> OldConverted = CSE->getTemplateArguments();
    729   SmallVector<TemplateArgument, 3> NewConverted;
    730   NewConverted.reserve(OldConverted.size());
    731   if (OldConverted.front().getKind() == TemplateArgument::Pack) {
    732     // The case:
    733     // template<typename... T> concept C = true;
    734     // template<C<int> T> struct S; -> constraint is C<{T, int}>
    735     NewConverted.push_back(ConstrainedType);
    736     for (auto &Arg : OldConverted.front().pack_elements().drop_front(1))
    737       NewConverted.push_back(Arg);
    738     TemplateArgument NewPack(NewConverted);
    739 
    740     NewConverted.clear();
    741     NewConverted.push_back(NewPack);
    742     assert(OldConverted.size() == 1 &&
    743            "Template parameter pack should be the last parameter");
    744   } else {
    745     assert(OldConverted.front().getKind() == TemplateArgument::Type &&
    746            "Unexpected first argument kind for immediately-declared "
    747            "constraint");
    748     NewConverted.push_back(ConstrainedType);
    749     for (auto &Arg : OldConverted.drop_front(1))
    750       NewConverted.push_back(Arg);
    751   }
    752   Expr *NewIDC = ConceptSpecializationExpr::Create(
    753       C, CSE->getNamedConcept(), NewConverted, nullptr,
    754       CSE->isInstantiationDependent(), CSE->containsUnexpandedParameterPack());
    755 
    756   if (auto *OrigFold = dyn_cast<CXXFoldExpr>(IDC))
    757     NewIDC = new (C) CXXFoldExpr(
    758         OrigFold->getType(), /*Callee*/nullptr, SourceLocation(), NewIDC,
    759         BinaryOperatorKind::BO_LAnd, SourceLocation(), /*RHS=*/nullptr,
    760         SourceLocation(), /*NumExpansions=*/None);
    761   return NewIDC;
    762 }
    763 
    764 TemplateTemplateParmDecl *
    765 ASTContext::getCanonicalTemplateTemplateParmDecl(
    766                                           TemplateTemplateParmDecl *TTP) const {
    767   // Check if we already have a canonical template template parameter.
    768   llvm::FoldingSetNodeID ID;
    769   CanonicalTemplateTemplateParm::Profile(ID, *this, TTP);
    770   void *InsertPos = nullptr;
    771   CanonicalTemplateTemplateParm *Canonical
    772     = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
    773   if (Canonical)
    774     return Canonical->getParam();
    775 
    776   // Build a canonical template parameter list.
    777   TemplateParameterList *Params = TTP->getTemplateParameters();
    778   SmallVector<NamedDecl *, 4> CanonParams;
    779   CanonParams.reserve(Params->size());
    780   for (TemplateParameterList::const_iterator P = Params->begin(),
    781                                           PEnd = Params->end();
    782        P != PEnd; ++P) {
    783     if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
    784       TemplateTypeParmDecl *NewTTP = TemplateTypeParmDecl::Create(*this,
    785           getTranslationUnitDecl(), SourceLocation(), SourceLocation(),
    786           TTP->getDepth(), TTP->getIndex(), nullptr, false,
    787           TTP->isParameterPack(), TTP->hasTypeConstraint(),
    788           TTP->isExpandedParameterPack() ?
    789           llvm::Optional<unsigned>(TTP->getNumExpansionParameters()) : None);
    790       if (const auto *TC = TTP->getTypeConstraint()) {
    791         QualType ParamAsArgument(NewTTP->getTypeForDecl(), 0);
    792         Expr *NewIDC = canonicalizeImmediatelyDeclaredConstraint(
    793                 *this, TC->getImmediatelyDeclaredConstraint(),
    794                 ParamAsArgument);
    795         TemplateArgumentListInfo CanonArgsAsWritten;
    796         if (auto *Args = TC->getTemplateArgsAsWritten())
    797           for (const auto &ArgLoc : Args->arguments())
    798             CanonArgsAsWritten.addArgument(
    799                 TemplateArgumentLoc(ArgLoc.getArgument(),
    800                                     TemplateArgumentLocInfo()));
    801         NewTTP->setTypeConstraint(
    802             NestedNameSpecifierLoc(),
    803             DeclarationNameInfo(TC->getNamedConcept()->getDeclName(),
    804                                 SourceLocation()), /*FoundDecl=*/nullptr,
    805             // Actually canonicalizing a TemplateArgumentLoc is difficult so we
    806             // simply omit the ArgsAsWritten
    807             TC->getNamedConcept(), /*ArgsAsWritten=*/nullptr, NewIDC);
    808       }
    809       CanonParams.push_back(NewTTP);
    810     } else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
    811       QualType T = getCanonicalType(NTTP->getType());
    812       TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
    813       NonTypeTemplateParmDecl *Param;
    814       if (NTTP->isExpandedParameterPack()) {
    815         SmallVector<QualType, 2> ExpandedTypes;
    816         SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
    817         for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
    818           ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
    819           ExpandedTInfos.push_back(
    820                                 getTrivialTypeSourceInfo(ExpandedTypes.back()));
    821         }
    822 
    823         Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
    824                                                 SourceLocation(),
    825                                                 SourceLocation(),
    826                                                 NTTP->getDepth(),
    827                                                 NTTP->getPosition(), nullptr,
    828                                                 T,
    829                                                 TInfo,
    830                                                 ExpandedTypes,
    831                                                 ExpandedTInfos);
    832       } else {
    833         Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
    834                                                 SourceLocation(),
    835                                                 SourceLocation(),
    836                                                 NTTP->getDepth(),
    837                                                 NTTP->getPosition(), nullptr,
    838                                                 T,
    839                                                 NTTP->isParameterPack(),
    840                                                 TInfo);
    841       }
    842       if (AutoType *AT = T->getContainedAutoType()) {
    843         if (AT->isConstrained()) {
    844           Param->setPlaceholderTypeConstraint(
    845               canonicalizeImmediatelyDeclaredConstraint(
    846                   *this, NTTP->getPlaceholderTypeConstraint(), T));
    847         }
    848       }
    849       CanonParams.push_back(Param);
    850 
    851     } else
    852       CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
    853                                            cast<TemplateTemplateParmDecl>(*P)));
    854   }
    855 
    856   Expr *CanonRequiresClause = nullptr;
    857   if (Expr *RequiresClause = TTP->getTemplateParameters()->getRequiresClause())
    858     CanonRequiresClause = RequiresClause;
    859 
    860   TemplateTemplateParmDecl *CanonTTP
    861     = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
    862                                        SourceLocation(), TTP->getDepth(),
    863                                        TTP->getPosition(),
    864                                        TTP->isParameterPack(),
    865                                        nullptr,
    866                          TemplateParameterList::Create(*this, SourceLocation(),
    867                                                        SourceLocation(),
    868                                                        CanonParams,
    869                                                        SourceLocation(),
    870                                                        CanonRequiresClause));
    871 
    872   // Get the new insert position for the node we care about.
    873   Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
    874   assert(!Canonical && "Shouldn't be in the map!");
    875   (void)Canonical;
    876 
    877   // Create the canonical template template parameter entry.
    878   Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
    879   CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
    880   return CanonTTP;
    881 }
    882 
    883 TargetCXXABI::Kind ASTContext::getCXXABIKind() const {
    884   auto Kind = getTargetInfo().getCXXABI().getKind();
    885   return getLangOpts().CXXABI.getValueOr(Kind);
    886 }
    887 
    888 CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
    889   if (!LangOpts.CPlusPlus) return nullptr;
    890 
    891   switch (getCXXABIKind()) {
    892   case TargetCXXABI::AppleARM64:
    893   case TargetCXXABI::Fuchsia:
    894   case TargetCXXABI::GenericARM: // Same as Itanium at this level
    895   case TargetCXXABI::iOS:
    896   case TargetCXXABI::WatchOS:
    897   case TargetCXXABI::GenericAArch64:
    898   case TargetCXXABI::GenericMIPS:
    899   case TargetCXXABI::GenericItanium:
    900   case TargetCXXABI::WebAssembly:
    901   case TargetCXXABI::XL:
    902     return CreateItaniumCXXABI(*this);
    903   case TargetCXXABI::Microsoft:
    904     return CreateMicrosoftCXXABI(*this);
    905   }
    906   llvm_unreachable("Invalid CXXABI type!");
    907 }
    908 
    909 interp::Context &ASTContext::getInterpContext() {
    910   if (!InterpContext) {
    911     InterpContext.reset(new interp::Context(*this));
    912   }
    913   return *InterpContext.get();
    914 }
    915 
    916 ParentMapContext &ASTContext::getParentMapContext() {
    917   if (!ParentMapCtx)
    918     ParentMapCtx.reset(new ParentMapContext(*this));
    919   return *ParentMapCtx.get();
    920 }
    921 
    922 static const LangASMap *getAddressSpaceMap(const TargetInfo &T,
    923                                            const LangOptions &LOpts) {
    924   if (LOpts.FakeAddressSpaceMap) {
    925     // The fake address space map must have a distinct entry for each
    926     // language-specific address space.
    927     static const unsigned FakeAddrSpaceMap[] = {
    928         0,  // Default
    929         1,  // opencl_global
    930         3,  // opencl_local
    931         2,  // opencl_constant
    932         0,  // opencl_private
    933         4,  // opencl_generic
    934         5,  // opencl_global_device
    935         6,  // opencl_global_host
    936         7,  // cuda_device
    937         8,  // cuda_constant
    938         9,  // cuda_shared
    939         1,  // sycl_global
    940         5,  // sycl_global_device
    941         6,  // sycl_global_host
    942         3,  // sycl_local
    943         0,  // sycl_private
    944         10, // ptr32_sptr
    945         11, // ptr32_uptr
    946         12  // ptr64
    947     };
    948     return &FakeAddrSpaceMap;
    949   } else {
    950     return &T.getAddressSpaceMap();
    951   }
    952 }
    953 
    954 static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
    955                                           const LangOptions &LangOpts) {
    956   switch (LangOpts.getAddressSpaceMapMangling()) {
    957   case LangOptions::ASMM_Target:
    958     return TI.useAddressSpaceMapMangling();
    959   case LangOptions::ASMM_On:
    960     return true;
    961   case LangOptions::ASMM_Off:
    962     return false;
    963   }
    964   llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
    965 }
    966 
    967 ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
    968                        IdentifierTable &idents, SelectorTable &sels,
    969                        Builtin::Context &builtins)
    970     : ConstantArrayTypes(this_()), FunctionProtoTypes(this_()),
    971       TemplateSpecializationTypes(this_()),
    972       DependentTemplateSpecializationTypes(this_()), AutoTypes(this_()),
    973       SubstTemplateTemplateParmPacks(this_()),
    974       CanonTemplateTemplateParms(this_()), SourceMgr(SM), LangOpts(LOpts),
    975       NoSanitizeL(new NoSanitizeList(LangOpts.NoSanitizeFiles, SM)),
    976       XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
    977                                         LangOpts.XRayNeverInstrumentFiles,
    978                                         LangOpts.XRayAttrListFiles, SM)),
    979       ProfList(new ProfileList(LangOpts.ProfileListFiles, SM)),
    980       PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
    981       BuiltinInfo(builtins), DeclarationNames(*this), Comments(SM),
    982       CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
    983       CompCategories(this_()), LastSDM(nullptr, 0) {
    984   TUDecl = TranslationUnitDecl::Create(*this);
    985   TraversalScope = {TUDecl};
    986 }
    987 
    988 ASTContext::~ASTContext() {
    989   // Release the DenseMaps associated with DeclContext objects.
    990   // FIXME: Is this the ideal solution?
    991   ReleaseDeclContextMaps();
    992 
    993   // Call all of the deallocation functions on all of their targets.
    994   for (auto &Pair : Deallocations)
    995     (Pair.first)(Pair.second);
    996 
    997   // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
    998   // because they can contain DenseMaps.
    999   for (llvm::DenseMap<const ObjCContainerDecl*,
   1000        const ASTRecordLayout*>::iterator
   1001        I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
   1002     // Increment in loop to prevent using deallocated memory.
   1003     if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
   1004       R->Destroy(*this);
   1005 
   1006   for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
   1007        I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
   1008     // Increment in loop to prevent using deallocated memory.
   1009     if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
   1010       R->Destroy(*this);
   1011   }
   1012 
   1013   for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
   1014                                                     AEnd = DeclAttrs.end();
   1015        A != AEnd; ++A)
   1016     A->second->~AttrVec();
   1017 
   1018   for (const auto &Value : ModuleInitializers)
   1019     Value.second->~PerModuleInitializers();
   1020 }
   1021 
   1022 void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) {
   1023   TraversalScope = TopLevelDecls;
   1024   getParentMapContext().clear();
   1025 }
   1026 
   1027 void ASTContext::AddDeallocation(void (*Callback)(void *), void *Data) const {
   1028   Deallocations.push_back({Callback, Data});
   1029 }
   1030 
   1031 void
   1032 ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
   1033   ExternalSource = std::move(Source);
   1034 }
   1035 
   1036 void ASTContext::PrintStats() const {
   1037   llvm::errs() << "\n*** AST Context Stats:\n";
   1038   llvm::errs() << "  " << Types.size() << " types total.\n";
   1039 
   1040   unsigned counts[] = {
   1041 #define TYPE(Name, Parent) 0,
   1042 #define ABSTRACT_TYPE(Name, Parent)
   1043 #include "clang/AST/TypeNodes.inc"
   1044     0 // Extra
   1045   };
   1046 
   1047   for (unsigned i = 0, e = Types.size(); i != e; ++i) {
   1048     Type *T = Types[i];
   1049     counts[(unsigned)T->getTypeClass()]++;
   1050   }
   1051 
   1052   unsigned Idx = 0;
   1053   unsigned TotalBytes = 0;
   1054 #define TYPE(Name, Parent)                                              \
   1055   if (counts[Idx])                                                      \
   1056     llvm::errs() << "    " << counts[Idx] << " " << #Name               \
   1057                  << " types, " << sizeof(Name##Type) << " each "        \
   1058                  << "(" << counts[Idx] * sizeof(Name##Type)             \
   1059                  << " bytes)\n";                                        \
   1060   TotalBytes += counts[Idx] * sizeof(Name##Type);                       \
   1061   ++Idx;
   1062 #define ABSTRACT_TYPE(Name, Parent)
   1063 #include "clang/AST/TypeNodes.inc"
   1064 
   1065   llvm::errs() << "Total bytes = " << TotalBytes << "\n";
   1066 
   1067   // Implicit special member functions.
   1068   llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
   1069                << NumImplicitDefaultConstructors
   1070                << " implicit default constructors created\n";
   1071   llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
   1072                << NumImplicitCopyConstructors
   1073                << " implicit copy constructors created\n";
   1074   if (getLangOpts().CPlusPlus)
   1075     llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
   1076                  << NumImplicitMoveConstructors
   1077                  << " implicit move constructors created\n";
   1078   llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
   1079                << NumImplicitCopyAssignmentOperators
   1080                << " implicit copy assignment operators created\n";
   1081   if (getLangOpts().CPlusPlus)
   1082     llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
   1083                  << NumImplicitMoveAssignmentOperators
   1084                  << " implicit move assignment operators created\n";
   1085   llvm::errs() << NumImplicitDestructorsDeclared << "/"
   1086                << NumImplicitDestructors
   1087                << " implicit destructors created\n";
   1088 
   1089   if (ExternalSource) {
   1090     llvm::errs() << "\n";
   1091     ExternalSource->PrintStats();
   1092   }
   1093 
   1094   BumpAlloc.PrintStats();
   1095 }
   1096 
   1097 void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
   1098                                            bool NotifyListeners) {
   1099   if (NotifyListeners)
   1100     if (auto *Listener = getASTMutationListener())
   1101       Listener->RedefinedHiddenDefinition(ND, M);
   1102 
   1103   MergedDefModules[cast<NamedDecl>(ND->getCanonicalDecl())].push_back(M);
   1104 }
   1105 
   1106 void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
   1107   auto It = MergedDefModules.find(cast<NamedDecl>(ND->getCanonicalDecl()));
   1108   if (It == MergedDefModules.end())
   1109     return;
   1110 
   1111   auto &Merged = It->second;
   1112   llvm::DenseSet<Module*> Found;
   1113   for (Module *&M : Merged)
   1114     if (!Found.insert(M).second)
   1115       M = nullptr;
   1116   Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end());
   1117 }
   1118 
   1119 ArrayRef<Module *>
   1120 ASTContext::getModulesWithMergedDefinition(const NamedDecl *Def) {
   1121   auto MergedIt =
   1122       MergedDefModules.find(cast<NamedDecl>(Def->getCanonicalDecl()));
   1123   if (MergedIt == MergedDefModules.end())
   1124     return None;
   1125   return MergedIt->second;
   1126 }
   1127 
   1128 void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
   1129   if (LazyInitializers.empty())
   1130     return;
   1131 
   1132   auto *Source = Ctx.getExternalSource();
   1133   assert(Source && "lazy initializers but no external source");
   1134 
   1135   auto LazyInits = std::move(LazyInitializers);
   1136   LazyInitializers.clear();
   1137 
   1138   for (auto ID : LazyInits)
   1139     Initializers.push_back(Source->GetExternalDecl(ID));
   1140 
   1141   assert(LazyInitializers.empty() &&
   1142          "GetExternalDecl for lazy module initializer added more inits");
   1143 }
   1144 
   1145 void ASTContext::addModuleInitializer(Module *M, Decl *D) {
   1146   // One special case: if we add a module initializer that imports another
   1147   // module, and that module's only initializer is an ImportDecl, simplify.
   1148   if (const auto *ID = dyn_cast<ImportDecl>(D)) {
   1149     auto It = ModuleInitializers.find(ID->getImportedModule());
   1150 
   1151     // Maybe the ImportDecl does nothing at all. (Common case.)
   1152     if (It == ModuleInitializers.end())
   1153       return;
   1154 
   1155     // Maybe the ImportDecl only imports another ImportDecl.
   1156     auto &Imported = *It->second;
   1157     if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
   1158       Imported.resolve(*this);
   1159       auto *OnlyDecl = Imported.Initializers.front();
   1160       if (isa<ImportDecl>(OnlyDecl))
   1161         D = OnlyDecl;
   1162     }
   1163   }
   1164 
   1165   auto *&Inits = ModuleInitializers[M];
   1166   if (!Inits)
   1167     Inits = new (*this) PerModuleInitializers;
   1168   Inits->Initializers.push_back(D);
   1169 }
   1170 
   1171 void ASTContext::addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs) {
   1172   auto *&Inits = ModuleInitializers[M];
   1173   if (!Inits)
   1174     Inits = new (*this) PerModuleInitializers;
   1175   Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
   1176                                  IDs.begin(), IDs.end());
   1177 }
   1178 
   1179 ArrayRef<Decl *> ASTContext::getModuleInitializers(Module *M) {
   1180   auto It = ModuleInitializers.find(M);
   1181   if (It == ModuleInitializers.end())
   1182     return None;
   1183 
   1184   auto *Inits = It->second;
   1185   Inits->resolve(*this);
   1186   return Inits->Initializers;
   1187 }
   1188 
   1189 ExternCContextDecl *ASTContext::getExternCContextDecl() const {
   1190   if (!ExternCContext)
   1191     ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
   1192 
   1193   return ExternCContext;
   1194 }
   1195 
   1196 BuiltinTemplateDecl *
   1197 ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
   1198                                      const IdentifierInfo *II) const {
   1199   auto *BuiltinTemplate = BuiltinTemplateDecl::Create(*this, TUDecl, II, BTK);
   1200   BuiltinTemplate->setImplicit();
   1201   TUDecl->addDecl(BuiltinTemplate);
   1202 
   1203   return BuiltinTemplate;
   1204 }
   1205 
   1206 BuiltinTemplateDecl *
   1207 ASTContext::getMakeIntegerSeqDecl() const {
   1208   if (!MakeIntegerSeqDecl)
   1209     MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq,
   1210                                                   getMakeIntegerSeqName());
   1211   return MakeIntegerSeqDecl;
   1212 }
   1213 
   1214 BuiltinTemplateDecl *
   1215 ASTContext::getTypePackElementDecl() const {
   1216   if (!TypePackElementDecl)
   1217     TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element,
   1218                                                    getTypePackElementName());
   1219   return TypePackElementDecl;
   1220 }
   1221 
   1222 RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
   1223                                             RecordDecl::TagKind TK) const {
   1224   SourceLocation Loc;
   1225   RecordDecl *NewDecl;
   1226   if (getLangOpts().CPlusPlus)
   1227     NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
   1228                                     Loc, &Idents.get(Name));
   1229   else
   1230     NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
   1231                                  &Idents.get(Name));
   1232   NewDecl->setImplicit();
   1233   NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
   1234       const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
   1235   return NewDecl;
   1236 }
   1237 
   1238 TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
   1239                                               StringRef Name) const {
   1240   TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
   1241   TypedefDecl *NewDecl = TypedefDecl::Create(
   1242       const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
   1243       SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
   1244   NewDecl->setImplicit();
   1245   return NewDecl;
   1246 }
   1247 
   1248 TypedefDecl *ASTContext::getInt128Decl() const {
   1249   if (!Int128Decl)
   1250     Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
   1251   return Int128Decl;
   1252 }
   1253 
   1254 TypedefDecl *ASTContext::getUInt128Decl() const {
   1255   if (!UInt128Decl)
   1256     UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
   1257   return UInt128Decl;
   1258 }
   1259 
   1260 void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
   1261   auto *Ty = new (*this, TypeAlignment) BuiltinType(K);
   1262   R = CanQualType::CreateUnsafe(QualType(Ty, 0));
   1263   Types.push_back(Ty);
   1264 }
   1265 
   1266 void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
   1267                                   const TargetInfo *AuxTarget) {
   1268   assert((!this->Target || this->Target == &Target) &&
   1269          "Incorrect target reinitialization");
   1270   assert(VoidTy.isNull() && "Context reinitialized?");
   1271 
   1272   this->Target = &Target;
   1273   this->AuxTarget = AuxTarget;
   1274 
   1275   ABI.reset(createCXXABI(Target));
   1276   AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
   1277   AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
   1278 
   1279   // C99 6.2.5p19.
   1280   InitBuiltinType(VoidTy,              BuiltinType::Void);
   1281 
   1282   // C99 6.2.5p2.
   1283   InitBuiltinType(BoolTy,              BuiltinType::Bool);
   1284   // C99 6.2.5p3.
   1285   if (LangOpts.CharIsSigned)
   1286     InitBuiltinType(CharTy,            BuiltinType::Char_S);
   1287   else
   1288     InitBuiltinType(CharTy,            BuiltinType::Char_U);
   1289   // C99 6.2.5p4.
   1290   InitBuiltinType(SignedCharTy,        BuiltinType::SChar);
   1291   InitBuiltinType(ShortTy,             BuiltinType::Short);
   1292   InitBuiltinType(IntTy,               BuiltinType::Int);
   1293   InitBuiltinType(LongTy,              BuiltinType::Long);
   1294   InitBuiltinType(LongLongTy,          BuiltinType::LongLong);
   1295 
   1296   // C99 6.2.5p6.
   1297   InitBuiltinType(UnsignedCharTy,      BuiltinType::UChar);
   1298   InitBuiltinType(UnsignedShortTy,     BuiltinType::UShort);
   1299   InitBuiltinType(UnsignedIntTy,       BuiltinType::UInt);
   1300   InitBuiltinType(UnsignedLongTy,      BuiltinType::ULong);
   1301   InitBuiltinType(UnsignedLongLongTy,  BuiltinType::ULongLong);
   1302 
   1303   // C99 6.2.5p10.
   1304   InitBuiltinType(FloatTy,             BuiltinType::Float);
   1305   InitBuiltinType(DoubleTy,            BuiltinType::Double);
   1306   InitBuiltinType(LongDoubleTy,        BuiltinType::LongDouble);
   1307 
   1308   // GNU extension, __float128 for IEEE quadruple precision
   1309   InitBuiltinType(Float128Ty,          BuiltinType::Float128);
   1310 
   1311   // C11 extension ISO/IEC TS 18661-3
   1312   InitBuiltinType(Float16Ty,           BuiltinType::Float16);
   1313 
   1314   // ISO/IEC JTC1 SC22 WG14 N1169 Extension
   1315   InitBuiltinType(ShortAccumTy,            BuiltinType::ShortAccum);
   1316   InitBuiltinType(AccumTy,                 BuiltinType::Accum);
   1317   InitBuiltinType(LongAccumTy,             BuiltinType::LongAccum);
   1318   InitBuiltinType(UnsignedShortAccumTy,    BuiltinType::UShortAccum);
   1319   InitBuiltinType(UnsignedAccumTy,         BuiltinType::UAccum);
   1320   InitBuiltinType(UnsignedLongAccumTy,     BuiltinType::ULongAccum);
   1321   InitBuiltinType(ShortFractTy,            BuiltinType::ShortFract);
   1322   InitBuiltinType(FractTy,                 BuiltinType::Fract);
   1323   InitBuiltinType(LongFractTy,             BuiltinType::LongFract);
   1324   InitBuiltinType(UnsignedShortFractTy,    BuiltinType::UShortFract);
   1325   InitBuiltinType(UnsignedFractTy,         BuiltinType::UFract);
   1326   InitBuiltinType(UnsignedLongFractTy,     BuiltinType::ULongFract);
   1327   InitBuiltinType(SatShortAccumTy,         BuiltinType::SatShortAccum);
   1328   InitBuiltinType(SatAccumTy,              BuiltinType::SatAccum);
   1329   InitBuiltinType(SatLongAccumTy,          BuiltinType::SatLongAccum);
   1330   InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum);
   1331   InitBuiltinType(SatUnsignedAccumTy,      BuiltinType::SatUAccum);
   1332   InitBuiltinType(SatUnsignedLongAccumTy,  BuiltinType::SatULongAccum);
   1333   InitBuiltinType(SatShortFractTy,         BuiltinType::SatShortFract);
   1334   InitBuiltinType(SatFractTy,              BuiltinType::SatFract);
   1335   InitBuiltinType(SatLongFractTy,          BuiltinType::SatLongFract);
   1336   InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract);
   1337   InitBuiltinType(SatUnsignedFractTy,      BuiltinType::SatUFract);
   1338   InitBuiltinType(SatUnsignedLongFractTy,  BuiltinType::SatULongFract);
   1339 
   1340   // GNU extension, 128-bit integers.
   1341   InitBuiltinType(Int128Ty,            BuiltinType::Int128);
   1342   InitBuiltinType(UnsignedInt128Ty,    BuiltinType::UInt128);
   1343 
   1344   // C++ 3.9.1p5
   1345   if (TargetInfo::isTypeSigned(Target.getWCharType()))
   1346     InitBuiltinType(WCharTy,           BuiltinType::WChar_S);
   1347   else  // -fshort-wchar makes wchar_t be unsigned.
   1348     InitBuiltinType(WCharTy,           BuiltinType::WChar_U);
   1349   if (LangOpts.CPlusPlus && LangOpts.WChar)
   1350     WideCharTy = WCharTy;
   1351   else {
   1352     // C99 (or C++ using -fno-wchar).
   1353     WideCharTy = getFromTargetType(Target.getWCharType());
   1354   }
   1355 
   1356   WIntTy = getFromTargetType(Target.getWIntType());
   1357 
   1358   // C++20 (proposed)
   1359   InitBuiltinType(Char8Ty,              BuiltinType::Char8);
   1360 
   1361   if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
   1362     InitBuiltinType(Char16Ty,           BuiltinType::Char16);
   1363   else // C99
   1364     Char16Ty = getFromTargetType(Target.getChar16Type());
   1365 
   1366   if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
   1367     InitBuiltinType(Char32Ty,           BuiltinType::Char32);
   1368   else // C99
   1369     Char32Ty = getFromTargetType(Target.getChar32Type());
   1370 
   1371   // Placeholder type for type-dependent expressions whose type is
   1372   // completely unknown. No code should ever check a type against
   1373   // DependentTy and users should never see it; however, it is here to
   1374   // help diagnose failures to properly check for type-dependent
   1375   // expressions.
   1376   InitBuiltinType(DependentTy,         BuiltinType::Dependent);
   1377 
   1378   // Placeholder type for functions.
   1379   InitBuiltinType(OverloadTy,          BuiltinType::Overload);
   1380 
   1381   // Placeholder type for bound members.
   1382   InitBuiltinType(BoundMemberTy,       BuiltinType::BoundMember);
   1383 
   1384   // Placeholder type for pseudo-objects.
   1385   InitBuiltinType(PseudoObjectTy,      BuiltinType::PseudoObject);
   1386 
   1387   // "any" type; useful for debugger-like clients.
   1388   InitBuiltinType(UnknownAnyTy,        BuiltinType::UnknownAny);
   1389 
   1390   // Placeholder type for unbridged ARC casts.
   1391   InitBuiltinType(ARCUnbridgedCastTy,  BuiltinType::ARCUnbridgedCast);
   1392 
   1393   // Placeholder type for builtin functions.
   1394   InitBuiltinType(BuiltinFnTy,  BuiltinType::BuiltinFn);
   1395 
   1396   // Placeholder type for OMP array sections.
   1397   if (LangOpts.OpenMP) {
   1398     InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
   1399     InitBuiltinType(OMPArrayShapingTy, BuiltinType::OMPArrayShaping);
   1400     InitBuiltinType(OMPIteratorTy, BuiltinType::OMPIterator);
   1401   }
   1402   if (LangOpts.MatrixTypes)
   1403     InitBuiltinType(IncompleteMatrixIdxTy, BuiltinType::IncompleteMatrixIdx);
   1404 
   1405   // C99 6.2.5p11.
   1406   FloatComplexTy      = getComplexType(FloatTy);
   1407   DoubleComplexTy     = getComplexType(DoubleTy);
   1408   LongDoubleComplexTy = getComplexType(LongDoubleTy);
   1409   Float128ComplexTy   = getComplexType(Float128Ty);
   1410 
   1411   // Builtin types for 'id', 'Class', and 'SEL'.
   1412   InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
   1413   InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
   1414   InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
   1415 
   1416   if (LangOpts.OpenCL) {
   1417 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
   1418     InitBuiltinType(SingletonId, BuiltinType::Id);
   1419 #include "clang/Basic/OpenCLImageTypes.def"
   1420 
   1421     InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
   1422     InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
   1423     InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
   1424     InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
   1425     InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
   1426 
   1427 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
   1428     InitBuiltinType(Id##Ty, BuiltinType::Id);
   1429 #include "clang/Basic/OpenCLExtensionTypes.def"
   1430   }
   1431 
   1432   if (Target.hasAArch64SVETypes()) {
   1433 #define SVE_TYPE(Name, Id, SingletonId) \
   1434     InitBuiltinType(SingletonId, BuiltinType::Id);
   1435 #include "clang/Basic/AArch64SVEACLETypes.def"
   1436   }
   1437 
   1438   if (Target.getTriple().isPPC64() &&
   1439       Target.hasFeature("paired-vector-memops")) {
   1440     if (Target.hasFeature("mma")) {
   1441 #define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \
   1442       InitBuiltinType(Id##Ty, BuiltinType::Id);
   1443 #include "clang/Basic/PPCTypes.def"
   1444     }
   1445 #define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \
   1446     InitBuiltinType(Id##Ty, BuiltinType::Id);
   1447 #include "clang/Basic/PPCTypes.def"
   1448   }
   1449 
   1450   if (Target.hasRISCVVTypes()) {
   1451 #define RVV_TYPE(Name, Id, SingletonId)                                        \
   1452   InitBuiltinType(SingletonId, BuiltinType::Id);
   1453 #include "clang/Basic/RISCVVTypes.def"
   1454   }
   1455 
   1456   // Builtin type for __objc_yes and __objc_no
   1457   ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
   1458                        SignedCharTy : BoolTy);
   1459 
   1460   ObjCConstantStringType = QualType();
   1461 
   1462   ObjCSuperType = QualType();
   1463 
   1464   // void * type
   1465   if (LangOpts.OpenCLGenericAddressSpace) {
   1466     auto Q = VoidTy.getQualifiers();
   1467     Q.setAddressSpace(LangAS::opencl_generic);
   1468     VoidPtrTy = getPointerType(getCanonicalType(
   1469         getQualifiedType(VoidTy.getUnqualifiedType(), Q)));
   1470   } else {
   1471     VoidPtrTy = getPointerType(VoidTy);
   1472   }
   1473 
   1474   // nullptr type (C++0x 2.14.7)
   1475   InitBuiltinType(NullPtrTy,           BuiltinType::NullPtr);
   1476 
   1477   // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
   1478   InitBuiltinType(HalfTy, BuiltinType::Half);
   1479 
   1480   InitBuiltinType(BFloat16Ty, BuiltinType::BFloat16);
   1481 
   1482   // Builtin type used to help define __builtin_va_list.
   1483   VaListTagDecl = nullptr;
   1484 
   1485   // MSVC predeclares struct _GUID, and we need it to create MSGuidDecls.
   1486   if (LangOpts.MicrosoftExt || LangOpts.Borland) {
   1487     MSGuidTagDecl = buildImplicitRecord("_GUID");
   1488     TUDecl->addDecl(MSGuidTagDecl);
   1489   }
   1490 }
   1491 
   1492 DiagnosticsEngine &ASTContext::getDiagnostics() const {
   1493   return SourceMgr.getDiagnostics();
   1494 }
   1495 
   1496 AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
   1497   AttrVec *&Result = DeclAttrs[D];
   1498   if (!Result) {
   1499     void *Mem = Allocate(sizeof(AttrVec));
   1500     Result = new (Mem) AttrVec;
   1501   }
   1502 
   1503   return *Result;
   1504 }
   1505 
   1506 /// Erase the attributes corresponding to the given declaration.
   1507 void ASTContext::eraseDeclAttrs(const Decl *D) {
   1508   llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
   1509   if (Pos != DeclAttrs.end()) {
   1510     Pos->second->~AttrVec();
   1511     DeclAttrs.erase(Pos);
   1512   }
   1513 }
   1514 
   1515 // FIXME: Remove ?
   1516 MemberSpecializationInfo *
   1517 ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
   1518   assert(Var->isStaticDataMember() && "Not a static data member");
   1519   return getTemplateOrSpecializationInfo(Var)
   1520       .dyn_cast<MemberSpecializationInfo *>();
   1521 }
   1522 
   1523 ASTContext::TemplateOrSpecializationInfo
   1524 ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
   1525   llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
   1526       TemplateOrInstantiation.find(Var);
   1527   if (Pos == TemplateOrInstantiation.end())
   1528     return {};
   1529 
   1530   return Pos->second;
   1531 }
   1532 
   1533 void
   1534 ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
   1535                                                 TemplateSpecializationKind TSK,
   1536                                           SourceLocation PointOfInstantiation) {
   1537   assert(Inst->isStaticDataMember() && "Not a static data member");
   1538   assert(Tmpl->isStaticDataMember() && "Not a static data member");
   1539   setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
   1540                                             Tmpl, TSK, PointOfInstantiation));
   1541 }
   1542 
   1543 void
   1544 ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
   1545                                             TemplateOrSpecializationInfo TSI) {
   1546   assert(!TemplateOrInstantiation[Inst] &&
   1547          "Already noted what the variable was instantiated from");
   1548   TemplateOrInstantiation[Inst] = TSI;
   1549 }
   1550 
   1551 NamedDecl *
   1552 ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) {
   1553   auto Pos = InstantiatedFromUsingDecl.find(UUD);
   1554   if (Pos == InstantiatedFromUsingDecl.end())
   1555     return nullptr;
   1556 
   1557   return Pos->second;
   1558 }
   1559 
   1560 void
   1561 ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) {
   1562   assert((isa<UsingDecl>(Pattern) ||
   1563           isa<UnresolvedUsingValueDecl>(Pattern) ||
   1564           isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
   1565          "pattern decl is not a using decl");
   1566   assert((isa<UsingDecl>(Inst) ||
   1567           isa<UnresolvedUsingValueDecl>(Inst) ||
   1568           isa<UnresolvedUsingTypenameDecl>(Inst)) &&
   1569          "instantiation did not produce a using decl");
   1570   assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
   1571   InstantiatedFromUsingDecl[Inst] = Pattern;
   1572 }
   1573 
   1574 UsingShadowDecl *
   1575 ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
   1576   llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
   1577     = InstantiatedFromUsingShadowDecl.find(Inst);
   1578   if (Pos == InstantiatedFromUsingShadowDecl.end())
   1579     return nullptr;
   1580 
   1581   return Pos->second;
   1582 }
   1583 
   1584 void
   1585 ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
   1586                                                UsingShadowDecl *Pattern) {
   1587   assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
   1588   InstantiatedFromUsingShadowDecl[Inst] = Pattern;
   1589 }
   1590 
   1591 FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
   1592   llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
   1593     = InstantiatedFromUnnamedFieldDecl.find(Field);
   1594   if (Pos == InstantiatedFromUnnamedFieldDecl.end())
   1595     return nullptr;
   1596 
   1597   return Pos->second;
   1598 }
   1599 
   1600 void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
   1601                                                      FieldDecl *Tmpl) {
   1602   assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
   1603   assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
   1604   assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
   1605          "Already noted what unnamed field was instantiated from");
   1606 
   1607   InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
   1608 }
   1609 
   1610 ASTContext::overridden_cxx_method_iterator
   1611 ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
   1612   return overridden_methods(Method).begin();
   1613 }
   1614 
   1615 ASTContext::overridden_cxx_method_iterator
   1616 ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
   1617   return overridden_methods(Method).end();
   1618 }
   1619 
   1620 unsigned
   1621 ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
   1622   auto Range = overridden_methods(Method);
   1623   return Range.end() - Range.begin();
   1624 }
   1625 
   1626 ASTContext::overridden_method_range
   1627 ASTContext::overridden_methods(const CXXMethodDecl *Method) const {
   1628   llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
   1629       OverriddenMethods.find(Method->getCanonicalDecl());
   1630   if (Pos == OverriddenMethods.end())
   1631     return overridden_method_range(nullptr, nullptr);
   1632   return overridden_method_range(Pos->second.begin(), Pos->second.end());
   1633 }
   1634 
   1635 void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
   1636                                      const CXXMethodDecl *Overridden) {
   1637   assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
   1638   OverriddenMethods[Method].push_back(Overridden);
   1639 }
   1640 
   1641 void ASTContext::getOverriddenMethods(
   1642                       const NamedDecl *D,
   1643                       SmallVectorImpl<const NamedDecl *> &Overridden) const {
   1644   assert(D);
   1645 
   1646   if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
   1647     Overridden.append(overridden_methods_begin(CXXMethod),
   1648                       overridden_methods_end(CXXMethod));
   1649     return;
   1650   }
   1651 
   1652   const auto *Method = dyn_cast<ObjCMethodDecl>(D);
   1653   if (!Method)
   1654     return;
   1655 
   1656   SmallVector<const ObjCMethodDecl *, 8> OverDecls;
   1657   Method->getOverriddenMethods(OverDecls);
   1658   Overridden.append(OverDecls.begin(), OverDecls.end());
   1659 }
   1660 
   1661 void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
   1662   assert(!Import->getNextLocalImport() &&
   1663          "Import declaration already in the chain");
   1664   assert(!Import->isFromASTFile() && "Non-local import declaration");
   1665   if (!FirstLocalImport) {
   1666     FirstLocalImport = Import;
   1667     LastLocalImport = Import;
   1668     return;
   1669   }
   1670 
   1671   LastLocalImport->setNextLocalImport(Import);
   1672   LastLocalImport = Import;
   1673 }
   1674 
   1675 //===----------------------------------------------------------------------===//
   1676 //                         Type Sizing and Analysis
   1677 //===----------------------------------------------------------------------===//
   1678 
   1679 /// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
   1680 /// scalar floating point type.
   1681 const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
   1682   switch (T->castAs<BuiltinType>()->getKind()) {
   1683   default:
   1684     llvm_unreachable("Not a floating point type!");
   1685   case BuiltinType::BFloat16:
   1686     return Target->getBFloat16Format();
   1687   case BuiltinType::Float16:
   1688   case BuiltinType::Half:
   1689     return Target->getHalfFormat();
   1690   case BuiltinType::Float:      return Target->getFloatFormat();
   1691   case BuiltinType::Double:     return Target->getDoubleFormat();
   1692   case BuiltinType::LongDouble:
   1693     if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice)
   1694       return AuxTarget->getLongDoubleFormat();
   1695     return Target->getLongDoubleFormat();
   1696   case BuiltinType::Float128:
   1697     if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice)
   1698       return AuxTarget->getFloat128Format();
   1699     return Target->getFloat128Format();
   1700   }
   1701 }
   1702 
   1703 CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
   1704   unsigned Align = Target->getCharWidth();
   1705 
   1706   bool UseAlignAttrOnly = false;
   1707   if (unsigned AlignFromAttr = D->getMaxAlignment()) {
   1708     Align = AlignFromAttr;
   1709 
   1710     // __attribute__((aligned)) can increase or decrease alignment
   1711     // *except* on a struct or struct member, where it only increases
   1712     // alignment unless 'packed' is also specified.
   1713     //
   1714     // It is an error for alignas to decrease alignment, so we can
   1715     // ignore that possibility;  Sema should diagnose it.
   1716     if (isa<FieldDecl>(D)) {
   1717       UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
   1718         cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
   1719     } else {
   1720       UseAlignAttrOnly = true;
   1721     }
   1722   }
   1723   else if (isa<FieldDecl>(D))
   1724       UseAlignAttrOnly =
   1725         D->hasAttr<PackedAttr>() ||
   1726         cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
   1727 
   1728   // If we're using the align attribute only, just ignore everything
   1729   // else about the declaration and its type.
   1730   if (UseAlignAttrOnly) {
   1731     // do nothing
   1732   } else if (const auto *VD = dyn_cast<ValueDecl>(D)) {
   1733     QualType T = VD->getType();
   1734     if (const auto *RT = T->getAs<ReferenceType>()) {
   1735       if (ForAlignof)
   1736         T = RT->getPointeeType();
   1737       else
   1738         T = getPointerType(RT->getPointeeType());
   1739     }
   1740     QualType BaseT = getBaseElementType(T);
   1741     if (T->isFunctionType())
   1742       Align = getTypeInfoImpl(T.getTypePtr()).Align;
   1743     else if (!BaseT->isIncompleteType()) {
   1744       // Adjust alignments of declarations with array type by the
   1745       // large-array alignment on the target.
   1746       if (const ArrayType *arrayType = getAsArrayType(T)) {
   1747         unsigned MinWidth = Target->getLargeArrayMinWidth();
   1748         if (!ForAlignof && MinWidth) {
   1749           if (isa<VariableArrayType>(arrayType))
   1750             Align = std::max(Align, Target->getLargeArrayAlign());
   1751           else if (isa<ConstantArrayType>(arrayType) &&
   1752                    MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
   1753             Align = std::max(Align, Target->getLargeArrayAlign());
   1754         }
   1755       }
   1756       Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
   1757       if (BaseT.getQualifiers().hasUnaligned())
   1758         Align = Target->getCharWidth();
   1759       if (const auto *VD = dyn_cast<VarDecl>(D)) {
   1760         if (VD->hasGlobalStorage() && !ForAlignof) {
   1761           uint64_t TypeSize = getTypeSize(T.getTypePtr());
   1762           Align = std::max(Align, getTargetInfo().getMinGlobalAlign(TypeSize));
   1763         }
   1764       }
   1765     }
   1766 
   1767     // Fields can be subject to extra alignment constraints, like if
   1768     // the field is packed, the struct is packed, or the struct has a
   1769     // a max-field-alignment constraint (#pragma pack).  So calculate
   1770     // the actual alignment of the field within the struct, and then
   1771     // (as we're expected to) constrain that by the alignment of the type.
   1772     if (const auto *Field = dyn_cast<FieldDecl>(VD)) {
   1773       const RecordDecl *Parent = Field->getParent();
   1774       // We can only produce a sensible answer if the record is valid.
   1775       if (!Parent->isInvalidDecl()) {
   1776         const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
   1777 
   1778         // Start with the record's overall alignment.
   1779         unsigned FieldAlign = toBits(Layout.getAlignment());
   1780 
   1781         // Use the GCD of that and the offset within the record.
   1782         uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
   1783         if (Offset > 0) {
   1784           // Alignment is always a power of 2, so the GCD will be a power of 2,
   1785           // which means we get to do this crazy thing instead of Euclid's.
   1786           uint64_t LowBitOfOffset = Offset & (~Offset + 1);
   1787           if (LowBitOfOffset < FieldAlign)
   1788             FieldAlign = static_cast<unsigned>(LowBitOfOffset);
   1789         }
   1790 
   1791         Align = std::min(Align, FieldAlign);
   1792       }
   1793     }
   1794   }
   1795 
   1796   // Some targets have hard limitation on the maximum requestable alignment in
   1797   // aligned attribute for static variables.
   1798   const unsigned MaxAlignedAttr = getTargetInfo().getMaxAlignedAttribute();
   1799   const auto *VD = dyn_cast<VarDecl>(D);
   1800   if (MaxAlignedAttr && VD && VD->getStorageClass() == SC_Static)
   1801     Align = std::min(Align, MaxAlignedAttr);
   1802 
   1803   return toCharUnitsFromBits(Align);
   1804 }
   1805 
   1806 CharUnits ASTContext::getExnObjectAlignment() const {
   1807   return toCharUnitsFromBits(Target->getExnObjectAlignment());
   1808 }
   1809 
   1810 // getTypeInfoDataSizeInChars - Return the size of a type, in
   1811 // chars. If the type is a record, its data size is returned.  This is
   1812 // the size of the memcpy that's performed when assigning this type
   1813 // using a trivial copy/move assignment operator.
   1814 TypeInfoChars ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
   1815   TypeInfoChars Info = getTypeInfoInChars(T);
   1816 
   1817   // In C++, objects can sometimes be allocated into the tail padding
   1818   // of a base-class subobject.  We decide whether that's possible
   1819   // during class layout, so here we can just trust the layout results.
   1820   if (getLangOpts().CPlusPlus) {
   1821     if (const auto *RT = T->getAs<RecordType>()) {
   1822       const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
   1823       Info.Width = layout.getDataSize();
   1824     }
   1825   }
   1826 
   1827   return Info;
   1828 }
   1829 
   1830 /// getConstantArrayInfoInChars - Performing the computation in CharUnits
   1831 /// instead of in bits prevents overflowing the uint64_t for some large arrays.
   1832 TypeInfoChars
   1833 static getConstantArrayInfoInChars(const ASTContext &Context,
   1834                                    const ConstantArrayType *CAT) {
   1835   TypeInfoChars EltInfo = Context.getTypeInfoInChars(CAT->getElementType());
   1836   uint64_t Size = CAT->getSize().getZExtValue();
   1837   assert((Size == 0 || static_cast<uint64_t>(EltInfo.Width.getQuantity()) <=
   1838               (uint64_t)(-1)/Size) &&
   1839          "Overflow in array type char size evaluation");
   1840   uint64_t Width = EltInfo.Width.getQuantity() * Size;
   1841   unsigned Align = EltInfo.Align.getQuantity();
   1842   if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
   1843       Context.getTargetInfo().getPointerWidth(0) == 64)
   1844     Width = llvm::alignTo(Width, Align);
   1845   return TypeInfoChars(CharUnits::fromQuantity(Width),
   1846                        CharUnits::fromQuantity(Align),
   1847                        EltInfo.AlignIsRequired);
   1848 }
   1849 
   1850 TypeInfoChars ASTContext::getTypeInfoInChars(const Type *T) const {
   1851   if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
   1852     return getConstantArrayInfoInChars(*this, CAT);
   1853   TypeInfo Info = getTypeInfo(T);
   1854   return TypeInfoChars(toCharUnitsFromBits(Info.Width),
   1855                        toCharUnitsFromBits(Info.Align),
   1856                        Info.AlignIsRequired);
   1857 }
   1858 
   1859 TypeInfoChars ASTContext::getTypeInfoInChars(QualType T) const {
   1860   return getTypeInfoInChars(T.getTypePtr());
   1861 }
   1862 
   1863 bool ASTContext::isAlignmentRequired(const Type *T) const {
   1864   return getTypeInfo(T).AlignIsRequired;
   1865 }
   1866 
   1867 bool ASTContext::isAlignmentRequired(QualType T) const {
   1868   return isAlignmentRequired(T.getTypePtr());
   1869 }
   1870 
   1871 unsigned ASTContext::getTypeAlignIfKnown(QualType T,
   1872                                          bool NeedsPreferredAlignment) const {
   1873   // An alignment on a typedef overrides anything else.
   1874   if (const auto *TT = T->getAs<TypedefType>())
   1875     if (unsigned Align = TT->getDecl()->getMaxAlignment())
   1876       return Align;
   1877 
   1878   // If we have an (array of) complete type, we're done.
   1879   T = getBaseElementType(T);
   1880   if (!T->isIncompleteType())
   1881     return NeedsPreferredAlignment ? getPreferredTypeAlign(T) : getTypeAlign(T);
   1882 
   1883   // If we had an array type, its element type might be a typedef
   1884   // type with an alignment attribute.
   1885   if (const auto *TT = T->getAs<TypedefType>())
   1886     if (unsigned Align = TT->getDecl()->getMaxAlignment())
   1887       return Align;
   1888 
   1889   // Otherwise, see if the declaration of the type had an attribute.
   1890   if (const auto *TT = T->getAs<TagType>())
   1891     return TT->getDecl()->getMaxAlignment();
   1892 
   1893   return 0;
   1894 }
   1895 
   1896 TypeInfo ASTContext::getTypeInfo(const Type *T) const {
   1897   TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
   1898   if (I != MemoizedTypeInfo.end())
   1899     return I->second;
   1900 
   1901   // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
   1902   TypeInfo TI = getTypeInfoImpl(T);
   1903   MemoizedTypeInfo[T] = TI;
   1904   return TI;
   1905 }
   1906 
   1907 /// getTypeInfoImpl - Return the size of the specified type, in bits.  This
   1908 /// method does not work on incomplete types.
   1909 ///
   1910 /// FIXME: Pointers into different addr spaces could have different sizes and
   1911 /// alignment requirements: getPointerInfo should take an AddrSpace, this
   1912 /// should take a QualType, &c.
   1913 TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
   1914   uint64_t Width = 0;
   1915   unsigned Align = 8;
   1916   bool AlignIsRequired = false;
   1917   unsigned AS = 0;
   1918   switch (T->getTypeClass()) {
   1919 #define TYPE(Class, Base)
   1920 #define ABSTRACT_TYPE(Class, Base)
   1921 #define NON_CANONICAL_TYPE(Class, Base)
   1922 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
   1923 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)                       \
   1924   case Type::Class:                                                            \
   1925   assert(!T->isDependentType() && "should not see dependent types here");      \
   1926   return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
   1927 #include "clang/AST/TypeNodes.inc"
   1928     llvm_unreachable("Should not see dependent types");
   1929 
   1930   case Type::FunctionNoProto:
   1931   case Type::FunctionProto:
   1932     // GCC extension: alignof(function) = 32 bits
   1933     Width = 0;
   1934     Align = 32;
   1935     break;
   1936 
   1937   case Type::IncompleteArray:
   1938   case Type::VariableArray:
   1939   case Type::ConstantArray: {
   1940     // Model non-constant sized arrays as size zero, but track the alignment.
   1941     uint64_t Size = 0;
   1942     if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
   1943       Size = CAT->getSize().getZExtValue();
   1944 
   1945     TypeInfo EltInfo = getTypeInfo(cast<ArrayType>(T)->getElementType());
   1946     assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
   1947            "Overflow in array type bit size evaluation");
   1948     Width = EltInfo.Width * Size;
   1949     Align = EltInfo.Align;
   1950     AlignIsRequired = EltInfo.AlignIsRequired;
   1951     if (!getTargetInfo().getCXXABI().isMicrosoft() ||
   1952         getTargetInfo().getPointerWidth(0) == 64)
   1953       Width = llvm::alignTo(Width, Align);
   1954     break;
   1955   }
   1956 
   1957   case Type::ExtVector:
   1958   case Type::Vector: {
   1959     const auto *VT = cast<VectorType>(T);
   1960     TypeInfo EltInfo = getTypeInfo(VT->getElementType());
   1961     Width = EltInfo.Width * VT->getNumElements();
   1962     Align = Width;
   1963     // If the alignment is not a power of 2, round up to the next power of 2.
   1964     // This happens for non-power-of-2 length vectors.
   1965     if (Align & (Align-1)) {
   1966       Align = llvm::NextPowerOf2(Align);
   1967       Width = llvm::alignTo(Width, Align);
   1968     }
   1969     // Adjust the alignment based on the target max.
   1970     uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
   1971     if (TargetVectorAlign && TargetVectorAlign < Align)
   1972       Align = TargetVectorAlign;
   1973     if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector)
   1974       // Adjust the alignment for fixed-length SVE vectors. This is important
   1975       // for non-power-of-2 vector lengths.
   1976       Align = 128;
   1977     else if (VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector)
   1978       // Adjust the alignment for fixed-length SVE predicates.
   1979       Align = 16;
   1980     break;
   1981   }
   1982 
   1983   case Type::ConstantMatrix: {
   1984     const auto *MT = cast<ConstantMatrixType>(T);
   1985     TypeInfo ElementInfo = getTypeInfo(MT->getElementType());
   1986     // The internal layout of a matrix value is implementation defined.
   1987     // Initially be ABI compatible with arrays with respect to alignment and
   1988     // size.
   1989     Width = ElementInfo.Width * MT->getNumRows() * MT->getNumColumns();
   1990     Align = ElementInfo.Align;
   1991     break;
   1992   }
   1993 
   1994   case Type::Builtin:
   1995     switch (cast<BuiltinType>(T)->getKind()) {
   1996     default: llvm_unreachable("Unknown builtin type!");
   1997     case BuiltinType::Void:
   1998       // GCC extension: alignof(void) = 8 bits.
   1999       Width = 0;
   2000       Align = 8;
   2001       break;
   2002     case BuiltinType::Bool:
   2003       Width = Target->getBoolWidth();
   2004       Align = Target->getBoolAlign();
   2005       break;
   2006     case BuiltinType::Char_S:
   2007     case BuiltinType::Char_U:
   2008     case BuiltinType::UChar:
   2009     case BuiltinType::SChar:
   2010     case BuiltinType::Char8:
   2011       Width = Target->getCharWidth();
   2012       Align = Target->getCharAlign();
   2013       break;
   2014     case BuiltinType::WChar_S:
   2015     case BuiltinType::WChar_U:
   2016       Width = Target->getWCharWidth();
   2017       Align = Target->getWCharAlign();
   2018       break;
   2019     case BuiltinType::Char16:
   2020       Width = Target->getChar16Width();
   2021       Align = Target->getChar16Align();
   2022       break;
   2023     case BuiltinType::Char32:
   2024       Width = Target->getChar32Width();
   2025       Align = Target->getChar32Align();
   2026       break;
   2027     case BuiltinType::UShort:
   2028     case BuiltinType::Short:
   2029       Width = Target->getShortWidth();
   2030       Align = Target->getShortAlign();
   2031       break;
   2032     case BuiltinType::UInt:
   2033     case BuiltinType::Int:
   2034       Width = Target->getIntWidth();
   2035       Align = Target->getIntAlign();
   2036       break;
   2037     case BuiltinType::ULong:
   2038     case BuiltinType::Long:
   2039       Width = Target->getLongWidth();
   2040       Align = Target->getLongAlign();
   2041       break;
   2042     case BuiltinType::ULongLong:
   2043     case BuiltinType::LongLong:
   2044       Width = Target->getLongLongWidth();
   2045       Align = Target->getLongLongAlign();
   2046       break;
   2047     case BuiltinType::Int128:
   2048     case BuiltinType::UInt128:
   2049       Width = 128;
   2050       Align = 128; // int128_t is 128-bit aligned on all targets.
   2051       break;
   2052     case BuiltinType::ShortAccum:
   2053     case BuiltinType::UShortAccum:
   2054     case BuiltinType::SatShortAccum:
   2055     case BuiltinType::SatUShortAccum:
   2056       Width = Target->getShortAccumWidth();
   2057       Align = Target->getShortAccumAlign();
   2058       break;
   2059     case BuiltinType::Accum:
   2060     case BuiltinType::UAccum:
   2061     case BuiltinType::SatAccum:
   2062     case BuiltinType::SatUAccum:
   2063       Width = Target->getAccumWidth();
   2064       Align = Target->getAccumAlign();
   2065       break;
   2066     case BuiltinType::LongAccum:
   2067     case BuiltinType::ULongAccum:
   2068     case BuiltinType::SatLongAccum:
   2069     case BuiltinType::SatULongAccum:
   2070       Width = Target->getLongAccumWidth();
   2071       Align = Target->getLongAccumAlign();
   2072       break;
   2073     case BuiltinType::ShortFract:
   2074     case BuiltinType::UShortFract:
   2075     case BuiltinType::SatShortFract:
   2076     case BuiltinType::SatUShortFract:
   2077       Width = Target->getShortFractWidth();
   2078       Align = Target->getShortFractAlign();
   2079       break;
   2080     case BuiltinType::Fract:
   2081     case BuiltinType::UFract:
   2082     case BuiltinType::SatFract:
   2083     case BuiltinType::SatUFract:
   2084       Width = Target->getFractWidth();
   2085       Align = Target->getFractAlign();
   2086       break;
   2087     case BuiltinType::LongFract:
   2088     case BuiltinType::ULongFract:
   2089     case BuiltinType::SatLongFract:
   2090     case BuiltinType::SatULongFract:
   2091       Width = Target->getLongFractWidth();
   2092       Align = Target->getLongFractAlign();
   2093       break;
   2094     case BuiltinType::BFloat16:
   2095       Width = Target->getBFloat16Width();
   2096       Align = Target->getBFloat16Align();
   2097       break;
   2098     case BuiltinType::Float16:
   2099     case BuiltinType::Half:
   2100       if (Target->hasFloat16Type() || !getLangOpts().OpenMP ||
   2101           !getLangOpts().OpenMPIsDevice) {
   2102         Width = Target->getHalfWidth();
   2103         Align = Target->getHalfAlign();
   2104       } else {
   2105         assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
   2106                "Expected OpenMP device compilation.");
   2107         Width = AuxTarget->getHalfWidth();
   2108         Align = AuxTarget->getHalfAlign();
   2109       }
   2110       break;
   2111     case BuiltinType::Float:
   2112       Width = Target->getFloatWidth();
   2113       Align = Target->getFloatAlign();
   2114       break;
   2115     case BuiltinType::Double:
   2116       Width = Target->getDoubleWidth();
   2117       Align = Target->getDoubleAlign();
   2118       break;
   2119     case BuiltinType::LongDouble:
   2120       if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
   2121           (Target->getLongDoubleWidth() != AuxTarget->getLongDoubleWidth() ||
   2122            Target->getLongDoubleAlign() != AuxTarget->getLongDoubleAlign())) {
   2123         Width = AuxTarget->getLongDoubleWidth();
   2124         Align = AuxTarget->getLongDoubleAlign();
   2125       } else {
   2126         Width = Target->getLongDoubleWidth();
   2127         Align = Target->getLongDoubleAlign();
   2128       }
   2129       break;
   2130     case BuiltinType::Float128:
   2131       if (Target->hasFloat128Type() || !getLangOpts().OpenMP ||
   2132           !getLangOpts().OpenMPIsDevice) {
   2133         Width = Target->getFloat128Width();
   2134         Align = Target->getFloat128Align();
   2135       } else {
   2136         assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
   2137                "Expected OpenMP device compilation.");
   2138         Width = AuxTarget->getFloat128Width();
   2139         Align = AuxTarget->getFloat128Align();
   2140       }
   2141       break;
   2142     case BuiltinType::NullPtr:
   2143       Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
   2144       Align = Target->getPointerAlign(0); //   == sizeof(void*)
   2145       break;
   2146     case BuiltinType::ObjCId:
   2147     case BuiltinType::ObjCClass:
   2148     case BuiltinType::ObjCSel:
   2149       Width = Target->getPointerWidth(0);
   2150       Align = Target->getPointerAlign(0);
   2151       break;
   2152     case BuiltinType::OCLSampler:
   2153     case BuiltinType::OCLEvent:
   2154     case BuiltinType::OCLClkEvent:
   2155     case BuiltinType::OCLQueue:
   2156     case BuiltinType::OCLReserveID:
   2157 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
   2158     case BuiltinType::Id:
   2159 #include "clang/Basic/OpenCLImageTypes.def"
   2160 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
   2161   case BuiltinType::Id:
   2162 #include "clang/Basic/OpenCLExtensionTypes.def"
   2163       AS = getTargetAddressSpace(
   2164           Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T)));
   2165       Width = Target->getPointerWidth(AS);
   2166       Align = Target->getPointerAlign(AS);
   2167       break;
   2168     // The SVE types are effectively target-specific.  The length of an
   2169     // SVE_VECTOR_TYPE is only known at runtime, but it is always a multiple
   2170     // of 128 bits.  There is one predicate bit for each vector byte, so the
   2171     // length of an SVE_PREDICATE_TYPE is always a multiple of 16 bits.
   2172     //
   2173     // Because the length is only known at runtime, we use a dummy value
   2174     // of 0 for the static length.  The alignment values are those defined
   2175     // by the Procedure Call Standard for the Arm Architecture.
   2176 #define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId, NumEls, ElBits,    \
   2177                         IsSigned, IsFP, IsBF)                                  \
   2178   case BuiltinType::Id:                                                        \
   2179     Width = 0;                                                                 \
   2180     Align = 128;                                                               \
   2181     break;
   2182 #define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId, NumEls)         \
   2183   case BuiltinType::Id:                                                        \
   2184     Width = 0;                                                                 \
   2185     Align = 16;                                                                \
   2186     break;
   2187 #include "clang/Basic/AArch64SVEACLETypes.def"
   2188 #define PPC_VECTOR_TYPE(Name, Id, Size)                                        \
   2189   case BuiltinType::Id:                                                        \
   2190     Width = Size;                                                              \
   2191     Align = Size;                                                              \
   2192     break;
   2193 #include "clang/Basic/PPCTypes.def"
   2194 #define RVV_VECTOR_TYPE(Name, Id, SingletonId, ElKind, ElBits, NF, IsSigned,   \
   2195                         IsFP)                                                  \
   2196   case BuiltinType::Id:                                                        \
   2197     Width = 0;                                                                 \
   2198     Align = ElBits;                                                            \
   2199     break;
   2200 #define RVV_PREDICATE_TYPE(Name, Id, SingletonId, ElKind)                      \
   2201   case BuiltinType::Id:                                                        \
   2202     Width = 0;                                                                 \
   2203     Align = 8;                                                                 \
   2204     break;
   2205 #include "clang/Basic/RISCVVTypes.def"
   2206     }
   2207     break;
   2208   case Type::ObjCObjectPointer:
   2209     Width = Target->getPointerWidth(0);
   2210     Align = Target->getPointerAlign(0);
   2211     break;
   2212   case Type::BlockPointer:
   2213     AS = getTargetAddressSpace(cast<BlockPointerType>(T)->getPointeeType());
   2214     Width = Target->getPointerWidth(AS);
   2215     Align = Target->getPointerAlign(AS);
   2216     break;
   2217   case Type::LValueReference:
   2218   case Type::RValueReference:
   2219     // alignof and sizeof should never enter this code path here, so we go
   2220     // the pointer route.
   2221     AS = getTargetAddressSpace(cast<ReferenceType>(T)->getPointeeType());
   2222     Width = Target->getPointerWidth(AS);
   2223     Align = Target->getPointerAlign(AS);
   2224     break;
   2225   case Type::Pointer:
   2226     AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
   2227     Width = Target->getPointerWidth(AS);
   2228     Align = Target->getPointerAlign(AS);
   2229     break;
   2230   case Type::MemberPointer: {
   2231     const auto *MPT = cast<MemberPointerType>(T);
   2232     CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT);
   2233     Width = MPI.Width;
   2234     Align = MPI.Align;
   2235     break;
   2236   }
   2237   case Type::Complex: {
   2238     // Complex types have the same alignment as their elements, but twice the
   2239     // size.
   2240     TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
   2241     Width = EltInfo.Width * 2;
   2242     Align = EltInfo.Align;
   2243     break;
   2244   }
   2245   case Type::ObjCObject:
   2246     return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
   2247   case Type::Adjusted:
   2248   case Type::Decayed:
   2249     return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
   2250   case Type::ObjCInterface: {
   2251     const auto *ObjCI = cast<ObjCInterfaceType>(T);
   2252     if (ObjCI->getDecl()->isInvalidDecl()) {
   2253       Width = 8;
   2254       Align = 8;
   2255       break;
   2256     }
   2257     const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
   2258     Width = toBits(Layout.getSize());
   2259     Align = toBits(Layout.getAlignment());
   2260     break;
   2261   }
   2262   case Type::ExtInt: {
   2263     const auto *EIT = cast<ExtIntType>(T);
   2264     Align =
   2265         std::min(static_cast<unsigned>(std::max(
   2266                      getCharWidth(), llvm::PowerOf2Ceil(EIT->getNumBits()))),
   2267                  Target->getLongLongAlign());
   2268     Width = llvm::alignTo(EIT->getNumBits(), Align);
   2269     break;
   2270   }
   2271   case Type::Record:
   2272   case Type::Enum: {
   2273     const auto *TT = cast<TagType>(T);
   2274 
   2275     if (TT->getDecl()->isInvalidDecl()) {
   2276       Width = 8;
   2277       Align = 8;
   2278       break;
   2279     }
   2280 
   2281     if (const auto *ET = dyn_cast<EnumType>(TT)) {
   2282       const EnumDecl *ED = ET->getDecl();
   2283       TypeInfo Info =
   2284           getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
   2285       if (unsigned AttrAlign = ED->getMaxAlignment()) {
   2286         Info.Align = AttrAlign;
   2287         Info.AlignIsRequired = true;
   2288       }
   2289       return Info;
   2290     }
   2291 
   2292     const auto *RT = cast<RecordType>(TT);
   2293     const RecordDecl *RD = RT->getDecl();
   2294     const ASTRecordLayout &Layout = getASTRecordLayout(RD);
   2295     Width = toBits(Layout.getSize());
   2296     Align = toBits(Layout.getAlignment());
   2297     AlignIsRequired = RD->hasAttr<AlignedAttr>();
   2298     break;
   2299   }
   2300 
   2301   case Type::SubstTemplateTypeParm:
   2302     return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
   2303                        getReplacementType().getTypePtr());
   2304 
   2305   case Type::Auto:
   2306   case Type::DeducedTemplateSpecialization: {
   2307     const auto *A = cast<DeducedType>(T);
   2308     assert(!A->getDeducedType().isNull() &&
   2309            "cannot request the size of an undeduced or dependent auto type");
   2310     return getTypeInfo(A->getDeducedType().getTypePtr());
   2311   }
   2312 
   2313   case Type::Paren:
   2314     return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
   2315 
   2316   case Type::MacroQualified:
   2317     return getTypeInfo(
   2318         cast<MacroQualifiedType>(T)->getUnderlyingType().getTypePtr());
   2319 
   2320   case Type::ObjCTypeParam:
   2321     return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
   2322 
   2323   case Type::Typedef: {
   2324     const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
   2325     TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
   2326     // If the typedef has an aligned attribute on it, it overrides any computed
   2327     // alignment we have.  This violates the GCC documentation (which says that
   2328     // attribute(aligned) can only round up) but matches its implementation.
   2329     if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
   2330       Align = AttrAlign;
   2331       AlignIsRequired = true;
   2332     } else {
   2333       Align = Info.Align;
   2334       AlignIsRequired = Info.AlignIsRequired;
   2335     }
   2336     Width = Info.Width;
   2337     break;
   2338   }
   2339 
   2340   case Type::Elaborated:
   2341     return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
   2342 
   2343   case Type::Attributed:
   2344     return getTypeInfo(
   2345                   cast<AttributedType>(T)->getEquivalentType().getTypePtr());
   2346 
   2347   case Type::Atomic: {
   2348     // Start with the base type information.
   2349     TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
   2350     Width = Info.Width;
   2351     Align = Info.Align;
   2352 
   2353     if (!Width) {
   2354       // An otherwise zero-sized type should still generate an
   2355       // atomic operation.
   2356       Width = Target->getCharWidth();
   2357       assert(Align);
   2358     } else if (Width <= Target->getMaxAtomicPromoteWidth()) {
   2359       // If the size of the type doesn't exceed the platform's max
   2360       // atomic promotion width, make the size and alignment more
   2361       // favorable to atomic operations:
   2362 
   2363       // Round the size up to a power of 2.
   2364       if (!llvm::isPowerOf2_64(Width))
   2365         Width = llvm::NextPowerOf2(Width);
   2366 
   2367       // Set the alignment equal to the size.
   2368       Align = static_cast<unsigned>(Width);
   2369     }
   2370   }
   2371   break;
   2372 
   2373   case Type::Pipe:
   2374     Width = Target->getPointerWidth(getTargetAddressSpace(LangAS::opencl_global));
   2375     Align = Target->getPointerAlign(getTargetAddressSpace(LangAS::opencl_global));
   2376     break;
   2377   }
   2378 
   2379   assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
   2380   return TypeInfo(Width, Align, AlignIsRequired);
   2381 }
   2382 
   2383 unsigned ASTContext::getTypeUnadjustedAlign(const Type *T) const {
   2384   UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T);
   2385   if (I != MemoizedUnadjustedAlign.end())
   2386     return I->second;
   2387 
   2388   unsigned UnadjustedAlign;
   2389   if (const auto *RT = T->getAs<RecordType>()) {
   2390     const RecordDecl *RD = RT->getDecl();
   2391     const ASTRecordLayout &Layout = getASTRecordLayout(RD);
   2392     UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
   2393   } else if (const auto *ObjCI = T->getAs<ObjCInterfaceType>()) {
   2394     const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
   2395     UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
   2396   } else {
   2397     UnadjustedAlign = getTypeAlign(T->getUnqualifiedDesugaredType());
   2398   }
   2399 
   2400   MemoizedUnadjustedAlign[T] = UnadjustedAlign;
   2401   return UnadjustedAlign;
   2402 }
   2403 
   2404 unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
   2405   unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
   2406   return SimdAlign;
   2407 }
   2408 
   2409 /// toCharUnitsFromBits - Convert a size in bits to a size in characters.
   2410 CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
   2411   return CharUnits::fromQuantity(BitSize / getCharWidth());
   2412 }
   2413 
   2414 /// toBits - Convert a size in characters to a size in characters.
   2415 int64_t ASTContext::toBits(CharUnits CharSize) const {
   2416   return CharSize.getQuantity() * getCharWidth();
   2417 }
   2418 
   2419 /// getTypeSizeInChars - Return the size of the specified type, in characters.
   2420 /// This method does not work on incomplete types.
   2421 CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
   2422   return getTypeInfoInChars(T).Width;
   2423 }
   2424 CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
   2425   return getTypeInfoInChars(T).Width;
   2426 }
   2427 
   2428 /// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
   2429 /// characters. This method does not work on incomplete types.
   2430 CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
   2431   return toCharUnitsFromBits(getTypeAlign(T));
   2432 }
   2433 CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
   2434   return toCharUnitsFromBits(getTypeAlign(T));
   2435 }
   2436 
   2437 /// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a
   2438 /// type, in characters, before alignment adustments. This method does
   2439 /// not work on incomplete types.
   2440 CharUnits ASTContext::getTypeUnadjustedAlignInChars(QualType T) const {
   2441   return toCharUnitsFromBits(getTypeUnadjustedAlign(T));
   2442 }
   2443 CharUnits ASTContext::getTypeUnadjustedAlignInChars(const Type *T) const {
   2444   return toCharUnitsFromBits(getTypeUnadjustedAlign(T));
   2445 }
   2446 
   2447 /// getPreferredTypeAlign - Return the "preferred" alignment of the specified
   2448 /// type for the current target in bits.  This can be different than the ABI
   2449 /// alignment in cases where it is beneficial for performance or backwards
   2450 /// compatibility preserving to overalign a data type. (Note: despite the name,
   2451 /// the preferred alignment is ABI-impacting, and not an optimization.)
   2452 unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
   2453   TypeInfo TI = getTypeInfo(T);
   2454   unsigned ABIAlign = TI.Align;
   2455 
   2456   T = T->getBaseElementTypeUnsafe();
   2457 
   2458   // The preferred alignment of member pointers is that of a pointer.
   2459   if (T->isMemberPointerType())
   2460     return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
   2461 
   2462   if (!Target->allowsLargerPreferedTypeAlignment())
   2463     return ABIAlign;
   2464 
   2465   if (const auto *RT = T->getAs<RecordType>()) {
   2466     if (TI.AlignIsRequired || RT->getDecl()->isInvalidDecl())
   2467       return ABIAlign;
   2468 
   2469     unsigned PreferredAlign = static_cast<unsigned>(
   2470         toBits(getASTRecordLayout(RT->getDecl()).PreferredAlignment));
   2471     assert(PreferredAlign >= ABIAlign &&
   2472            "PreferredAlign should be at least as large as ABIAlign.");
   2473     return PreferredAlign;
   2474   }
   2475 
   2476   // Double (and, for targets supporting AIX `power` alignment, long double) and
   2477   // long long should be naturally aligned (despite requiring less alignment) if
   2478   // possible.
   2479   if (const auto *CT = T->getAs<ComplexType>())
   2480     T = CT->getElementType().getTypePtr();
   2481   if (const auto *ET = T->getAs<EnumType>())
   2482     T = ET->getDecl()->getIntegerType().getTypePtr();
   2483   if (T->isSpecificBuiltinType(BuiltinType::Double) ||
   2484       T->isSpecificBuiltinType(BuiltinType::LongLong) ||
   2485       T->isSpecificBuiltinType(BuiltinType::ULongLong) ||
   2486       (T->isSpecificBuiltinType(BuiltinType::LongDouble) &&
   2487        Target->defaultsToAIXPowerAlignment()))
   2488     // Don't increase the alignment if an alignment attribute was specified on a
   2489     // typedef declaration.
   2490     if (!TI.AlignIsRequired)
   2491       return std::max(ABIAlign, (unsigned)getTypeSize(T));
   2492 
   2493   return ABIAlign;
   2494 }
   2495 
   2496 /// getTargetDefaultAlignForAttributeAligned - Return the default alignment
   2497 /// for __attribute__((aligned)) on this target, to be used if no alignment
   2498 /// value is specified.
   2499 unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const {
   2500   return getTargetInfo().getDefaultAlignForAttributeAligned();
   2501 }
   2502 
   2503 /// getAlignOfGlobalVar - Return the alignment in bits that should be given
   2504 /// to a global variable of the specified type.
   2505 unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
   2506   uint64_t TypeSize = getTypeSize(T.getTypePtr());
   2507   return std::max(getPreferredTypeAlign(T),
   2508                   getTargetInfo().getMinGlobalAlign(TypeSize));
   2509 }
   2510 
   2511 /// getAlignOfGlobalVarInChars - Return the alignment in characters that
   2512 /// should be given to a global variable of the specified type.
   2513 CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
   2514   return toCharUnitsFromBits(getAlignOfGlobalVar(T));
   2515 }
   2516 
   2517 CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
   2518   CharUnits Offset = CharUnits::Zero();
   2519   const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
   2520   while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
   2521     Offset += Layout->getBaseClassOffset(Base);
   2522     Layout = &getASTRecordLayout(Base);
   2523   }
   2524   return Offset;
   2525 }
   2526 
   2527 CharUnits ASTContext::getMemberPointerPathAdjustment(const APValue &MP) const {
   2528   const ValueDecl *MPD = MP.getMemberPointerDecl();
   2529   CharUnits ThisAdjustment = CharUnits::Zero();
   2530   ArrayRef<const CXXRecordDecl*> Path = MP.getMemberPointerPath();
   2531   bool DerivedMember = MP.isMemberPointerToDerivedMember();
   2532   const CXXRecordDecl *RD = cast<CXXRecordDecl>(MPD->getDeclContext());
   2533   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
   2534     const CXXRecordDecl *Base = RD;
   2535     const CXXRecordDecl *Derived = Path[I];
   2536     if (DerivedMember)
   2537       std::swap(Base, Derived);
   2538     ThisAdjustment += getASTRecordLayout(Derived).getBaseClassOffset(Base);
   2539     RD = Path[I];
   2540   }
   2541   if (DerivedMember)
   2542     ThisAdjustment = -ThisAdjustment;
   2543   return ThisAdjustment;
   2544 }
   2545 
   2546 /// DeepCollectObjCIvars -
   2547 /// This routine first collects all declared, but not synthesized, ivars in
   2548 /// super class and then collects all ivars, including those synthesized for
   2549 /// current class. This routine is used for implementation of current class
   2550 /// when all ivars, declared and synthesized are known.
   2551 void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
   2552                                       bool leafClass,
   2553                             SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
   2554   if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
   2555     DeepCollectObjCIvars(SuperClass, false, Ivars);
   2556   if (!leafClass) {
   2557     for (const auto *I : OI->ivars())
   2558       Ivars.push_back(I);
   2559   } else {
   2560     auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
   2561     for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
   2562          Iv= Iv->getNextIvar())
   2563       Ivars.push_back(Iv);
   2564   }
   2565 }
   2566 
   2567 /// CollectInheritedProtocols - Collect all protocols in current class and
   2568 /// those inherited by it.
   2569 void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
   2570                           llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
   2571   if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
   2572     // We can use protocol_iterator here instead of
   2573     // all_referenced_protocol_iterator since we are walking all categories.
   2574     for (auto *Proto : OI->all_referenced_protocols()) {
   2575       CollectInheritedProtocols(Proto, Protocols);
   2576     }
   2577 
   2578     // Categories of this Interface.
   2579     for (const auto *Cat : OI->visible_categories())
   2580       CollectInheritedProtocols(Cat, Protocols);
   2581 
   2582     if (ObjCInterfaceDecl *SD = OI->getSuperClass())
   2583       while (SD) {
   2584         CollectInheritedProtocols(SD, Protocols);
   2585         SD = SD->getSuperClass();
   2586       }
   2587   } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
   2588     for (auto *Proto : OC->protocols()) {
   2589       CollectInheritedProtocols(Proto, Protocols);
   2590     }
   2591   } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
   2592     // Insert the protocol.
   2593     if (!Protocols.insert(
   2594           const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
   2595       return;
   2596 
   2597     for (auto *Proto : OP->protocols())
   2598       CollectInheritedProtocols(Proto, Protocols);
   2599   }
   2600 }
   2601 
   2602 static bool unionHasUniqueObjectRepresentations(const ASTContext &Context,
   2603                                                 const RecordDecl *RD) {
   2604   assert(RD->isUnion() && "Must be union type");
   2605   CharUnits UnionSize = Context.getTypeSizeInChars(RD->getTypeForDecl());
   2606 
   2607   for (const auto *Field : RD->fields()) {
   2608     if (!Context.hasUniqueObjectRepresentations(Field->getType()))
   2609       return false;
   2610     CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType());
   2611     if (FieldSize != UnionSize)
   2612       return false;
   2613   }
   2614   return !RD->field_empty();
   2615 }
   2616 
   2617 static bool isStructEmpty(QualType Ty) {
   2618   const RecordDecl *RD = Ty->castAs<RecordType>()->getDecl();
   2619 
   2620   if (!RD->field_empty())
   2621     return false;
   2622 
   2623   if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD))
   2624     return ClassDecl->isEmpty();
   2625 
   2626   return true;
   2627 }
   2628 
   2629 static llvm::Optional<int64_t>
   2630 structHasUniqueObjectRepresentations(const ASTContext &Context,
   2631                                      const RecordDecl *RD) {
   2632   assert(!RD->isUnion() && "Must be struct/class type");
   2633   const auto &Layout = Context.getASTRecordLayout(RD);
   2634 
   2635   int64_t CurOffsetInBits = 0;
   2636   if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) {
   2637     if (ClassDecl->isDynamicClass())
   2638       return llvm::None;
   2639 
   2640     SmallVector<std::pair<QualType, int64_t>, 4> Bases;
   2641     for (const auto &Base : ClassDecl->bases()) {
   2642       // Empty types can be inherited from, and non-empty types can potentially
   2643       // have tail padding, so just make sure there isn't an error.
   2644       if (!isStructEmpty(Base.getType())) {
   2645         llvm::Optional<int64_t> Size = structHasUniqueObjectRepresentations(
   2646             Context, Base.getType()->castAs<RecordType>()->getDecl());
   2647         if (!Size)
   2648           return llvm::None;
   2649         Bases.emplace_back(Base.getType(), Size.getValue());
   2650       }
   2651     }
   2652 
   2653     llvm::sort(Bases, [&](const std::pair<QualType, int64_t> &L,
   2654                           const std::pair<QualType, int64_t> &R) {
   2655       return Layout.getBaseClassOffset(L.first->getAsCXXRecordDecl()) <
   2656              Layout.getBaseClassOffset(R.first->getAsCXXRecordDecl());
   2657     });
   2658 
   2659     for (const auto &Base : Bases) {
   2660       int64_t BaseOffset = Context.toBits(
   2661           Layout.getBaseClassOffset(Base.first->getAsCXXRecordDecl()));
   2662       int64_t BaseSize = Base.second;
   2663       if (BaseOffset != CurOffsetInBits)
   2664         return llvm::None;
   2665       CurOffsetInBits = BaseOffset + BaseSize;
   2666     }
   2667   }
   2668 
   2669   for (const auto *Field : RD->fields()) {
   2670     if (!Field->getType()->isReferenceType() &&
   2671         !Context.hasUniqueObjectRepresentations(Field->getType()))
   2672       return llvm::None;
   2673 
   2674     int64_t FieldSizeInBits =
   2675         Context.toBits(Context.getTypeSizeInChars(Field->getType()));
   2676     if (Field->isBitField()) {
   2677       int64_t BitfieldSize = Field->getBitWidthValue(Context);
   2678 
   2679       if (BitfieldSize > FieldSizeInBits)
   2680         return llvm::None;
   2681       FieldSizeInBits = BitfieldSize;
   2682     }
   2683 
   2684     int64_t FieldOffsetInBits = Context.getFieldOffset(Field);
   2685 
   2686     if (FieldOffsetInBits != CurOffsetInBits)
   2687       return llvm::None;
   2688 
   2689     CurOffsetInBits = FieldSizeInBits + FieldOffsetInBits;
   2690   }
   2691 
   2692   return CurOffsetInBits;
   2693 }
   2694 
   2695 bool ASTContext::hasUniqueObjectRepresentations(QualType Ty) const {
   2696   // C++17 [meta.unary.prop]:
   2697   //   The predicate condition for a template specialization
   2698   //   has_unique_object_representations<T> shall be
   2699   //   satisfied if and only if:
   2700   //     (9.1) - T is trivially copyable, and
   2701   //     (9.2) - any two objects of type T with the same value have the same
   2702   //     object representation, where two objects
   2703   //   of array or non-union class type are considered to have the same value
   2704   //   if their respective sequences of
   2705   //   direct subobjects have the same values, and two objects of union type
   2706   //   are considered to have the same
   2707   //   value if they have the same active member and the corresponding members
   2708   //   have the same value.
   2709   //   The set of scalar types for which this condition holds is
   2710   //   implementation-defined. [ Note: If a type has padding
   2711   //   bits, the condition does not hold; otherwise, the condition holds true
   2712   //   for unsigned integral types. -- end note ]
   2713   assert(!Ty.isNull() && "Null QualType sent to unique object rep check");
   2714 
   2715   // Arrays are unique only if their element type is unique.
   2716   if (Ty->isArrayType())
   2717     return hasUniqueObjectRepresentations(getBaseElementType(Ty));
   2718 
   2719   // (9.1) - T is trivially copyable...
   2720   if (!Ty.isTriviallyCopyableType(*this))
   2721     return false;
   2722 
   2723   // All integrals and enums are unique.
   2724   if (Ty->isIntegralOrEnumerationType())
   2725     return true;
   2726 
   2727   // All other pointers are unique.
   2728   if (Ty->isPointerType())
   2729     return true;
   2730 
   2731   if (Ty->isMemberPointerType()) {
   2732     const auto *MPT = Ty->getAs<MemberPointerType>();
   2733     return !ABI->getMemberPointerInfo(MPT).HasPadding;
   2734   }
   2735 
   2736   if (Ty->isRecordType()) {
   2737     const RecordDecl *Record = Ty->castAs<RecordType>()->getDecl();
   2738 
   2739     if (Record->isInvalidDecl())
   2740       return false;
   2741 
   2742     if (Record->isUnion())
   2743       return unionHasUniqueObjectRepresentations(*this, Record);
   2744 
   2745     Optional<int64_t> StructSize =
   2746         structHasUniqueObjectRepresentations(*this, Record);
   2747 
   2748     return StructSize &&
   2749            StructSize.getValue() == static_cast<int64_t>(getTypeSize(Ty));
   2750   }
   2751 
   2752   // FIXME: More cases to handle here (list by rsmith):
   2753   // vectors (careful about, eg, vector of 3 foo)
   2754   // _Complex int and friends
   2755   // _Atomic T
   2756   // Obj-C block pointers
   2757   // Obj-C object pointers
   2758   // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t,
   2759   // clk_event_t, queue_t, reserve_id_t)
   2760   // There're also Obj-C class types and the Obj-C selector type, but I think it
   2761   // makes sense for those to return false here.
   2762 
   2763   return false;
   2764 }
   2765 
   2766 unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
   2767   unsigned count = 0;
   2768   // Count ivars declared in class extension.
   2769   for (const auto *Ext : OI->known_extensions())
   2770     count += Ext->ivar_size();
   2771 
   2772   // Count ivar defined in this class's implementation.  This
   2773   // includes synthesized ivars.
   2774   if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
   2775     count += ImplDecl->ivar_size();
   2776 
   2777   return count;
   2778 }
   2779 
   2780 bool ASTContext::isSentinelNullExpr(const Expr *E) {
   2781   if (!E)
   2782     return false;
   2783 
   2784   // nullptr_t is always treated as null.
   2785   if (E->getType()->isNullPtrType()) return true;
   2786 
   2787   if (E->getType()->isAnyPointerType() &&
   2788       E->IgnoreParenCasts()->isNullPointerConstant(*this,
   2789                                                 Expr::NPC_ValueDependentIsNull))
   2790     return true;
   2791 
   2792   // Unfortunately, __null has type 'int'.
   2793   if (isa<GNUNullExpr>(E)) return true;
   2794 
   2795   return false;
   2796 }
   2797 
   2798 /// Get the implementation of ObjCInterfaceDecl, or nullptr if none
   2799 /// exists.
   2800 ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
   2801   llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
   2802     I = ObjCImpls.find(D);
   2803   if (I != ObjCImpls.end())
   2804     return cast<ObjCImplementationDecl>(I->second);
   2805   return nullptr;
   2806 }
   2807 
   2808 /// Get the implementation of ObjCCategoryDecl, or nullptr if none
   2809 /// exists.
   2810 ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
   2811   llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
   2812     I = ObjCImpls.find(D);
   2813   if (I != ObjCImpls.end())
   2814     return cast<ObjCCategoryImplDecl>(I->second);
   2815   return nullptr;
   2816 }
   2817 
   2818 /// Set the implementation of ObjCInterfaceDecl.
   2819 void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
   2820                            ObjCImplementationDecl *ImplD) {
   2821   assert(IFaceD && ImplD && "Passed null params");
   2822   ObjCImpls[IFaceD] = ImplD;
   2823 }
   2824 
   2825 /// Set the implementation of ObjCCategoryDecl.
   2826 void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
   2827                            ObjCCategoryImplDecl *ImplD) {
   2828   assert(CatD && ImplD && "Passed null params");
   2829   ObjCImpls[CatD] = ImplD;
   2830 }
   2831 
   2832 const ObjCMethodDecl *
   2833 ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const {
   2834   return ObjCMethodRedecls.lookup(MD);
   2835 }
   2836 
   2837 void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
   2838                                             const ObjCMethodDecl *Redecl) {
   2839   assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
   2840   ObjCMethodRedecls[MD] = Redecl;
   2841 }
   2842 
   2843 const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
   2844                                               const NamedDecl *ND) const {
   2845   if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
   2846     return ID;
   2847   if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
   2848     return CD->getClassInterface();
   2849   if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
   2850     return IMD->getClassInterface();
   2851 
   2852   return nullptr;
   2853 }
   2854 
   2855 /// Get the copy initialization expression of VarDecl, or nullptr if
   2856 /// none exists.
   2857 BlockVarCopyInit ASTContext::getBlockVarCopyInit(const VarDecl *VD) const {
   2858   assert(VD && "Passed null params");
   2859   assert(VD->hasAttr<BlocksAttr>() &&
   2860          "getBlockVarCopyInits - not __block var");
   2861   auto I = BlockVarCopyInits.find(VD);
   2862   if (I != BlockVarCopyInits.end())
   2863     return I->second;
   2864   return {nullptr, false};
   2865 }
   2866 
   2867 /// Set the copy initialization expression of a block var decl.
   2868 void ASTContext::setBlockVarCopyInit(const VarDecl*VD, Expr *CopyExpr,
   2869                                      bool CanThrow) {
   2870   assert(VD && CopyExpr && "Passed null params");
   2871   assert(VD->hasAttr<BlocksAttr>() &&
   2872          "setBlockVarCopyInits - not __block var");
   2873   BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow);
   2874 }
   2875 
   2876 TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
   2877                                                  unsigned DataSize) const {
   2878   if (!DataSize)
   2879     DataSize = TypeLoc::getFullDataSizeForType(T);
   2880   else
   2881     assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
   2882            "incorrect data size provided to CreateTypeSourceInfo!");
   2883 
   2884   auto *TInfo =
   2885     (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
   2886   new (TInfo) TypeSourceInfo(T);
   2887   return TInfo;
   2888 }
   2889 
   2890 TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
   2891                                                      SourceLocation L) const {
   2892   TypeSourceInfo *DI = CreateTypeSourceInfo(T);
   2893   DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
   2894   return DI;
   2895 }
   2896 
   2897 const ASTRecordLayout &
   2898 ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
   2899   return getObjCLayout(D, nullptr);
   2900 }
   2901 
   2902 const ASTRecordLayout &
   2903 ASTContext::getASTObjCImplementationLayout(
   2904                                         const ObjCImplementationDecl *D) const {
   2905   return getObjCLayout(D->getClassInterface(), D);
   2906 }
   2907 
   2908 //===----------------------------------------------------------------------===//
   2909 //                   Type creation/memoization methods
   2910 //===----------------------------------------------------------------------===//
   2911 
   2912 QualType
   2913 ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
   2914   unsigned fastQuals = quals.getFastQualifiers();
   2915   quals.removeFastQualifiers();
   2916 
   2917   // Check if we've already instantiated this type.
   2918   llvm::FoldingSetNodeID ID;
   2919   ExtQuals::Profile(ID, baseType, quals);
   2920   void *insertPos = nullptr;
   2921   if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
   2922     assert(eq->getQualifiers() == quals);
   2923     return QualType(eq, fastQuals);
   2924   }
   2925 
   2926   // If the base type is not canonical, make the appropriate canonical type.
   2927   QualType canon;
   2928   if (!baseType->isCanonicalUnqualified()) {
   2929     SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
   2930     canonSplit.Quals.addConsistentQualifiers(quals);
   2931     canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
   2932 
   2933     // Re-find the insert position.
   2934     (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
   2935   }
   2936 
   2937   auto *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
   2938   ExtQualNodes.InsertNode(eq, insertPos);
   2939   return QualType(eq, fastQuals);
   2940 }
   2941 
   2942 QualType ASTContext::getAddrSpaceQualType(QualType T,
   2943                                           LangAS AddressSpace) const {
   2944   QualType CanT = getCanonicalType(T);
   2945   if (CanT.getAddressSpace() == AddressSpace)
   2946     return T;
   2947 
   2948   // If we are composing extended qualifiers together, merge together
   2949   // into one ExtQuals node.
   2950   QualifierCollector Quals;
   2951   const Type *TypeNode = Quals.strip(T);
   2952 
   2953   // If this type already has an address space specified, it cannot get
   2954   // another one.
   2955   assert(!Quals.hasAddressSpace() &&
   2956          "Type cannot be in multiple addr spaces!");
   2957   Quals.addAddressSpace(AddressSpace);
   2958 
   2959   return getExtQualType(TypeNode, Quals);
   2960 }
   2961 
   2962 QualType ASTContext::removeAddrSpaceQualType(QualType T) const {
   2963   // If the type is not qualified with an address space, just return it
   2964   // immediately.
   2965   if (!T.hasAddressSpace())
   2966     return T;
   2967 
   2968   // If we are composing extended qualifiers together, merge together
   2969   // into one ExtQuals node.
   2970   QualifierCollector Quals;
   2971   const Type *TypeNode;
   2972 
   2973   while (T.hasAddressSpace()) {
   2974     TypeNode = Quals.strip(T);
   2975 
   2976     // If the type no longer has an address space after stripping qualifiers,
   2977     // jump out.
   2978     if (!QualType(TypeNode, 0).hasAddressSpace())
   2979       break;
   2980 
   2981     // There might be sugar in the way. Strip it and try again.
   2982     T = T.getSingleStepDesugaredType(*this);
   2983   }
   2984 
   2985   Quals.removeAddressSpace();
   2986 
   2987   // Removal of the address space can mean there are no longer any
   2988   // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
   2989   // or required.
   2990   if (Quals.hasNonFastQualifiers())
   2991     return getExtQualType(TypeNode, Quals);
   2992   else
   2993     return QualType(TypeNode, Quals.getFastQualifiers());
   2994 }
   2995 
   2996 QualType ASTContext::getObjCGCQualType(QualType T,
   2997                                        Qualifiers::GC GCAttr) const {
   2998   QualType CanT = getCanonicalType(T);
   2999   if (CanT.getObjCGCAttr() == GCAttr)
   3000     return T;
   3001 
   3002   if (const auto *ptr = T->getAs<PointerType>()) {
   3003     QualType Pointee = ptr->getPointeeType();
   3004     if (Pointee->isAnyPointerType()) {
   3005       QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
   3006       return getPointerType(ResultType);
   3007     }
   3008   }
   3009 
   3010   // If we are composing extended qualifiers together, merge together
   3011   // into one ExtQuals node.
   3012   QualifierCollector Quals;
   3013   const Type *TypeNode = Quals.strip(T);
   3014 
   3015   // If this type already has an ObjCGC specified, it cannot get
   3016   // another one.
   3017   assert(!Quals.hasObjCGCAttr() &&
   3018          "Type cannot have multiple ObjCGCs!");
   3019   Quals.addObjCGCAttr(GCAttr);
   3020 
   3021   return getExtQualType(TypeNode, Quals);
   3022 }
   3023 
   3024 QualType ASTContext::removePtrSizeAddrSpace(QualType T) const {
   3025   if (const PointerType *Ptr = T->getAs<PointerType>()) {
   3026     QualType Pointee = Ptr->getPointeeType();
   3027     if (isPtrSizeAddressSpace(Pointee.getAddressSpace())) {
   3028       return getPointerType(removeAddrSpaceQualType(Pointee));
   3029     }
   3030   }
   3031   return T;
   3032 }
   3033 
   3034 const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
   3035                                                    FunctionType::ExtInfo Info) {
   3036   if (T->getExtInfo() == Info)
   3037     return T;
   3038 
   3039   QualType Result;
   3040   if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
   3041     Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
   3042   } else {
   3043     const auto *FPT = cast<FunctionProtoType>(T);
   3044     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
   3045     EPI.ExtInfo = Info;
   3046     Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
   3047   }
   3048 
   3049   return cast<FunctionType>(Result.getTypePtr());
   3050 }
   3051 
   3052 void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
   3053                                                  QualType ResultType) {
   3054   FD = FD->getMostRecentDecl();
   3055   while (true) {
   3056     const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
   3057     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
   3058     FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
   3059     if (FunctionDecl *Next = FD->getPreviousDecl())
   3060       FD = Next;
   3061     else
   3062       break;
   3063   }
   3064   if (ASTMutationListener *L = getASTMutationListener())
   3065     L->DeducedReturnType(FD, ResultType);
   3066 }
   3067 
   3068 /// Get a function type and produce the equivalent function type with the
   3069 /// specified exception specification. Type sugar that can be present on a
   3070 /// declaration of a function with an exception specification is permitted
   3071 /// and preserved. Other type sugar (for instance, typedefs) is not.
   3072 QualType ASTContext::getFunctionTypeWithExceptionSpec(
   3073     QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) {
   3074   // Might have some parens.
   3075   if (const auto *PT = dyn_cast<ParenType>(Orig))
   3076     return getParenType(
   3077         getFunctionTypeWithExceptionSpec(PT->getInnerType(), ESI));
   3078 
   3079   // Might be wrapped in a macro qualified type.
   3080   if (const auto *MQT = dyn_cast<MacroQualifiedType>(Orig))
   3081     return getMacroQualifiedType(
   3082         getFunctionTypeWithExceptionSpec(MQT->getUnderlyingType(), ESI),
   3083         MQT->getMacroIdentifier());
   3084 
   3085   // Might have a calling-convention attribute.
   3086   if (const auto *AT = dyn_cast<AttributedType>(Orig))
   3087     return getAttributedType(
   3088         AT->getAttrKind(),
   3089         getFunctionTypeWithExceptionSpec(AT->getModifiedType(), ESI),
   3090         getFunctionTypeWithExceptionSpec(AT->getEquivalentType(), ESI));
   3091 
   3092   // Anything else must be a function type. Rebuild it with the new exception
   3093   // specification.
   3094   const auto *Proto = Orig->castAs<FunctionProtoType>();
   3095   return getFunctionType(
   3096       Proto->getReturnType(), Proto->getParamTypes(),
   3097       Proto->getExtProtoInfo().withExceptionSpec(ESI));
   3098 }
   3099 
   3100 bool ASTContext::hasSameFunctionTypeIgnoringExceptionSpec(QualType T,
   3101                                                           QualType U) {
   3102   return hasSameType(T, U) ||
   3103          (getLangOpts().CPlusPlus17 &&
   3104           hasSameType(getFunctionTypeWithExceptionSpec(T, EST_None),
   3105                       getFunctionTypeWithExceptionSpec(U, EST_None)));
   3106 }
   3107 
   3108 QualType ASTContext::getFunctionTypeWithoutPtrSizes(QualType T) {
   3109   if (const auto *Proto = T->getAs<FunctionProtoType>()) {
   3110     QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
   3111     SmallVector<QualType, 16> Args(Proto->param_types());
   3112     for (unsigned i = 0, n = Args.size(); i != n; ++i)
   3113       Args[i] = removePtrSizeAddrSpace(Args[i]);
   3114     return getFunctionType(RetTy, Args, Proto->getExtProtoInfo());
   3115   }
   3116 
   3117   if (const FunctionNoProtoType *Proto = T->getAs<FunctionNoProtoType>()) {
   3118     QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
   3119     return getFunctionNoProtoType(RetTy, Proto->getExtInfo());
   3120   }
   3121 
   3122   return T;
   3123 }
   3124 
   3125 bool ASTContext::hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U) {
   3126   return hasSameType(T, U) ||
   3127          hasSameType(getFunctionTypeWithoutPtrSizes(T),
   3128                      getFunctionTypeWithoutPtrSizes(U));
   3129 }
   3130 
   3131 void ASTContext::adjustExceptionSpec(
   3132     FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
   3133     bool AsWritten) {
   3134   // Update the type.
   3135   QualType Updated =
   3136       getFunctionTypeWithExceptionSpec(FD->getType(), ESI);
   3137   FD->setType(Updated);
   3138 
   3139   if (!AsWritten)
   3140     return;
   3141 
   3142   // Update the type in the type source information too.
   3143   if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
   3144     // If the type and the type-as-written differ, we may need to update
   3145     // the type-as-written too.
   3146     if (TSInfo->getType() != FD->getType())
   3147       Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI);
   3148 
   3149     // FIXME: When we get proper type location information for exceptions,
   3150     // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
   3151     // up the TypeSourceInfo;
   3152     assert(TypeLoc::getFullDataSizeForType(Updated) ==
   3153                TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
   3154            "TypeLoc size mismatch from updating exception specification");
   3155     TSInfo->overrideType(Updated);
   3156   }
   3157 }
   3158 
   3159 /// getComplexType - Return the uniqued reference to the type for a complex
   3160 /// number with the specified element type.
   3161 QualType ASTContext::getComplexType(QualType T) const {
   3162   // Unique pointers, to guarantee there is only one pointer of a particular
   3163   // structure.
   3164   llvm::FoldingSetNodeID ID;
   3165   ComplexType::Profile(ID, T);
   3166 
   3167   void *InsertPos = nullptr;
   3168   if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
   3169     return QualType(CT, 0);
   3170 
   3171   // If the pointee type isn't canonical, this won't be a canonical type either,
   3172   // so fill in the canonical type field.
   3173   QualType Canonical;
   3174   if (!T.isCanonical()) {
   3175     Canonical = getComplexType(getCanonicalType(T));
   3176 
   3177     // Get the new insert position for the node we care about.
   3178     ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
   3179     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
   3180   }
   3181   auto *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
   3182   Types.push_back(New);
   3183   ComplexTypes.InsertNode(New, InsertPos);
   3184   return QualType(New, 0);
   3185 }
   3186 
   3187 /// getPointerType - Return the uniqued reference to the type for a pointer to
   3188 /// the specified type.
   3189 QualType ASTContext::getPointerType(QualType T) const {
   3190   // Unique pointers, to guarantee there is only one pointer of a particular
   3191   // structure.
   3192   llvm::FoldingSetNodeID ID;
   3193   PointerType::Profile(ID, T);
   3194 
   3195   void *InsertPos = nullptr;
   3196   if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
   3197     return QualType(PT, 0);
   3198 
   3199   // If the pointee type isn't canonical, this won't be a canonical type either,
   3200   // so fill in the canonical type field.
   3201   QualType Canonical;
   3202   if (!T.isCanonical()) {
   3203     Canonical = getPointerType(getCanonicalType(T));
   3204 
   3205     // Get the new insert position for the node we care about.
   3206     PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
   3207     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
   3208   }
   3209   auto *New = new (*this, TypeAlignment) PointerType(T, Canonical);
   3210   Types.push_back(New);
   3211   PointerTypes.InsertNode(New, InsertPos);
   3212   return QualType(New, 0);
   3213 }
   3214 
   3215 QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
   3216   llvm::FoldingSetNodeID ID;
   3217   AdjustedType::Profile(ID, Orig, New);
   3218   void *InsertPos = nullptr;
   3219   AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
   3220   if (AT)
   3221     return QualType(AT, 0);
   3222 
   3223   QualType Canonical = getCanonicalType(New);
   3224 
   3225   // Get the new insert position for the node we care about.
   3226   AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
   3227   assert(!AT && "Shouldn't be in the map!");
   3228 
   3229   AT = new (*this, TypeAlignment)
   3230       AdjustedType(Type::Adjusted, Orig, New, Canonical);
   3231   Types.push_back(AT);
   3232   AdjustedTypes.InsertNode(AT, InsertPos);
   3233   return QualType(AT, 0);
   3234 }
   3235 
   3236 QualType ASTContext::getDecayedType(QualType T) const {
   3237   assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
   3238 
   3239   QualType Decayed;
   3240 
   3241   // C99 6.7.5.3p7:
   3242   //   A declaration of a parameter as "array of type" shall be
   3243   //   adjusted to "qualified pointer to type", where the type
   3244   //   qualifiers (if any) are those specified within the [ and ] of
   3245   //   the array type derivation.
   3246   if (T->isArrayType())
   3247     Decayed = getArrayDecayedType(T);
   3248 
   3249   // C99 6.7.5.3p8:
   3250   //   A declaration of a parameter as "function returning type"
   3251   //   shall be adjusted to "pointer to function returning type", as
   3252   //   in 6.3.2.1.
   3253   if (T->isFunctionType())
   3254     Decayed = getPointerType(T);
   3255 
   3256   llvm::FoldingSetNodeID ID;
   3257   AdjustedType::Profile(ID, T, Decayed);
   3258   void *InsertPos = nullptr;
   3259   AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
   3260   if (AT)
   3261     return QualType(AT, 0);
   3262 
   3263   QualType Canonical = getCanonicalType(Decayed);
   3264 
   3265   // Get the new insert position for the node we care about.
   3266   AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
   3267   assert(!AT && "Shouldn't be in the map!");
   3268 
   3269   AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
   3270   Types.push_back(AT);
   3271   AdjustedTypes.InsertNode(AT, InsertPos);
   3272   return QualType(AT, 0);
   3273 }
   3274 
   3275 /// getBlockPointerType - Return the uniqued reference to the type for
   3276 /// a pointer to the specified block.
   3277 QualType ASTContext::getBlockPointerType(QualType T) const {
   3278   assert(T->isFunctionType() && "block of function types only");
   3279   // Unique pointers, to guarantee there is only one block of a particular
   3280   // structure.
   3281   llvm::FoldingSetNodeID ID;
   3282   BlockPointerType::Profile(ID, T);
   3283 
   3284   void *InsertPos = nullptr;
   3285   if (BlockPointerType *PT =
   3286         BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
   3287     return QualType(PT, 0);
   3288 
   3289   // If the block pointee type isn't canonical, this won't be a canonical
   3290   // type either so fill in the canonical type field.
   3291   QualType Canonical;
   3292   if (!T.isCanonical()) {
   3293     Canonical = getBlockPointerType(getCanonicalType(T));
   3294 
   3295     // Get the new insert position for the node we care about.
   3296     BlockPointerType *NewIP =
   3297       BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
   3298     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
   3299   }
   3300   auto *New = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
   3301   Types.push_back(New);
   3302   BlockPointerTypes.InsertNode(New, InsertPos);
   3303   return QualType(New, 0);
   3304 }
   3305 
   3306 /// getLValueReferenceType - Return the uniqued reference to the type for an
   3307 /// lvalue reference to the specified type.
   3308 QualType
   3309 ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
   3310   assert(getCanonicalType(T) != OverloadTy &&
   3311          "Unresolved overloaded function type");
   3312 
   3313   // Unique pointers, to guarantee there is only one pointer of a particular
   3314   // structure.
   3315   llvm::FoldingSetNodeID ID;
   3316   ReferenceType::Profile(ID, T, SpelledAsLValue);
   3317 
   3318   void *InsertPos = nullptr;
   3319   if (LValueReferenceType *RT =
   3320         LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
   3321     return QualType(RT, 0);
   3322 
   3323   const auto *InnerRef = T->getAs<ReferenceType>();
   3324 
   3325   // If the referencee type isn't canonical, this won't be a canonical type
   3326   // either, so fill in the canonical type field.
   3327   QualType Canonical;
   3328   if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
   3329     QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
   3330     Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
   3331 
   3332     // Get the new insert position for the node we care about.
   3333     LValueReferenceType *NewIP =
   3334       LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
   3335     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
   3336   }
   3337 
   3338   auto *New = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
   3339                                                              SpelledAsLValue);
   3340   Types.push_back(New);
   3341   LValueReferenceTypes.InsertNode(New, InsertPos);
   3342 
   3343   return QualType(New, 0);
   3344 }
   3345 
   3346 /// getRValueReferenceType - Return the uniqued reference to the type for an
   3347 /// rvalue reference to the specified type.
   3348 QualType ASTContext::getRValueReferenceType(QualType T) const {
   3349   // Unique pointers, to guarantee there is only one pointer of a particular
   3350   // structure.
   3351   llvm::FoldingSetNodeID ID;
   3352   ReferenceType::Profile(ID, T, false);
   3353 
   3354   void *InsertPos = nullptr;
   3355   if (RValueReferenceType *RT =
   3356         RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
   3357     return QualType(RT, 0);
   3358 
   3359   const auto *InnerRef = T->getAs<ReferenceType>();
   3360 
   3361   // If the referencee type isn't canonical, this won't be a canonical type
   3362   // either, so fill in the canonical type field.
   3363   QualType Canonical;
   3364   if (InnerRef || !T.isCanonical()) {
   3365     QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
   3366     Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
   3367 
   3368     // Get the new insert position for the node we care about.
   3369     RValueReferenceType *NewIP =
   3370       RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
   3371     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
   3372   }
   3373 
   3374   auto *New = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
   3375   Types.push_back(New);
   3376   RValueReferenceTypes.InsertNode(New, InsertPos);
   3377   return QualType(New, 0);
   3378 }
   3379 
   3380 /// getMemberPointerType - Return the uniqued reference to the type for a
   3381 /// member pointer to the specified type, in the specified class.
   3382 QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
   3383   // Unique pointers, to guarantee there is only one pointer of a particular
   3384   // structure.
   3385   llvm::FoldingSetNodeID ID;
   3386   MemberPointerType::Profile(ID, T, Cls);
   3387 
   3388   void *InsertPos = nullptr;
   3389   if (MemberPointerType *PT =
   3390       MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
   3391     return QualType(PT, 0);
   3392 
   3393   // If the pointee or class type isn't canonical, this won't be a canonical
   3394   // type either, so fill in the canonical type field.
   3395   QualType Canonical;
   3396   if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
   3397     Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
   3398 
   3399     // Get the new insert position for the node we care about.
   3400     MemberPointerType *NewIP =
   3401       MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
   3402     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
   3403   }
   3404   auto *New = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
   3405   Types.push_back(New);
   3406   MemberPointerTypes.InsertNode(New, InsertPos);
   3407   return QualType(New, 0);
   3408 }
   3409 
   3410 /// getConstantArrayType - Return the unique reference to the type for an
   3411 /// array of the specified element type.
   3412 QualType ASTContext::getConstantArrayType(QualType EltTy,
   3413                                           const llvm::APInt &ArySizeIn,
   3414                                           const Expr *SizeExpr,
   3415                                           ArrayType::ArraySizeModifier ASM,
   3416                                           unsigned IndexTypeQuals) const {
   3417   assert((EltTy->isDependentType() ||
   3418           EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
   3419          "Constant array of VLAs is illegal!");
   3420 
   3421   // We only need the size as part of the type if it's instantiation-dependent.
   3422   if (SizeExpr && !SizeExpr->isInstantiationDependent())
   3423     SizeExpr = nullptr;
   3424 
   3425   // Convert the array size into a canonical width matching the pointer size for
   3426   // the target.
   3427   llvm::APInt ArySize(ArySizeIn);
   3428   ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
   3429 
   3430   llvm::FoldingSetNodeID ID;
   3431   ConstantArrayType::Profile(ID, *this, EltTy, ArySize, SizeExpr, ASM,
   3432                              IndexTypeQuals);
   3433 
   3434   void *InsertPos = nullptr;
   3435   if (ConstantArrayType *ATP =
   3436       ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
   3437     return QualType(ATP, 0);
   3438 
   3439   // If the element type isn't canonical or has qualifiers, or the array bound
   3440   // is instantiation-dependent, this won't be a canonical type either, so fill
   3441   // in the canonical type field.
   3442   QualType Canon;
   3443   if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers() || SizeExpr) {
   3444     SplitQualType canonSplit = getCanonicalType(EltTy).split();
   3445     Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize, nullptr,
   3446                                  ASM, IndexTypeQuals);
   3447     Canon = getQualifiedType(Canon, canonSplit.Quals);
   3448 
   3449     // Get the new insert position for the node we care about.
   3450     ConstantArrayType *NewIP =
   3451       ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
   3452     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
   3453   }
   3454 
   3455   void *Mem = Allocate(
   3456       ConstantArrayType::totalSizeToAlloc<const Expr *>(SizeExpr ? 1 : 0),
   3457       TypeAlignment);
   3458   auto *New = new (Mem)
   3459     ConstantArrayType(EltTy, Canon, ArySize, SizeExpr, ASM, IndexTypeQuals);
   3460   ConstantArrayTypes.InsertNode(New, InsertPos);
   3461   Types.push_back(New);
   3462   return QualType(New, 0);
   3463 }
   3464 
   3465 /// getVariableArrayDecayedType - Turns the given type, which may be
   3466 /// variably-modified, into the corresponding type with all the known
   3467 /// sizes replaced with [*].
   3468 QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
   3469   // Vastly most common case.
   3470   if (!type->isVariablyModifiedType()) return type;
   3471 
   3472   QualType result;
   3473 
   3474   SplitQualType split = type.getSplitDesugaredType();
   3475   const Type *ty = split.Ty;
   3476   switch (ty->getTypeClass()) {
   3477 #define TYPE(Class, Base)
   3478 #define ABSTRACT_TYPE(Class, Base)
   3479 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
   3480 #include "clang/AST/TypeNodes.inc"
   3481     llvm_unreachable("didn't desugar past all non-canonical types?");
   3482 
   3483   // These types should never be variably-modified.
   3484   case Type::Builtin:
   3485   case Type::Complex:
   3486   case Type::Vector:
   3487   case Type::DependentVector:
   3488   case Type::ExtVector:
   3489   case Type::DependentSizedExtVector:
   3490   case Type::ConstantMatrix:
   3491   case Type::DependentSizedMatrix:
   3492   case Type::DependentAddressSpace:
   3493   case Type::ObjCObject:
   3494   case Type::ObjCInterface:
   3495   case Type::ObjCObjectPointer:
   3496   case Type::Record:
   3497   case Type::Enum:
   3498   case Type::UnresolvedUsing:
   3499   case Type::TypeOfExpr:
   3500   case Type::TypeOf:
   3501   case Type::Decltype:
   3502   case Type::UnaryTransform:
   3503   case Type::DependentName:
   3504   case Type::InjectedClassName:
   3505   case Type::TemplateSpecialization:
   3506   case Type::DependentTemplateSpecialization:
   3507   case Type::TemplateTypeParm:
   3508   case Type::SubstTemplateTypeParmPack:
   3509   case Type::Auto:
   3510   case Type::DeducedTemplateSpecialization:
   3511   case Type::PackExpansion:
   3512   case Type::ExtInt:
   3513   case Type::DependentExtInt:
   3514     llvm_unreachable("type should never be variably-modified");
   3515 
   3516   // These types can be variably-modified but should never need to
   3517   // further decay.
   3518   case Type::FunctionNoProto:
   3519   case Type::FunctionProto:
   3520   case Type::BlockPointer:
   3521   case Type::MemberPointer:
   3522   case Type::Pipe:
   3523     return type;
   3524 
   3525   // These types can be variably-modified.  All these modifications
   3526   // preserve structure except as noted by comments.
   3527   // TODO: if we ever care about optimizing VLAs, there are no-op
   3528   // optimizations available here.
   3529   case Type::Pointer:
   3530     result = getPointerType(getVariableArrayDecayedType(
   3531                               cast<PointerType>(ty)->getPointeeType()));
   3532     break;
   3533 
   3534   case Type::LValueReference: {
   3535     const auto *lv = cast<LValueReferenceType>(ty);
   3536     result = getLValueReferenceType(
   3537                  getVariableArrayDecayedType(lv->getPointeeType()),
   3538                                     lv->isSpelledAsLValue());
   3539     break;
   3540   }
   3541 
   3542   case Type::RValueReference: {
   3543     const auto *lv = cast<RValueReferenceType>(ty);
   3544     result = getRValueReferenceType(
   3545                  getVariableArrayDecayedType(lv->getPointeeType()));
   3546     break;
   3547   }
   3548 
   3549   case Type::Atomic: {
   3550     const auto *at = cast<AtomicType>(ty);
   3551     result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
   3552     break;
   3553   }
   3554 
   3555   case Type::ConstantArray: {
   3556     const auto *cat = cast<ConstantArrayType>(ty);
   3557     result = getConstantArrayType(
   3558                  getVariableArrayDecayedType(cat->getElementType()),
   3559                                   cat->getSize(),
   3560                                   cat->getSizeExpr(),
   3561                                   cat->getSizeModifier(),
   3562                                   cat->getIndexTypeCVRQualifiers());
   3563     break;
   3564   }
   3565 
   3566   case Type::DependentSizedArray: {
   3567     const auto *dat = cast<DependentSizedArrayType>(ty);
   3568     result = getDependentSizedArrayType(
   3569                  getVariableArrayDecayedType(dat->getElementType()),
   3570                                         dat->getSizeExpr(),
   3571                                         dat->getSizeModifier(),
   3572                                         dat->getIndexTypeCVRQualifiers(),
   3573                                         dat->getBracketsRange());
   3574     break;
   3575   }
   3576 
   3577   // Turn incomplete types into [*] types.
   3578   case Type::IncompleteArray: {
   3579     const auto *iat = cast<IncompleteArrayType>(ty);
   3580     result = getVariableArrayType(
   3581                  getVariableArrayDecayedType(iat->getElementType()),
   3582                                   /*size*/ nullptr,
   3583                                   ArrayType::Normal,
   3584                                   iat->getIndexTypeCVRQualifiers(),
   3585                                   SourceRange());
   3586     break;
   3587   }
   3588 
   3589   // Turn VLA types into [*] types.
   3590   case Type::VariableArray: {
   3591     const auto *vat = cast<VariableArrayType>(ty);
   3592     result = getVariableArrayType(
   3593                  getVariableArrayDecayedType(vat->getElementType()),
   3594                                   /*size*/ nullptr,
   3595                                   ArrayType::Star,
   3596                                   vat->getIndexTypeCVRQualifiers(),
   3597                                   vat->getBracketsRange());
   3598     break;
   3599   }
   3600   }
   3601 
   3602   // Apply the top-level qualifiers from the original.
   3603   return getQualifiedType(result, split.Quals);
   3604 }
   3605 
   3606 /// getVariableArrayType - Returns a non-unique reference to the type for a
   3607 /// variable array of the specified element type.
   3608 QualType ASTContext::getVariableArrayType(QualType EltTy,
   3609                                           Expr *NumElts,
   3610                                           ArrayType::ArraySizeModifier ASM,
   3611                                           unsigned IndexTypeQuals,
   3612                                           SourceRange Brackets) const {
   3613   // Since we don't unique expressions, it isn't possible to unique VLA's
   3614   // that have an expression provided for their size.
   3615   QualType Canon;
   3616 
   3617   // Be sure to pull qualifiers off the element type.
   3618   if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
   3619     SplitQualType canonSplit = getCanonicalType(EltTy).split();
   3620     Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
   3621                                  IndexTypeQuals, Brackets);
   3622     Canon = getQualifiedType(Canon, canonSplit.Quals);
   3623   }
   3624 
   3625   auto *New = new (*this, TypeAlignment)
   3626     VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
   3627 
   3628   VariableArrayTypes.push_back(New);
   3629   Types.push_back(New);
   3630   return QualType(New, 0);
   3631 }
   3632 
   3633 /// getDependentSizedArrayType - Returns a non-unique reference to
   3634 /// the type for a dependently-sized array of the specified element
   3635 /// type.
   3636 QualType ASTContext::getDependentSizedArrayType(QualType elementType,
   3637                                                 Expr *numElements,
   3638                                                 ArrayType::ArraySizeModifier ASM,
   3639                                                 unsigned elementTypeQuals,
   3640                                                 SourceRange brackets) const {
   3641   assert((!numElements || numElements->isTypeDependent() ||
   3642           numElements->isValueDependent()) &&
   3643          "Size must be type- or value-dependent!");
   3644 
   3645   // Dependently-sized array types that do not have a specified number
   3646   // of elements will have their sizes deduced from a dependent
   3647   // initializer.  We do no canonicalization here at all, which is okay
   3648   // because they can't be used in most locations.
   3649   if (!numElements) {
   3650     auto *newType
   3651       = new (*this, TypeAlignment)
   3652           DependentSizedArrayType(*this, elementType, QualType(),
   3653                                   numElements, ASM, elementTypeQuals,
   3654                                   brackets);
   3655     Types.push_back(newType);
   3656     return QualType(newType, 0);
   3657   }
   3658 
   3659   // Otherwise, we actually build a new type every time, but we
   3660   // also build a canonical type.
   3661 
   3662   SplitQualType canonElementType = getCanonicalType(elementType).split();
   3663 
   3664   void *insertPos = nullptr;
   3665   llvm::FoldingSetNodeID ID;
   3666   DependentSizedArrayType::Profile(ID, *this,
   3667                                    QualType(canonElementType.Ty, 0),
   3668                                    ASM, elementTypeQuals, numElements);
   3669 
   3670   // Look for an existing type with these properties.
   3671   DependentSizedArrayType *canonTy =
   3672     DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
   3673 
   3674   // If we don't have one, build one.
   3675   if (!canonTy) {
   3676     canonTy = new (*this, TypeAlignment)
   3677       DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
   3678                               QualType(), numElements, ASM, elementTypeQuals,
   3679                               brackets);
   3680     DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
   3681     Types.push_back(canonTy);
   3682   }
   3683 
   3684   // Apply qualifiers from the element type to the array.
   3685   QualType canon = getQualifiedType(QualType(canonTy,0),
   3686                                     canonElementType.Quals);
   3687 
   3688   // If we didn't need extra canonicalization for the element type or the size
   3689   // expression, then just use that as our result.
   3690   if (QualType(canonElementType.Ty, 0) == elementType &&
   3691       canonTy->getSizeExpr() == numElements)
   3692     return canon;
   3693 
   3694   // Otherwise, we need to build a type which follows the spelling
   3695   // of the element type.
   3696   auto *sugaredType
   3697     = new (*this, TypeAlignment)
   3698         DependentSizedArrayType(*this, elementType, canon, numElements,
   3699                                 ASM, elementTypeQuals, brackets);
   3700   Types.push_back(sugaredType);
   3701   return QualType(sugaredType, 0);
   3702 }
   3703 
   3704 QualType ASTContext::getIncompleteArrayType(QualType elementType,
   3705                                             ArrayType::ArraySizeModifier ASM,
   3706                                             unsigned elementTypeQuals) const {
   3707   llvm::FoldingSetNodeID ID;
   3708   IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
   3709 
   3710   void *insertPos = nullptr;
   3711   if (IncompleteArrayType *iat =
   3712        IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
   3713     return QualType(iat, 0);
   3714 
   3715   // If the element type isn't canonical, this won't be a canonical type
   3716   // either, so fill in the canonical type field.  We also have to pull
   3717   // qualifiers off the element type.
   3718   QualType canon;
   3719 
   3720   if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
   3721     SplitQualType canonSplit = getCanonicalType(elementType).split();
   3722     canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
   3723                                    ASM, elementTypeQuals);
   3724     canon = getQualifiedType(canon, canonSplit.Quals);
   3725 
   3726     // Get the new insert position for the node we care about.
   3727     IncompleteArrayType *existing =
   3728       IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
   3729     assert(!existing && "Shouldn't be in the map!"); (void) existing;
   3730   }
   3731 
   3732   auto *newType = new (*this, TypeAlignment)
   3733     IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
   3734 
   3735   IncompleteArrayTypes.InsertNode(newType, insertPos);
   3736   Types.push_back(newType);
   3737   return QualType(newType, 0);
   3738 }
   3739 
   3740 ASTContext::BuiltinVectorTypeInfo
   3741 ASTContext::getBuiltinVectorTypeInfo(const BuiltinType *Ty) const {
   3742 #define SVE_INT_ELTTY(BITS, ELTS, SIGNED, NUMVECTORS)                          \
   3743   {getIntTypeForBitwidth(BITS, SIGNED), llvm::ElementCount::getScalable(ELTS), \
   3744    NUMVECTORS};
   3745 
   3746 #define SVE_ELTTY(ELTTY, ELTS, NUMVECTORS)                                     \
   3747   {ELTTY, llvm::ElementCount::getScalable(ELTS), NUMVECTORS};
   3748 
   3749   switch (Ty->getKind()) {
   3750   default:
   3751     llvm_unreachable("Unsupported builtin vector type");
   3752   case BuiltinType::SveInt8:
   3753     return SVE_INT_ELTTY(8, 16, true, 1);
   3754   case BuiltinType::SveUint8:
   3755     return SVE_INT_ELTTY(8, 16, false, 1);
   3756   case BuiltinType::SveInt8x2:
   3757     return SVE_INT_ELTTY(8, 16, true, 2);
   3758   case BuiltinType::SveUint8x2:
   3759     return SVE_INT_ELTTY(8, 16, false, 2);
   3760   case BuiltinType::SveInt8x3:
   3761     return SVE_INT_ELTTY(8, 16, true, 3);
   3762   case BuiltinType::SveUint8x3:
   3763     return SVE_INT_ELTTY(8, 16, false, 3);
   3764   case BuiltinType::SveInt8x4:
   3765     return SVE_INT_ELTTY(8, 16, true, 4);
   3766   case BuiltinType::SveUint8x4:
   3767     return SVE_INT_ELTTY(8, 16, false, 4);
   3768   case BuiltinType::SveInt16:
   3769     return SVE_INT_ELTTY(16, 8, true, 1);
   3770   case BuiltinType::SveUint16:
   3771     return SVE_INT_ELTTY(16, 8, false, 1);
   3772   case BuiltinType::SveInt16x2:
   3773     return SVE_INT_ELTTY(16, 8, true, 2);
   3774   case BuiltinType::SveUint16x2:
   3775     return SVE_INT_ELTTY(16, 8, false, 2);
   3776   case BuiltinType::SveInt16x3:
   3777     return SVE_INT_ELTTY(16, 8, true, 3);
   3778   case BuiltinType::SveUint16x3:
   3779     return SVE_INT_ELTTY(16, 8, false, 3);
   3780   case BuiltinType::SveInt16x4:
   3781     return SVE_INT_ELTTY(16, 8, true, 4);
   3782   case BuiltinType::SveUint16x4:
   3783     return SVE_INT_ELTTY(16, 8, false, 4);
   3784   case BuiltinType::SveInt32:
   3785     return SVE_INT_ELTTY(32, 4, true, 1);
   3786   case BuiltinType::SveUint32:
   3787     return SVE_INT_ELTTY(32, 4, false, 1);
   3788   case BuiltinType::SveInt32x2:
   3789     return SVE_INT_ELTTY(32, 4, true, 2);
   3790   case BuiltinType::SveUint32x2:
   3791     return SVE_INT_ELTTY(32, 4, false, 2);
   3792   case BuiltinType::SveInt32x3:
   3793     return SVE_INT_ELTTY(32, 4, true, 3);
   3794   case BuiltinType::SveUint32x3:
   3795     return SVE_INT_ELTTY(32, 4, false, 3);
   3796   case BuiltinType::SveInt32x4:
   3797     return SVE_INT_ELTTY(32, 4, true, 4);
   3798   case BuiltinType::SveUint32x4:
   3799     return SVE_INT_ELTTY(32, 4, false, 4);
   3800   case BuiltinType::SveInt64:
   3801     return SVE_INT_ELTTY(64, 2, true, 1);
   3802   case BuiltinType::SveUint64:
   3803     return SVE_INT_ELTTY(64, 2, false, 1);
   3804   case BuiltinType::SveInt64x2:
   3805     return SVE_INT_ELTTY(64, 2, true, 2);
   3806   case BuiltinType::SveUint64x2:
   3807     return SVE_INT_ELTTY(64, 2, false, 2);
   3808   case BuiltinType::SveInt64x3:
   3809     return SVE_INT_ELTTY(64, 2, true, 3);
   3810   case BuiltinType::SveUint64x3:
   3811     return SVE_INT_ELTTY(64, 2, false, 3);
   3812   case BuiltinType::SveInt64x4:
   3813     return SVE_INT_ELTTY(64, 2, true, 4);
   3814   case BuiltinType::SveUint64x4:
   3815     return SVE_INT_ELTTY(64, 2, false, 4);
   3816   case BuiltinType::SveBool:
   3817     return SVE_ELTTY(BoolTy, 16, 1);
   3818   case BuiltinType::SveFloat16:
   3819     return SVE_ELTTY(HalfTy, 8, 1);
   3820   case BuiltinType::SveFloat16x2:
   3821     return SVE_ELTTY(HalfTy, 8, 2);
   3822   case BuiltinType::SveFloat16x3:
   3823     return SVE_ELTTY(HalfTy, 8, 3);
   3824   case BuiltinType::SveFloat16x4:
   3825     return SVE_ELTTY(HalfTy, 8, 4);
   3826   case BuiltinType::SveFloat32:
   3827     return SVE_ELTTY(FloatTy, 4, 1);
   3828   case BuiltinType::SveFloat32x2:
   3829     return SVE_ELTTY(FloatTy, 4, 2);
   3830   case BuiltinType::SveFloat32x3:
   3831     return SVE_ELTTY(FloatTy, 4, 3);
   3832   case BuiltinType::SveFloat32x4:
   3833     return SVE_ELTTY(FloatTy, 4, 4);
   3834   case BuiltinType::SveFloat64:
   3835     return SVE_ELTTY(DoubleTy, 2, 1);
   3836   case BuiltinType::SveFloat64x2:
   3837     return SVE_ELTTY(DoubleTy, 2, 2);
   3838   case BuiltinType::SveFloat64x3:
   3839     return SVE_ELTTY(DoubleTy, 2, 3);
   3840   case BuiltinType::SveFloat64x4:
   3841     return SVE_ELTTY(DoubleTy, 2, 4);
   3842   case BuiltinType::SveBFloat16:
   3843     return SVE_ELTTY(BFloat16Ty, 8, 1);
   3844   case BuiltinType::SveBFloat16x2:
   3845     return SVE_ELTTY(BFloat16Ty, 8, 2);
   3846   case BuiltinType::SveBFloat16x3:
   3847     return SVE_ELTTY(BFloat16Ty, 8, 3);
   3848   case BuiltinType::SveBFloat16x4:
   3849     return SVE_ELTTY(BFloat16Ty, 8, 4);
   3850 #define RVV_VECTOR_TYPE_INT(Name, Id, SingletonId, NumEls, ElBits, NF,         \
   3851                             IsSigned)                                          \
   3852   case BuiltinType::Id:                                                        \
   3853     return {getIntTypeForBitwidth(ElBits, IsSigned),                           \
   3854             llvm::ElementCount::getScalable(NumEls), NF};
   3855 #define RVV_VECTOR_TYPE_FLOAT(Name, Id, SingletonId, NumEls, ElBits, NF)       \
   3856   case BuiltinType::Id:                                                        \
   3857     return {ElBits == 16 ? HalfTy : (ElBits == 32 ? FloatTy : DoubleTy),       \
   3858             llvm::ElementCount::getScalable(NumEls), NF};
   3859 #define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls)                      \
   3860   case BuiltinType::Id:                                                        \
   3861     return {BoolTy, llvm::ElementCount::getScalable(NumEls), 1};
   3862 #include "clang/Basic/RISCVVTypes.def"
   3863   }
   3864 }
   3865 
   3866 /// getScalableVectorType - Return the unique reference to a scalable vector
   3867 /// type of the specified element type and size. VectorType must be a built-in
   3868 /// type.
   3869 QualType ASTContext::getScalableVectorType(QualType EltTy,
   3870                                            unsigned NumElts) const {
   3871   if (Target->hasAArch64SVETypes()) {
   3872     uint64_t EltTySize = getTypeSize(EltTy);
   3873 #define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId, NumEls, ElBits,    \
   3874                         IsSigned, IsFP, IsBF)                                  \
   3875   if (!EltTy->isBooleanType() &&                                               \
   3876       ((EltTy->hasIntegerRepresentation() &&                                   \
   3877         EltTy->hasSignedIntegerRepresentation() == IsSigned) ||                \
   3878        (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() &&      \
   3879         IsFP && !IsBF) ||                                                      \
   3880        (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() &&       \
   3881         IsBF && !IsFP)) &&                                                     \
   3882       EltTySize == ElBits && NumElts == NumEls) {                              \
   3883     return SingletonId;                                                        \
   3884   }
   3885 #define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId, NumEls)         \
   3886   if (EltTy->isBooleanType() && NumElts == NumEls)                             \
   3887     return SingletonId;
   3888 #include "clang/Basic/AArch64SVEACLETypes.def"
   3889   } else if (Target->hasRISCVVTypes()) {
   3890     uint64_t EltTySize = getTypeSize(EltTy);
   3891 #define RVV_VECTOR_TYPE(Name, Id, SingletonId, NumEls, ElBits, NF, IsSigned,   \
   3892                         IsFP)                                                  \
   3893     if (!EltTy->isBooleanType() &&                                             \
   3894         ((EltTy->hasIntegerRepresentation() &&                                 \
   3895           EltTy->hasSignedIntegerRepresentation() == IsSigned) ||              \
   3896          (EltTy->hasFloatingRepresentation() && IsFP)) &&                      \
   3897         EltTySize == ElBits && NumElts == NumEls)                              \
   3898       return SingletonId;
   3899 #define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls)                      \
   3900     if (EltTy->isBooleanType() && NumElts == NumEls)                           \
   3901       return SingletonId;
   3902 #include "clang/Basic/RISCVVTypes.def"
   3903   }
   3904   return QualType();
   3905 }
   3906 
   3907 /// getVectorType - Return the unique reference to a vector type of
   3908 /// the specified element type and size. VectorType must be a built-in type.
   3909 QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
   3910                                    VectorType::VectorKind VecKind) const {
   3911   assert(vecType->isBuiltinType());
   3912 
   3913   // Check if we've already instantiated a vector of this type.
   3914   llvm::FoldingSetNodeID ID;
   3915   VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
   3916 
   3917   void *InsertPos = nullptr;
   3918   if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
   3919     return QualType(VTP, 0);
   3920 
   3921   // If the element type isn't canonical, this won't be a canonical type either,
   3922   // so fill in the canonical type field.
   3923   QualType Canonical;
   3924   if (!vecType.isCanonical()) {
   3925     Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
   3926 
   3927     // Get the new insert position for the node we care about.
   3928     VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
   3929     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
   3930   }
   3931   auto *New = new (*this, TypeAlignment)
   3932     VectorType(vecType, NumElts, Canonical, VecKind);
   3933   VectorTypes.InsertNode(New, InsertPos);
   3934   Types.push_back(New);
   3935   return QualType(New, 0);
   3936 }
   3937 
   3938 QualType
   3939 ASTContext::getDependentVectorType(QualType VecType, Expr *SizeExpr,
   3940                                    SourceLocation AttrLoc,
   3941                                    VectorType::VectorKind VecKind) const {
   3942   llvm::FoldingSetNodeID ID;
   3943   DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr,
   3944                                VecKind);
   3945   void *InsertPos = nullptr;
   3946   DependentVectorType *Canon =
   3947       DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
   3948   DependentVectorType *New;
   3949 
   3950   if (Canon) {
   3951     New = new (*this, TypeAlignment) DependentVectorType(
   3952         *this, VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind);
   3953   } else {
   3954     QualType CanonVecTy = getCanonicalType(VecType);
   3955     if (CanonVecTy == VecType) {
   3956       New = new (*this, TypeAlignment) DependentVectorType(
   3957           *this, VecType, QualType(), SizeExpr, AttrLoc, VecKind);
   3958 
   3959       DependentVectorType *CanonCheck =
   3960           DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
   3961       assert(!CanonCheck &&
   3962              "Dependent-sized vector_size canonical type broken");
   3963       (void)CanonCheck;
   3964       DependentVectorTypes.InsertNode(New, InsertPos);
   3965     } else {
   3966       QualType CanonTy = getDependentVectorType(CanonVecTy, SizeExpr,
   3967                                                 SourceLocation(), VecKind);
   3968       New = new (*this, TypeAlignment) DependentVectorType(
   3969           *this, VecType, CanonTy, SizeExpr, AttrLoc, VecKind);
   3970     }
   3971   }
   3972 
   3973   Types.push_back(New);
   3974   return QualType(New, 0);
   3975 }
   3976 
   3977 /// getExtVectorType - Return the unique reference to an extended vector type of
   3978 /// the specified element type and size. VectorType must be a built-in type.
   3979 QualType
   3980 ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
   3981   assert(vecType->isBuiltinType() || vecType->isDependentType());
   3982 
   3983   // Check if we've already instantiated a vector of this type.
   3984   llvm::FoldingSetNodeID ID;
   3985   VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
   3986                       VectorType::GenericVector);
   3987   void *InsertPos = nullptr;
   3988   if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
   3989     return QualType(VTP, 0);
   3990 
   3991   // If the element type isn't canonical, this won't be a canonical type either,
   3992   // so fill in the canonical type field.
   3993   QualType Canonical;
   3994   if (!vecType.isCanonical()) {
   3995     Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
   3996 
   3997     // Get the new insert position for the node we care about.
   3998     VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
   3999     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
   4000   }
   4001   auto *New = new (*this, TypeAlignment)
   4002     ExtVectorType(vecType, NumElts, Canonical);
   4003   VectorTypes.InsertNode(New, InsertPos);
   4004   Types.push_back(New);
   4005   return QualType(New, 0);
   4006 }
   4007 
   4008 QualType
   4009 ASTContext::getDependentSizedExtVectorType(QualType vecType,
   4010                                            Expr *SizeExpr,
   4011                                            SourceLocation AttrLoc) const {
   4012   llvm::FoldingSetNodeID ID;
   4013   DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
   4014                                        SizeExpr);
   4015 
   4016   void *InsertPos = nullptr;
   4017   DependentSizedExtVectorType *Canon
   4018     = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
   4019   DependentSizedExtVectorType *New;
   4020   if (Canon) {
   4021     // We already have a canonical version of this array type; use it as
   4022     // the canonical type for a newly-built type.
   4023     New = new (*this, TypeAlignment)
   4024       DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
   4025                                   SizeExpr, AttrLoc);
   4026   } else {
   4027     QualType CanonVecTy = getCanonicalType(vecType);
   4028     if (CanonVecTy == vecType) {
   4029       New = new (*this, TypeAlignment)
   4030         DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
   4031                                     AttrLoc);
   4032 
   4033       DependentSizedExtVectorType *CanonCheck
   4034         = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
   4035       assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
   4036       (void)CanonCheck;
   4037       DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
   4038     } else {
   4039       QualType CanonExtTy = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
   4040                                                            SourceLocation());
   4041       New = new (*this, TypeAlignment) DependentSizedExtVectorType(
   4042           *this, vecType, CanonExtTy, SizeExpr, AttrLoc);
   4043     }
   4044   }
   4045 
   4046   Types.push_back(New);
   4047   return QualType(New, 0);
   4048 }
   4049 
   4050 QualType ASTContext::getConstantMatrixType(QualType ElementTy, unsigned NumRows,
   4051                                            unsigned NumColumns) const {
   4052   llvm::FoldingSetNodeID ID;
   4053   ConstantMatrixType::Profile(ID, ElementTy, NumRows, NumColumns,
   4054                               Type::ConstantMatrix);
   4055 
   4056   assert(MatrixType::isValidElementType(ElementTy) &&
   4057          "need a valid element type");
   4058   assert(ConstantMatrixType::isDimensionValid(NumRows) &&
   4059          ConstantMatrixType::isDimensionValid(NumColumns) &&
   4060          "need valid matrix dimensions");
   4061   void *InsertPos = nullptr;
   4062   if (ConstantMatrixType *MTP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos))
   4063     return QualType(MTP, 0);
   4064 
   4065   QualType Canonical;
   4066   if (!ElementTy.isCanonical()) {
   4067     Canonical =
   4068         getConstantMatrixType(getCanonicalType(ElementTy), NumRows, NumColumns);
   4069 
   4070     ConstantMatrixType *NewIP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
   4071     assert(!NewIP && "Matrix type shouldn't already exist in the map");
   4072     (void)NewIP;
   4073   }
   4074 
   4075   auto *New = new (*this, TypeAlignment)
   4076       ConstantMatrixType(ElementTy, NumRows, NumColumns, Canonical);
   4077   MatrixTypes.InsertNode(New, InsertPos);
   4078   Types.push_back(New);
   4079   return QualType(New, 0);
   4080 }
   4081 
   4082 QualType ASTContext::getDependentSizedMatrixType(QualType ElementTy,
   4083                                                  Expr *RowExpr,
   4084                                                  Expr *ColumnExpr,
   4085                                                  SourceLocation AttrLoc) const {
   4086   QualType CanonElementTy = getCanonicalType(ElementTy);
   4087   llvm::FoldingSetNodeID ID;
   4088   DependentSizedMatrixType::Profile(ID, *this, CanonElementTy, RowExpr,
   4089                                     ColumnExpr);
   4090 
   4091   void *InsertPos = nullptr;
   4092   DependentSizedMatrixType *Canon =
   4093       DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
   4094 
   4095   if (!Canon) {
   4096     Canon = new (*this, TypeAlignment) DependentSizedMatrixType(
   4097         *this, CanonElementTy, QualType(), RowExpr, ColumnExpr, AttrLoc);
   4098 #ifndef NDEBUG
   4099     DependentSizedMatrixType *CanonCheck =
   4100         DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
   4101     assert(!CanonCheck && "Dependent-sized matrix canonical type broken");
   4102 #endif
   4103     DependentSizedMatrixTypes.InsertNode(Canon, InsertPos);
   4104     Types.push_back(Canon);
   4105   }
   4106 
   4107   // Already have a canonical version of the matrix type
   4108   //
   4109   // If it exactly matches the requested type, use it directly.
   4110   if (Canon->getElementType() == ElementTy && Canon->getRowExpr() == RowExpr &&
   4111       Canon->getRowExpr() == ColumnExpr)
   4112     return QualType(Canon, 0);
   4113 
   4114   // Use Canon as the canonical type for newly-built type.
   4115   DependentSizedMatrixType *New = new (*this, TypeAlignment)
   4116       DependentSizedMatrixType(*this, ElementTy, QualType(Canon, 0), RowExpr,
   4117                                ColumnExpr, AttrLoc);
   4118   Types.push_back(New);
   4119   return QualType(New, 0);
   4120 }
   4121 
   4122 QualType ASTContext::getDependentAddressSpaceType(QualType PointeeType,
   4123                                                   Expr *AddrSpaceExpr,
   4124                                                   SourceLocation AttrLoc) const {
   4125   assert(AddrSpaceExpr->isInstantiationDependent());
   4126 
   4127   QualType canonPointeeType = getCanonicalType(PointeeType);
   4128 
   4129   void *insertPos = nullptr;
   4130   llvm::FoldingSetNodeID ID;
   4131   DependentAddressSpaceType::Profile(ID, *this, canonPointeeType,
   4132                                      AddrSpaceExpr);
   4133 
   4134   DependentAddressSpaceType *canonTy =
   4135     DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos);
   4136 
   4137   if (!canonTy) {
   4138     canonTy = new (*this, TypeAlignment)
   4139       DependentAddressSpaceType(*this, canonPointeeType,
   4140                                 QualType(), AddrSpaceExpr, AttrLoc);
   4141     DependentAddressSpaceTypes.InsertNode(canonTy, insertPos);
   4142     Types.push_back(canonTy);
   4143   }
   4144 
   4145   if (canonPointeeType == PointeeType &&
   4146       canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
   4147     return QualType(canonTy, 0);
   4148 
   4149   auto *sugaredType
   4150     = new (*this, TypeAlignment)
   4151         DependentAddressSpaceType(*this, PointeeType, QualType(canonTy, 0),
   4152                                   AddrSpaceExpr, AttrLoc);
   4153   Types.push_back(sugaredType);
   4154   return QualType(sugaredType, 0);
   4155 }
   4156 
   4157 /// Determine whether \p T is canonical as the result type of a function.
   4158 static bool isCanonicalResultType(QualType T) {
   4159   return T.isCanonical() &&
   4160          (T.getObjCLifetime() == Qualifiers::OCL_None ||
   4161           T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
   4162 }
   4163 
   4164 /// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
   4165 QualType
   4166 ASTContext::getFunctionNoProtoType(QualType ResultTy,
   4167                                    const FunctionType::ExtInfo &Info) const {
   4168   // Unique functions, to guarantee there is only one function of a particular
   4169   // structure.
   4170   llvm::FoldingSetNodeID ID;
   4171   FunctionNoProtoType::Profile(ID, ResultTy, Info);
   4172 
   4173   void *InsertPos = nullptr;
   4174   if (FunctionNoProtoType *FT =
   4175         FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
   4176     return QualType(FT, 0);
   4177 
   4178   QualType Canonical;
   4179   if (!isCanonicalResultType(ResultTy)) {
   4180     Canonical =
   4181       getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info);
   4182 
   4183     // Get the new insert position for the node we care about.
   4184     FunctionNoProtoType *NewIP =
   4185       FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
   4186     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
   4187   }
   4188 
   4189   auto *New = new (*this, TypeAlignment)
   4190     FunctionNoProtoType(ResultTy, Canonical, Info);
   4191   Types.push_back(New);
   4192   FunctionNoProtoTypes.InsertNode(New, InsertPos);
   4193   return QualType(New, 0);
   4194 }
   4195 
   4196 CanQualType
   4197 ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
   4198   CanQualType CanResultType = getCanonicalType(ResultType);
   4199 
   4200   // Canonical result types do not have ARC lifetime qualifiers.
   4201   if (CanResultType.getQualifiers().hasObjCLifetime()) {
   4202     Qualifiers Qs = CanResultType.getQualifiers();
   4203     Qs.removeObjCLifetime();
   4204     return CanQualType::CreateUnsafe(
   4205              getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
   4206   }
   4207 
   4208   return CanResultType;
   4209 }
   4210 
   4211 static bool isCanonicalExceptionSpecification(
   4212     const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
   4213   if (ESI.Type == EST_None)
   4214     return true;
   4215   if (!NoexceptInType)
   4216     return false;
   4217 
   4218   // C++17 onwards: exception specification is part of the type, as a simple
   4219   // boolean "can this function type throw".
   4220   if (ESI.Type == EST_BasicNoexcept)
   4221     return true;
   4222 
   4223   // A noexcept(expr) specification is (possibly) canonical if expr is
   4224   // value-dependent.
   4225   if (ESI.Type == EST_DependentNoexcept)
   4226     return true;
   4227 
   4228   // A dynamic exception specification is canonical if it only contains pack
   4229   // expansions (so we can't tell whether it's non-throwing) and all its
   4230   // contained types are canonical.
   4231   if (ESI.Type == EST_Dynamic) {
   4232     bool AnyPackExpansions = false;
   4233     for (QualType ET : ESI.Exceptions) {
   4234       if (!ET.isCanonical())
   4235         return false;
   4236       if (ET->getAs<PackExpansionType>())
   4237         AnyPackExpansions = true;
   4238     }
   4239     return AnyPackExpansions;
   4240   }
   4241 
   4242   return false;
   4243 }
   4244 
   4245 QualType ASTContext::getFunctionTypeInternal(
   4246     QualType ResultTy, ArrayRef<QualType> ArgArray,
   4247     const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
   4248   size_t NumArgs = ArgArray.size();
   4249 
   4250   // Unique functions, to guarantee there is only one function of a particular
   4251   // structure.
   4252   llvm::FoldingSetNodeID ID;
   4253   FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
   4254                              *this, true);
   4255 
   4256   QualType Canonical;
   4257   bool Unique = false;
   4258 
   4259   void *InsertPos = nullptr;
   4260   if (FunctionProtoType *FPT =
   4261         FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
   4262     QualType Existing = QualType(FPT, 0);
   4263 
   4264     // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
   4265     // it so long as our exception specification doesn't contain a dependent
   4266     // noexcept expression, or we're just looking for a canonical type.
   4267     // Otherwise, we're going to need to create a type
   4268     // sugar node to hold the concrete expression.
   4269     if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) ||
   4270         EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
   4271       return Existing;
   4272 
   4273     // We need a new type sugar node for this one, to hold the new noexcept
   4274     // expression. We do no canonicalization here, but that's OK since we don't
   4275     // expect to see the same noexcept expression much more than once.
   4276     Canonical = getCanonicalType(Existing);
   4277     Unique = true;
   4278   }
   4279 
   4280   bool NoexceptInType = getLangOpts().CPlusPlus17;
   4281   bool IsCanonicalExceptionSpec =
   4282       isCanonicalExceptionSpecification(EPI.ExceptionSpec, NoexceptInType);
   4283 
   4284   // Determine whether the type being created is already canonical or not.
   4285   bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
   4286                      isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
   4287   for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
   4288     if (!ArgArray[i].isCanonicalAsParam())
   4289       isCanonical = false;
   4290 
   4291   if (OnlyWantCanonical)
   4292     assert(isCanonical &&
   4293            "given non-canonical parameters constructing canonical type");
   4294 
   4295   // If this type isn't canonical, get the canonical version of it if we don't
   4296   // already have it. The exception spec is only partially part of the
   4297   // canonical type, and only in C++17 onwards.
   4298   if (!isCanonical && Canonical.isNull()) {
   4299     SmallVector<QualType, 16> CanonicalArgs;
   4300     CanonicalArgs.reserve(NumArgs);
   4301     for (unsigned i = 0; i != NumArgs; ++i)
   4302       CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
   4303 
   4304     llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
   4305     FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
   4306     CanonicalEPI.HasTrailingReturn = false;
   4307 
   4308     if (IsCanonicalExceptionSpec) {
   4309       // Exception spec is already OK.
   4310     } else if (NoexceptInType) {
   4311       switch (EPI.ExceptionSpec.Type) {
   4312       case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated:
   4313         // We don't know yet. It shouldn't matter what we pick here; no-one
   4314         // should ever look at this.
   4315         LLVM_FALLTHROUGH;
   4316       case EST_None: case EST_MSAny: case EST_NoexceptFalse:
   4317         CanonicalEPI.ExceptionSpec.Type = EST_None;
   4318         break;
   4319 
   4320         // A dynamic exception specification is almost always "not noexcept",
   4321         // with the exception that a pack expansion might expand to no types.
   4322       case EST_Dynamic: {
   4323         bool AnyPacks = false;
   4324         for (QualType ET : EPI.ExceptionSpec.Exceptions) {
   4325           if (ET->getAs<PackExpansionType>())
   4326             AnyPacks = true;
   4327           ExceptionTypeStorage.push_back(getCanonicalType(ET));
   4328         }
   4329         if (!AnyPacks)
   4330           CanonicalEPI.ExceptionSpec.Type = EST_None;
   4331         else {
   4332           CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
   4333           CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
   4334         }
   4335         break;
   4336       }
   4337 
   4338       case EST_DynamicNone:
   4339       case EST_BasicNoexcept:
   4340       case EST_NoexceptTrue:
   4341       case EST_NoThrow:
   4342         CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
   4343         break;
   4344 
   4345       case EST_DependentNoexcept:
   4346         llvm_unreachable("dependent noexcept is already canonical");
   4347       }
   4348     } else {
   4349       CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
   4350     }
   4351 
   4352     // Adjust the canonical function result type.
   4353     CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
   4354     Canonical =
   4355         getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
   4356 
   4357     // Get the new insert position for the node we care about.
   4358     FunctionProtoType *NewIP =
   4359       FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
   4360     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
   4361   }
   4362 
   4363   // Compute the needed size to hold this FunctionProtoType and the
   4364   // various trailing objects.
   4365   auto ESH = FunctionProtoType::getExceptionSpecSize(
   4366       EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size());
   4367   size_t Size = FunctionProtoType::totalSizeToAlloc<
   4368       QualType, SourceLocation, FunctionType::FunctionTypeExtraBitfields,
   4369       FunctionType::ExceptionType, Expr *, FunctionDecl *,
   4370       FunctionProtoType::ExtParameterInfo, Qualifiers>(
   4371       NumArgs, EPI.Variadic,
   4372       FunctionProtoType::hasExtraBitfields(EPI.ExceptionSpec.Type),
   4373       ESH.NumExceptionType, ESH.NumExprPtr, ESH.NumFunctionDeclPtr,
   4374       EPI.ExtParameterInfos ? NumArgs : 0,
   4375       EPI.TypeQuals.hasNonFastQualifiers() ? 1 : 0);
   4376 
   4377   auto *FTP = (FunctionProtoType *)Allocate(Size, TypeAlignment);
   4378   FunctionProtoType::ExtProtoInfo newEPI = EPI;
   4379   new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
   4380   Types.push_back(FTP);
   4381   if (!Unique)
   4382     FunctionProtoTypes.InsertNode(FTP, InsertPos);
   4383   return QualType(FTP, 0);
   4384 }
   4385 
   4386 QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
   4387   llvm::FoldingSetNodeID ID;
   4388   PipeType::Profile(ID, T, ReadOnly);
   4389 
   4390   void *InsertPos = nullptr;
   4391   if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
   4392     return QualType(PT, 0);
   4393 
   4394   // If the pipe element type isn't canonical, this won't be a canonical type
   4395   // either, so fill in the canonical type field.
   4396   QualType Canonical;
   4397   if (!T.isCanonical()) {
   4398     Canonical = getPipeType(getCanonicalType(T), ReadOnly);
   4399 
   4400     // Get the new insert position for the node we care about.
   4401     PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
   4402     assert(!NewIP && "Shouldn't be in the map!");
   4403     (void)NewIP;
   4404   }
   4405   auto *New = new (*this, TypeAlignment) PipeType(T, Canonical, ReadOnly);
   4406   Types.push_back(New);
   4407   PipeTypes.InsertNode(New, InsertPos);
   4408   return QualType(New, 0);
   4409 }
   4410 
   4411 QualType ASTContext::adjustStringLiteralBaseType(QualType Ty) const {
   4412   // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
   4413   return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant)
   4414                          : Ty;
   4415 }
   4416 
   4417 QualType ASTContext::getReadPipeType(QualType T) const {
   4418   return getPipeType(T, true);
   4419 }
   4420 
   4421 QualType ASTContext::getWritePipeType(QualType T) const {
   4422   return getPipeType(T, false);
   4423 }
   4424 
   4425 QualType ASTContext::getExtIntType(bool IsUnsigned, unsigned NumBits) const {
   4426   llvm::FoldingSetNodeID ID;
   4427   ExtIntType::Profile(ID, IsUnsigned, NumBits);
   4428 
   4429   void *InsertPos = nullptr;
   4430   if (ExtIntType *EIT = ExtIntTypes.FindNodeOrInsertPos(ID, InsertPos))
   4431     return QualType(EIT, 0);
   4432 
   4433   auto *New = new (*this, TypeAlignment) ExtIntType(IsUnsigned, NumBits);
   4434   ExtIntTypes.InsertNode(New, InsertPos);
   4435   Types.push_back(New);
   4436   return QualType(New, 0);
   4437 }
   4438 
   4439 QualType ASTContext::getDependentExtIntType(bool IsUnsigned,
   4440                                             Expr *NumBitsExpr) const {
   4441   assert(NumBitsExpr->isInstantiationDependent() && "Only good for dependent");
   4442   llvm::FoldingSetNodeID ID;
   4443   DependentExtIntType::Profile(ID, *this, IsUnsigned, NumBitsExpr);
   4444 
   4445   void *InsertPos = nullptr;
   4446   if (DependentExtIntType *Existing =
   4447           DependentExtIntTypes.FindNodeOrInsertPos(ID, InsertPos))
   4448     return QualType(Existing, 0);
   4449 
   4450   auto *New = new (*this, TypeAlignment)
   4451       DependentExtIntType(*this, IsUnsigned, NumBitsExpr);
   4452   DependentExtIntTypes.InsertNode(New, InsertPos);
   4453 
   4454   Types.push_back(New);
   4455   return QualType(New, 0);
   4456 }
   4457 
   4458 #ifndef NDEBUG
   4459 static bool NeedsInjectedClassNameType(const RecordDecl *D) {
   4460   if (!isa<CXXRecordDecl>(D)) return false;
   4461   const auto *RD = cast<CXXRecordDecl>(D);
   4462   if (isa<ClassTemplatePartialSpecializationDecl>(RD))
   4463     return true;
   4464   if (RD->getDescribedClassTemplate() &&
   4465       !isa<ClassTemplateSpecializationDecl>(RD))
   4466     return true;
   4467   return false;
   4468 }
   4469 #endif
   4470 
   4471 /// getInjectedClassNameType - Return the unique reference to the
   4472 /// injected class name type for the specified templated declaration.
   4473 QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
   4474                                               QualType TST) const {
   4475   assert(NeedsInjectedClassNameType(Decl));
   4476   if (Decl->TypeForDecl) {
   4477     assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
   4478   } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
   4479     assert(PrevDecl->TypeForDecl && "previous declaration has no type");
   4480     Decl->TypeForDecl = PrevDecl->TypeForDecl;
   4481     assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
   4482   } else {
   4483     Type *newType =
   4484       new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
   4485     Decl->TypeForDecl = newType;
   4486     Types.push_back(newType);
   4487   }
   4488   return QualType(Decl->TypeForDecl, 0);
   4489 }
   4490 
   4491 /// getTypeDeclType - Return the unique reference to the type for the
   4492 /// specified type declaration.
   4493 QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
   4494   assert(Decl && "Passed null for Decl param");
   4495   assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
   4496 
   4497   if (const auto *Typedef = dyn_cast<TypedefNameDecl>(Decl))
   4498     return getTypedefType(Typedef);
   4499 
   4500   assert(!isa<TemplateTypeParmDecl>(Decl) &&
   4501          "Template type parameter types are always available.");
   4502 
   4503   if (const auto *Record = dyn_cast<RecordDecl>(Decl)) {
   4504     assert(Record->isFirstDecl() && "struct/union has previous declaration");
   4505     assert(!NeedsInjectedClassNameType(Record));
   4506     return getRecordType(Record);
   4507   } else if (const auto *Enum = dyn_cast<EnumDecl>(Decl)) {
   4508     assert(Enum->isFirstDecl() && "enum has previous declaration");
   4509     return getEnumType(Enum);
   4510   } else if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
   4511     Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
   4512     Decl->TypeForDecl = newType;
   4513     Types.push_back(newType);
   4514   } else
   4515     llvm_unreachable("TypeDecl without a type?");
   4516 
   4517   return QualType(Decl->TypeForDecl, 0);
   4518 }
   4519 
   4520 /// getTypedefType - Return the unique reference to the type for the
   4521 /// specified typedef name decl.
   4522 QualType ASTContext::getTypedefType(const TypedefNameDecl *Decl,
   4523                                     QualType Underlying) const {
   4524   if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
   4525 
   4526   if (Underlying.isNull())
   4527     Underlying = Decl->getUnderlyingType();
   4528   QualType Canonical = getCanonicalType(Underlying);
   4529   auto *newType = new (*this, TypeAlignment)
   4530       TypedefType(Type::Typedef, Decl, Underlying, Canonical);
   4531   Decl->TypeForDecl = newType;
   4532   Types.push_back(newType);
   4533   return QualType(newType, 0);
   4534 }
   4535 
   4536 QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
   4537   if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
   4538 
   4539   if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
   4540     if (PrevDecl->TypeForDecl)
   4541       return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
   4542 
   4543   auto *newType = new (*this, TypeAlignment) RecordType(Decl);
   4544   Decl->TypeForDecl = newType;
   4545   Types.push_back(newType);
   4546   return QualType(newType, 0);
   4547 }
   4548 
   4549 QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
   4550   if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
   4551 
   4552   if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
   4553     if (PrevDecl->TypeForDecl)
   4554       return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
   4555 
   4556   auto *newType = new (*this, TypeAlignment) EnumType(Decl);
   4557   Decl->TypeForDecl = newType;
   4558   Types.push_back(newType);
   4559   return QualType(newType, 0);
   4560 }
   4561 
   4562 QualType ASTContext::getAttributedType(attr::Kind attrKind,
   4563                                        QualType modifiedType,
   4564                                        QualType equivalentType) {
   4565   llvm::FoldingSetNodeID id;
   4566   AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
   4567 
   4568   void *insertPos = nullptr;
   4569   AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
   4570   if (type) return QualType(type, 0);
   4571 
   4572   QualType canon = getCanonicalType(equivalentType);
   4573   type = new (*this, TypeAlignment)
   4574       AttributedType(canon, attrKind, modifiedType, equivalentType);
   4575 
   4576   Types.push_back(type);
   4577   AttributedTypes.InsertNode(type, insertPos);
   4578 
   4579   return QualType(type, 0);
   4580 }
   4581 
   4582 /// Retrieve a substitution-result type.
   4583 QualType
   4584 ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
   4585                                          QualType Replacement) const {
   4586   assert(Replacement.isCanonical()
   4587          && "replacement types must always be canonical");
   4588 
   4589   llvm::FoldingSetNodeID ID;
   4590   SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
   4591   void *InsertPos = nullptr;
   4592   SubstTemplateTypeParmType *SubstParm
   4593     = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
   4594 
   4595   if (!SubstParm) {
   4596     SubstParm = new (*this, TypeAlignment)
   4597       SubstTemplateTypeParmType(Parm, Replacement);
   4598     Types.push_back(SubstParm);
   4599     SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
   4600   }
   4601 
   4602   return QualType(SubstParm, 0);
   4603 }
   4604 
   4605 /// Retrieve a
   4606 QualType ASTContext::getSubstTemplateTypeParmPackType(
   4607                                           const TemplateTypeParmType *Parm,
   4608                                               const TemplateArgument &ArgPack) {
   4609 #ifndef NDEBUG
   4610   for (const auto &P : ArgPack.pack_elements()) {
   4611     assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
   4612     assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
   4613   }
   4614 #endif
   4615 
   4616   llvm::FoldingSetNodeID ID;
   4617   SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
   4618   void *InsertPos = nullptr;
   4619   if (SubstTemplateTypeParmPackType *SubstParm
   4620         = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
   4621     return QualType(SubstParm, 0);
   4622 
   4623   QualType Canon;
   4624   if (!Parm->isCanonicalUnqualified()) {
   4625     Canon = getCanonicalType(QualType(Parm, 0));
   4626     Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
   4627                                              ArgPack);
   4628     SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
   4629   }
   4630 
   4631   auto *SubstParm
   4632     = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
   4633                                                                ArgPack);
   4634   Types.push_back(SubstParm);
   4635   SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos);
   4636   return QualType(SubstParm, 0);
   4637 }
   4638 
   4639 /// Retrieve the template type parameter type for a template
   4640 /// parameter or parameter pack with the given depth, index, and (optionally)
   4641 /// name.
   4642 QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
   4643                                              bool ParameterPack,
   4644                                              TemplateTypeParmDecl *TTPDecl) const {
   4645   llvm::FoldingSetNodeID ID;
   4646   TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
   4647   void *InsertPos = nullptr;
   4648   TemplateTypeParmType *TypeParm
   4649     = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
   4650 
   4651   if (TypeParm)
   4652     return QualType(TypeParm, 0);
   4653 
   4654   if (TTPDecl) {
   4655     QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
   4656     TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
   4657 
   4658     TemplateTypeParmType *TypeCheck
   4659       = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
   4660     assert(!TypeCheck && "Template type parameter canonical type broken");
   4661     (void)TypeCheck;
   4662   } else
   4663     TypeParm = new (*this, TypeAlignment)
   4664       TemplateTypeParmType(Depth, Index, ParameterPack);
   4665 
   4666   Types.push_back(TypeParm);
   4667   TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
   4668 
   4669   return QualType(TypeParm, 0);
   4670 }
   4671 
   4672 TypeSourceInfo *
   4673 ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
   4674                                               SourceLocation NameLoc,
   4675                                         const TemplateArgumentListInfo &Args,
   4676                                               QualType Underlying) const {
   4677   assert(!Name.getAsDependentTemplateName() &&
   4678          "No dependent template names here!");
   4679   QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
   4680 
   4681   TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
   4682   TemplateSpecializationTypeLoc TL =
   4683       DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
   4684   TL.setTemplateKeywordLoc(SourceLocation());
   4685   TL.setTemplateNameLoc(NameLoc);
   4686   TL.setLAngleLoc(Args.getLAngleLoc());
   4687   TL.setRAngleLoc(Args.getRAngleLoc());
   4688   for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
   4689     TL.setArgLocInfo(i, Args[i].getLocInfo());
   4690   return DI;
   4691 }
   4692 
   4693 QualType
   4694 ASTContext::getTemplateSpecializationType(TemplateName Template,
   4695                                           const TemplateArgumentListInfo &Args,
   4696                                           QualType Underlying) const {
   4697   assert(!Template.getAsDependentTemplateName() &&
   4698          "No dependent template names here!");
   4699 
   4700   SmallVector<TemplateArgument, 4> ArgVec;
   4701   ArgVec.reserve(Args.size());
   4702   for (const TemplateArgumentLoc &Arg : Args.arguments())
   4703     ArgVec.push_back(Arg.getArgument());
   4704 
   4705   return getTemplateSpecializationType(Template, ArgVec, Underlying);
   4706 }
   4707 
   4708 #ifndef NDEBUG
   4709 static bool hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) {
   4710   for (const TemplateArgument &Arg : Args)
   4711     if (Arg.isPackExpansion())
   4712       return true;
   4713 
   4714   return true;
   4715 }
   4716 #endif
   4717 
   4718 QualType
   4719 ASTContext::getTemplateSpecializationType(TemplateName Template,
   4720                                           ArrayRef<TemplateArgument> Args,
   4721                                           QualType Underlying) const {
   4722   assert(!Template.getAsDependentTemplateName() &&
   4723          "No dependent template names here!");
   4724   // Look through qualified template names.
   4725   if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
   4726     Template = TemplateName(QTN->getTemplateDecl());
   4727 
   4728   bool IsTypeAlias =
   4729     Template.getAsTemplateDecl() &&
   4730     isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
   4731   QualType CanonType;
   4732   if (!Underlying.isNull())
   4733     CanonType = getCanonicalType(Underlying);
   4734   else {
   4735     // We can get here with an alias template when the specialization contains
   4736     // a pack expansion that does not match up with a parameter pack.
   4737     assert((!IsTypeAlias || hasAnyPackExpansions(Args)) &&
   4738            "Caller must compute aliased type");
   4739     IsTypeAlias = false;
   4740     CanonType = getCanonicalTemplateSpecializationType(Template, Args);
   4741   }
   4742 
   4743   // Allocate the (non-canonical) template specialization type, but don't
   4744   // try to unique it: these types typically have location information that
   4745   // we don't unique and don't want to lose.
   4746   void *Mem = Allocate(sizeof(TemplateSpecializationType) +
   4747                        sizeof(TemplateArgument) * Args.size() +
   4748                        (IsTypeAlias? sizeof(QualType) : 0),
   4749                        TypeAlignment);
   4750   auto *Spec
   4751     = new (Mem) TemplateSpecializationType(Template, Args, CanonType,
   4752                                          IsTypeAlias ? Underlying : QualType());
   4753 
   4754   Types.push_back(Spec);
   4755   return QualType(Spec, 0);
   4756 }
   4757 
   4758 QualType ASTContext::getCanonicalTemplateSpecializationType(
   4759     TemplateName Template, ArrayRef<TemplateArgument> Args) const {
   4760   assert(!Template.getAsDependentTemplateName() &&
   4761          "No dependent template names here!");
   4762 
   4763   // Look through qualified template names.
   4764   if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
   4765     Template = TemplateName(QTN->getTemplateDecl());
   4766 
   4767   // Build the canonical template specialization type.
   4768   TemplateName CanonTemplate = getCanonicalTemplateName(Template);
   4769   SmallVector<TemplateArgument, 4> CanonArgs;
   4770   unsigned NumArgs = Args.size();
   4771   CanonArgs.reserve(NumArgs);
   4772   for (const TemplateArgument &Arg : Args)
   4773     CanonArgs.push_back(getCanonicalTemplateArgument(Arg));
   4774 
   4775   // Determine whether this canonical template specialization type already
   4776   // exists.
   4777   llvm::FoldingSetNodeID ID;
   4778   TemplateSpecializationType::Profile(ID, CanonTemplate,
   4779                                       CanonArgs, *this);
   4780 
   4781   void *InsertPos = nullptr;
   4782   TemplateSpecializationType *Spec
   4783     = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
   4784 
   4785   if (!Spec) {
   4786     // Allocate a new canonical template specialization type.
   4787     void *Mem = Allocate((sizeof(TemplateSpecializationType) +
   4788                           sizeof(TemplateArgument) * NumArgs),
   4789                          TypeAlignment);
   4790     Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
   4791                                                 CanonArgs,
   4792                                                 QualType(), QualType());
   4793     Types.push_back(Spec);
   4794     TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
   4795   }
   4796 
   4797   assert(Spec->isDependentType() &&
   4798          "Non-dependent template-id type must have a canonical type");
   4799   return QualType(Spec, 0);
   4800 }
   4801 
   4802 QualType ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
   4803                                        NestedNameSpecifier *NNS,
   4804                                        QualType NamedType,
   4805                                        TagDecl *OwnedTagDecl) const {
   4806   llvm::FoldingSetNodeID ID;
   4807   ElaboratedType::Profile(ID, Keyword, NNS, NamedType, OwnedTagDecl);
   4808 
   4809   void *InsertPos = nullptr;
   4810   ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
   4811   if (T)
   4812     return QualType(T, 0);
   4813 
   4814   QualType Canon = NamedType;
   4815   if (!Canon.isCanonical()) {
   4816     Canon = getCanonicalType(NamedType);
   4817     ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
   4818     assert(!CheckT && "Elaborated canonical type broken");
   4819     (void)CheckT;
   4820   }
   4821 
   4822   void *Mem = Allocate(ElaboratedType::totalSizeToAlloc<TagDecl *>(!!OwnedTagDecl),
   4823                        TypeAlignment);
   4824   T = new (Mem) ElaboratedType(Keyword, NNS, NamedType, Canon, OwnedTagDecl);
   4825 
   4826   Types.push_back(T);
   4827   ElaboratedTypes.InsertNode(T, InsertPos);
   4828   return QualType(T, 0);
   4829 }
   4830 
   4831 QualType
   4832 ASTContext::getParenType(QualType InnerType) const {
   4833   llvm::FoldingSetNodeID ID;
   4834   ParenType::Profile(ID, InnerType);
   4835 
   4836   void *InsertPos = nullptr;
   4837   ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
   4838   if (T)
   4839     return QualType(T, 0);
   4840 
   4841   QualType Canon = InnerType;
   4842   if (!Canon.isCanonical()) {
   4843     Canon = getCanonicalType(InnerType);
   4844     ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
   4845     assert(!CheckT && "Paren canonical type broken");
   4846     (void)CheckT;
   4847   }
   4848 
   4849   T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
   4850   Types.push_back(T);
   4851   ParenTypes.InsertNode(T, InsertPos);
   4852   return QualType(T, 0);
   4853 }
   4854 
   4855 QualType
   4856 ASTContext::getMacroQualifiedType(QualType UnderlyingTy,
   4857                                   const IdentifierInfo *MacroII) const {
   4858   QualType Canon = UnderlyingTy;
   4859   if (!Canon.isCanonical())
   4860     Canon = getCanonicalType(UnderlyingTy);
   4861 
   4862   auto *newType = new (*this, TypeAlignment)
   4863       MacroQualifiedType(UnderlyingTy, Canon, MacroII);
   4864   Types.push_back(newType);
   4865   return QualType(newType, 0);
   4866 }
   4867 
   4868 QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
   4869                                           NestedNameSpecifier *NNS,
   4870                                           const IdentifierInfo *Name,
   4871                                           QualType Canon) const {
   4872   if (Canon.isNull()) {
   4873     NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
   4874     if (CanonNNS != NNS)
   4875       Canon = getDependentNameType(Keyword, CanonNNS, Name);
   4876   }
   4877 
   4878   llvm::FoldingSetNodeID ID;
   4879   DependentNameType::Profile(ID, Keyword, NNS, Name);
   4880 
   4881   void *InsertPos = nullptr;
   4882   DependentNameType *T
   4883     = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
   4884   if (T)
   4885     return QualType(T, 0);
   4886 
   4887   T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
   4888   Types.push_back(T);
   4889   DependentNameTypes.InsertNode(T, InsertPos);
   4890   return QualType(T, 0);
   4891 }
   4892 
   4893 QualType
   4894 ASTContext::getDependentTemplateSpecializationType(
   4895                                  ElaboratedTypeKeyword Keyword,
   4896                                  NestedNameSpecifier *NNS,
   4897                                  const IdentifierInfo *Name,
   4898                                  const TemplateArgumentListInfo &Args) const {
   4899   // TODO: avoid this copy
   4900   SmallVector<TemplateArgument, 16> ArgCopy;
   4901   for (unsigned I = 0, E = Args.size(); I != E; ++I)
   4902     ArgCopy.push_back(Args[I].getArgument());
   4903   return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy);
   4904 }
   4905 
   4906 QualType
   4907 ASTContext::getDependentTemplateSpecializationType(
   4908                                  ElaboratedTypeKeyword Keyword,
   4909                                  NestedNameSpecifier *NNS,
   4910                                  const IdentifierInfo *Name,
   4911                                  ArrayRef<TemplateArgument> Args) const {
   4912   assert((!NNS || NNS->isDependent()) &&
   4913          "nested-name-specifier must be dependent");
   4914 
   4915   llvm::FoldingSetNodeID ID;
   4916   DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
   4917                                                Name, Args);
   4918 
   4919   void *InsertPos = nullptr;
   4920   DependentTemplateSpecializationType *T
   4921     = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
   4922   if (T)
   4923     return QualType(T, 0);
   4924 
   4925   NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
   4926 
   4927   ElaboratedTypeKeyword CanonKeyword = Keyword;
   4928   if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
   4929 
   4930   bool AnyNonCanonArgs = false;
   4931   unsigned NumArgs = Args.size();
   4932   SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
   4933   for (unsigned I = 0; I != NumArgs; ++I) {
   4934     CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
   4935     if (!CanonArgs[I].structurallyEquals(Args[I]))
   4936       AnyNonCanonArgs = true;
   4937   }
   4938 
   4939   QualType Canon;
   4940   if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
   4941     Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
   4942                                                    Name,
   4943                                                    CanonArgs);
   4944 
   4945     // Find the insert position again.
   4946     DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
   4947   }
   4948 
   4949   void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
   4950                         sizeof(TemplateArgument) * NumArgs),
   4951                        TypeAlignment);
   4952   T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
   4953                                                     Name, Args, Canon);
   4954   Types.push_back(T);
   4955   DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
   4956   return QualType(T, 0);
   4957 }
   4958 
   4959 TemplateArgument ASTContext::getInjectedTemplateArg(NamedDecl *Param) {
   4960   TemplateArgument Arg;
   4961   if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
   4962     QualType ArgType = getTypeDeclType(TTP);
   4963     if (TTP->isParameterPack())
   4964       ArgType = getPackExpansionType(ArgType, None);
   4965 
   4966     Arg = TemplateArgument(ArgType);
   4967   } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
   4968     QualType T =
   4969         NTTP->getType().getNonPackExpansionType().getNonLValueExprType(*this);
   4970     // For class NTTPs, ensure we include the 'const' so the type matches that
   4971     // of a real template argument.
   4972     // FIXME: It would be more faithful to model this as something like an
   4973     // lvalue-to-rvalue conversion applied to a const-qualified lvalue.
   4974     if (T->isRecordType())
   4975       T.addConst();
   4976     Expr *E = new (*this) DeclRefExpr(
   4977         *this, NTTP, /*enclosing*/ false, T,
   4978         Expr::getValueKindForType(NTTP->getType()), NTTP->getLocation());
   4979 
   4980     if (NTTP->isParameterPack())
   4981       E = new (*this) PackExpansionExpr(DependentTy, E, NTTP->getLocation(),
   4982                                         None);
   4983     Arg = TemplateArgument(E);
   4984   } else {
   4985     auto *TTP = cast<TemplateTemplateParmDecl>(Param);
   4986     if (TTP->isParameterPack())
   4987       Arg = TemplateArgument(TemplateName(TTP), Optional<unsigned>());
   4988     else
   4989       Arg = TemplateArgument(TemplateName(TTP));
   4990   }
   4991 
   4992   if (Param->isTemplateParameterPack())
   4993     Arg = TemplateArgument::CreatePackCopy(*this, Arg);
   4994 
   4995   return Arg;
   4996 }
   4997 
   4998 void
   4999 ASTContext::getInjectedTemplateArgs(const TemplateParameterList *Params,
   5000                                     SmallVectorImpl<TemplateArgument> &Args) {
   5001   Args.reserve(Args.size() + Params->size());
   5002 
   5003   for (NamedDecl *Param : *Params)
   5004     Args.push_back(getInjectedTemplateArg(Param));
   5005 }
   5006 
   5007 QualType ASTContext::getPackExpansionType(QualType Pattern,
   5008                                           Optional<unsigned> NumExpansions,
   5009                                           bool ExpectPackInType) {
   5010   assert((!ExpectPackInType || Pattern->containsUnexpandedParameterPack()) &&
   5011          "Pack expansions must expand one or more parameter packs");
   5012 
   5013   llvm::FoldingSetNodeID ID;
   5014   PackExpansionType::Profile(ID, Pattern, NumExpansions);
   5015 
   5016   void *InsertPos = nullptr;
   5017   PackExpansionType *T = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
   5018   if (T)
   5019     return QualType(T, 0);
   5020 
   5021   QualType Canon;
   5022   if (!Pattern.isCanonical()) {
   5023     Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions,
   5024                                  /*ExpectPackInType=*/false);
   5025 
   5026     // Find the insert position again, in case we inserted an element into
   5027     // PackExpansionTypes and invalidated our insert position.
   5028     PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
   5029   }
   5030 
   5031   T = new (*this, TypeAlignment)
   5032       PackExpansionType(Pattern, Canon, NumExpansions);
   5033   Types.push_back(T);
   5034   PackExpansionTypes.InsertNode(T, InsertPos);
   5035   return QualType(T, 0);
   5036 }
   5037 
   5038 /// CmpProtocolNames - Comparison predicate for sorting protocols
   5039 /// alphabetically.
   5040 static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
   5041                             ObjCProtocolDecl *const *RHS) {
   5042   return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
   5043 }
   5044 
   5045 static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) {
   5046   if (Protocols.empty()) return true;
   5047 
   5048   if (Protocols[0]->getCanonicalDecl() != Protocols[0])
   5049     return false;
   5050 
   5051   for (unsigned i = 1; i != Protocols.size(); ++i)
   5052     if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
   5053         Protocols[i]->getCanonicalDecl() != Protocols[i])
   5054       return false;
   5055   return true;
   5056 }
   5057 
   5058 static void
   5059 SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
   5060   // Sort protocols, keyed by name.
   5061   llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
   5062 
   5063   // Canonicalize.
   5064   for (ObjCProtocolDecl *&P : Protocols)
   5065     P = P->getCanonicalDecl();
   5066 
   5067   // Remove duplicates.
   5068   auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
   5069   Protocols.erase(ProtocolsEnd, Protocols.end());
   5070 }
   5071 
   5072 QualType ASTContext::getObjCObjectType(QualType BaseType,
   5073                                        ObjCProtocolDecl * const *Protocols,
   5074                                        unsigned NumProtocols) const {
   5075   return getObjCObjectType(BaseType, {},
   5076                            llvm::makeArrayRef(Protocols, NumProtocols),
   5077                            /*isKindOf=*/false);
   5078 }
   5079 
   5080 QualType ASTContext::getObjCObjectType(
   5081            QualType baseType,
   5082            ArrayRef<QualType> typeArgs,
   5083            ArrayRef<ObjCProtocolDecl *> protocols,
   5084            bool isKindOf) const {
   5085   // If the base type is an interface and there aren't any protocols or
   5086   // type arguments to add, then the interface type will do just fine.
   5087   if (typeArgs.empty() && protocols.empty() && !isKindOf &&
   5088       isa<ObjCInterfaceType>(baseType))
   5089     return baseType;
   5090 
   5091   // Look in the folding set for an existing type.
   5092   llvm::FoldingSetNodeID ID;
   5093   ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
   5094   void *InsertPos = nullptr;
   5095   if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
   5096     return QualType(QT, 0);
   5097 
   5098   // Determine the type arguments to be used for canonicalization,
   5099   // which may be explicitly specified here or written on the base
   5100   // type.
   5101   ArrayRef<QualType> effectiveTypeArgs = typeArgs;
   5102   if (effectiveTypeArgs.empty()) {
   5103     if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
   5104       effectiveTypeArgs = baseObject->getTypeArgs();
   5105   }
   5106 
   5107   // Build the canonical type, which has the canonical base type and a
   5108   // sorted-and-uniqued list of protocols and the type arguments
   5109   // canonicalized.
   5110   QualType canonical;
   5111   bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(),
   5112                                           effectiveTypeArgs.end(),
   5113                                           [&](QualType type) {
   5114                                             return type.isCanonical();
   5115                                           });
   5116   bool protocolsSorted = areSortedAndUniqued(protocols);
   5117   if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
   5118     // Determine the canonical type arguments.
   5119     ArrayRef<QualType> canonTypeArgs;
   5120     SmallVector<QualType, 4> canonTypeArgsVec;
   5121     if (!typeArgsAreCanonical) {
   5122       canonTypeArgsVec.reserve(effectiveTypeArgs.size());
   5123       for (auto typeArg : effectiveTypeArgs)
   5124         canonTypeArgsVec.push_back(getCanonicalType(typeArg));
   5125       canonTypeArgs = canonTypeArgsVec;
   5126     } else {
   5127       canonTypeArgs = effectiveTypeArgs;
   5128     }
   5129 
   5130     ArrayRef<ObjCProtocolDecl *> canonProtocols;
   5131     SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
   5132     if (!protocolsSorted) {
   5133       canonProtocolsVec.append(protocols.begin(), protocols.end());
   5134       SortAndUniqueProtocols(canonProtocolsVec);
   5135       canonProtocols = canonProtocolsVec;
   5136     } else {
   5137       canonProtocols = protocols;
   5138     }
   5139 
   5140     canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
   5141                                   canonProtocols, isKindOf);
   5142 
   5143     // Regenerate InsertPos.
   5144     ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
   5145   }
   5146 
   5147   unsigned size = sizeof(ObjCObjectTypeImpl);
   5148   size += typeArgs.size() * sizeof(QualType);
   5149   size += protocols.size() * sizeof(ObjCProtocolDecl *);
   5150   void *mem = Allocate(size, TypeAlignment);
   5151   auto *T =
   5152     new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
   5153                                  isKindOf);
   5154 
   5155   Types.push_back(T);
   5156   ObjCObjectTypes.InsertNode(T, InsertPos);
   5157   return QualType(T, 0);
   5158 }
   5159 
   5160 /// Apply Objective-C protocol qualifiers to the given type.
   5161 /// If this is for the canonical type of a type parameter, we can apply
   5162 /// protocol qualifiers on the ObjCObjectPointerType.
   5163 QualType
   5164 ASTContext::applyObjCProtocolQualifiers(QualType type,
   5165                   ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
   5166                   bool allowOnPointerType) const {
   5167   hasError = false;
   5168 
   5169   if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
   5170     return getObjCTypeParamType(objT->getDecl(), protocols);
   5171   }
   5172 
   5173   // Apply protocol qualifiers to ObjCObjectPointerType.
   5174   if (allowOnPointerType) {
   5175     if (const auto *objPtr =
   5176             dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
   5177       const ObjCObjectType *objT = objPtr->getObjectType();
   5178       // Merge protocol lists and construct ObjCObjectType.
   5179       SmallVector<ObjCProtocolDecl*, 8> protocolsVec;
   5180       protocolsVec.append(objT->qual_begin(),
   5181                           objT->qual_end());
   5182       protocolsVec.append(protocols.begin(), protocols.end());
   5183       ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
   5184       type = getObjCObjectType(
   5185              objT->getBaseType(),
   5186              objT->getTypeArgsAsWritten(),
   5187              protocols,
   5188              objT->isKindOfTypeAsWritten());
   5189       return getObjCObjectPointerType(type);
   5190     }
   5191   }
   5192 
   5193   // Apply protocol qualifiers to ObjCObjectType.
   5194   if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
   5195     // FIXME: Check for protocols to which the class type is already
   5196     // known to conform.
   5197 
   5198     return getObjCObjectType(objT->getBaseType(),
   5199                              objT->getTypeArgsAsWritten(),
   5200                              protocols,
   5201                              objT->isKindOfTypeAsWritten());
   5202   }
   5203 
   5204   // If the canonical type is ObjCObjectType, ...
   5205   if (type->isObjCObjectType()) {
   5206     // Silently overwrite any existing protocol qualifiers.
   5207     // TODO: determine whether that's the right thing to do.
   5208 
   5209     // FIXME: Check for protocols to which the class type is already
   5210     // known to conform.
   5211     return getObjCObjectType(type, {}, protocols, false);
   5212   }
   5213 
   5214   // id<protocol-list>
   5215   if (type->isObjCIdType()) {
   5216     const auto *objPtr = type->castAs<ObjCObjectPointerType>();
   5217     type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols,
   5218                                  objPtr->isKindOfType());
   5219     return getObjCObjectPointerType(type);
   5220   }
   5221 
   5222   // Class<protocol-list>
   5223   if (type->isObjCClassType()) {
   5224     const auto *objPtr = type->castAs<ObjCObjectPointerType>();
   5225     type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols,
   5226                                  objPtr->isKindOfType());
   5227     return getObjCObjectPointerType(type);
   5228   }
   5229 
   5230   hasError = true;
   5231   return type;
   5232 }
   5233 
   5234 QualType
   5235 ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
   5236                                  ArrayRef<ObjCProtocolDecl *> protocols) const {
   5237   // Look in the folding set for an existing type.
   5238   llvm::FoldingSetNodeID ID;
   5239   ObjCTypeParamType::Profile(ID, Decl, Decl->getUnderlyingType(), protocols);
   5240   void *InsertPos = nullptr;
   5241   if (ObjCTypeParamType *TypeParam =
   5242       ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
   5243     return QualType(TypeParam, 0);
   5244 
   5245   // We canonicalize to the underlying type.
   5246   QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
   5247   if (!protocols.empty()) {
   5248     // Apply the protocol qualifers.
   5249     bool hasError;
   5250     Canonical = getCanonicalType(applyObjCProtocolQualifiers(
   5251         Canonical, protocols, hasError, true /*allowOnPointerType*/));
   5252     assert(!hasError && "Error when apply protocol qualifier to bound type");
   5253   }
   5254 
   5255   unsigned size = sizeof(ObjCTypeParamType);
   5256   size += protocols.size() * sizeof(ObjCProtocolDecl *);
   5257   void *mem = Allocate(size, TypeAlignment);
   5258   auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
   5259 
   5260   Types.push_back(newType);
   5261   ObjCTypeParamTypes.InsertNode(newType, InsertPos);
   5262   return QualType(newType, 0);
   5263 }
   5264 
   5265 void ASTContext::adjustObjCTypeParamBoundType(const ObjCTypeParamDecl *Orig,
   5266                                               ObjCTypeParamDecl *New) const {
   5267   New->setTypeSourceInfo(getTrivialTypeSourceInfo(Orig->getUnderlyingType()));
   5268   // Update TypeForDecl after updating TypeSourceInfo.
   5269   auto NewTypeParamTy = cast<ObjCTypeParamType>(New->getTypeForDecl());
   5270   SmallVector<ObjCProtocolDecl *, 8> protocols;
   5271   protocols.append(NewTypeParamTy->qual_begin(), NewTypeParamTy->qual_end());
   5272   QualType UpdatedTy = getObjCTypeParamType(New, protocols);
   5273   New->setTypeForDecl(UpdatedTy.getTypePtr());
   5274 }
   5275 
   5276 /// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
   5277 /// protocol list adopt all protocols in QT's qualified-id protocol
   5278 /// list.
   5279 bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
   5280                                                 ObjCInterfaceDecl *IC) {
   5281   if (!QT->isObjCQualifiedIdType())
   5282     return false;
   5283 
   5284   if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
   5285     // If both the right and left sides have qualifiers.
   5286     for (auto *Proto : OPT->quals()) {
   5287       if (!IC->ClassImplementsProtocol(Proto, false))
   5288         return false;
   5289     }
   5290     return true;
   5291   }
   5292   return false;
   5293 }
   5294 
   5295 /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
   5296 /// QT's qualified-id protocol list adopt all protocols in IDecl's list
   5297 /// of protocols.
   5298 bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
   5299                                                 ObjCInterfaceDecl *IDecl) {
   5300   if (!QT->isObjCQualifiedIdType())
   5301     return false;
   5302   const auto *OPT = QT->getAs<ObjCObjectPointerType>();
   5303   if (!OPT)
   5304     return false;
   5305   if (!IDecl->hasDefinition())
   5306     return false;
   5307   llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
   5308   CollectInheritedProtocols(IDecl, InheritedProtocols);
   5309   if (InheritedProtocols.empty())
   5310     return false;
   5311   // Check that if every protocol in list of id<plist> conforms to a protocol
   5312   // of IDecl's, then bridge casting is ok.
   5313   bool Conforms = false;
   5314   for (auto *Proto : OPT->quals()) {
   5315     Conforms = false;
   5316     for (auto *PI : InheritedProtocols) {
   5317       if (ProtocolCompatibleWithProtocol(Proto, PI)) {
   5318         Conforms = true;
   5319         break;
   5320       }
   5321     }
   5322     if (!Conforms)
   5323       break;
   5324   }
   5325   if (Conforms)
   5326     return true;
   5327 
   5328   for (auto *PI : InheritedProtocols) {
   5329     // If both the right and left sides have qualifiers.
   5330     bool Adopts = false;
   5331     for (auto *Proto : OPT->quals()) {
   5332       // return 'true' if 'PI' is in the inheritance hierarchy of Proto
   5333       if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
   5334         break;
   5335     }
   5336     if (!Adopts)
   5337       return false;
   5338   }
   5339   return true;
   5340 }
   5341 
   5342 /// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
   5343 /// the given object type.
   5344 QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
   5345   llvm::FoldingSetNodeID ID;
   5346   ObjCObjectPointerType::Profile(ID, ObjectT);
   5347 
   5348   void *InsertPos = nullptr;
   5349   if (ObjCObjectPointerType *QT =
   5350               ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
   5351     return QualType(QT, 0);
   5352 
   5353   // Find the canonical object type.
   5354   QualType Canonical;
   5355   if (!ObjectT.isCanonical()) {
   5356     Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
   5357 
   5358     // Regenerate InsertPos.
   5359     ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
   5360   }
   5361 
   5362   // No match.
   5363   void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
   5364   auto *QType =
   5365     new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
   5366 
   5367   Types.push_back(QType);
   5368   ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
   5369   return QualType(QType, 0);
   5370 }
   5371 
   5372 /// getObjCInterfaceType - Return the unique reference to the type for the
   5373 /// specified ObjC interface decl. The list of protocols is optional.
   5374 QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
   5375                                           ObjCInterfaceDecl *PrevDecl) const {
   5376   if (Decl->TypeForDecl)
   5377     return QualType(Decl->TypeForDecl, 0);
   5378 
   5379   if (PrevDecl) {
   5380     assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
   5381     Decl->TypeForDecl = PrevDecl->TypeForDecl;
   5382     return QualType(PrevDecl->TypeForDecl, 0);
   5383   }
   5384 
   5385   // Prefer the definition, if there is one.
   5386   if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
   5387     Decl = Def;
   5388 
   5389   void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
   5390   auto *T = new (Mem) ObjCInterfaceType(Decl);
   5391   Decl->TypeForDecl = T;
   5392   Types.push_back(T);
   5393   return QualType(T, 0);
   5394 }
   5395 
   5396 /// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
   5397 /// TypeOfExprType AST's (since expression's are never shared). For example,
   5398 /// multiple declarations that refer to "typeof(x)" all contain different
   5399 /// DeclRefExpr's. This doesn't effect the type checker, since it operates
   5400 /// on canonical type's (which are always unique).
   5401 QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
   5402   TypeOfExprType *toe;
   5403   if (tofExpr->isTypeDependent()) {
   5404     llvm::FoldingSetNodeID ID;
   5405     DependentTypeOfExprType::Profile(ID, *this, tofExpr);
   5406 
   5407     void *InsertPos = nullptr;
   5408     DependentTypeOfExprType *Canon
   5409       = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
   5410     if (Canon) {
   5411       // We already have a "canonical" version of an identical, dependent
   5412       // typeof(expr) type. Use that as our canonical type.
   5413       toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
   5414                                           QualType((TypeOfExprType*)Canon, 0));
   5415     } else {
   5416       // Build a new, canonical typeof(expr) type.
   5417       Canon
   5418         = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
   5419       DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
   5420       toe = Canon;
   5421     }
   5422   } else {
   5423     QualType Canonical = getCanonicalType(tofExpr->getType());
   5424     toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
   5425   }
   5426   Types.push_back(toe);
   5427   return QualType(toe, 0);
   5428 }
   5429 
   5430 /// getTypeOfType -  Unlike many "get<Type>" functions, we don't unique
   5431 /// TypeOfType nodes. The only motivation to unique these nodes would be
   5432 /// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
   5433 /// an issue. This doesn't affect the type checker, since it operates
   5434 /// on canonical types (which are always unique).
   5435 QualType ASTContext::getTypeOfType(QualType tofType) const {
   5436   QualType Canonical = getCanonicalType(tofType);
   5437   auto *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
   5438   Types.push_back(tot);
   5439   return QualType(tot, 0);
   5440 }
   5441 
   5442 /// Unlike many "get<Type>" functions, we don't unique DecltypeType
   5443 /// nodes. This would never be helpful, since each such type has its own
   5444 /// expression, and would not give a significant memory saving, since there
   5445 /// is an Expr tree under each such type.
   5446 QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
   5447   DecltypeType *dt;
   5448 
   5449   // C++11 [temp.type]p2:
   5450   //   If an expression e involves a template parameter, decltype(e) denotes a
   5451   //   unique dependent type. Two such decltype-specifiers refer to the same
   5452   //   type only if their expressions are equivalent (14.5.6.1).
   5453   if (e->isInstantiationDependent()) {
   5454     llvm::FoldingSetNodeID ID;
   5455     DependentDecltypeType::Profile(ID, *this, e);
   5456 
   5457     void *InsertPos = nullptr;
   5458     DependentDecltypeType *Canon
   5459       = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
   5460     if (!Canon) {
   5461       // Build a new, canonical decltype(expr) type.
   5462       Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
   5463       DependentDecltypeTypes.InsertNode(Canon, InsertPos);
   5464     }
   5465     dt = new (*this, TypeAlignment)
   5466         DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
   5467   } else {
   5468     dt = new (*this, TypeAlignment)
   5469         DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
   5470   }
   5471   Types.push_back(dt);
   5472   return QualType(dt, 0);
   5473 }
   5474 
   5475 /// getUnaryTransformationType - We don't unique these, since the memory
   5476 /// savings are minimal and these are rare.
   5477 QualType ASTContext::getUnaryTransformType(QualType BaseType,
   5478                                            QualType UnderlyingType,
   5479                                            UnaryTransformType::UTTKind Kind)
   5480     const {
   5481   UnaryTransformType *ut = nullptr;
   5482 
   5483   if (BaseType->isDependentType()) {
   5484     // Look in the folding set for an existing type.
   5485     llvm::FoldingSetNodeID ID;
   5486     DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind);
   5487 
   5488     void *InsertPos = nullptr;
   5489     DependentUnaryTransformType *Canon
   5490       = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
   5491 
   5492     if (!Canon) {
   5493       // Build a new, canonical __underlying_type(type) type.
   5494       Canon = new (*this, TypeAlignment)
   5495              DependentUnaryTransformType(*this, getCanonicalType(BaseType),
   5496                                          Kind);
   5497       DependentUnaryTransformTypes.InsertNode(Canon, InsertPos);
   5498     }
   5499     ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
   5500                                                         QualType(), Kind,
   5501                                                         QualType(Canon, 0));
   5502   } else {
   5503     QualType CanonType = getCanonicalType(UnderlyingType);
   5504     ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
   5505                                                         UnderlyingType, Kind,
   5506                                                         CanonType);
   5507   }
   5508   Types.push_back(ut);
   5509   return QualType(ut, 0);
   5510 }
   5511 
   5512 /// getAutoType - Return the uniqued reference to the 'auto' type which has been
   5513 /// deduced to the given type, or to the canonical undeduced 'auto' type, or the
   5514 /// canonical deduced-but-dependent 'auto' type.
   5515 QualType
   5516 ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
   5517                         bool IsDependent, bool IsPack,
   5518                         ConceptDecl *TypeConstraintConcept,
   5519                         ArrayRef<TemplateArgument> TypeConstraintArgs) const {
   5520   assert((!IsPack || IsDependent) && "only use IsPack for a dependent pack");
   5521   if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto &&
   5522       !TypeConstraintConcept && !IsDependent)
   5523     return getAutoDeductType();
   5524 
   5525   // Look in the folding set for an existing type.
   5526   void *InsertPos = nullptr;
   5527   llvm::FoldingSetNodeID ID;
   5528   AutoType::Profile(ID, *this, DeducedType, Keyword, IsDependent,
   5529                     TypeConstraintConcept, TypeConstraintArgs);
   5530   if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
   5531     return QualType(AT, 0);
   5532 
   5533   void *Mem = Allocate(sizeof(AutoType) +
   5534                        sizeof(TemplateArgument) * TypeConstraintArgs.size(),
   5535                        TypeAlignment);
   5536   auto *AT = new (Mem) AutoType(
   5537       DeducedType, Keyword,
   5538       (IsDependent ? TypeDependence::DependentInstantiation
   5539                    : TypeDependence::None) |
   5540           (IsPack ? TypeDependence::UnexpandedPack : TypeDependence::None),
   5541       TypeConstraintConcept, TypeConstraintArgs);
   5542   Types.push_back(AT);
   5543   if (InsertPos)
   5544     AutoTypes.InsertNode(AT, InsertPos);
   5545   return QualType(AT, 0);
   5546 }
   5547 
   5548 /// Return the uniqued reference to the deduced template specialization type
   5549 /// which has been deduced to the given type, or to the canonical undeduced
   5550 /// such type, or the canonical deduced-but-dependent such type.
   5551 QualType ASTContext::getDeducedTemplateSpecializationType(
   5552     TemplateName Template, QualType DeducedType, bool IsDependent) const {
   5553   // Look in the folding set for an existing type.
   5554   void *InsertPos = nullptr;
   5555   llvm::FoldingSetNodeID ID;
   5556   DeducedTemplateSpecializationType::Profile(ID, Template, DeducedType,
   5557                                              IsDependent);
   5558   if (DeducedTemplateSpecializationType *DTST =
   5559           DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
   5560     return QualType(DTST, 0);
   5561 
   5562   auto *DTST = new (*this, TypeAlignment)
   5563       DeducedTemplateSpecializationType(Template, DeducedType, IsDependent);
   5564   Types.push_back(DTST);
   5565   if (InsertPos)
   5566     DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
   5567   return QualType(DTST, 0);
   5568 }
   5569 
   5570 /// getAtomicType - Return the uniqued reference to the atomic type for
   5571 /// the given value type.
   5572 QualType ASTContext::getAtomicType(QualType T) const {
   5573   // Unique pointers, to guarantee there is only one pointer of a particular
   5574   // structure.
   5575   llvm::FoldingSetNodeID ID;
   5576   AtomicType::Profile(ID, T);
   5577 
   5578   void *InsertPos = nullptr;
   5579   if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
   5580     return QualType(AT, 0);
   5581 
   5582   // If the atomic value type isn't canonical, this won't be a canonical type
   5583   // either, so fill in the canonical type field.
   5584   QualType Canonical;
   5585   if (!T.isCanonical()) {
   5586     Canonical = getAtomicType(getCanonicalType(T));
   5587 
   5588     // Get the new insert position for the node we care about.
   5589     AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
   5590     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
   5591   }
   5592   auto *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
   5593   Types.push_back(New);
   5594   AtomicTypes.InsertNode(New, InsertPos);
   5595   return QualType(New, 0);
   5596 }
   5597 
   5598 /// getAutoDeductType - Get type pattern for deducing against 'auto'.
   5599 QualType ASTContext::getAutoDeductType() const {
   5600   if (AutoDeductTy.isNull())
   5601     AutoDeductTy = QualType(new (*this, TypeAlignment)
   5602                                 AutoType(QualType(), AutoTypeKeyword::Auto,
   5603                                          TypeDependence::None,
   5604                                          /*concept*/ nullptr, /*args*/ {}),
   5605                             0);
   5606   return AutoDeductTy;
   5607 }
   5608 
   5609 /// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
   5610 QualType ASTContext::getAutoRRefDeductType() const {
   5611   if (AutoRRefDeductTy.isNull())
   5612     AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
   5613   assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
   5614   return AutoRRefDeductTy;
   5615 }
   5616 
   5617 /// getTagDeclType - Return the unique reference to the type for the
   5618 /// specified TagDecl (struct/union/class/enum) decl.
   5619 QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
   5620   assert(Decl);
   5621   // FIXME: What is the design on getTagDeclType when it requires casting
   5622   // away const?  mutable?
   5623   return getTypeDeclType(const_cast<TagDecl*>(Decl));
   5624 }
   5625 
   5626 /// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
   5627 /// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
   5628 /// needs to agree with the definition in <stddef.h>.
   5629 CanQualType ASTContext::getSizeType() const {
   5630   return getFromTargetType(Target->getSizeType());
   5631 }
   5632 
   5633 /// Return the unique signed counterpart of the integer type
   5634 /// corresponding to size_t.
   5635 CanQualType ASTContext::getSignedSizeType() const {
   5636   return getFromTargetType(Target->getSignedSizeType());
   5637 }
   5638 
   5639 /// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
   5640 CanQualType ASTContext::getIntMaxType() const {
   5641   return getFromTargetType(Target->getIntMaxType());
   5642 }
   5643 
   5644 /// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
   5645 CanQualType ASTContext::getUIntMaxType() const {
   5646   return getFromTargetType(Target->getUIntMaxType());
   5647 }
   5648 
   5649 /// getSignedWCharType - Return the type of "signed wchar_t".
   5650 /// Used when in C++, as a GCC extension.
   5651 QualType ASTContext::getSignedWCharType() const {
   5652   // FIXME: derive from "Target" ?
   5653   return WCharTy;
   5654 }
   5655 
   5656 /// getUnsignedWCharType - Return the type of "unsigned wchar_t".
   5657 /// Used when in C++, as a GCC extension.
   5658 QualType ASTContext::getUnsignedWCharType() const {
   5659   // FIXME: derive from "Target" ?
   5660   return UnsignedIntTy;
   5661 }
   5662 
   5663 QualType ASTContext::getIntPtrType() const {
   5664   return getFromTargetType(Target->getIntPtrType());
   5665 }
   5666 
   5667 QualType ASTContext::getUIntPtrType() const {
   5668   return getCorrespondingUnsignedType(getIntPtrType());
   5669 }
   5670 
   5671 /// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
   5672 /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
   5673 QualType ASTContext::getPointerDiffType() const {
   5674   return getFromTargetType(Target->getPtrDiffType(0));
   5675 }
   5676 
   5677 /// Return the unique unsigned counterpart of "ptrdiff_t"
   5678 /// integer type. The standard (C11 7.21.6.1p7) refers to this type
   5679 /// in the definition of %tu format specifier.
   5680 QualType ASTContext::getUnsignedPointerDiffType() const {
   5681   return getFromTargetType(Target->getUnsignedPtrDiffType(0));
   5682 }
   5683 
   5684 /// Return the unique type for "pid_t" defined in
   5685 /// <sys/types.h>. We need this to compute the correct type for vfork().
   5686 QualType ASTContext::getProcessIDType() const {
   5687   return getFromTargetType(Target->getProcessIDType());
   5688 }
   5689 
   5690 //===----------------------------------------------------------------------===//
   5691 //                              Type Operators
   5692 //===----------------------------------------------------------------------===//
   5693 
   5694 CanQualType ASTContext::getCanonicalParamType(QualType T) const {
   5695   // Push qualifiers into arrays, and then discard any remaining
   5696   // qualifiers.
   5697   T = getCanonicalType(T);
   5698   T = getVariableArrayDecayedType(T);
   5699   const Type *Ty = T.getTypePtr();
   5700   QualType Result;
   5701   if (isa<ArrayType>(Ty)) {
   5702     Result = getArrayDecayedType(QualType(Ty,0));
   5703   } else if (isa<FunctionType>(Ty)) {
   5704     Result = getPointerType(QualType(Ty, 0));
   5705   } else {
   5706     Result = QualType(Ty, 0);
   5707   }
   5708 
   5709   return CanQualType::CreateUnsafe(Result);
   5710 }
   5711 
   5712 QualType ASTContext::getUnqualifiedArrayType(QualType type,
   5713                                              Qualifiers &quals) {
   5714   SplitQualType splitType = type.getSplitUnqualifiedType();
   5715 
   5716   // FIXME: getSplitUnqualifiedType() actually walks all the way to
   5717   // the unqualified desugared type and then drops it on the floor.
   5718   // We then have to strip that sugar back off with
   5719   // getUnqualifiedDesugaredType(), which is silly.
   5720   const auto *AT =
   5721       dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
   5722 
   5723   // If we don't have an array, just use the results in splitType.
   5724   if (!AT) {
   5725     quals = splitType.Quals;
   5726     return QualType(splitType.Ty, 0);
   5727   }
   5728 
   5729   // Otherwise, recurse on the array's element type.
   5730   QualType elementType = AT->getElementType();
   5731   QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
   5732 
   5733   // If that didn't change the element type, AT has no qualifiers, so we
   5734   // can just use the results in splitType.
   5735   if (elementType == unqualElementType) {
   5736     assert(quals.empty()); // from the recursive call
   5737     quals = splitType.Quals;
   5738     return QualType(splitType.Ty, 0);
   5739   }
   5740 
   5741   // Otherwise, add in the qualifiers from the outermost type, then
   5742   // build the type back up.
   5743   quals.addConsistentQualifiers(splitType.Quals);
   5744 
   5745   if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
   5746     return getConstantArrayType(unqualElementType, CAT->getSize(),
   5747                                 CAT->getSizeExpr(), CAT->getSizeModifier(), 0);
   5748   }
   5749 
   5750   if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) {
   5751     return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
   5752   }
   5753 
   5754   if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) {
   5755     return getVariableArrayType(unqualElementType,
   5756                                 VAT->getSizeExpr(),
   5757                                 VAT->getSizeModifier(),
   5758                                 VAT->getIndexTypeCVRQualifiers(),
   5759                                 VAT->getBracketsRange());
   5760   }
   5761 
   5762   const auto *DSAT = cast<DependentSizedArrayType>(AT);
   5763   return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
   5764                                     DSAT->getSizeModifier(), 0,
   5765                                     SourceRange());
   5766 }
   5767 
   5768 /// Attempt to unwrap two types that may both be array types with the same bound
   5769 /// (or both be array types of unknown bound) for the purpose of comparing the
   5770 /// cv-decomposition of two types per C++ [conv.qual].
   5771 void ASTContext::UnwrapSimilarArrayTypes(QualType &T1, QualType &T2) {
   5772   while (true) {
   5773     auto *AT1 = getAsArrayType(T1);
   5774     if (!AT1)
   5775       return;
   5776 
   5777     auto *AT2 = getAsArrayType(T2);
   5778     if (!AT2)
   5779       return;
   5780 
   5781     // If we don't have two array types with the same constant bound nor two
   5782     // incomplete array types, we've unwrapped everything we can.
   5783     if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) {
   5784       auto *CAT2 = dyn_cast<ConstantArrayType>(AT2);
   5785       if (!CAT2 || CAT1->getSize() != CAT2->getSize())
   5786         return;
   5787     } else if (!isa<IncompleteArrayType>(AT1) ||
   5788                !isa<IncompleteArrayType>(AT2)) {
   5789       return;
   5790     }
   5791 
   5792     T1 = AT1->getElementType();
   5793     T2 = AT2->getElementType();
   5794   }
   5795 }
   5796 
   5797 /// Attempt to unwrap two types that may be similar (C++ [conv.qual]).
   5798 ///
   5799 /// If T1 and T2 are both pointer types of the same kind, or both array types
   5800 /// with the same bound, unwraps layers from T1 and T2 until a pointer type is
   5801 /// unwrapped. Top-level qualifiers on T1 and T2 are ignored.
   5802 ///
   5803 /// This function will typically be called in a loop that successively
   5804 /// "unwraps" pointer and pointer-to-member types to compare them at each
   5805 /// level.
   5806 ///
   5807 /// \return \c true if a pointer type was unwrapped, \c false if we reached a
   5808 /// pair of types that can't be unwrapped further.
   5809 bool ASTContext::UnwrapSimilarTypes(QualType &T1, QualType &T2) {
   5810   UnwrapSimilarArrayTypes(T1, T2);
   5811 
   5812   const auto *T1PtrType = T1->getAs<PointerType>();
   5813   const auto *T2PtrType = T2->getAs<PointerType>();
   5814   if (T1PtrType && T2PtrType) {
   5815     T1 = T1PtrType->getPointeeType();
   5816     T2 = T2PtrType->getPointeeType();
   5817     return true;
   5818   }
   5819 
   5820   const auto *T1MPType = T1->getAs<MemberPointerType>();
   5821   const auto *T2MPType = T2->getAs<MemberPointerType>();
   5822   if (T1MPType && T2MPType &&
   5823       hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
   5824                              QualType(T2MPType->getClass(), 0))) {
   5825     T1 = T1MPType->getPointeeType();
   5826     T2 = T2MPType->getPointeeType();
   5827     return true;
   5828   }
   5829 
   5830   if (getLangOpts().ObjC) {
   5831     const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
   5832     const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
   5833     if (T1OPType && T2OPType) {
   5834       T1 = T1OPType->getPointeeType();
   5835       T2 = T2OPType->getPointeeType();
   5836       return true;
   5837     }
   5838   }
   5839 
   5840   // FIXME: Block pointers, too?
   5841 
   5842   return false;
   5843 }
   5844 
   5845 bool ASTContext::hasSimilarType(QualType T1, QualType T2) {
   5846   while (true) {
   5847     Qualifiers Quals;
   5848     T1 = getUnqualifiedArrayType(T1, Quals);
   5849     T2 = getUnqualifiedArrayType(T2, Quals);
   5850     if (hasSameType(T1, T2))
   5851       return true;
   5852     if (!UnwrapSimilarTypes(T1, T2))
   5853       return false;
   5854   }
   5855 }
   5856 
   5857 bool ASTContext::hasCvrSimilarType(QualType T1, QualType T2) {
   5858   while (true) {
   5859     Qualifiers Quals1, Quals2;
   5860     T1 = getUnqualifiedArrayType(T1, Quals1);
   5861     T2 = getUnqualifiedArrayType(T2, Quals2);
   5862 
   5863     Quals1.removeCVRQualifiers();
   5864     Quals2.removeCVRQualifiers();
   5865     if (Quals1 != Quals2)
   5866       return false;
   5867 
   5868     if (hasSameType(T1, T2))
   5869       return true;
   5870 
   5871     if (!UnwrapSimilarTypes(T1, T2))
   5872       return false;
   5873   }
   5874 }
   5875 
   5876 DeclarationNameInfo
   5877 ASTContext::getNameForTemplate(TemplateName Name,
   5878                                SourceLocation NameLoc) const {
   5879   switch (Name.getKind()) {
   5880   case TemplateName::QualifiedTemplate:
   5881   case TemplateName::Template:
   5882     // DNInfo work in progress: CHECKME: what about DNLoc?
   5883     return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
   5884                                NameLoc);
   5885 
   5886   case TemplateName::OverloadedTemplate: {
   5887     OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
   5888     // DNInfo work in progress: CHECKME: what about DNLoc?
   5889     return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
   5890   }
   5891 
   5892   case TemplateName::AssumedTemplate: {
   5893     AssumedTemplateStorage *Storage = Name.getAsAssumedTemplateName();
   5894     return DeclarationNameInfo(Storage->getDeclName(), NameLoc);
   5895   }
   5896 
   5897   case TemplateName::DependentTemplate: {
   5898     DependentTemplateName *DTN = Name.getAsDependentTemplateName();
   5899     DeclarationName DName;
   5900     if (DTN->isIdentifier()) {
   5901       DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
   5902       return DeclarationNameInfo(DName, NameLoc);
   5903     } else {
   5904       DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
   5905       // DNInfo work in progress: FIXME: source locations?
   5906       DeclarationNameLoc DNLoc =
   5907           DeclarationNameLoc::makeCXXOperatorNameLoc(SourceRange());
   5908       return DeclarationNameInfo(DName, NameLoc, DNLoc);
   5909     }
   5910   }
   5911 
   5912   case TemplateName::SubstTemplateTemplateParm: {
   5913     SubstTemplateTemplateParmStorage *subst
   5914       = Name.getAsSubstTemplateTemplateParm();
   5915     return DeclarationNameInfo(subst->getParameter()->getDeclName(),
   5916                                NameLoc);
   5917   }
   5918 
   5919   case TemplateName::SubstTemplateTemplateParmPack: {
   5920     SubstTemplateTemplateParmPackStorage *subst
   5921       = Name.getAsSubstTemplateTemplateParmPack();
   5922     return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
   5923                                NameLoc);
   5924   }
   5925   }
   5926 
   5927   llvm_unreachable("bad template name kind!");
   5928 }
   5929 
   5930 TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
   5931   switch (Name.getKind()) {
   5932   case TemplateName::QualifiedTemplate:
   5933   case TemplateName::Template: {
   5934     TemplateDecl *Template = Name.getAsTemplateDecl();
   5935     if (auto *TTP  = dyn_cast<TemplateTemplateParmDecl>(Template))
   5936       Template = getCanonicalTemplateTemplateParmDecl(TTP);
   5937 
   5938     // The canonical template name is the canonical template declaration.
   5939     return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
   5940   }
   5941 
   5942   case TemplateName::OverloadedTemplate:
   5943   case TemplateName::AssumedTemplate:
   5944     llvm_unreachable("cannot canonicalize unresolved template");
   5945 
   5946   case TemplateName::DependentTemplate: {
   5947     DependentTemplateName *DTN = Name.getAsDependentTemplateName();
   5948     assert(DTN && "Non-dependent template names must refer to template decls.");
   5949     return DTN->CanonicalTemplateName;
   5950   }
   5951 
   5952   case TemplateName::SubstTemplateTemplateParm: {
   5953     SubstTemplateTemplateParmStorage *subst
   5954       = Name.getAsSubstTemplateTemplateParm();
   5955     return getCanonicalTemplateName(subst->getReplacement());
   5956   }
   5957 
   5958   case TemplateName::SubstTemplateTemplateParmPack: {
   5959     SubstTemplateTemplateParmPackStorage *subst
   5960                                   = Name.getAsSubstTemplateTemplateParmPack();
   5961     TemplateTemplateParmDecl *canonParameter
   5962       = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
   5963     TemplateArgument canonArgPack
   5964       = getCanonicalTemplateArgument(subst->getArgumentPack());
   5965     return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
   5966   }
   5967   }
   5968 
   5969   llvm_unreachable("bad template name!");
   5970 }
   5971 
   5972 bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
   5973   X = getCanonicalTemplateName(X);
   5974   Y = getCanonicalTemplateName(Y);
   5975   return X.getAsVoidPointer() == Y.getAsVoidPointer();
   5976 }
   5977 
   5978 TemplateArgument
   5979 ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
   5980   switch (Arg.getKind()) {
   5981     case TemplateArgument::Null:
   5982       return Arg;
   5983 
   5984     case TemplateArgument::Expression:
   5985       return Arg;
   5986 
   5987     case TemplateArgument::Declaration: {
   5988       auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
   5989       return TemplateArgument(D, Arg.getParamTypeForDecl());
   5990     }
   5991 
   5992     case TemplateArgument::NullPtr:
   5993       return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
   5994                               /*isNullPtr*/true);
   5995 
   5996     case TemplateArgument::Template:
   5997       return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
   5998 
   5999     case TemplateArgument::TemplateExpansion:
   6000       return TemplateArgument(getCanonicalTemplateName(
   6001                                          Arg.getAsTemplateOrTemplatePattern()),
   6002                               Arg.getNumTemplateExpansions());
   6003 
   6004     case TemplateArgument::Integral:
   6005       return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
   6006 
   6007     case TemplateArgument::Type:
   6008       return TemplateArgument(getCanonicalType(Arg.getAsType()));
   6009 
   6010     case TemplateArgument::Pack: {
   6011       if (Arg.pack_size() == 0)
   6012         return Arg;
   6013 
   6014       auto *CanonArgs = new (*this) TemplateArgument[Arg.pack_size()];
   6015       unsigned Idx = 0;
   6016       for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
   6017                                         AEnd = Arg.pack_end();
   6018            A != AEnd; (void)++A, ++Idx)
   6019         CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
   6020 
   6021       return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
   6022     }
   6023   }
   6024 
   6025   // Silence GCC warning
   6026   llvm_unreachable("Unhandled template argument kind");
   6027 }
   6028 
   6029 NestedNameSpecifier *
   6030 ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
   6031   if (!NNS)
   6032     return nullptr;
   6033 
   6034   switch (NNS->getKind()) {
   6035   case NestedNameSpecifier::Identifier:
   6036     // Canonicalize the prefix but keep the identifier the same.
   6037     return NestedNameSpecifier::Create(*this,
   6038                          getCanonicalNestedNameSpecifier(NNS->getPrefix()),
   6039                                        NNS->getAsIdentifier());
   6040 
   6041   case NestedNameSpecifier::Namespace:
   6042     // A namespace is canonical; build a nested-name-specifier with
   6043     // this namespace and no prefix.
   6044     return NestedNameSpecifier::Create(*this, nullptr,
   6045                                  NNS->getAsNamespace()->getOriginalNamespace());
   6046 
   6047   case NestedNameSpecifier::NamespaceAlias:
   6048     // A namespace is canonical; build a nested-name-specifier with
   6049     // this namespace and no prefix.
   6050     return NestedNameSpecifier::Create(*this, nullptr,
   6051                                     NNS->getAsNamespaceAlias()->getNamespace()
   6052                                                       ->getOriginalNamespace());
   6053 
   6054   case NestedNameSpecifier::TypeSpec:
   6055   case NestedNameSpecifier::TypeSpecWithTemplate: {
   6056     QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
   6057 
   6058     // If we have some kind of dependent-named type (e.g., "typename T::type"),
   6059     // break it apart into its prefix and identifier, then reconsititute those
   6060     // as the canonical nested-name-specifier. This is required to canonicalize
   6061     // a dependent nested-name-specifier involving typedefs of dependent-name
   6062     // types, e.g.,
   6063     //   typedef typename T::type T1;
   6064     //   typedef typename T1::type T2;
   6065     if (const auto *DNT = T->getAs<DependentNameType>())
   6066       return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
   6067                            const_cast<IdentifierInfo *>(DNT->getIdentifier()));
   6068 
   6069     // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
   6070     // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
   6071     // first place?
   6072     return NestedNameSpecifier::Create(*this, nullptr, false,
   6073                                        const_cast<Type *>(T.getTypePtr()));
   6074   }
   6075 
   6076   case NestedNameSpecifier::Global:
   6077   case NestedNameSpecifier::Super:
   6078     // The global specifier and __super specifer are canonical and unique.
   6079     return NNS;
   6080   }
   6081 
   6082   llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
   6083 }
   6084 
   6085 const ArrayType *ASTContext::getAsArrayType(QualType T) const {
   6086   // Handle the non-qualified case efficiently.
   6087   if (!T.hasLocalQualifiers()) {
   6088     // Handle the common positive case fast.
   6089     if (const auto *AT = dyn_cast<ArrayType>(T))
   6090       return AT;
   6091   }
   6092 
   6093   // Handle the common negative case fast.
   6094   if (!isa<ArrayType>(T.getCanonicalType()))
   6095     return nullptr;
   6096 
   6097   // Apply any qualifiers from the array type to the element type.  This
   6098   // implements C99 6.7.3p8: "If the specification of an array type includes
   6099   // any type qualifiers, the element type is so qualified, not the array type."
   6100 
   6101   // If we get here, we either have type qualifiers on the type, or we have
   6102   // sugar such as a typedef in the way.  If we have type qualifiers on the type
   6103   // we must propagate them down into the element type.
   6104 
   6105   SplitQualType split = T.getSplitDesugaredType();
   6106   Qualifiers qs = split.Quals;
   6107 
   6108   // If we have a simple case, just return now.
   6109   const auto *ATy = dyn_cast<ArrayType>(split.Ty);
   6110   if (!ATy || qs.empty())
   6111     return ATy;
   6112 
   6113   // Otherwise, we have an array and we have qualifiers on it.  Push the
   6114   // qualifiers into the array element type and return a new array type.
   6115   QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
   6116 
   6117   if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy))
   6118     return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
   6119                                                 CAT->getSizeExpr(),
   6120                                                 CAT->getSizeModifier(),
   6121                                            CAT->getIndexTypeCVRQualifiers()));
   6122   if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy))
   6123     return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
   6124                                                   IAT->getSizeModifier(),
   6125                                            IAT->getIndexTypeCVRQualifiers()));
   6126 
   6127   if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy))
   6128     return cast<ArrayType>(
   6129                      getDependentSizedArrayType(NewEltTy,
   6130                                                 DSAT->getSizeExpr(),
   6131                                                 DSAT->getSizeModifier(),
   6132                                               DSAT->getIndexTypeCVRQualifiers(),
   6133                                                 DSAT->getBracketsRange()));
   6134 
   6135   const auto *VAT = cast<VariableArrayType>(ATy);
   6136   return cast<ArrayType>(getVariableArrayType(NewEltTy,
   6137                                               VAT->getSizeExpr(),
   6138                                               VAT->getSizeModifier(),
   6139                                               VAT->getIndexTypeCVRQualifiers(),
   6140                                               VAT->getBracketsRange()));
   6141 }
   6142 
   6143 QualType ASTContext::getAdjustedParameterType(QualType T) const {
   6144   if (T->isArrayType() || T->isFunctionType())
   6145     return getDecayedType(T);
   6146   return T;
   6147 }
   6148 
   6149 QualType ASTContext::getSignatureParameterType(QualType T) const {
   6150   T = getVariableArrayDecayedType(T);
   6151   T = getAdjustedParameterType(T);
   6152   return T.getUnqualifiedType();
   6153 }
   6154 
   6155 QualType ASTContext::getExceptionObjectType(QualType T) const {
   6156   // C++ [except.throw]p3:
   6157   //   A throw-expression initializes a temporary object, called the exception
   6158   //   object, the type of which is determined by removing any top-level
   6159   //   cv-qualifiers from the static type of the operand of throw and adjusting
   6160   //   the type from "array of T" or "function returning T" to "pointer to T"
   6161   //   or "pointer to function returning T", [...]
   6162   T = getVariableArrayDecayedType(T);
   6163   if (T->isArrayType() || T->isFunctionType())
   6164     T = getDecayedType(T);
   6165   return T.getUnqualifiedType();
   6166 }
   6167 
   6168 /// getArrayDecayedType - Return the properly qualified result of decaying the
   6169 /// specified array type to a pointer.  This operation is non-trivial when
   6170 /// handling typedefs etc.  The canonical type of "T" must be an array type,
   6171 /// this returns a pointer to a properly qualified element of the array.
   6172 ///
   6173 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
   6174 QualType ASTContext::getArrayDecayedType(QualType Ty) const {
   6175   // Get the element type with 'getAsArrayType' so that we don't lose any
   6176   // typedefs in the element type of the array.  This also handles propagation
   6177   // of type qualifiers from the array type into the element type if present
   6178   // (C99 6.7.3p8).
   6179   const ArrayType *PrettyArrayType = getAsArrayType(Ty);
   6180   assert(PrettyArrayType && "Not an array type!");
   6181 
   6182   QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
   6183 
   6184   // int x[restrict 4] ->  int *restrict
   6185   QualType Result = getQualifiedType(PtrTy,
   6186                                      PrettyArrayType->getIndexTypeQualifiers());
   6187 
   6188   // int x[_Nullable] -> int * _Nullable
   6189   if (auto Nullability = Ty->getNullability(*this)) {
   6190     Result = const_cast<ASTContext *>(this)->getAttributedType(
   6191         AttributedType::getNullabilityAttrKind(*Nullability), Result, Result);
   6192   }
   6193   return Result;
   6194 }
   6195 
   6196 QualType ASTContext::getBaseElementType(const ArrayType *array) const {
   6197   return getBaseElementType(array->getElementType());
   6198 }
   6199 
   6200 QualType ASTContext::getBaseElementType(QualType type) const {
   6201   Qualifiers qs;
   6202   while (true) {
   6203     SplitQualType split = type.getSplitDesugaredType();
   6204     const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
   6205     if (!array) break;
   6206 
   6207     type = array->getElementType();
   6208     qs.addConsistentQualifiers(split.Quals);
   6209   }
   6210 
   6211   return getQualifiedType(type, qs);
   6212 }
   6213 
   6214 /// getConstantArrayElementCount - Returns number of constant array elements.
   6215 uint64_t
   6216 ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA)  const {
   6217   uint64_t ElementCount = 1;
   6218   do {
   6219     ElementCount *= CA->getSize().getZExtValue();
   6220     CA = dyn_cast_or_null<ConstantArrayType>(
   6221       CA->getElementType()->getAsArrayTypeUnsafe());
   6222   } while (CA);
   6223   return ElementCount;
   6224 }
   6225 
   6226 /// getFloatingRank - Return a relative rank for floating point types.
   6227 /// This routine will assert if passed a built-in type that isn't a float.
   6228 static FloatingRank getFloatingRank(QualType T) {
   6229   if (const auto *CT = T->getAs<ComplexType>())
   6230     return getFloatingRank(CT->getElementType());
   6231 
   6232   switch (T->castAs<BuiltinType>()->getKind()) {
   6233   default: llvm_unreachable("getFloatingRank(): not a floating type");
   6234   case BuiltinType::Float16:    return Float16Rank;
   6235   case BuiltinType::Half:       return HalfRank;
   6236   case BuiltinType::Float:      return FloatRank;
   6237   case BuiltinType::Double:     return DoubleRank;
   6238   case BuiltinType::LongDouble: return LongDoubleRank;
   6239   case BuiltinType::Float128:   return Float128Rank;
   6240   case BuiltinType::BFloat16:   return BFloat16Rank;
   6241   }
   6242 }
   6243 
   6244 /// getFloatingTypeOfSizeWithinDomain - Returns a real floating
   6245 /// point or a complex type (based on typeDomain/typeSize).
   6246 /// 'typeDomain' is a real floating point or complex type.
   6247 /// 'typeSize' is a real floating point or complex type.
   6248 QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
   6249                                                        QualType Domain) const {
   6250   FloatingRank EltRank = getFloatingRank(Size);
   6251   if (Domain->isComplexType()) {
   6252     switch (EltRank) {
   6253     case BFloat16Rank: llvm_unreachable("Complex bfloat16 is not supported");
   6254     case Float16Rank:
   6255     case HalfRank: llvm_unreachable("Complex half is not supported");
   6256     case FloatRank:      return FloatComplexTy;
   6257     case DoubleRank:     return DoubleComplexTy;
   6258     case LongDoubleRank: return LongDoubleComplexTy;
   6259     case Float128Rank:   return Float128ComplexTy;
   6260     }
   6261   }
   6262 
   6263   assert(Domain->isRealFloatingType() && "Unknown domain!");
   6264   switch (EltRank) {
   6265   case Float16Rank:    return HalfTy;
   6266   case BFloat16Rank:   return BFloat16Ty;
   6267   case HalfRank:       return HalfTy;
   6268   case FloatRank:      return FloatTy;
   6269   case DoubleRank:     return DoubleTy;
   6270   case LongDoubleRank: return LongDoubleTy;
   6271   case Float128Rank:   return Float128Ty;
   6272   }
   6273   llvm_unreachable("getFloatingRank(): illegal value for rank");
   6274 }
   6275 
   6276 /// getFloatingTypeOrder - Compare the rank of the two specified floating
   6277 /// point types, ignoring the domain of the type (i.e. 'double' ==
   6278 /// '_Complex double').  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
   6279 /// LHS < RHS, return -1.
   6280 int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
   6281   FloatingRank LHSR = getFloatingRank(LHS);
   6282   FloatingRank RHSR = getFloatingRank(RHS);
   6283 
   6284   if (LHSR == RHSR)
   6285     return 0;
   6286   if (LHSR > RHSR)
   6287     return 1;
   6288   return -1;
   6289 }
   6290 
   6291 int ASTContext::getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const {
   6292   if (&getFloatTypeSemantics(LHS) == &getFloatTypeSemantics(RHS))
   6293     return 0;
   6294   return getFloatingTypeOrder(LHS, RHS);
   6295 }
   6296 
   6297 /// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
   6298 /// routine will assert if passed a built-in type that isn't an integer or enum,
   6299 /// or if it is not canonicalized.
   6300 unsigned ASTContext::getIntegerRank(const Type *T) const {
   6301   assert(T->isCanonicalUnqualified() && "T should be canonicalized");
   6302 
   6303   // Results in this 'losing' to any type of the same size, but winning if
   6304   // larger.
   6305   if (const auto *EIT = dyn_cast<ExtIntType>(T))
   6306     return 0 + (EIT->getNumBits() << 3);
   6307 
   6308   switch (cast<BuiltinType>(T)->getKind()) {
   6309   default: llvm_unreachable("getIntegerRank(): not a built-in integer");
   6310   case BuiltinType::Bool:
   6311     return 1 + (getIntWidth(BoolTy) << 3);
   6312   case BuiltinType::Char_S:
   6313   case BuiltinType::Char_U:
   6314   case BuiltinType::SChar:
   6315   case BuiltinType::UChar:
   6316     return 2 + (getIntWidth(CharTy) << 3);
   6317   case BuiltinType::Short:
   6318   case BuiltinType::UShort:
   6319     return 3 + (getIntWidth(ShortTy) << 3);
   6320   case BuiltinType::Int:
   6321   case BuiltinType::UInt:
   6322     return 4 + (getIntWidth(IntTy) << 3);
   6323   case BuiltinType::Long:
   6324   case BuiltinType::ULong:
   6325     return 5 + (getIntWidth(LongTy) << 3);
   6326   case BuiltinType::LongLong:
   6327   case BuiltinType::ULongLong:
   6328     return 6 + (getIntWidth(LongLongTy) << 3);
   6329   case BuiltinType::Int128:
   6330   case BuiltinType::UInt128:
   6331     return 7 + (getIntWidth(Int128Ty) << 3);
   6332   }
   6333 }
   6334 
   6335 /// Whether this is a promotable bitfield reference according
   6336 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
   6337 ///
   6338 /// \returns the type this bit-field will promote to, or NULL if no
   6339 /// promotion occurs.
   6340 QualType ASTContext::isPromotableBitField(Expr *E) const {
   6341   if (E->isTypeDependent() || E->isValueDependent())
   6342     return {};
   6343 
   6344   // C++ [conv.prom]p5:
   6345   //    If the bit-field has an enumerated type, it is treated as any other
   6346   //    value of that type for promotion purposes.
   6347   if (getLangOpts().CPlusPlus && E->getType()->isEnumeralType())
   6348     return {};
   6349 
   6350   // FIXME: We should not do this unless E->refersToBitField() is true. This
   6351   // matters in C where getSourceBitField() will find bit-fields for various
   6352   // cases where the source expression is not a bit-field designator.
   6353 
   6354   FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
   6355   if (!Field)
   6356     return {};
   6357 
   6358   QualType FT = Field->getType();
   6359 
   6360   uint64_t BitWidth = Field->getBitWidthValue(*this);
   6361   uint64_t IntSize = getTypeSize(IntTy);
   6362   // C++ [conv.prom]p5:
   6363   //   A prvalue for an integral bit-field can be converted to a prvalue of type
   6364   //   int if int can represent all the values of the bit-field; otherwise, it
   6365   //   can be converted to unsigned int if unsigned int can represent all the
   6366   //   values of the bit-field. If the bit-field is larger yet, no integral
   6367   //   promotion applies to it.
   6368   // C11 6.3.1.1/2:
   6369   //   [For a bit-field of type _Bool, int, signed int, or unsigned int:]
   6370   //   If an int can represent all values of the original type (as restricted by
   6371   //   the width, for a bit-field), the value is converted to an int; otherwise,
   6372   //   it is converted to an unsigned int.
   6373   //
   6374   // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
   6375   //        We perform that promotion here to match GCC and C++.
   6376   // FIXME: C does not permit promotion of an enum bit-field whose rank is
   6377   //        greater than that of 'int'. We perform that promotion to match GCC.
   6378   if (BitWidth < IntSize)
   6379     return IntTy;
   6380 
   6381   if (BitWidth == IntSize)
   6382     return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
   6383 
   6384   // Bit-fields wider than int are not subject to promotions, and therefore act
   6385   // like the base type. GCC has some weird bugs in this area that we
   6386   // deliberately do not follow (GCC follows a pre-standard resolution to
   6387   // C's DR315 which treats bit-width as being part of the type, and this leaks
   6388   // into their semantics in some cases).
   6389   return {};
   6390 }
   6391 
   6392 /// getPromotedIntegerType - Returns the type that Promotable will
   6393 /// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
   6394 /// integer type.
   6395 QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
   6396   assert(!Promotable.isNull());
   6397   assert(Promotable->isPromotableIntegerType());
   6398   if (const auto *ET = Promotable->getAs<EnumType>())
   6399     return ET->getDecl()->getPromotionType();
   6400 
   6401   if (const auto *BT = Promotable->getAs<BuiltinType>()) {
   6402     // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
   6403     // (3.9.1) can be converted to a prvalue of the first of the following
   6404     // types that can represent all the values of its underlying type:
   6405     // int, unsigned int, long int, unsigned long int, long long int, or
   6406     // unsigned long long int [...]
   6407     // FIXME: Is there some better way to compute this?
   6408     if (BT->getKind() == BuiltinType::WChar_S ||
   6409         BT->getKind() == BuiltinType::WChar_U ||
   6410         BT->getKind() == BuiltinType::Char8 ||
   6411         BT->getKind() == BuiltinType::Char16 ||
   6412         BT->getKind() == BuiltinType::Char32) {
   6413       bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
   6414       uint64_t FromSize = getTypeSize(BT);
   6415       QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
   6416                                   LongLongTy, UnsignedLongLongTy };
   6417       for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
   6418         uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
   6419         if (FromSize < ToSize ||
   6420             (FromSize == ToSize &&
   6421              FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
   6422           return PromoteTypes[Idx];
   6423       }
   6424       llvm_unreachable("char type should fit into long long");
   6425     }
   6426   }
   6427 
   6428   // At this point, we should have a signed or unsigned integer type.
   6429   if (Promotable->isSignedIntegerType())
   6430     return IntTy;
   6431   uint64_t PromotableSize = getIntWidth(Promotable);
   6432   uint64_t IntSize = getIntWidth(IntTy);
   6433   assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
   6434   return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
   6435 }
   6436 
   6437 /// Recurses in pointer/array types until it finds an objc retainable
   6438 /// type and returns its ownership.
   6439 Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
   6440   while (!T.isNull()) {
   6441     if (T.getObjCLifetime() != Qualifiers::OCL_None)
   6442       return T.getObjCLifetime();
   6443     if (T->isArrayType())
   6444       T = getBaseElementType(T);
   6445     else if (const auto *PT = T->getAs<PointerType>())
   6446       T = PT->getPointeeType();
   6447     else if (const auto *RT = T->getAs<ReferenceType>())
   6448       T = RT->getPointeeType();
   6449     else
   6450       break;
   6451   }
   6452 
   6453   return Qualifiers::OCL_None;
   6454 }
   6455 
   6456 static const Type *getIntegerTypeForEnum(const EnumType *ET) {
   6457   // Incomplete enum types are not treated as integer types.
   6458   // FIXME: In C++, enum types are never integer types.
   6459   if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
   6460     return ET->getDecl()->getIntegerType().getTypePtr();
   6461   return nullptr;
   6462 }
   6463 
   6464 /// getIntegerTypeOrder - Returns the highest ranked integer type:
   6465 /// C99 6.3.1.8p1.  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
   6466 /// LHS < RHS, return -1.
   6467 int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
   6468   const Type *LHSC = getCanonicalType(LHS).getTypePtr();
   6469   const Type *RHSC = getCanonicalType(RHS).getTypePtr();
   6470 
   6471   // Unwrap enums to their underlying type.
   6472   if (const auto *ET = dyn_cast<EnumType>(LHSC))
   6473     LHSC = getIntegerTypeForEnum(ET);
   6474   if (const auto *ET = dyn_cast<EnumType>(RHSC))
   6475     RHSC = getIntegerTypeForEnum(ET);
   6476 
   6477   if (LHSC == RHSC) return 0;
   6478 
   6479   bool LHSUnsigned = LHSC->isUnsignedIntegerType();
   6480   bool RHSUnsigned = RHSC->isUnsignedIntegerType();
   6481 
   6482   unsigned LHSRank = getIntegerRank(LHSC);
   6483   unsigned RHSRank = getIntegerRank(RHSC);
   6484 
   6485   if (LHSUnsigned == RHSUnsigned) {  // Both signed or both unsigned.
   6486     if (LHSRank == RHSRank) return 0;
   6487     return LHSRank > RHSRank ? 1 : -1;
   6488   }
   6489 
   6490   // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
   6491   if (LHSUnsigned) {
   6492     // If the unsigned [LHS] type is larger, return it.
   6493     if (LHSRank >= RHSRank)
   6494       return 1;
   6495 
   6496     // If the signed type can represent all values of the unsigned type, it
   6497     // wins.  Because we are dealing with 2's complement and types that are
   6498     // powers of two larger than each other, this is always safe.
   6499     return -1;
   6500   }
   6501 
   6502   // If the unsigned [RHS] type is larger, return it.
   6503   if (RHSRank >= LHSRank)
   6504     return -1;
   6505 
   6506   // If the signed type can represent all values of the unsigned type, it
   6507   // wins.  Because we are dealing with 2's complement and types that are
   6508   // powers of two larger than each other, this is always safe.
   6509   return 1;
   6510 }
   6511 
   6512 TypedefDecl *ASTContext::getCFConstantStringDecl() const {
   6513   if (CFConstantStringTypeDecl)
   6514     return CFConstantStringTypeDecl;
   6515 
   6516   assert(!CFConstantStringTagDecl &&
   6517          "tag and typedef should be initialized together");
   6518   CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
   6519   CFConstantStringTagDecl->startDefinition();
   6520 
   6521   struct {
   6522     QualType Type;
   6523     const char *Name;
   6524   } Fields[5];
   6525   unsigned Count = 0;
   6526 
   6527   /// Objective-C ABI
   6528   ///
   6529   ///    typedef struct __NSConstantString_tag {
   6530   ///      const int *isa;
   6531   ///      int flags;
   6532   ///      const char *str;
   6533   ///      long length;
   6534   ///    } __NSConstantString;
   6535   ///
   6536   /// Swift ABI (4.1, 4.2)
   6537   ///
   6538   ///    typedef struct __NSConstantString_tag {
   6539   ///      uintptr_t _cfisa;
   6540   ///      uintptr_t _swift_rc;
   6541   ///      _Atomic(uint64_t) _cfinfoa;
   6542   ///      const char *_ptr;
   6543   ///      uint32_t _length;
   6544   ///    } __NSConstantString;
   6545   ///
   6546   /// Swift ABI (5.0)
   6547   ///
   6548   ///    typedef struct __NSConstantString_tag {
   6549   ///      uintptr_t _cfisa;
   6550   ///      uintptr_t _swift_rc;
   6551   ///      _Atomic(uint64_t) _cfinfoa;
   6552   ///      const char *_ptr;
   6553   ///      uintptr_t _length;
   6554   ///    } __NSConstantString;
   6555 
   6556   const auto CFRuntime = getLangOpts().CFRuntime;
   6557   if (static_cast<unsigned>(CFRuntime) <
   6558       static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) {
   6559     Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" };
   6560     Fields[Count++] = { IntTy, "flags" };
   6561     Fields[Count++] = { getPointerType(CharTy.withConst()), "str" };
   6562     Fields[Count++] = { LongTy, "length" };
   6563   } else {
   6564     Fields[Count++] = { getUIntPtrType(), "_cfisa" };
   6565     Fields[Count++] = { getUIntPtrType(), "_swift_rc" };
   6566     Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" };
   6567     Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" };
   6568     if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
   6569         CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
   6570       Fields[Count++] = { IntTy, "_ptr" };
   6571     else
   6572       Fields[Count++] = { getUIntPtrType(), "_ptr" };
   6573   }
   6574 
   6575   // Create fields
   6576   for (unsigned i = 0; i < Count; ++i) {
   6577     FieldDecl *Field =
   6578         FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(),
   6579                           SourceLocation(), &Idents.get(Fields[i].Name),
   6580                           Fields[i].Type, /*TInfo=*/nullptr,
   6581                           /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
   6582     Field->setAccess(AS_public);
   6583     CFConstantStringTagDecl->addDecl(Field);
   6584   }
   6585 
   6586   CFConstantStringTagDecl->completeDefinition();
   6587   // This type is designed to be compatible with NSConstantString, but cannot
   6588   // use the same name, since NSConstantString is an interface.
   6589   auto tagType = getTagDeclType(CFConstantStringTagDecl);
   6590   CFConstantStringTypeDecl =
   6591       buildImplicitTypedef(tagType, "__NSConstantString");
   6592 
   6593   return CFConstantStringTypeDecl;
   6594 }
   6595 
   6596 RecordDecl *ASTContext::getCFConstantStringTagDecl() const {
   6597   if (!CFConstantStringTagDecl)
   6598     getCFConstantStringDecl(); // Build the tag and the typedef.
   6599   return CFConstantStringTagDecl;
   6600 }
   6601 
   6602 // getCFConstantStringType - Return the type used for constant CFStrings.
   6603 QualType ASTContext::getCFConstantStringType() const {
   6604   return getTypedefType(getCFConstantStringDecl());
   6605 }
   6606 
   6607 QualType ASTContext::getObjCSuperType() const {
   6608   if (ObjCSuperType.isNull()) {
   6609     RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
   6610     TUDecl->addDecl(ObjCSuperTypeDecl);
   6611     ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
   6612   }
   6613   return ObjCSuperType;
   6614 }
   6615 
   6616 void ASTContext::setCFConstantStringType(QualType T) {
   6617   const auto *TD = T->castAs<TypedefType>();
   6618   CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl());
   6619   const auto *TagType =
   6620       CFConstantStringTypeDecl->getUnderlyingType()->castAs<RecordType>();
   6621   CFConstantStringTagDecl = TagType->getDecl();
   6622 }
   6623 
   6624 QualType ASTContext::getBlockDescriptorType() const {
   6625   if (BlockDescriptorType)
   6626     return getTagDeclType(BlockDescriptorType);
   6627 
   6628   RecordDecl *RD;
   6629   // FIXME: Needs the FlagAppleBlock bit.
   6630   RD = buildImplicitRecord("__block_descriptor");
   6631   RD->startDefinition();
   6632 
   6633   QualType FieldTypes[] = {
   6634     UnsignedLongTy,
   6635     UnsignedLongTy,
   6636   };
   6637 
   6638   static const char *const FieldNames[] = {
   6639     "reserved",
   6640     "Size"
   6641   };
   6642 
   6643   for (size_t i = 0; i < 2; ++i) {
   6644     FieldDecl *Field = FieldDecl::Create(
   6645         *this, RD, SourceLocation(), SourceLocation(),
   6646         &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
   6647         /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
   6648     Field->setAccess(AS_public);
   6649     RD->addDecl(Field);
   6650   }
   6651 
   6652   RD->completeDefinition();
   6653 
   6654   BlockDescriptorType = RD;
   6655 
   6656   return getTagDeclType(BlockDescriptorType);
   6657 }
   6658 
   6659 QualType ASTContext::getBlockDescriptorExtendedType() const {
   6660   if (BlockDescriptorExtendedType)
   6661     return getTagDeclType(BlockDescriptorExtendedType);
   6662 
   6663   RecordDecl *RD;
   6664   // FIXME: Needs the FlagAppleBlock bit.
   6665   RD = buildImplicitRecord("__block_descriptor_withcopydispose");
   6666   RD->startDefinition();
   6667 
   6668   QualType FieldTypes[] = {
   6669     UnsignedLongTy,
   6670     UnsignedLongTy,
   6671     getPointerType(VoidPtrTy),
   6672     getPointerType(VoidPtrTy)
   6673   };
   6674 
   6675   static const char *const FieldNames[] = {
   6676     "reserved",
   6677     "Size",
   6678     "CopyFuncPtr",
   6679     "DestroyFuncPtr"
   6680   };
   6681 
   6682   for (size_t i = 0; i < 4; ++i) {
   6683     FieldDecl *Field = FieldDecl::Create(
   6684         *this, RD, SourceLocation(), SourceLocation(),
   6685         &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
   6686         /*BitWidth=*/nullptr,
   6687         /*Mutable=*/false, ICIS_NoInit);
   6688     Field->setAccess(AS_public);
   6689     RD->addDecl(Field);
   6690   }
   6691 
   6692   RD->completeDefinition();
   6693 
   6694   BlockDescriptorExtendedType = RD;
   6695   return getTagDeclType(BlockDescriptorExtendedType);
   6696 }
   6697 
   6698 OpenCLTypeKind ASTContext::getOpenCLTypeKind(const Type *T) const {
   6699   const auto *BT = dyn_cast<BuiltinType>(T);
   6700 
   6701   if (!BT) {
   6702     if (isa<PipeType>(T))
   6703       return OCLTK_Pipe;
   6704 
   6705     return OCLTK_Default;
   6706   }
   6707 
   6708   switch (BT->getKind()) {
   6709 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix)                   \
   6710   case BuiltinType::Id:                                                        \
   6711     return OCLTK_Image;
   6712 #include "clang/Basic/OpenCLImageTypes.def"
   6713 
   6714   case BuiltinType::OCLClkEvent:
   6715     return OCLTK_ClkEvent;
   6716 
   6717   case BuiltinType::OCLEvent:
   6718     return OCLTK_Event;
   6719 
   6720   case BuiltinType::OCLQueue:
   6721     return OCLTK_Queue;
   6722 
   6723   case BuiltinType::OCLReserveID:
   6724     return OCLTK_ReserveID;
   6725 
   6726   case BuiltinType::OCLSampler:
   6727     return OCLTK_Sampler;
   6728 
   6729   default:
   6730     return OCLTK_Default;
   6731   }
   6732 }
   6733 
   6734 LangAS ASTContext::getOpenCLTypeAddrSpace(const Type *T) const {
   6735   return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
   6736 }
   6737 
   6738 /// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
   6739 /// requires copy/dispose. Note that this must match the logic
   6740 /// in buildByrefHelpers.
   6741 bool ASTContext::BlockRequiresCopying(QualType Ty,
   6742                                       const VarDecl *D) {
   6743   if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
   6744     const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr();
   6745     if (!copyExpr && record->hasTrivialDestructor()) return false;
   6746 
   6747     return true;
   6748   }
   6749 
   6750   // The block needs copy/destroy helpers if Ty is non-trivial to destructively
   6751   // move or destroy.
   6752   if (Ty.isNonTrivialToPrimitiveDestructiveMove() || Ty.isDestructedType())
   6753     return true;
   6754 
   6755   if (!Ty->isObjCRetainableType()) return false;
   6756 
   6757   Qualifiers qs = Ty.getQualifiers();
   6758 
   6759   // If we have lifetime, that dominates.
   6760   if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
   6761     switch (lifetime) {
   6762       case Qualifiers::OCL_None: llvm_unreachable("impossible");
   6763 
   6764       // These are just bits as far as the runtime is concerned.
   6765       case Qualifiers::OCL_ExplicitNone:
   6766       case Qualifiers::OCL_Autoreleasing:
   6767         return false;
   6768 
   6769       // These cases should have been taken care of when checking the type's
   6770       // non-triviality.
   6771       case Qualifiers::OCL_Weak:
   6772       case Qualifiers::OCL_Strong:
   6773         llvm_unreachable("impossible");
   6774     }
   6775     llvm_unreachable("fell out of lifetime switch!");
   6776   }
   6777   return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
   6778           Ty->isObjCObjectPointerType());
   6779 }
   6780 
   6781 bool ASTContext::getByrefLifetime(QualType Ty,
   6782                               Qualifiers::ObjCLifetime &LifeTime,
   6783                               bool &HasByrefExtendedLayout) const {
   6784   if (!getLangOpts().ObjC ||
   6785       getLangOpts().getGC() != LangOptions::NonGC)
   6786     return false;
   6787 
   6788   HasByrefExtendedLayout = false;
   6789   if (Ty->isRecordType()) {
   6790     HasByrefExtendedLayout = true;
   6791     LifeTime = Qualifiers::OCL_None;
   6792   } else if ((LifeTime = Ty.getObjCLifetime())) {
   6793     // Honor the ARC qualifiers.
   6794   } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
   6795     // The MRR rule.
   6796     LifeTime = Qualifiers::OCL_ExplicitNone;
   6797   } else {
   6798     LifeTime = Qualifiers::OCL_None;
   6799   }
   6800   return true;
   6801 }
   6802 
   6803 CanQualType ASTContext::getNSUIntegerType() const {
   6804   assert(Target && "Expected target to be initialized");
   6805   const llvm::Triple &T = Target->getTriple();
   6806   // Windows is LLP64 rather than LP64
   6807   if (T.isOSWindows() && T.isArch64Bit())
   6808     return UnsignedLongLongTy;
   6809   return UnsignedLongTy;
   6810 }
   6811 
   6812 CanQualType ASTContext::getNSIntegerType() const {
   6813   assert(Target && "Expected target to be initialized");
   6814   const llvm::Triple &T = Target->getTriple();
   6815   // Windows is LLP64 rather than LP64
   6816   if (T.isOSWindows() && T.isArch64Bit())
   6817     return LongLongTy;
   6818   return LongTy;
   6819 }
   6820 
   6821 TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
   6822   if (!ObjCInstanceTypeDecl)
   6823     ObjCInstanceTypeDecl =
   6824         buildImplicitTypedef(getObjCIdType(), "instancetype");
   6825   return ObjCInstanceTypeDecl;
   6826 }
   6827 
   6828 // This returns true if a type has been typedefed to BOOL:
   6829 // typedef <type> BOOL;
   6830 static bool isTypeTypedefedAsBOOL(QualType T) {
   6831   if (const auto *TT = dyn_cast<TypedefType>(T))
   6832     if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
   6833       return II->isStr("BOOL");
   6834 
   6835   return false;
   6836 }
   6837 
   6838 /// getObjCEncodingTypeSize returns size of type for objective-c encoding
   6839 /// purpose.
   6840 CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
   6841   if (!type->isIncompleteArrayType() && type->isIncompleteType())
   6842     return CharUnits::Zero();
   6843 
   6844   CharUnits sz = getTypeSizeInChars(type);
   6845 
   6846   // Make all integer and enum types at least as large as an int
   6847   if (sz.isPositive() && type->isIntegralOrEnumerationType())
   6848     sz = std::max(sz, getTypeSizeInChars(IntTy));
   6849   // Treat arrays as pointers, since that's how they're passed in.
   6850   else if (type->isArrayType())
   6851     sz = getTypeSizeInChars(VoidPtrTy);
   6852   return sz;
   6853 }
   6854 
   6855 bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
   6856   return getTargetInfo().getCXXABI().isMicrosoft() &&
   6857          VD->isStaticDataMember() &&
   6858          VD->getType()->isIntegralOrEnumerationType() &&
   6859          !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
   6860 }
   6861 
   6862 ASTContext::InlineVariableDefinitionKind
   6863 ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const {
   6864   if (!VD->isInline())
   6865     return InlineVariableDefinitionKind::None;
   6866 
   6867   // In almost all cases, it's a weak definition.
   6868   auto *First = VD->getFirstDecl();
   6869   if (First->isInlineSpecified() || !First->isStaticDataMember())
   6870     return InlineVariableDefinitionKind::Weak;
   6871 
   6872   // If there's a file-context declaration in this translation unit, it's a
   6873   // non-discardable definition.
   6874   for (auto *D : VD->redecls())
   6875     if (D->getLexicalDeclContext()->isFileContext() &&
   6876         !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
   6877       return InlineVariableDefinitionKind::Strong;
   6878 
   6879   // If we've not seen one yet, we don't know.
   6880   return InlineVariableDefinitionKind::WeakUnknown;
   6881 }
   6882 
   6883 static std::string charUnitsToString(const CharUnits &CU) {
   6884   return llvm::itostr(CU.getQuantity());
   6885 }
   6886 
   6887 /// getObjCEncodingForBlock - Return the encoded type for this block
   6888 /// declaration.
   6889 std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
   6890   std::string S;
   6891 
   6892   const BlockDecl *Decl = Expr->getBlockDecl();
   6893   QualType BlockTy =
   6894       Expr->getType()->castAs<BlockPointerType>()->getPointeeType();
   6895   QualType BlockReturnTy = BlockTy->castAs<FunctionType>()->getReturnType();
   6896   // Encode result type.
   6897   if (getLangOpts().EncodeExtendedBlockSig)
   6898     getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, BlockReturnTy, S,
   6899                                       true /*Extended*/);
   6900   else
   6901     getObjCEncodingForType(BlockReturnTy, S);
   6902   // Compute size of all parameters.
   6903   // Start with computing size of a pointer in number of bytes.
   6904   // FIXME: There might(should) be a better way of doing this computation!
   6905   CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
   6906   CharUnits ParmOffset = PtrSize;
   6907   for (auto PI : Decl->parameters()) {
   6908     QualType PType = PI->getType();
   6909     CharUnits sz = getObjCEncodingTypeSize(PType);
   6910     if (sz.isZero())
   6911       continue;
   6912     assert(sz.isPositive() && "BlockExpr - Incomplete param type");
   6913     ParmOffset += sz;
   6914   }
   6915   // Size of the argument frame
   6916   S += charUnitsToString(ParmOffset);
   6917   // Block pointer and offset.
   6918   S += "@?0";
   6919 
   6920   // Argument types.
   6921   ParmOffset = PtrSize;
   6922   for (auto PVDecl : Decl->parameters()) {
   6923     QualType PType = PVDecl->getOriginalType();
   6924     if (const auto *AT =
   6925             dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
   6926       // Use array's original type only if it has known number of
   6927       // elements.
   6928       if (!isa<ConstantArrayType>(AT))
   6929         PType = PVDecl->getType();
   6930     } else if (PType->isFunctionType())
   6931       PType = PVDecl->getType();
   6932     if (getLangOpts().EncodeExtendedBlockSig)
   6933       getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
   6934                                       S, true /*Extended*/);
   6935     else
   6936       getObjCEncodingForType(PType, S);
   6937     S += charUnitsToString(ParmOffset);
   6938     ParmOffset += getObjCEncodingTypeSize(PType);
   6939   }
   6940 
   6941   return S;
   6942 }
   6943 
   6944 std::string
   6945 ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const {
   6946   std::string S;
   6947   // Encode result type.
   6948   getObjCEncodingForType(Decl->getReturnType(), S);
   6949   CharUnits ParmOffset;
   6950   // Compute size of all parameters.
   6951   for (auto PI : Decl->parameters()) {
   6952     QualType PType = PI->getType();
   6953     CharUnits sz = getObjCEncodingTypeSize(PType);
   6954     if (sz.isZero())
   6955       continue;
   6956 
   6957     assert(sz.isPositive() &&
   6958            "getObjCEncodingForFunctionDecl - Incomplete param type");
   6959     ParmOffset += sz;
   6960   }
   6961   S += charUnitsToString(ParmOffset);
   6962   ParmOffset = CharUnits::Zero();
   6963 
   6964   // Argument types.
   6965   for (auto PVDecl : Decl->parameters()) {
   6966     QualType PType = PVDecl->getOriginalType();
   6967     if (const auto *AT =
   6968             dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
   6969       // Use array's original type only if it has known number of
   6970       // elements.
   6971       if (!isa<ConstantArrayType>(AT))
   6972         PType = PVDecl->getType();
   6973     } else if (PType->isFunctionType())
   6974       PType = PVDecl->getType();
   6975     getObjCEncodingForType(PType, S);
   6976     S += charUnitsToString(ParmOffset);
   6977     ParmOffset += getObjCEncodingTypeSize(PType);
   6978   }
   6979 
   6980   return S;
   6981 }
   6982 
   6983 /// getObjCEncodingForMethodParameter - Return the encoded type for a single
   6984 /// method parameter or return type. If Extended, include class names and
   6985 /// block object types.
   6986 void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
   6987                                                    QualType T, std::string& S,
   6988                                                    bool Extended) const {
   6989   // Encode type qualifer, 'in', 'inout', etc. for the parameter.
   6990   getObjCEncodingForTypeQualifier(QT, S);
   6991   // Encode parameter type.
   6992   ObjCEncOptions Options = ObjCEncOptions()
   6993                                .setExpandPointedToStructures()
   6994                                .setExpandStructures()
   6995                                .setIsOutermostType();
   6996   if (Extended)
   6997     Options.setEncodeBlockParameters().setEncodeClassNames();
   6998   getObjCEncodingForTypeImpl(T, S, Options, /*Field=*/nullptr);
   6999 }
   7000 
   7001 /// getObjCEncodingForMethodDecl - Return the encoded type for this method
   7002 /// declaration.
   7003 std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
   7004                                                      bool Extended) const {
   7005   // FIXME: This is not very efficient.
   7006   // Encode return type.
   7007   std::string S;
   7008   getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
   7009                                     Decl->getReturnType(), S, Extended);
   7010   // Compute size of all parameters.
   7011   // Start with computing size of a pointer in number of bytes.
   7012   // FIXME: There might(should) be a better way of doing this computation!
   7013   CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
   7014   // The first two arguments (self and _cmd) are pointers; account for
   7015   // their size.
   7016   CharUnits ParmOffset = 2 * PtrSize;
   7017   for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
   7018        E = Decl->sel_param_end(); PI != E; ++PI) {
   7019     QualType PType = (*PI)->getType();
   7020     CharUnits sz = getObjCEncodingTypeSize(PType);
   7021     if (sz.isZero())
   7022       continue;
   7023 
   7024     assert(sz.isPositive() &&
   7025            "getObjCEncodingForMethodDecl - Incomplete param type");
   7026     ParmOffset += sz;
   7027   }
   7028   S += charUnitsToString(ParmOffset);
   7029   S += "@0:";
   7030   S += charUnitsToString(PtrSize);
   7031 
   7032   // Argument types.
   7033   ParmOffset = 2 * PtrSize;
   7034   for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
   7035        E = Decl->sel_param_end(); PI != E; ++PI) {
   7036     const ParmVarDecl *PVDecl = *PI;
   7037     QualType PType = PVDecl->getOriginalType();
   7038     if (const auto *AT =
   7039             dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
   7040       // Use array's original type only if it has known number of
   7041       // elements.
   7042       if (!isa<ConstantArrayType>(AT))
   7043         PType = PVDecl->getType();
   7044     } else if (PType->isFunctionType())
   7045       PType = PVDecl->getType();
   7046     getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
   7047                                       PType, S, Extended);
   7048     S += charUnitsToString(ParmOffset);
   7049     ParmOffset += getObjCEncodingTypeSize(PType);
   7050   }
   7051 
   7052   return S;
   7053 }
   7054 
   7055 ObjCPropertyImplDecl *
   7056 ASTContext::getObjCPropertyImplDeclForPropertyDecl(
   7057                                       const ObjCPropertyDecl *PD,
   7058                                       const Decl *Container) const {
   7059   if (!Container)
   7060     return nullptr;
   7061   if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) {
   7062     for (auto *PID : CID->property_impls())
   7063       if (PID->getPropertyDecl() == PD)
   7064         return PID;
   7065   } else {
   7066     const auto *OID = cast<ObjCImplementationDecl>(Container);
   7067     for (auto *PID : OID->property_impls())
   7068       if (PID->getPropertyDecl() == PD)
   7069         return PID;
   7070   }
   7071   return nullptr;
   7072 }
   7073 
   7074 /// getObjCEncodingForPropertyDecl - Return the encoded type for this
   7075 /// property declaration. If non-NULL, Container must be either an
   7076 /// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
   7077 /// NULL when getting encodings for protocol properties.
   7078 /// Property attributes are stored as a comma-delimited C string. The simple
   7079 /// attributes readonly and bycopy are encoded as single characters. The
   7080 /// parametrized attributes, getter=name, setter=name, and ivar=name, are
   7081 /// encoded as single characters, followed by an identifier. Property types
   7082 /// are also encoded as a parametrized attribute. The characters used to encode
   7083 /// these attributes are defined by the following enumeration:
   7084 /// @code
   7085 /// enum PropertyAttributes {
   7086 /// kPropertyReadOnly = 'R',   // property is read-only.
   7087 /// kPropertyBycopy = 'C',     // property is a copy of the value last assigned
   7088 /// kPropertyByref = '&',  // property is a reference to the value last assigned
   7089 /// kPropertyDynamic = 'D',    // property is dynamic
   7090 /// kPropertyGetter = 'G',     // followed by getter selector name
   7091 /// kPropertySetter = 'S',     // followed by setter selector name
   7092 /// kPropertyInstanceVariable = 'V'  // followed by instance variable  name
   7093 /// kPropertyType = 'T'              // followed by old-style type encoding.
   7094 /// kPropertyWeak = 'W'              // 'weak' property
   7095 /// kPropertyStrong = 'P'            // property GC'able
   7096 /// kPropertyNonAtomic = 'N'         // property non-atomic
   7097 /// };
   7098 /// @endcode
   7099 std::string
   7100 ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
   7101                                            const Decl *Container) const {
   7102   // Collect information from the property implementation decl(s).
   7103   bool Dynamic = false;
   7104   ObjCPropertyImplDecl *SynthesizePID = nullptr;
   7105 
   7106   if (ObjCPropertyImplDecl *PropertyImpDecl =
   7107       getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
   7108     if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
   7109       Dynamic = true;
   7110     else
   7111       SynthesizePID = PropertyImpDecl;
   7112   }
   7113 
   7114   // FIXME: This is not very efficient.
   7115   std::string S = "T";
   7116 
   7117   // Encode result type.
   7118   // GCC has some special rules regarding encoding of properties which
   7119   // closely resembles encoding of ivars.
   7120   getObjCEncodingForPropertyType(PD->getType(), S);
   7121 
   7122   if (PD->isReadOnly()) {
   7123     S += ",R";
   7124     if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_copy)
   7125       S += ",C";
   7126     if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_retain)
   7127       S += ",&";
   7128     if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_weak)
   7129       S += ",W";
   7130   } else {
   7131     switch (PD->getSetterKind()) {
   7132     case ObjCPropertyDecl::Assign: break;
   7133     case ObjCPropertyDecl::Copy:   S += ",C"; break;
   7134     case ObjCPropertyDecl::Retain: S += ",&"; break;
   7135     case ObjCPropertyDecl::Weak:   S += ",W"; break;
   7136     }
   7137   }
   7138 
   7139   // It really isn't clear at all what this means, since properties
   7140   // are "dynamic by default".
   7141   if (Dynamic)
   7142     S += ",D";
   7143 
   7144   if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_nonatomic)
   7145     S += ",N";
   7146 
   7147   if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_getter) {
   7148     S += ",G";
   7149     S += PD->getGetterName().getAsString();
   7150   }
   7151 
   7152   if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_setter) {
   7153     S += ",S";
   7154     S += PD->getSetterName().getAsString();
   7155   }
   7156 
   7157   if (SynthesizePID) {
   7158     const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
   7159     S += ",V";
   7160     S += OID->getNameAsString();
   7161   }
   7162 
   7163   // FIXME: OBJCGC: weak & strong
   7164   return S;
   7165 }
   7166 
   7167 /// getLegacyIntegralTypeEncoding -
   7168 /// Another legacy compatibility encoding: 32-bit longs are encoded as
   7169 /// 'l' or 'L' , but not always.  For typedefs, we need to use
   7170 /// 'i' or 'I' instead if encoding a struct field, or a pointer!
   7171 void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
   7172   if (isa<TypedefType>(PointeeTy.getTypePtr())) {
   7173     if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
   7174       if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
   7175         PointeeTy = UnsignedIntTy;
   7176       else
   7177         if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
   7178           PointeeTy = IntTy;
   7179     }
   7180   }
   7181 }
   7182 
   7183 void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
   7184                                         const FieldDecl *Field,
   7185                                         QualType *NotEncodedT) const {
   7186   // We follow the behavior of gcc, expanding structures which are
   7187   // directly pointed to, and expanding embedded structures. Note that
   7188   // these rules are sufficient to prevent recursive encoding of the
   7189   // same type.
   7190   getObjCEncodingForTypeImpl(T, S,
   7191                              ObjCEncOptions()
   7192                                  .setExpandPointedToStructures()
   7193                                  .setExpandStructures()
   7194                                  .setIsOutermostType(),
   7195                              Field, NotEncodedT);
   7196 }
   7197 
   7198 void ASTContext::getObjCEncodingForPropertyType(QualType T,
   7199                                                 std::string& S) const {
   7200   // Encode result type.
   7201   // GCC has some special rules regarding encoding of properties which
   7202   // closely resembles encoding of ivars.
   7203   getObjCEncodingForTypeImpl(T, S,
   7204                              ObjCEncOptions()
   7205                                  .setExpandPointedToStructures()
   7206                                  .setExpandStructures()
   7207                                  .setIsOutermostType()
   7208                                  .setEncodingProperty(),
   7209                              /*Field=*/nullptr);
   7210 }
   7211 
   7212 static char getObjCEncodingForPrimitiveType(const ASTContext *C,
   7213                                             const BuiltinType *BT) {
   7214     BuiltinType::Kind kind = BT->getKind();
   7215     switch (kind) {
   7216     case BuiltinType::Void:       return 'v';
   7217     case BuiltinType::Bool:       return 'B';
   7218     case BuiltinType::Char8:
   7219     case BuiltinType::Char_U:
   7220     case BuiltinType::UChar:      return 'C';
   7221     case BuiltinType::Char16:
   7222     case BuiltinType::UShort:     return 'S';
   7223     case BuiltinType::Char32:
   7224     case BuiltinType::UInt:       return 'I';
   7225     case BuiltinType::ULong:
   7226         return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
   7227     case BuiltinType::UInt128:    return 'T';
   7228     case BuiltinType::ULongLong:  return 'Q';
   7229     case BuiltinType::Char_S:
   7230     case BuiltinType::SChar:      return 'c';
   7231     case BuiltinType::Short:      return 's';
   7232     case BuiltinType::WChar_S:
   7233     case BuiltinType::WChar_U:
   7234     case BuiltinType::Int:        return 'i';
   7235     case BuiltinType::Long:
   7236       return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
   7237     case BuiltinType::LongLong:   return 'q';
   7238     case BuiltinType::Int128:     return 't';
   7239     case BuiltinType::Float:      return 'f';
   7240     case BuiltinType::Double:     return 'd';
   7241     case BuiltinType::LongDouble: return 'D';
   7242     case BuiltinType::NullPtr:    return '*'; // like char*
   7243 
   7244     case BuiltinType::BFloat16:
   7245     case BuiltinType::Float16:
   7246     case BuiltinType::Float128:
   7247     case BuiltinType::Half:
   7248     case BuiltinType::ShortAccum:
   7249     case BuiltinType::Accum:
   7250     case BuiltinType::LongAccum:
   7251     case BuiltinType::UShortAccum:
   7252     case BuiltinType::UAccum:
   7253     case BuiltinType::ULongAccum:
   7254     case BuiltinType::ShortFract:
   7255     case BuiltinType::Fract:
   7256     case BuiltinType::LongFract:
   7257     case BuiltinType::UShortFract:
   7258     case BuiltinType::UFract:
   7259     case BuiltinType::ULongFract:
   7260     case BuiltinType::SatShortAccum:
   7261     case BuiltinType::SatAccum:
   7262     case BuiltinType::SatLongAccum:
   7263     case BuiltinType::SatUShortAccum:
   7264     case BuiltinType::SatUAccum:
   7265     case BuiltinType::SatULongAccum:
   7266     case BuiltinType::SatShortFract:
   7267     case BuiltinType::SatFract:
   7268     case BuiltinType::SatLongFract:
   7269     case BuiltinType::SatUShortFract:
   7270     case BuiltinType::SatUFract:
   7271     case BuiltinType::SatULongFract:
   7272       // FIXME: potentially need @encodes for these!
   7273       return ' ';
   7274 
   7275 #define SVE_TYPE(Name, Id, SingletonId) \
   7276     case BuiltinType::Id:
   7277 #include "clang/Basic/AArch64SVEACLETypes.def"
   7278 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
   7279 #include "clang/Basic/RISCVVTypes.def"
   7280       {
   7281         DiagnosticsEngine &Diags = C->getDiagnostics();
   7282         unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
   7283                                                 "cannot yet @encode type %0");
   7284         Diags.Report(DiagID) << BT->getName(C->getPrintingPolicy());
   7285         return ' ';
   7286       }
   7287 
   7288     case BuiltinType::ObjCId:
   7289     case BuiltinType::ObjCClass:
   7290     case BuiltinType::ObjCSel:
   7291       llvm_unreachable("@encoding ObjC primitive type");
   7292 
   7293     // OpenCL and placeholder types don't need @encodings.
   7294 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
   7295     case BuiltinType::Id:
   7296 #include "clang/Basic/OpenCLImageTypes.def"
   7297 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
   7298     case BuiltinType::Id:
   7299 #include "clang/Basic/OpenCLExtensionTypes.def"
   7300     case BuiltinType::OCLEvent:
   7301     case BuiltinType::OCLClkEvent:
   7302     case BuiltinType::OCLQueue:
   7303     case BuiltinType::OCLReserveID:
   7304     case BuiltinType::OCLSampler:
   7305     case BuiltinType::Dependent:
   7306 #define PPC_VECTOR_TYPE(Name, Id, Size) \
   7307     case BuiltinType::Id:
   7308 #include "clang/Basic/PPCTypes.def"
   7309 #define BUILTIN_TYPE(KIND, ID)
   7310 #define PLACEHOLDER_TYPE(KIND, ID) \
   7311     case BuiltinType::KIND:
   7312 #include "clang/AST/BuiltinTypes.def"
   7313       llvm_unreachable("invalid builtin type for @encode");
   7314     }
   7315     llvm_unreachable("invalid BuiltinType::Kind value");
   7316 }
   7317 
   7318 static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
   7319   EnumDecl *Enum = ET->getDecl();
   7320 
   7321   // The encoding of an non-fixed enum type is always 'i', regardless of size.
   7322   if (!Enum->isFixed())
   7323     return 'i';
   7324 
   7325   // The encoding of a fixed enum type matches its fixed underlying type.
   7326   const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
   7327   return getObjCEncodingForPrimitiveType(C, BT);
   7328 }
   7329 
   7330 static void EncodeBitField(const ASTContext *Ctx, std::string& S,
   7331                            QualType T, const FieldDecl *FD) {
   7332   assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
   7333   S += 'b';
   7334   // The NeXT runtime encodes bit fields as b followed by the number of bits.
   7335   // The GNU runtime requires more information; bitfields are encoded as b,
   7336   // then the offset (in bits) of the first element, then the type of the
   7337   // bitfield, then the size in bits.  For example, in this structure:
   7338   //
   7339   // struct
   7340   // {
   7341   //    int integer;
   7342   //    int flags:2;
   7343   // };
   7344   // On a 32-bit system, the encoding for flags would be b2 for the NeXT
   7345   // runtime, but b32i2 for the GNU runtime.  The reason for this extra
   7346   // information is not especially sensible, but we're stuck with it for
   7347   // compatibility with GCC, although providing it breaks anything that
   7348   // actually uses runtime introspection and wants to work on both runtimes...
   7349   if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
   7350     uint64_t Offset;
   7351 
   7352     if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
   7353       Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), nullptr,
   7354                                          IVD);
   7355     } else {
   7356       const RecordDecl *RD = FD->getParent();
   7357       const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
   7358       Offset = RL.getFieldOffset(FD->getFieldIndex());
   7359     }
   7360 
   7361     S += llvm::utostr(Offset);
   7362 
   7363     if (const auto *ET = T->getAs<EnumType>())
   7364       S += ObjCEncodingForEnumType(Ctx, ET);
   7365     else {
   7366       const auto *BT = T->castAs<BuiltinType>();
   7367       S += getObjCEncodingForPrimitiveType(Ctx, BT);
   7368     }
   7369   }
   7370   S += llvm::utostr(FD->getBitWidthValue(*Ctx));
   7371 }
   7372 
   7373 // Helper function for determining whether the encoded type string would include
   7374 // a template specialization type.
   7375 static bool hasTemplateSpecializationInEncodedString(const Type *T,
   7376                                                      bool VisitBasesAndFields) {
   7377   T = T->getBaseElementTypeUnsafe();
   7378 
   7379   if (auto *PT = T->getAs<PointerType>())
   7380     return hasTemplateSpecializationInEncodedString(
   7381         PT->getPointeeType().getTypePtr(), false);
   7382 
   7383   auto *CXXRD = T->getAsCXXRecordDecl();
   7384 
   7385   if (!CXXRD)
   7386     return false;
   7387 
   7388   if (isa<ClassTemplateSpecializationDecl>(CXXRD))
   7389     return true;
   7390 
   7391   if (!CXXRD->hasDefinition() || !VisitBasesAndFields)
   7392     return false;
   7393 
   7394   for (auto B : CXXRD->bases())
   7395     if (hasTemplateSpecializationInEncodedString(B.getType().getTypePtr(),
   7396                                                  true))
   7397       return true;
   7398 
   7399   for (auto *FD : CXXRD->fields())
   7400     if (hasTemplateSpecializationInEncodedString(FD->getType().getTypePtr(),
   7401                                                  true))
   7402       return true;
   7403 
   7404   return false;
   7405 }
   7406 
   7407 // FIXME: Use SmallString for accumulating string.
   7408 void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
   7409                                             const ObjCEncOptions Options,
   7410                                             const FieldDecl *FD,
   7411                                             QualType *NotEncodedT) const {
   7412   CanQualType CT = getCanonicalType(T);
   7413   switch (CT->getTypeClass()) {
   7414   case Type::Builtin:
   7415   case Type::Enum:
   7416     if (FD && FD->isBitField())
   7417       return EncodeBitField(this, S, T, FD);
   7418     if (const auto *BT = dyn_cast<BuiltinType>(CT))
   7419       S += getObjCEncodingForPrimitiveType(this, BT);
   7420     else
   7421       S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
   7422     return;
   7423 
   7424   case Type::Complex:
   7425     S += 'j';
   7426     getObjCEncodingForTypeImpl(T->castAs<ComplexType>()->getElementType(), S,
   7427                                ObjCEncOptions(),
   7428                                /*Field=*/nullptr);
   7429     return;
   7430 
   7431   case Type::Atomic:
   7432     S += 'A';
   7433     getObjCEncodingForTypeImpl(T->castAs<AtomicType>()->getValueType(), S,
   7434                                ObjCEncOptions(),
   7435                                /*Field=*/nullptr);
   7436     return;
   7437 
   7438   // encoding for pointer or reference types.
   7439   case Type::Pointer:
   7440   case Type::LValueReference:
   7441   case Type::RValueReference: {
   7442     QualType PointeeTy;
   7443     if (isa<PointerType>(CT)) {
   7444       const auto *PT = T->castAs<PointerType>();
   7445       if (PT->isObjCSelType()) {
   7446         S += ':';
   7447         return;
   7448       }
   7449       PointeeTy = PT->getPointeeType();
   7450     } else {
   7451       PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
   7452     }
   7453 
   7454     bool isReadOnly = false;
   7455     // For historical/compatibility reasons, the read-only qualifier of the
   7456     // pointee gets emitted _before_ the '^'.  The read-only qualifier of
   7457     // the pointer itself gets ignored, _unless_ we are looking at a typedef!
   7458     // Also, do not emit the 'r' for anything but the outermost type!
   7459     if (isa<TypedefType>(T.getTypePtr())) {
   7460       if (Options.IsOutermostType() && T.isConstQualified()) {
   7461         isReadOnly = true;
   7462         S += 'r';
   7463       }
   7464     } else if (Options.IsOutermostType()) {
   7465       QualType P = PointeeTy;
   7466       while (auto PT = P->getAs<PointerType>())
   7467         P = PT->getPointeeType();
   7468       if (P.isConstQualified()) {
   7469         isReadOnly = true;
   7470         S += 'r';
   7471       }
   7472     }
   7473     if (isReadOnly) {
   7474       // Another legacy compatibility encoding. Some ObjC qualifier and type
   7475       // combinations need to be rearranged.
   7476       // Rewrite "in const" from "nr" to "rn"
   7477       if (StringRef(S).endswith("nr"))
   7478         S.replace(S.end()-2, S.end(), "rn");
   7479     }
   7480 
   7481     if (PointeeTy->isCharType()) {
   7482       // char pointer types should be encoded as '*' unless it is a
   7483       // type that has been typedef'd to 'BOOL'.
   7484       if (!isTypeTypedefedAsBOOL(PointeeTy)) {
   7485         S += '*';
   7486         return;
   7487       }
   7488     } else if (const auto *RTy = PointeeTy->getAs<RecordType>()) {
   7489       // GCC binary compat: Need to convert "struct objc_class *" to "#".
   7490       if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
   7491         S += '#';
   7492         return;
   7493       }
   7494       // GCC binary compat: Need to convert "struct objc_object *" to "@".
   7495       if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
   7496         S += '@';
   7497         return;
   7498       }
   7499       // If the encoded string for the class includes template names, just emit
   7500       // "^v" for pointers to the class.
   7501       if (getLangOpts().CPlusPlus &&
   7502           (!getLangOpts().EncodeCXXClassTemplateSpec &&
   7503            hasTemplateSpecializationInEncodedString(
   7504                RTy, Options.ExpandPointedToStructures()))) {
   7505         S += "^v";
   7506         return;
   7507       }
   7508       // fall through...
   7509     }
   7510     S += '^';
   7511     getLegacyIntegralTypeEncoding(PointeeTy);
   7512 
   7513     ObjCEncOptions NewOptions;
   7514     if (Options.ExpandPointedToStructures())
   7515       NewOptions.setExpandStructures();
   7516     getObjCEncodingForTypeImpl(PointeeTy, S, NewOptions,
   7517                                /*Field=*/nullptr, NotEncodedT);
   7518     return;
   7519   }
   7520 
   7521   case Type::ConstantArray:
   7522   case Type::IncompleteArray:
   7523   case Type::VariableArray: {
   7524     const auto *AT = cast<ArrayType>(CT);
   7525 
   7526     if (isa<IncompleteArrayType>(AT) && !Options.IsStructField()) {
   7527       // Incomplete arrays are encoded as a pointer to the array element.
   7528       S += '^';
   7529 
   7530       getObjCEncodingForTypeImpl(
   7531           AT->getElementType(), S,
   7532           Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD);
   7533     } else {
   7534       S += '[';
   7535 
   7536       if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
   7537         S += llvm::utostr(CAT->getSize().getZExtValue());
   7538       else {
   7539         //Variable length arrays are encoded as a regular array with 0 elements.
   7540         assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
   7541                "Unknown array type!");
   7542         S += '0';
   7543       }
   7544 
   7545       getObjCEncodingForTypeImpl(
   7546           AT->getElementType(), S,
   7547           Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD,
   7548           NotEncodedT);
   7549       S += ']';
   7550     }
   7551     return;
   7552   }
   7553 
   7554   case Type::FunctionNoProto:
   7555   case Type::FunctionProto:
   7556     S += '?';
   7557     return;
   7558 
   7559   case Type::Record: {
   7560     RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
   7561     S += RDecl->isUnion() ? '(' : '{';
   7562     // Anonymous structures print as '?'
   7563     if (const IdentifierInfo *II = RDecl->getIdentifier()) {
   7564       S += II->getName();
   7565       if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
   7566         const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
   7567         llvm::raw_string_ostream OS(S);
   7568         printTemplateArgumentList(OS, TemplateArgs.asArray(),
   7569                                   getPrintingPolicy());
   7570       }
   7571     } else {
   7572       S += '?';
   7573     }
   7574     if (Options.ExpandStructures()) {
   7575       S += '=';
   7576       if (!RDecl->isUnion()) {
   7577         getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
   7578       } else {
   7579         for (const auto *Field : RDecl->fields()) {
   7580           if (FD) {
   7581             S += '"';
   7582             S += Field->getNameAsString();
   7583             S += '"';
   7584           }
   7585 
   7586           // Special case bit-fields.
   7587           if (Field->isBitField()) {
   7588             getObjCEncodingForTypeImpl(Field->getType(), S,
   7589                                        ObjCEncOptions().setExpandStructures(),
   7590                                        Field);
   7591           } else {
   7592             QualType qt = Field->getType();
   7593             getLegacyIntegralTypeEncoding(qt);
   7594             getObjCEncodingForTypeImpl(
   7595                 qt, S,
   7596                 ObjCEncOptions().setExpandStructures().setIsStructField(), FD,
   7597                 NotEncodedT);
   7598           }
   7599         }
   7600       }
   7601     }
   7602     S += RDecl->isUnion() ? ')' : '}';
   7603     return;
   7604   }
   7605 
   7606   case Type::BlockPointer: {
   7607     const auto *BT = T->castAs<BlockPointerType>();
   7608     S += "@?"; // Unlike a pointer-to-function, which is "^?".
   7609     if (Options.EncodeBlockParameters()) {
   7610       const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
   7611 
   7612       S += '<';
   7613       // Block return type
   7614       getObjCEncodingForTypeImpl(FT->getReturnType(), S,
   7615                                  Options.forComponentType(), FD, NotEncodedT);
   7616       // Block self
   7617       S += "@?";
   7618       // Block parameters
   7619       if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) {
   7620         for (const auto &I : FPT->param_types())
   7621           getObjCEncodingForTypeImpl(I, S, Options.forComponentType(), FD,
   7622                                      NotEncodedT);
   7623       }
   7624       S += '>';
   7625     }
   7626     return;
   7627   }
   7628 
   7629   case Type::ObjCObject: {
   7630     // hack to match legacy encoding of *id and *Class
   7631     QualType Ty = getObjCObjectPointerType(CT);
   7632     if (Ty->isObjCIdType()) {
   7633       S += "{objc_object=}";
   7634       return;
   7635     }
   7636     else if (Ty->isObjCClassType()) {
   7637       S += "{objc_class=}";
   7638       return;
   7639     }
   7640     // TODO: Double check to make sure this intentionally falls through.
   7641     LLVM_FALLTHROUGH;
   7642   }
   7643 
   7644   case Type::ObjCInterface: {
   7645     // Ignore protocol qualifiers when mangling at this level.
   7646     // @encode(class_name)
   7647     ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
   7648     S += '{';
   7649     S += OI->getObjCRuntimeNameAsString();
   7650     if (Options.ExpandStructures()) {
   7651       S += '=';
   7652       SmallVector<const ObjCIvarDecl*, 32> Ivars;
   7653       DeepCollectObjCIvars(OI, true, Ivars);
   7654       for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
   7655         const FieldDecl *Field = Ivars[i];
   7656         if (Field->isBitField())
   7657           getObjCEncodingForTypeImpl(Field->getType(), S,
   7658                                      ObjCEncOptions().setExpandStructures(),
   7659                                      Field);
   7660         else
   7661           getObjCEncodingForTypeImpl(Field->getType(), S,
   7662                                      ObjCEncOptions().setExpandStructures(), FD,
   7663                                      NotEncodedT);
   7664       }
   7665     }
   7666     S += '}';
   7667     return;
   7668   }
   7669 
   7670   case Type::ObjCObjectPointer: {
   7671     const auto *OPT = T->castAs<ObjCObjectPointerType>();
   7672     if (OPT->isObjCIdType()) {
   7673       S += '@';
   7674       return;
   7675     }
   7676 
   7677     if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
   7678       // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
   7679       // Since this is a binary compatibility issue, need to consult with
   7680       // runtime folks. Fortunately, this is a *very* obscure construct.
   7681       S += '#';
   7682       return;
   7683     }
   7684 
   7685     if (OPT->isObjCQualifiedIdType()) {
   7686       getObjCEncodingForTypeImpl(
   7687           getObjCIdType(), S,
   7688           Options.keepingOnly(ObjCEncOptions()
   7689                                   .setExpandPointedToStructures()
   7690                                   .setExpandStructures()),
   7691           FD);
   7692       if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) {
   7693         // Note that we do extended encoding of protocol qualifer list
   7694         // Only when doing ivar or property encoding.
   7695         S += '"';
   7696         for (const auto *I : OPT->quals()) {
   7697           S += '<';
   7698           S += I->getObjCRuntimeNameAsString();
   7699           S += '>';
   7700         }
   7701         S += '"';
   7702       }
   7703       return;
   7704     }
   7705 
   7706     S += '@';
   7707     if (OPT->getInterfaceDecl() &&
   7708         (FD || Options.EncodingProperty() || Options.EncodeClassNames())) {
   7709       S += '"';
   7710       S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
   7711       for (const auto *I : OPT->quals()) {
   7712         S += '<';
   7713         S += I->getObjCRuntimeNameAsString();
   7714         S += '>';
   7715       }
   7716       S += '"';
   7717     }
   7718     return;
   7719   }
   7720 
   7721   // gcc just blithely ignores member pointers.
   7722   // FIXME: we should do better than that.  'M' is available.
   7723   case Type::MemberPointer:
   7724   // This matches gcc's encoding, even though technically it is insufficient.
   7725   //FIXME. We should do a better job than gcc.
   7726   case Type::Vector:
   7727   case Type::ExtVector:
   7728   // Until we have a coherent encoding of these three types, issue warning.
   7729     if (NotEncodedT)
   7730       *NotEncodedT = T;
   7731     return;
   7732 
   7733   case Type::ConstantMatrix:
   7734     if (NotEncodedT)
   7735       *NotEncodedT = T;
   7736     return;
   7737 
   7738   // We could see an undeduced auto type here during error recovery.
   7739   // Just ignore it.
   7740   case Type::Auto:
   7741   case Type::DeducedTemplateSpecialization:
   7742     return;
   7743 
   7744   case Type::Pipe:
   7745   case Type::ExtInt:
   7746 #define ABSTRACT_TYPE(KIND, BASE)
   7747 #define TYPE(KIND, BASE)
   7748 #define DEPENDENT_TYPE(KIND, BASE) \
   7749   case Type::KIND:
   7750 #define NON_CANONICAL_TYPE(KIND, BASE) \
   7751   case Type::KIND:
   7752 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
   7753   case Type::KIND:
   7754 #include "clang/AST/TypeNodes.inc"
   7755     llvm_unreachable("@encode for dependent type!");
   7756   }
   7757   llvm_unreachable("bad type kind!");
   7758 }
   7759 
   7760 void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
   7761                                                  std::string &S,
   7762                                                  const FieldDecl *FD,
   7763                                                  bool includeVBases,
   7764                                                  QualType *NotEncodedT) const {
   7765   assert(RDecl && "Expected non-null RecordDecl");
   7766   assert(!RDecl->isUnion() && "Should not be called for unions");
   7767   if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
   7768     return;
   7769 
   7770   const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
   7771   std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
   7772   const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
   7773 
   7774   if (CXXRec) {
   7775     for (const auto &BI : CXXRec->bases()) {
   7776       if (!BI.isVirtual()) {
   7777         CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
   7778         if (base->isEmpty())
   7779           continue;
   7780         uint64_t offs = toBits(layout.getBaseClassOffset(base));
   7781         FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
   7782                                   std::make_pair(offs, base));
   7783       }
   7784     }
   7785   }
   7786 
   7787   unsigned i = 0;
   7788   for (FieldDecl *Field : RDecl->fields()) {
   7789     if (!Field->isZeroLengthBitField(*this) && Field->isZeroSize(*this))
   7790       continue;
   7791     uint64_t offs = layout.getFieldOffset(i);
   7792     FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
   7793                               std::make_pair(offs, Field));
   7794     ++i;
   7795   }
   7796 
   7797   if (CXXRec && includeVBases) {
   7798     for (const auto &BI : CXXRec->vbases()) {
   7799       CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
   7800       if (base->isEmpty())
   7801         continue;
   7802       uint64_t offs = toBits(layout.getVBaseClassOffset(base));
   7803       if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
   7804           FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
   7805         FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
   7806                                   std::make_pair(offs, base));
   7807     }
   7808   }
   7809 
   7810   CharUnits size;
   7811   if (CXXRec) {
   7812     size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
   7813   } else {
   7814     size = layout.getSize();
   7815   }
   7816 
   7817 #ifndef NDEBUG
   7818   uint64_t CurOffs = 0;
   7819 #endif
   7820   std::multimap<uint64_t, NamedDecl *>::iterator
   7821     CurLayObj = FieldOrBaseOffsets.begin();
   7822 
   7823   if (CXXRec && CXXRec->isDynamicClass() &&
   7824       (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
   7825     if (FD) {
   7826       S += "\"_vptr$";
   7827       std::string recname = CXXRec->getNameAsString();
   7828       if (recname.empty()) recname = "?";
   7829       S += recname;
   7830       S += '"';
   7831     }
   7832     S += "^^?";
   7833 #ifndef NDEBUG
   7834     CurOffs += getTypeSize(VoidPtrTy);
   7835 #endif
   7836   }
   7837 
   7838   if (!RDecl->hasFlexibleArrayMember()) {
   7839     // Mark the end of the structure.
   7840     uint64_t offs = toBits(size);
   7841     FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
   7842                               std::make_pair(offs, nullptr));
   7843   }
   7844 
   7845   for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
   7846 #ifndef NDEBUG
   7847     assert(CurOffs <= CurLayObj->first);
   7848     if (CurOffs < CurLayObj->first) {
   7849       uint64_t padding = CurLayObj->first - CurOffs;
   7850       // FIXME: There doesn't seem to be a way to indicate in the encoding that
   7851       // packing/alignment of members is different that normal, in which case
   7852       // the encoding will be out-of-sync with the real layout.
   7853       // If the runtime switches to just consider the size of types without
   7854       // taking into account alignment, we could make padding explicit in the
   7855       // encoding (e.g. using arrays of chars). The encoding strings would be
   7856       // longer then though.
   7857       CurOffs += padding;
   7858     }
   7859 #endif
   7860 
   7861     NamedDecl *dcl = CurLayObj->second;
   7862     if (!dcl)
   7863       break; // reached end of structure.
   7864 
   7865     if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) {
   7866       // We expand the bases without their virtual bases since those are going
   7867       // in the initial structure. Note that this differs from gcc which
   7868       // expands virtual bases each time one is encountered in the hierarchy,
   7869       // making the encoding type bigger than it really is.
   7870       getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
   7871                                       NotEncodedT);
   7872       assert(!base->isEmpty());
   7873 #ifndef NDEBUG
   7874       CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
   7875 #endif
   7876     } else {
   7877       const auto *field = cast<FieldDecl>(dcl);
   7878       if (FD) {
   7879         S += '"';
   7880         S += field->getNameAsString();
   7881         S += '"';
   7882       }
   7883 
   7884       if (field->isBitField()) {
   7885         EncodeBitField(this, S, field->getType(), field);
   7886 #ifndef NDEBUG
   7887         CurOffs += field->getBitWidthValue(*this);
   7888 #endif
   7889       } else {
   7890         QualType qt = field->getType();
   7891         getLegacyIntegralTypeEncoding(qt);
   7892         getObjCEncodingForTypeImpl(
   7893             qt, S, ObjCEncOptions().setExpandStructures().setIsStructField(),
   7894             FD, NotEncodedT);
   7895 #ifndef NDEBUG
   7896         CurOffs += getTypeSize(field->getType());
   7897 #endif
   7898       }
   7899     }
   7900   }
   7901 }
   7902 
   7903 void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
   7904                                                  std::string& S) const {
   7905   if (QT & Decl::OBJC_TQ_In)
   7906     S += 'n';
   7907   if (QT & Decl::OBJC_TQ_Inout)
   7908     S += 'N';
   7909   if (QT & Decl::OBJC_TQ_Out)
   7910     S += 'o';
   7911   if (QT & Decl::OBJC_TQ_Bycopy)
   7912     S += 'O';
   7913   if (QT & Decl::OBJC_TQ_Byref)
   7914     S += 'R';
   7915   if (QT & Decl::OBJC_TQ_Oneway)
   7916     S += 'V';
   7917 }
   7918 
   7919 TypedefDecl *ASTContext::getObjCIdDecl() const {
   7920   if (!ObjCIdDecl) {
   7921     QualType T = getObjCObjectType(ObjCBuiltinIdTy, {}, {});
   7922     T = getObjCObjectPointerType(T);
   7923     ObjCIdDecl = buildImplicitTypedef(T, "id");
   7924   }
   7925   return ObjCIdDecl;
   7926 }
   7927 
   7928 TypedefDecl *ASTContext::getObjCSelDecl() const {
   7929   if (!ObjCSelDecl) {
   7930     QualType T = getPointerType(ObjCBuiltinSelTy);
   7931     ObjCSelDecl = buildImplicitTypedef(T, "SEL");
   7932   }
   7933   return ObjCSelDecl;
   7934 }
   7935 
   7936 TypedefDecl *ASTContext::getObjCClassDecl() const {
   7937   if (!ObjCClassDecl) {
   7938     QualType T = getObjCObjectType(ObjCBuiltinClassTy, {}, {});
   7939     T = getObjCObjectPointerType(T);
   7940     ObjCClassDecl = buildImplicitTypedef(T, "Class");
   7941   }
   7942   return ObjCClassDecl;
   7943 }
   7944 
   7945 ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
   7946   if (!ObjCProtocolClassDecl) {
   7947     ObjCProtocolClassDecl
   7948       = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
   7949                                   SourceLocation(),
   7950                                   &Idents.get("Protocol"),
   7951                                   /*typeParamList=*/nullptr,
   7952                                   /*PrevDecl=*/nullptr,
   7953                                   SourceLocation(), true);
   7954   }
   7955 
   7956   return ObjCProtocolClassDecl;
   7957 }
   7958 
   7959 //===----------------------------------------------------------------------===//
   7960 // __builtin_va_list Construction Functions
   7961 //===----------------------------------------------------------------------===//
   7962 
   7963 static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
   7964                                                  StringRef Name) {
   7965   // typedef char* __builtin[_ms]_va_list;
   7966   QualType T = Context->getPointerType(Context->CharTy);
   7967   return Context->buildImplicitTypedef(T, Name);
   7968 }
   7969 
   7970 static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
   7971   return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
   7972 }
   7973 
   7974 static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
   7975   return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
   7976 }
   7977 
   7978 static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
   7979   // typedef void* __builtin_va_list;
   7980   QualType T = Context->getPointerType(Context->VoidTy);
   7981   return Context->buildImplicitTypedef(T, "__builtin_va_list");
   7982 }
   7983 
   7984 static TypedefDecl *
   7985 CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
   7986   // struct __va_list
   7987   RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
   7988   if (Context->getLangOpts().CPlusPlus) {
   7989     // namespace std { struct __va_list {
   7990     NamespaceDecl *NS;
   7991     NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
   7992                                Context->getTranslationUnitDecl(),
   7993                                /*Inline*/ false, SourceLocation(),
   7994                                SourceLocation(), &Context->Idents.get("std"),
   7995                                /*PrevDecl*/ nullptr);
   7996     NS->setImplicit();
   7997     VaListTagDecl->setDeclContext(NS);
   7998   }
   7999 
   8000   VaListTagDecl->startDefinition();
   8001 
   8002   const size_t NumFields = 5;
   8003   QualType FieldTypes[NumFields];
   8004   const char *FieldNames[NumFields];
   8005 
   8006   // void *__stack;
   8007   FieldTypes[0] = Context->getPointerType(Context->VoidTy);
   8008   FieldNames[0] = "__stack";
   8009 
   8010   // void *__gr_top;
   8011   FieldTypes[1] = Context->getPointerType(Context->VoidTy);
   8012   FieldNames[1] = "__gr_top";
   8013 
   8014   // void *__vr_top;
   8015   FieldTypes[2] = Context->getPointerType(Context->VoidTy);
   8016   FieldNames[2] = "__vr_top";
   8017 
   8018   // int __gr_offs;
   8019   FieldTypes[3] = Context->IntTy;
   8020   FieldNames[3] = "__gr_offs";
   8021 
   8022   // int __vr_offs;
   8023   FieldTypes[4] = Context->IntTy;
   8024   FieldNames[4] = "__vr_offs";
   8025 
   8026   // Create fields
   8027   for (unsigned i = 0; i < NumFields; ++i) {
   8028     FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
   8029                                          VaListTagDecl,
   8030                                          SourceLocation(),
   8031                                          SourceLocation(),
   8032                                          &Context->Idents.get(FieldNames[i]),
   8033                                          FieldTypes[i], /*TInfo=*/nullptr,
   8034                                          /*BitWidth=*/nullptr,
   8035                                          /*Mutable=*/false,
   8036                                          ICIS_NoInit);
   8037     Field->setAccess(AS_public);
   8038     VaListTagDecl->addDecl(Field);
   8039   }
   8040   VaListTagDecl->completeDefinition();
   8041   Context->VaListTagDecl = VaListTagDecl;
   8042   QualType VaListTagType = Context->getRecordType(VaListTagDecl);
   8043 
   8044   // } __builtin_va_list;
   8045   return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
   8046 }
   8047 
   8048 static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
   8049   // typedef struct __va_list_tag {
   8050   RecordDecl *VaListTagDecl;
   8051 
   8052   VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
   8053   VaListTagDecl->startDefinition();
   8054 
   8055   const size_t NumFields = 5;
   8056   QualType FieldTypes[NumFields];
   8057   const char *FieldNames[NumFields];
   8058 
   8059   //   unsigned char gpr;
   8060   FieldTypes[0] = Context->UnsignedCharTy;
   8061   FieldNames[0] = "gpr";
   8062 
   8063   //   unsigned char fpr;
   8064   FieldTypes[1] = Context->UnsignedCharTy;
   8065   FieldNames[1] = "fpr";
   8066 
   8067   //   unsigned short reserved;
   8068   FieldTypes[2] = Context->UnsignedShortTy;
   8069   FieldNames[2] = "reserved";
   8070 
   8071   //   void* overflow_arg_area;
   8072   FieldTypes[3] = Context->getPointerType(Context->VoidTy);
   8073   FieldNames[3] = "overflow_arg_area";
   8074 
   8075   //   void* reg_save_area;
   8076   FieldTypes[4] = Context->getPointerType(Context->VoidTy);
   8077   FieldNames[4] = "reg_save_area";
   8078 
   8079   // Create fields
   8080   for (unsigned i = 0; i < NumFields; ++i) {
   8081     FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
   8082                                          SourceLocation(),
   8083                                          SourceLocation(),
   8084                                          &Context->Idents.get(FieldNames[i]),
   8085                                          FieldTypes[i], /*TInfo=*/nullptr,
   8086                                          /*BitWidth=*/nullptr,
   8087                                          /*Mutable=*/false,
   8088                                          ICIS_NoInit);
   8089     Field->setAccess(AS_public);
   8090     VaListTagDecl->addDecl(Field);
   8091   }
   8092   VaListTagDecl->completeDefinition();
   8093   Context->VaListTagDecl = VaListTagDecl;
   8094   QualType VaListTagType = Context->getRecordType(VaListTagDecl);
   8095 
   8096   // } __va_list_tag;
   8097   TypedefDecl *VaListTagTypedefDecl =
   8098       Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
   8099 
   8100   QualType VaListTagTypedefType =
   8101     Context->getTypedefType(VaListTagTypedefDecl);
   8102 
   8103   // typedef __va_list_tag __builtin_va_list[1];
   8104   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
   8105   QualType VaListTagArrayType
   8106     = Context->getConstantArrayType(VaListTagTypedefType,
   8107                                     Size, nullptr, ArrayType::Normal, 0);
   8108   return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
   8109 }
   8110 
   8111 static TypedefDecl *
   8112 CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
   8113   // struct __va_list_tag {
   8114   RecordDecl *VaListTagDecl;
   8115   VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
   8116   VaListTagDecl->startDefinition();
   8117 
   8118   const size_t NumFields = 4;
   8119   QualType FieldTypes[NumFields];
   8120   const char *FieldNames[NumFields];
   8121 
   8122   //   unsigned gp_offset;
   8123   FieldTypes[0] = Context->UnsignedIntTy;
   8124   FieldNames[0] = "gp_offset";
   8125 
   8126   //   unsigned fp_offset;
   8127   FieldTypes[1] = Context->UnsignedIntTy;
   8128   FieldNames[1] = "fp_offset";
   8129 
   8130   //   void* overflow_arg_area;
   8131   FieldTypes[2] = Context->getPointerType(Context->VoidTy);
   8132   FieldNames[2] = "overflow_arg_area";
   8133 
   8134   //   void* reg_save_area;
   8135   FieldTypes[3] = Context->getPointerType(Context->VoidTy);
   8136   FieldNames[3] = "reg_save_area";
   8137 
   8138   // Create fields
   8139   for (unsigned i = 0; i < NumFields; ++i) {
   8140     FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
   8141                                          VaListTagDecl,
   8142                                          SourceLocation(),
   8143                                          SourceLocation(),
   8144                                          &Context->Idents.get(FieldNames[i]),
   8145                                          FieldTypes[i], /*TInfo=*/nullptr,
   8146                                          /*BitWidth=*/nullptr,
   8147                                          /*Mutable=*/false,
   8148                                          ICIS_NoInit);
   8149     Field->setAccess(AS_public);
   8150     VaListTagDecl->addDecl(Field);
   8151   }
   8152   VaListTagDecl->completeDefinition();
   8153   Context->VaListTagDecl = VaListTagDecl;
   8154   QualType VaListTagType = Context->getRecordType(VaListTagDecl);
   8155 
   8156   // };
   8157 
   8158   // typedef struct __va_list_tag __builtin_va_list[1];
   8159   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
   8160   QualType VaListTagArrayType = Context->getConstantArrayType(
   8161       VaListTagType, Size, nullptr, ArrayType::Normal, 0);
   8162   return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
   8163 }
   8164 
   8165 static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
   8166   // typedef int __builtin_va_list[4];
   8167   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
   8168   QualType IntArrayType = Context->getConstantArrayType(
   8169       Context->IntTy, Size, nullptr, ArrayType::Normal, 0);
   8170   return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
   8171 }
   8172 
   8173 static TypedefDecl *
   8174 CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
   8175   // struct __va_list
   8176   RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
   8177   if (Context->getLangOpts().CPlusPlus) {
   8178     // namespace std { struct __va_list {
   8179     NamespaceDecl *NS;
   8180     NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
   8181                                Context->getTranslationUnitDecl(),
   8182                                /*Inline*/false, SourceLocation(),
   8183                                SourceLocation(), &Context->Idents.get("std"),
   8184                                /*PrevDecl*/ nullptr);
   8185     NS->setImplicit();
   8186     VaListDecl->setDeclContext(NS);
   8187   }
   8188 
   8189   VaListDecl->startDefinition();
   8190 
   8191   // void * __ap;
   8192   FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
   8193                                        VaListDecl,
   8194                                        SourceLocation(),
   8195                                        SourceLocation(),
   8196                                        &Context->Idents.get("__ap"),
   8197                                        Context->getPointerType(Context->VoidTy),
   8198                                        /*TInfo=*/nullptr,
   8199                                        /*BitWidth=*/nullptr,
   8200                                        /*Mutable=*/false,
   8201                                        ICIS_NoInit);
   8202   Field->setAccess(AS_public);
   8203   VaListDecl->addDecl(Field);
   8204 
   8205   // };
   8206   VaListDecl->completeDefinition();
   8207   Context->VaListTagDecl = VaListDecl;
   8208 
   8209   // typedef struct __va_list __builtin_va_list;
   8210   QualType T = Context->getRecordType(VaListDecl);
   8211   return Context->buildImplicitTypedef(T, "__builtin_va_list");
   8212 }
   8213 
   8214 static TypedefDecl *
   8215 CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
   8216   // struct __va_list_tag {
   8217   RecordDecl *VaListTagDecl;
   8218   VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
   8219   VaListTagDecl->startDefinition();
   8220 
   8221   const size_t NumFields = 4;
   8222   QualType FieldTypes[NumFields];
   8223   const char *FieldNames[NumFields];
   8224 
   8225   //   long __gpr;
   8226   FieldTypes[0] = Context->LongTy;
   8227   FieldNames[0] = "__gpr";
   8228 
   8229   //   long __fpr;
   8230   FieldTypes[1] = Context->LongTy;
   8231   FieldNames[1] = "__fpr";
   8232 
   8233   //   void *__overflow_arg_area;
   8234   FieldTypes[2] = Context->getPointerType(Context->VoidTy);
   8235   FieldNames[2] = "__overflow_arg_area";
   8236 
   8237   //   void *__reg_save_area;
   8238   FieldTypes[3] = Context->getPointerType(Context->VoidTy);
   8239   FieldNames[3] = "__reg_save_area";
   8240 
   8241   // Create fields
   8242   for (unsigned i = 0; i < NumFields; ++i) {
   8243     FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
   8244                                          VaListTagDecl,
   8245                                          SourceLocation(),
   8246                                          SourceLocation(),
   8247                                          &Context->Idents.get(FieldNames[i]),
   8248                                          FieldTypes[i], /*TInfo=*/nullptr,
   8249                                          /*BitWidth=*/nullptr,
   8250                                          /*Mutable=*/false,
   8251                                          ICIS_NoInit);
   8252     Field->setAccess(AS_public);
   8253     VaListTagDecl->addDecl(Field);
   8254   }
   8255   VaListTagDecl->completeDefinition();
   8256   Context->VaListTagDecl = VaListTagDecl;
   8257   QualType VaListTagType = Context->getRecordType(VaListTagDecl);
   8258 
   8259   // };
   8260 
   8261   // typedef __va_list_tag __builtin_va_list[1];
   8262   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
   8263   QualType VaListTagArrayType = Context->getConstantArrayType(
   8264       VaListTagType, Size, nullptr, ArrayType::Normal, 0);
   8265 
   8266   return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
   8267 }
   8268 
   8269 static TypedefDecl *CreateHexagonBuiltinVaListDecl(const ASTContext *Context) {
   8270   // typedef struct __va_list_tag {
   8271   RecordDecl *VaListTagDecl;
   8272   VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
   8273   VaListTagDecl->startDefinition();
   8274 
   8275   const size_t NumFields = 3;
   8276   QualType FieldTypes[NumFields];
   8277   const char *FieldNames[NumFields];
   8278 
   8279   //   void *CurrentSavedRegisterArea;
   8280   FieldTypes[0] = Context->getPointerType(Context->VoidTy);
   8281   FieldNames[0] = "__current_saved_reg_area_pointer";
   8282 
   8283   //   void *SavedRegAreaEnd;
   8284   FieldTypes[1] = Context->getPointerType(Context->VoidTy);
   8285   FieldNames[1] = "__saved_reg_area_end_pointer";
   8286 
   8287   //   void *OverflowArea;
   8288   FieldTypes[2] = Context->getPointerType(Context->VoidTy);
   8289   FieldNames[2] = "__overflow_area_pointer";
   8290 
   8291   // Create fields
   8292   for (unsigned i = 0; i < NumFields; ++i) {
   8293     FieldDecl *Field = FieldDecl::Create(
   8294         const_cast<ASTContext &>(*Context), VaListTagDecl, SourceLocation(),
   8295         SourceLocation(), &Context->Idents.get(FieldNames[i]), FieldTypes[i],
   8296         /*TInfo=*/0,
   8297         /*BitWidth=*/0,
   8298         /*Mutable=*/false, ICIS_NoInit);
   8299     Field->setAccess(AS_public);
   8300     VaListTagDecl->addDecl(Field);
   8301   }
   8302   VaListTagDecl->completeDefinition();
   8303   Context->VaListTagDecl = VaListTagDecl;
   8304   QualType VaListTagType = Context->getRecordType(VaListTagDecl);
   8305 
   8306   // } __va_list_tag;
   8307   TypedefDecl *VaListTagTypedefDecl =
   8308       Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
   8309 
   8310   QualType VaListTagTypedefType = Context->getTypedefType(VaListTagTypedefDecl);
   8311 
   8312   // typedef __va_list_tag __builtin_va_list[1];
   8313   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
   8314   QualType VaListTagArrayType = Context->getConstantArrayType(
   8315       VaListTagTypedefType, Size, nullptr, ArrayType::Normal, 0);
   8316 
   8317   return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
   8318 }
   8319 
   8320 static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
   8321                                      TargetInfo::BuiltinVaListKind Kind) {
   8322   switch (Kind) {
   8323   case TargetInfo::CharPtrBuiltinVaList:
   8324     return CreateCharPtrBuiltinVaListDecl(Context);
   8325   case TargetInfo::VoidPtrBuiltinVaList:
   8326     return CreateVoidPtrBuiltinVaListDecl(Context);
   8327   case TargetInfo::AArch64ABIBuiltinVaList:
   8328     return CreateAArch64ABIBuiltinVaListDecl(Context);
   8329   case TargetInfo::PowerABIBuiltinVaList:
   8330     return CreatePowerABIBuiltinVaListDecl(Context);
   8331   case TargetInfo::X86_64ABIBuiltinVaList:
   8332     return CreateX86_64ABIBuiltinVaListDecl(Context);
   8333   case TargetInfo::PNaClABIBuiltinVaList:
   8334     return CreatePNaClABIBuiltinVaListDecl(Context);
   8335   case TargetInfo::AAPCSABIBuiltinVaList:
   8336     return CreateAAPCSABIBuiltinVaListDecl(Context);
   8337   case TargetInfo::SystemZBuiltinVaList:
   8338     return CreateSystemZBuiltinVaListDecl(Context);
   8339   case TargetInfo::HexagonBuiltinVaList:
   8340     return CreateHexagonBuiltinVaListDecl(Context);
   8341   }
   8342 
   8343   llvm_unreachable("Unhandled __builtin_va_list type kind");
   8344 }
   8345 
   8346 TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
   8347   if (!BuiltinVaListDecl) {
   8348     BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
   8349     assert(BuiltinVaListDecl->isImplicit());
   8350   }
   8351 
   8352   return BuiltinVaListDecl;
   8353 }
   8354 
   8355 Decl *ASTContext::getVaListTagDecl() const {
   8356   // Force the creation of VaListTagDecl by building the __builtin_va_list
   8357   // declaration.
   8358   if (!VaListTagDecl)
   8359     (void)getBuiltinVaListDecl();
   8360 
   8361   return VaListTagDecl;
   8362 }
   8363 
   8364 TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
   8365   if (!BuiltinMSVaListDecl)
   8366     BuiltinMSVaListDecl = CreateMSVaListDecl(this);
   8367 
   8368   return BuiltinMSVaListDecl;
   8369 }
   8370 
   8371 bool ASTContext::canBuiltinBeRedeclared(const FunctionDecl *FD) const {
   8372   return BuiltinInfo.canBeRedeclared(FD->getBuiltinID());
   8373 }
   8374 
   8375 void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
   8376   assert(ObjCConstantStringType.isNull() &&
   8377          "'NSConstantString' type already set!");
   8378 
   8379   ObjCConstantStringType = getObjCInterfaceType(Decl);
   8380 }
   8381 
   8382 /// Retrieve the template name that corresponds to a non-empty
   8383 /// lookup.
   8384 TemplateName
   8385 ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
   8386                                       UnresolvedSetIterator End) const {
   8387   unsigned size = End - Begin;
   8388   assert(size > 1 && "set is not overloaded!");
   8389 
   8390   void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
   8391                           size * sizeof(FunctionTemplateDecl*));
   8392   auto *OT = new (memory) OverloadedTemplateStorage(size);
   8393 
   8394   NamedDecl **Storage = OT->getStorage();
   8395   for (UnresolvedSetIterator I = Begin; I != End; ++I) {
   8396     NamedDecl *D = *I;
   8397     assert(isa<FunctionTemplateDecl>(D) ||
   8398            isa<UnresolvedUsingValueDecl>(D) ||
   8399            (isa<UsingShadowDecl>(D) &&
   8400             isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
   8401     *Storage++ = D;
   8402   }
   8403 
   8404   return TemplateName(OT);
   8405 }
   8406 
   8407 /// Retrieve a template name representing an unqualified-id that has been
   8408 /// assumed to name a template for ADL purposes.
   8409 TemplateName ASTContext::getAssumedTemplateName(DeclarationName Name) const {
   8410   auto *OT = new (*this) AssumedTemplateStorage(Name);
   8411   return TemplateName(OT);
   8412 }
   8413 
   8414 /// Retrieve the template name that represents a qualified
   8415 /// template name such as \c std::vector.
   8416 TemplateName
   8417 ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
   8418                                      bool TemplateKeyword,
   8419                                      TemplateDecl *Template) const {
   8420   assert(NNS && "Missing nested-name-specifier in qualified template name");
   8421 
   8422   // FIXME: Canonicalization?
   8423   llvm::FoldingSetNodeID ID;
   8424   QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
   8425 
   8426   void *InsertPos = nullptr;
   8427   QualifiedTemplateName *QTN =
   8428     QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
   8429   if (!QTN) {
   8430     QTN = new (*this, alignof(QualifiedTemplateName))
   8431         QualifiedTemplateName(NNS, TemplateKeyword, Template);
   8432     QualifiedTemplateNames.InsertNode(QTN, InsertPos);
   8433   }
   8434 
   8435   return TemplateName(QTN);
   8436 }
   8437 
   8438 /// Retrieve the template name that represents a dependent
   8439 /// template name such as \c MetaFun::template apply.
   8440 TemplateName
   8441 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
   8442                                      const IdentifierInfo *Name) const {
   8443   assert((!NNS || NNS->isDependent()) &&
   8444          "Nested name specifier must be dependent");
   8445 
   8446   llvm::FoldingSetNodeID ID;
   8447   DependentTemplateName::Profile(ID, NNS, Name);
   8448 
   8449   void *InsertPos = nullptr;
   8450   DependentTemplateName *QTN =
   8451     DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
   8452 
   8453   if (QTN)
   8454     return TemplateName(QTN);
   8455 
   8456   NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
   8457   if (CanonNNS == NNS) {
   8458     QTN = new (*this, alignof(DependentTemplateName))
   8459         DependentTemplateName(NNS, Name);
   8460   } else {
   8461     TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
   8462     QTN = new (*this, alignof(DependentTemplateName))
   8463         DependentTemplateName(NNS, Name, Canon);
   8464     DependentTemplateName *CheckQTN =
   8465       DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
   8466     assert(!CheckQTN && "Dependent type name canonicalization broken");
   8467     (void)CheckQTN;
   8468   }
   8469 
   8470   DependentTemplateNames.InsertNode(QTN, InsertPos);
   8471   return TemplateName(QTN);
   8472 }
   8473 
   8474 /// Retrieve the template name that represents a dependent
   8475 /// template name such as \c MetaFun::template operator+.
   8476 TemplateName
   8477 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
   8478                                      OverloadedOperatorKind Operator) const {
   8479   assert((!NNS || NNS->isDependent()) &&
   8480          "Nested name specifier must be dependent");
   8481 
   8482   llvm::FoldingSetNodeID ID;
   8483   DependentTemplateName::Profile(ID, NNS, Operator);
   8484 
   8485   void *InsertPos = nullptr;
   8486   DependentTemplateName *QTN
   8487     = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
   8488 
   8489   if (QTN)
   8490     return TemplateName(QTN);
   8491 
   8492   NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
   8493   if (CanonNNS == NNS) {
   8494     QTN = new (*this, alignof(DependentTemplateName))
   8495         DependentTemplateName(NNS, Operator);
   8496   } else {
   8497     TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
   8498     QTN = new (*this, alignof(DependentTemplateName))
   8499         DependentTemplateName(NNS, Operator, Canon);
   8500 
   8501     DependentTemplateName *CheckQTN
   8502       = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
   8503     assert(!CheckQTN && "Dependent template name canonicalization broken");
   8504     (void)CheckQTN;
   8505   }
   8506 
   8507   DependentTemplateNames.InsertNode(QTN, InsertPos);
   8508   return TemplateName(QTN);
   8509 }
   8510 
   8511 TemplateName
   8512 ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
   8513                                          TemplateName replacement) const {
   8514   llvm::FoldingSetNodeID ID;
   8515   SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
   8516 
   8517   void *insertPos = nullptr;
   8518   SubstTemplateTemplateParmStorage *subst
   8519     = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
   8520 
   8521   if (!subst) {
   8522     subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
   8523     SubstTemplateTemplateParms.InsertNode(subst, insertPos);
   8524   }
   8525 
   8526   return TemplateName(subst);
   8527 }
   8528 
   8529 TemplateName
   8530 ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
   8531                                        const TemplateArgument &ArgPack) const {
   8532   auto &Self = const_cast<ASTContext &>(*this);
   8533   llvm::FoldingSetNodeID ID;
   8534   SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
   8535 
   8536   void *InsertPos = nullptr;
   8537   SubstTemplateTemplateParmPackStorage *Subst
   8538     = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
   8539 
   8540   if (!Subst) {
   8541     Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
   8542                                                            ArgPack.pack_size(),
   8543                                                          ArgPack.pack_begin());
   8544     SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
   8545   }
   8546 
   8547   return TemplateName(Subst);
   8548 }
   8549 
   8550 /// getFromTargetType - Given one of the integer types provided by
   8551 /// TargetInfo, produce the corresponding type. The unsigned @p Type
   8552 /// is actually a value of type @c TargetInfo::IntType.
   8553 CanQualType ASTContext::getFromTargetType(unsigned Type) const {
   8554   switch (Type) {
   8555   case TargetInfo::NoInt: return {};
   8556   case TargetInfo::SignedChar: return SignedCharTy;
   8557   case TargetInfo::UnsignedChar: return UnsignedCharTy;
   8558   case TargetInfo::SignedShort: return ShortTy;
   8559   case TargetInfo::UnsignedShort: return UnsignedShortTy;
   8560   case TargetInfo::SignedInt: return IntTy;
   8561   case TargetInfo::UnsignedInt: return UnsignedIntTy;
   8562   case TargetInfo::SignedLong: return LongTy;
   8563   case TargetInfo::UnsignedLong: return UnsignedLongTy;
   8564   case TargetInfo::SignedLongLong: return LongLongTy;
   8565   case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
   8566   }
   8567 
   8568   llvm_unreachable("Unhandled TargetInfo::IntType value");
   8569 }
   8570 
   8571 //===----------------------------------------------------------------------===//
   8572 //                        Type Predicates.
   8573 //===----------------------------------------------------------------------===//
   8574 
   8575 /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
   8576 /// garbage collection attribute.
   8577 ///
   8578 Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
   8579   if (getLangOpts().getGC() == LangOptions::NonGC)
   8580     return Qualifiers::GCNone;
   8581 
   8582   assert(getLangOpts().ObjC);
   8583   Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
   8584 
   8585   // Default behaviour under objective-C's gc is for ObjC pointers
   8586   // (or pointers to them) be treated as though they were declared
   8587   // as __strong.
   8588   if (GCAttrs == Qualifiers::GCNone) {
   8589     if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
   8590       return Qualifiers::Strong;
   8591     else if (Ty->isPointerType())
   8592       return getObjCGCAttrKind(Ty->castAs<PointerType>()->getPointeeType());
   8593   } else {
   8594     // It's not valid to set GC attributes on anything that isn't a
   8595     // pointer.
   8596 #ifndef NDEBUG
   8597     QualType CT = Ty->getCanonicalTypeInternal();
   8598     while (const auto *AT = dyn_cast<ArrayType>(CT))
   8599       CT = AT->getElementType();
   8600     assert(CT->isAnyPointerType() || CT->isBlockPointerType());
   8601 #endif
   8602   }
   8603   return GCAttrs;
   8604 }
   8605 
   8606 //===----------------------------------------------------------------------===//
   8607 //                        Type Compatibility Testing
   8608 //===----------------------------------------------------------------------===//
   8609 
   8610 /// areCompatVectorTypes - Return true if the two specified vector types are
   8611 /// compatible.
   8612 static bool areCompatVectorTypes(const VectorType *LHS,
   8613                                  const VectorType *RHS) {
   8614   assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
   8615   return LHS->getElementType() == RHS->getElementType() &&
   8616          LHS->getNumElements() == RHS->getNumElements();
   8617 }
   8618 
   8619 /// areCompatMatrixTypes - Return true if the two specified matrix types are
   8620 /// compatible.
   8621 static bool areCompatMatrixTypes(const ConstantMatrixType *LHS,
   8622                                  const ConstantMatrixType *RHS) {
   8623   assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
   8624   return LHS->getElementType() == RHS->getElementType() &&
   8625          LHS->getNumRows() == RHS->getNumRows() &&
   8626          LHS->getNumColumns() == RHS->getNumColumns();
   8627 }
   8628 
   8629 bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
   8630                                           QualType SecondVec) {
   8631   assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
   8632   assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
   8633 
   8634   if (hasSameUnqualifiedType(FirstVec, SecondVec))
   8635     return true;
   8636 
   8637   // Treat Neon vector types and most AltiVec vector types as if they are the
   8638   // equivalent GCC vector types.
   8639   const auto *First = FirstVec->castAs<VectorType>();
   8640   const auto *Second = SecondVec->castAs<VectorType>();
   8641   if (First->getNumElements() == Second->getNumElements() &&
   8642       hasSameType(First->getElementType(), Second->getElementType()) &&
   8643       First->getVectorKind() != VectorType::AltiVecPixel &&
   8644       First->getVectorKind() != VectorType::AltiVecBool &&
   8645       Second->getVectorKind() != VectorType::AltiVecPixel &&
   8646       Second->getVectorKind() != VectorType::AltiVecBool &&
   8647       First->getVectorKind() != VectorType::SveFixedLengthDataVector &&
   8648       First->getVectorKind() != VectorType::SveFixedLengthPredicateVector &&
   8649       Second->getVectorKind() != VectorType::SveFixedLengthDataVector &&
   8650       Second->getVectorKind() != VectorType::SveFixedLengthPredicateVector)
   8651     return true;
   8652 
   8653   return false;
   8654 }
   8655 
   8656 bool ASTContext::areCompatibleSveTypes(QualType FirstType,
   8657                                        QualType SecondType) {
   8658   assert(((FirstType->isSizelessBuiltinType() && SecondType->isVectorType()) ||
   8659           (FirstType->isVectorType() && SecondType->isSizelessBuiltinType())) &&
   8660          "Expected SVE builtin type and vector type!");
   8661 
   8662   auto IsValidCast = [this](QualType FirstType, QualType SecondType) {
   8663     if (const auto *BT = FirstType->getAs<BuiltinType>()) {
   8664       if (const auto *VT = SecondType->getAs<VectorType>()) {
   8665         // Predicates have the same representation as uint8 so we also have to
   8666         // check the kind to make these types incompatible.
   8667         if (VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector)
   8668           return BT->getKind() == BuiltinType::SveBool;
   8669         else if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector)
   8670           return VT->getElementType().getCanonicalType() ==
   8671                  FirstType->getSveEltType(*this);
   8672         else if (VT->getVectorKind() == VectorType::GenericVector)
   8673           return getTypeSize(SecondType) == getLangOpts().ArmSveVectorBits &&
   8674                  hasSameType(VT->getElementType(),
   8675                              getBuiltinVectorTypeInfo(BT).ElementType);
   8676       }
   8677     }
   8678     return false;
   8679   };
   8680 
   8681   return IsValidCast(FirstType, SecondType) ||
   8682          IsValidCast(SecondType, FirstType);
   8683 }
   8684 
   8685 bool ASTContext::areLaxCompatibleSveTypes(QualType FirstType,
   8686                                           QualType SecondType) {
   8687   assert(((FirstType->isSizelessBuiltinType() && SecondType->isVectorType()) ||
   8688           (FirstType->isVectorType() && SecondType->isSizelessBuiltinType())) &&
   8689          "Expected SVE builtin type and vector type!");
   8690 
   8691   auto IsLaxCompatible = [this](QualType FirstType, QualType SecondType) {
   8692     if (!FirstType->getAs<BuiltinType>())
   8693       return false;
   8694 
   8695     const auto *VecTy = SecondType->getAs<VectorType>();
   8696     if (VecTy &&
   8697         (VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector ||
   8698          VecTy->getVectorKind() == VectorType::GenericVector)) {
   8699       const LangOptions::LaxVectorConversionKind LVCKind =
   8700           getLangOpts().getLaxVectorConversions();
   8701 
   8702       // If __ARM_FEATURE_SVE_BITS != N do not allow GNU vector lax conversion.
   8703       // "Whenever __ARM_FEATURE_SVE_BITS==N, GNUT implicitly
   8704       // converts to VLAT and VLAT implicitly converts to GNUT."
   8705       // ACLE Spec Version 00bet6, 3.7.3.2. Behavior common to vectors and
   8706       // predicates.
   8707       if (VecTy->getVectorKind() == VectorType::GenericVector &&
   8708           getTypeSize(SecondType) != getLangOpts().ArmSveVectorBits)
   8709         return false;
   8710 
   8711       // If -flax-vector-conversions=all is specified, the types are
   8712       // certainly compatible.
   8713       if (LVCKind == LangOptions::LaxVectorConversionKind::All)
   8714         return true;
   8715 
   8716       // If -flax-vector-conversions=integer is specified, the types are
   8717       // compatible if the elements are integer types.
   8718       if (LVCKind == LangOptions::LaxVectorConversionKind::Integer)
   8719         return VecTy->getElementType().getCanonicalType()->isIntegerType() &&
   8720                FirstType->getSveEltType(*this)->isIntegerType();
   8721     }
   8722 
   8723     return false;
   8724   };
   8725 
   8726   return IsLaxCompatible(FirstType, SecondType) ||
   8727          IsLaxCompatible(SecondType, FirstType);
   8728 }
   8729 
   8730 bool ASTContext::hasDirectOwnershipQualifier(QualType Ty) const {
   8731   while (true) {
   8732     // __strong id
   8733     if (const AttributedType *Attr = dyn_cast<AttributedType>(Ty)) {
   8734       if (Attr->getAttrKind() == attr::ObjCOwnership)
   8735         return true;
   8736 
   8737       Ty = Attr->getModifiedType();
   8738 
   8739     // X *__strong (...)
   8740     } else if (const ParenType *Paren = dyn_cast<ParenType>(Ty)) {
   8741       Ty = Paren->getInnerType();
   8742 
   8743     // We do not want to look through typedefs, typeof(expr),
   8744     // typeof(type), or any other way that the type is somehow
   8745     // abstracted.
   8746     } else {
   8747       return false;
   8748     }
   8749   }
   8750 }
   8751 
   8752 //===----------------------------------------------------------------------===//
   8753 // ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
   8754 //===----------------------------------------------------------------------===//
   8755 
   8756 /// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
   8757 /// inheritance hierarchy of 'rProto'.
   8758 bool
   8759 ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
   8760                                            ObjCProtocolDecl *rProto) const {
   8761   if (declaresSameEntity(lProto, rProto))
   8762     return true;
   8763   for (auto *PI : rProto->protocols())
   8764     if (ProtocolCompatibleWithProtocol(lProto, PI))
   8765       return true;
   8766   return false;
   8767 }
   8768 
   8769 /// ObjCQualifiedClassTypesAreCompatible - compare  Class<pr,...> and
   8770 /// Class<pr1, ...>.
   8771 bool ASTContext::ObjCQualifiedClassTypesAreCompatible(
   8772     const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs) {
   8773   for (auto *lhsProto : lhs->quals()) {
   8774     bool match = false;
   8775     for (auto *rhsProto : rhs->quals()) {
   8776       if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
   8777         match = true;
   8778         break;
   8779       }
   8780     }
   8781     if (!match)
   8782       return false;
   8783   }
   8784   return true;
   8785 }
   8786 
   8787 /// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
   8788 /// ObjCQualifiedIDType.
   8789 bool ASTContext::ObjCQualifiedIdTypesAreCompatible(
   8790     const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs,
   8791     bool compare) {
   8792   // Allow id<P..> and an 'id' in all cases.
   8793   if (lhs->isObjCIdType() || rhs->isObjCIdType())
   8794     return true;
   8795 
   8796   // Don't allow id<P..> to convert to Class or Class<P..> in either direction.
   8797   if (lhs->isObjCClassType() || lhs->isObjCQualifiedClassType() ||
   8798       rhs->isObjCClassType() || rhs->isObjCQualifiedClassType())
   8799     return false;
   8800 
   8801   if (lhs->isObjCQualifiedIdType()) {
   8802     if (rhs->qual_empty()) {
   8803       // If the RHS is a unqualified interface pointer "NSString*",
   8804       // make sure we check the class hierarchy.
   8805       if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
   8806         for (auto *I : lhs->quals()) {
   8807           // when comparing an id<P> on lhs with a static type on rhs,
   8808           // see if static class implements all of id's protocols, directly or
   8809           // through its super class and categories.
   8810           if (!rhsID->ClassImplementsProtocol(I, true))
   8811             return false;
   8812         }
   8813       }
   8814       // If there are no qualifiers and no interface, we have an 'id'.
   8815       return true;
   8816     }
   8817     // Both the right and left sides have qualifiers.
   8818     for (auto *lhsProto : lhs->quals()) {
   8819       bool match = false;
   8820 
   8821       // when comparing an id<P> on lhs with a static type on rhs,
   8822       // see if static class implements all of id's protocols, directly or
   8823       // through its super class and categories.
   8824       for (auto *rhsProto : rhs->quals()) {
   8825         if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
   8826             (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
   8827           match = true;
   8828           break;
   8829         }
   8830       }
   8831       // If the RHS is a qualified interface pointer "NSString<P>*",
   8832       // make sure we check the class hierarchy.
   8833       if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
   8834         for (auto *I : lhs->quals()) {
   8835           // when comparing an id<P> on lhs with a static type on rhs,
   8836           // see if static class implements all of id's protocols, directly or
   8837           // through its super class and categories.
   8838           if (rhsID->ClassImplementsProtocol(I, true)) {
   8839             match = true;
   8840             break;
   8841           }
   8842         }
   8843       }
   8844       if (!match)
   8845         return false;
   8846     }
   8847 
   8848     return true;
   8849   }
   8850 
   8851   assert(rhs->isObjCQualifiedIdType() && "One of the LHS/RHS should be id<x>");
   8852 
   8853   if (lhs->getInterfaceType()) {
   8854     // If both the right and left sides have qualifiers.
   8855     for (auto *lhsProto : lhs->quals()) {
   8856       bool match = false;
   8857 
   8858       // when comparing an id<P> on rhs with a static type on lhs,
   8859       // see if static class implements all of id's protocols, directly or
   8860       // through its super class and categories.
   8861       // First, lhs protocols in the qualifier list must be found, direct
   8862       // or indirect in rhs's qualifier list or it is a mismatch.
   8863       for (auto *rhsProto : rhs->quals()) {
   8864         if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
   8865             (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
   8866           match = true;
   8867           break;
   8868         }
   8869       }
   8870       if (!match)
   8871         return false;
   8872     }
   8873 
   8874     // Static class's protocols, or its super class or category protocols
   8875     // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
   8876     if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) {
   8877       llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
   8878       CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
   8879       // This is rather dubious but matches gcc's behavior. If lhs has
   8880       // no type qualifier and its class has no static protocol(s)
   8881       // assume that it is mismatch.
   8882       if (LHSInheritedProtocols.empty() && lhs->qual_empty())
   8883         return false;
   8884       for (auto *lhsProto : LHSInheritedProtocols) {
   8885         bool match = false;
   8886         for (auto *rhsProto : rhs->quals()) {
   8887           if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
   8888               (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
   8889             match = true;
   8890             break;
   8891           }
   8892         }
   8893         if (!match)
   8894           return false;
   8895       }
   8896     }
   8897     return true;
   8898   }
   8899   return false;
   8900 }
   8901 
   8902 /// canAssignObjCInterfaces - Return true if the two interface types are
   8903 /// compatible for assignment from RHS to LHS.  This handles validation of any
   8904 /// protocol qualifiers on the LHS or RHS.
   8905 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
   8906                                          const ObjCObjectPointerType *RHSOPT) {
   8907   const ObjCObjectType* LHS = LHSOPT->getObjectType();
   8908   const ObjCObjectType* RHS = RHSOPT->getObjectType();
   8909 
   8910   // If either type represents the built-in 'id' type, return true.
   8911   if (LHS->isObjCUnqualifiedId() || RHS->isObjCUnqualifiedId())
   8912     return true;
   8913 
   8914   // Function object that propagates a successful result or handles
   8915   // __kindof types.
   8916   auto finish = [&](bool succeeded) -> bool {
   8917     if (succeeded)
   8918       return true;
   8919 
   8920     if (!RHS->isKindOfType())
   8921       return false;
   8922 
   8923     // Strip off __kindof and protocol qualifiers, then check whether
   8924     // we can assign the other way.
   8925     return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
   8926                                    LHSOPT->stripObjCKindOfTypeAndQuals(*this));
   8927   };
   8928 
   8929   // Casts from or to id<P> are allowed when the other side has compatible
   8930   // protocols.
   8931   if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
   8932     return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false));
   8933   }
   8934 
   8935   // Verify protocol compatibility for casts from Class<P1> to Class<P2>.
   8936   if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
   8937     return finish(ObjCQualifiedClassTypesAreCompatible(LHSOPT, RHSOPT));
   8938   }
   8939 
   8940   // Casts from Class to Class<Foo>, or vice-versa, are allowed.
   8941   if (LHS->isObjCClass() && RHS->isObjCClass()) {
   8942     return true;
   8943   }
   8944 
   8945   // If we have 2 user-defined types, fall into that path.
   8946   if (LHS->getInterface() && RHS->getInterface()) {
   8947     return finish(canAssignObjCInterfaces(LHS, RHS));
   8948   }
   8949 
   8950   return false;
   8951 }
   8952 
   8953 /// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
   8954 /// for providing type-safety for objective-c pointers used to pass/return
   8955 /// arguments in block literals. When passed as arguments, passing 'A*' where
   8956 /// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
   8957 /// not OK. For the return type, the opposite is not OK.
   8958 bool ASTContext::canAssignObjCInterfacesInBlockPointer(
   8959                                          const ObjCObjectPointerType *LHSOPT,
   8960                                          const ObjCObjectPointerType *RHSOPT,
   8961                                          bool BlockReturnType) {
   8962 
   8963   // Function object that propagates a successful result or handles
   8964   // __kindof types.
   8965   auto finish = [&](bool succeeded) -> bool {
   8966     if (succeeded)
   8967       return true;
   8968 
   8969     const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
   8970     if (!Expected->isKindOfType())
   8971       return false;
   8972 
   8973     // Strip off __kindof and protocol qualifiers, then check whether
   8974     // we can assign the other way.
   8975     return canAssignObjCInterfacesInBlockPointer(
   8976              RHSOPT->stripObjCKindOfTypeAndQuals(*this),
   8977              LHSOPT->stripObjCKindOfTypeAndQuals(*this),
   8978              BlockReturnType);
   8979   };
   8980 
   8981   if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
   8982     return true;
   8983 
   8984   if (LHSOPT->isObjCBuiltinType()) {
   8985     return finish(RHSOPT->isObjCBuiltinType() ||
   8986                   RHSOPT->isObjCQualifiedIdType());
   8987   }
   8988 
   8989   if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) {
   8990     if (getLangOpts().CompatibilityQualifiedIdBlockParamTypeChecking)
   8991       // Use for block parameters previous type checking for compatibility.
   8992       return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false) ||
   8993                     // Or corrected type checking as in non-compat mode.
   8994                     (!BlockReturnType &&
   8995                      ObjCQualifiedIdTypesAreCompatible(RHSOPT, LHSOPT, false)));
   8996     else
   8997       return finish(ObjCQualifiedIdTypesAreCompatible(
   8998           (BlockReturnType ? LHSOPT : RHSOPT),
   8999           (BlockReturnType ? RHSOPT : LHSOPT), false));
   9000   }
   9001 
   9002   const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
   9003   const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
   9004   if (LHS && RHS)  { // We have 2 user-defined types.
   9005     if (LHS != RHS) {
   9006       if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
   9007         return finish(BlockReturnType);
   9008       if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
   9009         return finish(!BlockReturnType);
   9010     }
   9011     else
   9012       return true;
   9013   }
   9014   return false;
   9015 }
   9016 
   9017 /// Comparison routine for Objective-C protocols to be used with
   9018 /// llvm::array_pod_sort.
   9019 static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
   9020                                       ObjCProtocolDecl * const *rhs) {
   9021   return (*lhs)->getName().compare((*rhs)->getName());
   9022 }
   9023 
   9024 /// getIntersectionOfProtocols - This routine finds the intersection of set
   9025 /// of protocols inherited from two distinct objective-c pointer objects with
   9026 /// the given common base.
   9027 /// It is used to build composite qualifier list of the composite type of
   9028 /// the conditional expression involving two objective-c pointer objects.
   9029 static
   9030 void getIntersectionOfProtocols(ASTContext &Context,
   9031                                 const ObjCInterfaceDecl *CommonBase,
   9032                                 const ObjCObjectPointerType *LHSOPT,
   9033                                 const ObjCObjectPointerType *RHSOPT,
   9034       SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
   9035 
   9036   const ObjCObjectType* LHS = LHSOPT->getObjectType();
   9037   const ObjCObjectType* RHS = RHSOPT->getObjectType();
   9038   assert(LHS->getInterface() && "LHS must have an interface base");
   9039   assert(RHS->getInterface() && "RHS must have an interface base");
   9040 
   9041   // Add all of the protocols for the LHS.
   9042   llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
   9043 
   9044   // Start with the protocol qualifiers.
   9045   for (auto proto : LHS->quals()) {
   9046     Context.CollectInheritedProtocols(proto, LHSProtocolSet);
   9047   }
   9048 
   9049   // Also add the protocols associated with the LHS interface.
   9050   Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
   9051 
   9052   // Add all of the protocols for the RHS.
   9053   llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
   9054 
   9055   // Start with the protocol qualifiers.
   9056   for (auto proto : RHS->quals()) {
   9057     Context.CollectInheritedProtocols(proto, RHSProtocolSet);
   9058   }
   9059 
   9060   // Also add the protocols associated with the RHS interface.
   9061   Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
   9062 
   9063   // Compute the intersection of the collected protocol sets.
   9064   for (auto proto : LHSProtocolSet) {
   9065     if (RHSProtocolSet.count(proto))
   9066       IntersectionSet.push_back(proto);
   9067   }
   9068 
   9069   // Compute the set of protocols that is implied by either the common type or
   9070   // the protocols within the intersection.
   9071   llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
   9072   Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
   9073 
   9074   // Remove any implied protocols from the list of inherited protocols.
   9075   if (!ImpliedProtocols.empty()) {
   9076     IntersectionSet.erase(
   9077       std::remove_if(IntersectionSet.begin(),
   9078                      IntersectionSet.end(),
   9079                      [&](ObjCProtocolDecl *proto) -> bool {
   9080                        return ImpliedProtocols.count(proto) > 0;
   9081                      }),
   9082       IntersectionSet.end());
   9083   }
   9084 
   9085   // Sort the remaining protocols by name.
   9086   llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
   9087                        compareObjCProtocolsByName);
   9088 }
   9089 
   9090 /// Determine whether the first type is a subtype of the second.
   9091 static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
   9092                                      QualType rhs) {
   9093   // Common case: two object pointers.
   9094   const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
   9095   const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
   9096   if (lhsOPT && rhsOPT)
   9097     return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
   9098 
   9099   // Two block pointers.
   9100   const auto *lhsBlock = lhs->getAs<BlockPointerType>();
   9101   const auto *rhsBlock = rhs->getAs<BlockPointerType>();
   9102   if (lhsBlock && rhsBlock)
   9103     return ctx.typesAreBlockPointerCompatible(lhs, rhs);
   9104 
   9105   // If either is an unqualified 'id' and the other is a block, it's
   9106   // acceptable.
   9107   if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
   9108       (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
   9109     return true;
   9110 
   9111   return false;
   9112 }
   9113 
   9114 // Check that the given Objective-C type argument lists are equivalent.
   9115 static bool sameObjCTypeArgs(ASTContext &ctx,
   9116                              const ObjCInterfaceDecl *iface,
   9117                              ArrayRef<QualType> lhsArgs,
   9118                              ArrayRef<QualType> rhsArgs,
   9119                              bool stripKindOf) {
   9120   if (lhsArgs.size() != rhsArgs.size())
   9121     return false;
   9122 
   9123   ObjCTypeParamList *typeParams = iface->getTypeParamList();
   9124   for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
   9125     if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
   9126       continue;
   9127 
   9128     switch (typeParams->begin()[i]->getVariance()) {
   9129     case ObjCTypeParamVariance::Invariant:
   9130       if (!stripKindOf ||
   9131           !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
   9132                            rhsArgs[i].stripObjCKindOfType(ctx))) {
   9133         return false;
   9134       }
   9135       break;
   9136 
   9137     case ObjCTypeParamVariance::Covariant:
   9138       if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
   9139         return false;
   9140       break;
   9141 
   9142     case ObjCTypeParamVariance::Contravariant:
   9143       if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
   9144         return false;
   9145       break;
   9146     }
   9147   }
   9148 
   9149   return true;
   9150 }
   9151 
   9152 QualType ASTContext::areCommonBaseCompatible(
   9153            const ObjCObjectPointerType *Lptr,
   9154            const ObjCObjectPointerType *Rptr) {
   9155   const ObjCObjectType *LHS = Lptr->getObjectType();
   9156   const ObjCObjectType *RHS = Rptr->getObjectType();
   9157   const ObjCInterfaceDecl* LDecl = LHS->getInterface();
   9158   const ObjCInterfaceDecl* RDecl = RHS->getInterface();
   9159 
   9160   if (!LDecl || !RDecl)
   9161     return {};
   9162 
   9163   // When either LHS or RHS is a kindof type, we should return a kindof type.
   9164   // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
   9165   // kindof(A).
   9166   bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
   9167 
   9168   // Follow the left-hand side up the class hierarchy until we either hit a
   9169   // root or find the RHS. Record the ancestors in case we don't find it.
   9170   llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
   9171     LHSAncestors;
   9172   while (true) {
   9173     // Record this ancestor. We'll need this if the common type isn't in the
   9174     // path from the LHS to the root.
   9175     LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
   9176 
   9177     if (declaresSameEntity(LHS->getInterface(), RDecl)) {
   9178       // Get the type arguments.
   9179       ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
   9180       bool anyChanges = false;
   9181       if (LHS->isSpecialized() && RHS->isSpecialized()) {
   9182         // Both have type arguments, compare them.
   9183         if (!sameObjCTypeArgs(*this, LHS->getInterface(),
   9184                               LHS->getTypeArgs(), RHS->getTypeArgs(),
   9185                               /*stripKindOf=*/true))
   9186           return {};
   9187       } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
   9188         // If only one has type arguments, the result will not have type
   9189         // arguments.
   9190         LHSTypeArgs = {};
   9191         anyChanges = true;
   9192       }
   9193 
   9194       // Compute the intersection of protocols.
   9195       SmallVector<ObjCProtocolDecl *, 8> Protocols;
   9196       getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
   9197                                  Protocols);
   9198       if (!Protocols.empty())
   9199         anyChanges = true;
   9200 
   9201       // If anything in the LHS will have changed, build a new result type.
   9202       // If we need to return a kindof type but LHS is not a kindof type, we
   9203       // build a new result type.
   9204       if (anyChanges || LHS->isKindOfType() != anyKindOf) {
   9205         QualType Result = getObjCInterfaceType(LHS->getInterface());
   9206         Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
   9207                                    anyKindOf || LHS->isKindOfType());
   9208         return getObjCObjectPointerType(Result);
   9209       }
   9210 
   9211       return getObjCObjectPointerType(QualType(LHS, 0));
   9212     }
   9213 
   9214     // Find the superclass.
   9215     QualType LHSSuperType = LHS->getSuperClassType();
   9216     if (LHSSuperType.isNull())
   9217       break;
   9218 
   9219     LHS = LHSSuperType->castAs<ObjCObjectType>();
   9220   }
   9221 
   9222   // We didn't find anything by following the LHS to its root; now check
   9223   // the RHS against the cached set of ancestors.
   9224   while (true) {
   9225     auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
   9226     if (KnownLHS != LHSAncestors.end()) {
   9227       LHS = KnownLHS->second;
   9228 
   9229       // Get the type arguments.
   9230       ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
   9231       bool anyChanges = false;
   9232       if (LHS->isSpecialized() && RHS->isSpecialized()) {
   9233         // Both have type arguments, compare them.
   9234         if (!sameObjCTypeArgs(*this, LHS->getInterface(),
   9235                               LHS->getTypeArgs(), RHS->getTypeArgs(),
   9236                               /*stripKindOf=*/true))
   9237           return {};
   9238       } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
   9239         // If only one has type arguments, the result will not have type
   9240         // arguments.
   9241         RHSTypeArgs = {};
   9242         anyChanges = true;
   9243       }
   9244 
   9245       // Compute the intersection of protocols.
   9246       SmallVector<ObjCProtocolDecl *, 8> Protocols;
   9247       getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
   9248                                  Protocols);
   9249       if (!Protocols.empty())
   9250         anyChanges = true;
   9251 
   9252       // If we need to return a kindof type but RHS is not a kindof type, we
   9253       // build a new result type.
   9254       if (anyChanges || RHS->isKindOfType() != anyKindOf) {
   9255         QualType Result = getObjCInterfaceType(RHS->getInterface());
   9256         Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
   9257                                    anyKindOf || RHS->isKindOfType());
   9258         return getObjCObjectPointerType(Result);
   9259       }
   9260 
   9261       return getObjCObjectPointerType(QualType(RHS, 0));
   9262     }
   9263 
   9264     // Find the superclass of the RHS.
   9265     QualType RHSSuperType = RHS->getSuperClassType();
   9266     if (RHSSuperType.isNull())
   9267       break;
   9268 
   9269     RHS = RHSSuperType->castAs<ObjCObjectType>();
   9270   }
   9271 
   9272   return {};
   9273 }
   9274 
   9275 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
   9276                                          const ObjCObjectType *RHS) {
   9277   assert(LHS->getInterface() && "LHS is not an interface type");
   9278   assert(RHS->getInterface() && "RHS is not an interface type");
   9279 
   9280   // Verify that the base decls are compatible: the RHS must be a subclass of
   9281   // the LHS.
   9282   ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
   9283   bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
   9284   if (!IsSuperClass)
   9285     return false;
   9286 
   9287   // If the LHS has protocol qualifiers, determine whether all of them are
   9288   // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
   9289   // LHS).
   9290   if (LHS->getNumProtocols() > 0) {
   9291     // OK if conversion of LHS to SuperClass results in narrowing of types
   9292     // ; i.e., SuperClass may implement at least one of the protocols
   9293     // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
   9294     // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
   9295     llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
   9296     CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
   9297     // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
   9298     // qualifiers.
   9299     for (auto *RHSPI : RHS->quals())
   9300       CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
   9301     // If there is no protocols associated with RHS, it is not a match.
   9302     if (SuperClassInheritedProtocols.empty())
   9303       return false;
   9304 
   9305     for (const auto *LHSProto : LHS->quals()) {
   9306       bool SuperImplementsProtocol = false;
   9307       for (auto *SuperClassProto : SuperClassInheritedProtocols)
   9308         if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
   9309           SuperImplementsProtocol = true;
   9310           break;
   9311         }
   9312       if (!SuperImplementsProtocol)
   9313         return false;
   9314     }
   9315   }
   9316 
   9317   // If the LHS is specialized, we may need to check type arguments.
   9318   if (LHS->isSpecialized()) {
   9319     // Follow the superclass chain until we've matched the LHS class in the
   9320     // hierarchy. This substitutes type arguments through.
   9321     const ObjCObjectType *RHSSuper = RHS;
   9322     while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
   9323       RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
   9324 
   9325     // If the RHS is specializd, compare type arguments.
   9326     if (RHSSuper->isSpecialized() &&
   9327         !sameObjCTypeArgs(*this, LHS->getInterface(),
   9328                           LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
   9329                           /*stripKindOf=*/true)) {
   9330       return false;
   9331     }
   9332   }
   9333 
   9334   return true;
   9335 }
   9336 
   9337 bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
   9338   // get the "pointed to" types
   9339   const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
   9340   const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
   9341 
   9342   if (!LHSOPT || !RHSOPT)
   9343     return false;
   9344 
   9345   return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
   9346          canAssignObjCInterfaces(RHSOPT, LHSOPT);
   9347 }
   9348 
   9349 bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
   9350   return canAssignObjCInterfaces(
   9351       getObjCObjectPointerType(To)->castAs<ObjCObjectPointerType>(),
   9352       getObjCObjectPointerType(From)->castAs<ObjCObjectPointerType>());
   9353 }
   9354 
   9355 /// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
   9356 /// both shall have the identically qualified version of a compatible type.
   9357 /// C99 6.2.7p1: Two types have compatible types if their types are the
   9358 /// same. See 6.7.[2,3,5] for additional rules.
   9359 bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
   9360                                     bool CompareUnqualified) {
   9361   if (getLangOpts().CPlusPlus)
   9362     return hasSameType(LHS, RHS);
   9363 
   9364   return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
   9365 }
   9366 
   9367 bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
   9368   return typesAreCompatible(LHS, RHS);
   9369 }
   9370 
   9371 bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
   9372   return !mergeTypes(LHS, RHS, true).isNull();
   9373 }
   9374 
   9375 /// mergeTransparentUnionType - if T is a transparent union type and a member
   9376 /// of T is compatible with SubType, return the merged type, else return
   9377 /// QualType()
   9378 QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
   9379                                                bool OfBlockPointer,
   9380                                                bool Unqualified) {
   9381   if (const RecordType *UT = T->getAsUnionType()) {
   9382     RecordDecl *UD = UT->getDecl();
   9383     if (UD->hasAttr<TransparentUnionAttr>()) {
   9384       for (const auto *I : UD->fields()) {
   9385         QualType ET = I->getType().getUnqualifiedType();
   9386         QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
   9387         if (!MT.isNull())
   9388           return MT;
   9389       }
   9390     }
   9391   }
   9392 
   9393   return {};
   9394 }
   9395 
   9396 /// mergeFunctionParameterTypes - merge two types which appear as function
   9397 /// parameter types
   9398 QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
   9399                                                  bool OfBlockPointer,
   9400                                                  bool Unqualified) {
   9401   // GNU extension: two types are compatible if they appear as a function
   9402   // argument, one of the types is a transparent union type and the other
   9403   // type is compatible with a union member
   9404   QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
   9405                                               Unqualified);
   9406   if (!lmerge.isNull())
   9407     return lmerge;
   9408 
   9409   QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
   9410                                               Unqualified);
   9411   if (!rmerge.isNull())
   9412     return rmerge;
   9413 
   9414   return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
   9415 }
   9416 
   9417 QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
   9418                                         bool OfBlockPointer, bool Unqualified,
   9419                                         bool AllowCXX) {
   9420   const auto *lbase = lhs->castAs<FunctionType>();
   9421   const auto *rbase = rhs->castAs<FunctionType>();
   9422   const auto *lproto = dyn_cast<FunctionProtoType>(lbase);
   9423   const auto *rproto = dyn_cast<FunctionProtoType>(rbase);
   9424   bool allLTypes = true;
   9425   bool allRTypes = true;
   9426 
   9427   // Check return type
   9428   QualType retType;
   9429   if (OfBlockPointer) {
   9430     QualType RHS = rbase->getReturnType();
   9431     QualType LHS = lbase->getReturnType();
   9432     bool UnqualifiedResult = Unqualified;
   9433     if (!UnqualifiedResult)
   9434       UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
   9435     retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
   9436   }
   9437   else
   9438     retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
   9439                          Unqualified);
   9440   if (retType.isNull())
   9441     return {};
   9442 
   9443   if (Unqualified)
   9444     retType = retType.getUnqualifiedType();
   9445 
   9446   CanQualType LRetType = getCanonicalType(lbase->getReturnType());
   9447   CanQualType RRetType = getCanonicalType(rbase->getReturnType());
   9448   if (Unqualified) {
   9449     LRetType = LRetType.getUnqualifiedType();
   9450     RRetType = RRetType.getUnqualifiedType();
   9451   }
   9452 
   9453   if (getCanonicalType(retType) != LRetType)
   9454     allLTypes = false;
   9455   if (getCanonicalType(retType) != RRetType)
   9456     allRTypes = false;
   9457 
   9458   // FIXME: double check this
   9459   // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
   9460   //                           rbase->getRegParmAttr() != 0 &&
   9461   //                           lbase->getRegParmAttr() != rbase->getRegParmAttr()?
   9462   FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
   9463   FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
   9464 
   9465   // Compatible functions must have compatible calling conventions
   9466   if (lbaseInfo.getCC() != rbaseInfo.getCC())
   9467     return {};
   9468 
   9469   // Regparm is part of the calling convention.
   9470   if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
   9471     return {};
   9472   if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
   9473     return {};
   9474 
   9475   if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
   9476     return {};
   9477   if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
   9478     return {};
   9479   if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
   9480     return {};
   9481 
   9482   // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
   9483   bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
   9484 
   9485   if (lbaseInfo.getNoReturn() != NoReturn)
   9486     allLTypes = false;
   9487   if (rbaseInfo.getNoReturn() != NoReturn)
   9488     allRTypes = false;
   9489 
   9490   FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
   9491 
   9492   if (lproto && rproto) { // two C99 style function prototypes
   9493     assert((AllowCXX ||
   9494             (!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec())) &&
   9495            "C++ shouldn't be here");
   9496     // Compatible functions must have the same number of parameters
   9497     if (lproto->getNumParams() != rproto->getNumParams())
   9498       return {};
   9499 
   9500     // Variadic and non-variadic functions aren't compatible
   9501     if (lproto->isVariadic() != rproto->isVariadic())
   9502       return {};
   9503 
   9504     if (lproto->getMethodQuals() != rproto->getMethodQuals())
   9505       return {};
   9506 
   9507     SmallVector<FunctionProtoType::ExtParameterInfo, 4> newParamInfos;
   9508     bool canUseLeft, canUseRight;
   9509     if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight,
   9510                                newParamInfos))
   9511       return {};
   9512 
   9513     if (!canUseLeft)
   9514       allLTypes = false;
   9515     if (!canUseRight)
   9516       allRTypes = false;
   9517 
   9518     // Check parameter type compatibility
   9519     SmallVector<QualType, 10> types;
   9520     for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
   9521       QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
   9522       QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
   9523       QualType paramType = mergeFunctionParameterTypes(
   9524           lParamType, rParamType, OfBlockPointer, Unqualified);
   9525       if (paramType.isNull())
   9526         return {};
   9527 
   9528       if (Unqualified)
   9529         paramType = paramType.getUnqualifiedType();
   9530 
   9531       types.push_back(paramType);
   9532       if (Unqualified) {
   9533         lParamType = lParamType.getUnqualifiedType();
   9534         rParamType = rParamType.getUnqualifiedType();
   9535       }
   9536 
   9537       if (getCanonicalType(paramType) != getCanonicalType(lParamType))
   9538         allLTypes = false;
   9539       if (getCanonicalType(paramType) != getCanonicalType(rParamType))
   9540         allRTypes = false;
   9541     }
   9542 
   9543     if (allLTypes) return lhs;
   9544     if (allRTypes) return rhs;
   9545 
   9546     FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
   9547     EPI.ExtInfo = einfo;
   9548     EPI.ExtParameterInfos =
   9549         newParamInfos.empty() ? nullptr : newParamInfos.data();
   9550     return getFunctionType(retType, types, EPI);
   9551   }
   9552 
   9553   if (lproto) allRTypes = false;
   9554   if (rproto) allLTypes = false;
   9555 
   9556   const FunctionProtoType *proto = lproto ? lproto : rproto;
   9557   if (proto) {
   9558     assert((AllowCXX || !proto->hasExceptionSpec()) && "C++ shouldn't be here");
   9559     if (proto->isVariadic())
   9560       return {};
   9561     // Check that the types are compatible with the types that
   9562     // would result from default argument promotions (C99 6.7.5.3p15).
   9563     // The only types actually affected are promotable integer
   9564     // types and floats, which would be passed as a different
   9565     // type depending on whether the prototype is visible.
   9566     for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
   9567       QualType paramTy = proto->getParamType(i);
   9568 
   9569       // Look at the converted type of enum types, since that is the type used
   9570       // to pass enum values.
   9571       if (const auto *Enum = paramTy->getAs<EnumType>()) {
   9572         paramTy = Enum->getDecl()->getIntegerType();
   9573         if (paramTy.isNull())
   9574           return {};
   9575       }
   9576 
   9577       if (paramTy->isPromotableIntegerType() ||
   9578           getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
   9579         return {};
   9580     }
   9581 
   9582     if (allLTypes) return lhs;
   9583     if (allRTypes) return rhs;
   9584 
   9585     FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
   9586     EPI.ExtInfo = einfo;
   9587     return getFunctionType(retType, proto->getParamTypes(), EPI);
   9588   }
   9589 
   9590   if (allLTypes) return lhs;
   9591   if (allRTypes) return rhs;
   9592   return getFunctionNoProtoType(retType, einfo);
   9593 }
   9594 
   9595 /// Given that we have an enum type and a non-enum type, try to merge them.
   9596 static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
   9597                                      QualType other, bool isBlockReturnType) {
   9598   // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
   9599   // a signed integer type, or an unsigned integer type.
   9600   // Compatibility is based on the underlying type, not the promotion
   9601   // type.
   9602   QualType underlyingType = ET->getDecl()->getIntegerType();
   9603   if (underlyingType.isNull())
   9604     return {};
   9605   if (Context.hasSameType(underlyingType, other))
   9606     return other;
   9607 
   9608   // In block return types, we're more permissive and accept any
   9609   // integral type of the same size.
   9610   if (isBlockReturnType && other->isIntegerType() &&
   9611       Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
   9612     return other;
   9613 
   9614   return {};
   9615 }
   9616 
   9617 QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
   9618                                 bool OfBlockPointer,
   9619                                 bool Unqualified, bool BlockReturnType) {
   9620   // C++ [expr]: If an expression initially has the type "reference to T", the
   9621   // type is adjusted to "T" prior to any further analysis, the expression
   9622   // designates the object or function denoted by the reference, and the
   9623   // expression is an lvalue unless the reference is an rvalue reference and
   9624   // the expression is a function call (possibly inside parentheses).
   9625   if (LHS->getAs<ReferenceType>() || RHS->getAs<ReferenceType>())
   9626     return {};
   9627 
   9628   if (Unqualified) {
   9629     LHS = LHS.getUnqualifiedType();
   9630     RHS = RHS.getUnqualifiedType();
   9631   }
   9632 
   9633   QualType LHSCan = getCanonicalType(LHS),
   9634            RHSCan = getCanonicalType(RHS);
   9635 
   9636   // If two types are identical, they are compatible.
   9637   if (LHSCan == RHSCan)
   9638     return LHS;
   9639 
   9640   // If the qualifiers are different, the types aren't compatible... mostly.
   9641   Qualifiers LQuals = LHSCan.getLocalQualifiers();
   9642   Qualifiers RQuals = RHSCan.getLocalQualifiers();
   9643   if (LQuals != RQuals) {
   9644     // If any of these qualifiers are different, we have a type
   9645     // mismatch.
   9646     if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
   9647         LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
   9648         LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
   9649         LQuals.hasUnaligned() != RQuals.hasUnaligned())
   9650       return {};
   9651 
   9652     // Exactly one GC qualifier difference is allowed: __strong is
   9653     // okay if the other type has no GC qualifier but is an Objective
   9654     // C object pointer (i.e. implicitly strong by default).  We fix
   9655     // this by pretending that the unqualified type was actually
   9656     // qualified __strong.
   9657     Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
   9658     Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
   9659     assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
   9660 
   9661     if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
   9662       return {};
   9663 
   9664     if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
   9665       return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
   9666     }
   9667     if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
   9668       return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
   9669     }
   9670     return {};
   9671   }
   9672 
   9673   // Okay, qualifiers are equal.
   9674 
   9675   Type::TypeClass LHSClass = LHSCan->getTypeClass();
   9676   Type::TypeClass RHSClass = RHSCan->getTypeClass();
   9677 
   9678   // We want to consider the two function types to be the same for these
   9679   // comparisons, just force one to the other.
   9680   if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
   9681   if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
   9682 
   9683   // Same as above for arrays
   9684   if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
   9685     LHSClass = Type::ConstantArray;
   9686   if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
   9687     RHSClass = Type::ConstantArray;
   9688 
   9689   // ObjCInterfaces are just specialized ObjCObjects.
   9690   if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
   9691   if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
   9692 
   9693   // Canonicalize ExtVector -> Vector.
   9694   if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
   9695   if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
   9696 
   9697   // If the canonical type classes don't match.
   9698   if (LHSClass != RHSClass) {
   9699     // Note that we only have special rules for turning block enum
   9700     // returns into block int returns, not vice-versa.
   9701     if (const auto *ETy = LHS->getAs<EnumType>()) {
   9702       return mergeEnumWithInteger(*this, ETy, RHS, false);
   9703     }
   9704     if (const EnumType* ETy = RHS->getAs<EnumType>()) {
   9705       return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
   9706     }
   9707     // allow block pointer type to match an 'id' type.
   9708     if (OfBlockPointer && !BlockReturnType) {
   9709        if (LHS->isObjCIdType() && RHS->isBlockPointerType())
   9710          return LHS;
   9711       if (RHS->isObjCIdType() && LHS->isBlockPointerType())
   9712         return RHS;
   9713     }
   9714 
   9715     return {};
   9716   }
   9717 
   9718   // The canonical type classes match.
   9719   switch (LHSClass) {
   9720 #define TYPE(Class, Base)
   9721 #define ABSTRACT_TYPE(Class, Base)
   9722 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
   9723 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
   9724 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
   9725 #include "clang/AST/TypeNodes.inc"
   9726     llvm_unreachable("Non-canonical and dependent types shouldn't get here");
   9727 
   9728   case Type::Auto:
   9729   case Type::DeducedTemplateSpecialization:
   9730   case Type::LValueReference:
   9731   case Type::RValueReference:
   9732   case Type::MemberPointer:
   9733     llvm_unreachable("C++ should never be in mergeTypes");
   9734 
   9735   case Type::ObjCInterface:
   9736   case Type::IncompleteArray:
   9737   case Type::VariableArray:
   9738   case Type::FunctionProto:
   9739   case Type::ExtVector:
   9740     llvm_unreachable("Types are eliminated above");
   9741 
   9742   case Type::Pointer:
   9743   {
   9744     // Merge two pointer types, while trying to preserve typedef info
   9745     QualType LHSPointee = LHS->castAs<PointerType>()->getPointeeType();
   9746     QualType RHSPointee = RHS->castAs<PointerType>()->getPointeeType();
   9747     if (Unqualified) {
   9748       LHSPointee = LHSPointee.getUnqualifiedType();
   9749       RHSPointee = RHSPointee.getUnqualifiedType();
   9750     }
   9751     QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
   9752                                      Unqualified);
   9753     if (ResultType.isNull())
   9754       return {};
   9755     if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
   9756       return LHS;
   9757     if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
   9758       return RHS;
   9759     return getPointerType(ResultType);
   9760   }
   9761   case Type::BlockPointer:
   9762   {
   9763     // Merge two block pointer types, while trying to preserve typedef info
   9764     QualType LHSPointee = LHS->castAs<BlockPointerType>()->getPointeeType();
   9765     QualType RHSPointee = RHS->castAs<BlockPointerType>()->getPointeeType();
   9766     if (Unqualified) {
   9767       LHSPointee = LHSPointee.getUnqualifiedType();
   9768       RHSPointee = RHSPointee.getUnqualifiedType();
   9769     }
   9770     if (getLangOpts().OpenCL) {
   9771       Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
   9772       Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
   9773       // Blocks can't be an expression in a ternary operator (OpenCL v2.0
   9774       // 6.12.5) thus the following check is asymmetric.
   9775       if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual))
   9776         return {};
   9777       LHSPteeQual.removeAddressSpace();
   9778       RHSPteeQual.removeAddressSpace();
   9779       LHSPointee =
   9780           QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
   9781       RHSPointee =
   9782           QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
   9783     }
   9784     QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
   9785                                      Unqualified);
   9786     if (ResultType.isNull())
   9787       return {};
   9788     if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
   9789       return LHS;
   9790     if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
   9791       return RHS;
   9792     return getBlockPointerType(ResultType);
   9793   }
   9794   case Type::Atomic:
   9795   {
   9796     // Merge two pointer types, while trying to preserve typedef info
   9797     QualType LHSValue = LHS->castAs<AtomicType>()->getValueType();
   9798     QualType RHSValue = RHS->castAs<AtomicType>()->getValueType();
   9799     if (Unqualified) {
   9800       LHSValue = LHSValue.getUnqualifiedType();
   9801       RHSValue = RHSValue.getUnqualifiedType();
   9802     }
   9803     QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
   9804                                      Unqualified);
   9805     if (ResultType.isNull())
   9806       return {};
   9807     if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
   9808       return LHS;
   9809     if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
   9810       return RHS;
   9811     return getAtomicType(ResultType);
   9812   }
   9813   case Type::ConstantArray:
   9814   {
   9815     const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
   9816     const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
   9817     if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
   9818       return {};
   9819 
   9820     QualType LHSElem = getAsArrayType(LHS)->getElementType();
   9821     QualType RHSElem = getAsArrayType(RHS)->getElementType();
   9822     if (Unqualified) {
   9823       LHSElem = LHSElem.getUnqualifiedType();
   9824       RHSElem = RHSElem.getUnqualifiedType();
   9825     }
   9826 
   9827     QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
   9828     if (ResultType.isNull())
   9829       return {};
   9830 
   9831     const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
   9832     const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
   9833 
   9834     // If either side is a variable array, and both are complete, check whether
   9835     // the current dimension is definite.
   9836     if (LVAT || RVAT) {
   9837       auto SizeFetch = [this](const VariableArrayType* VAT,
   9838           const ConstantArrayType* CAT)
   9839           -> std::pair<bool,llvm::APInt> {
   9840         if (VAT) {
   9841           Optional<llvm::APSInt> TheInt;
   9842           Expr *E = VAT->getSizeExpr();
   9843           if (E && (TheInt = E->getIntegerConstantExpr(*this)))
   9844             return std::make_pair(true, *TheInt);
   9845           return std::make_pair(false, llvm::APSInt());
   9846         }
   9847         if (CAT)
   9848           return std::make_pair(true, CAT->getSize());
   9849         return std::make_pair(false, llvm::APInt());
   9850       };
   9851 
   9852       bool HaveLSize, HaveRSize;
   9853       llvm::APInt LSize, RSize;
   9854       std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT);
   9855       std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT);
   9856       if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize))
   9857         return {}; // Definite, but unequal, array dimension
   9858     }
   9859 
   9860     if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
   9861       return LHS;
   9862     if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
   9863       return RHS;
   9864     if (LCAT)
   9865       return getConstantArrayType(ResultType, LCAT->getSize(),
   9866                                   LCAT->getSizeExpr(),
   9867                                   ArrayType::ArraySizeModifier(), 0);
   9868     if (RCAT)
   9869       return getConstantArrayType(ResultType, RCAT->getSize(),
   9870                                   RCAT->getSizeExpr(),
   9871                                   ArrayType::ArraySizeModifier(), 0);
   9872     if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
   9873       return LHS;
   9874     if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
   9875       return RHS;
   9876     if (LVAT) {
   9877       // FIXME: This isn't correct! But tricky to implement because
   9878       // the array's size has to be the size of LHS, but the type
   9879       // has to be different.
   9880       return LHS;
   9881     }
   9882     if (RVAT) {
   9883       // FIXME: This isn't correct! But tricky to implement because
   9884       // the array's size has to be the size of RHS, but the type
   9885       // has to be different.
   9886       return RHS;
   9887     }
   9888     if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
   9889     if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
   9890     return getIncompleteArrayType(ResultType,
   9891                                   ArrayType::ArraySizeModifier(), 0);
   9892   }
   9893   case Type::FunctionNoProto:
   9894     return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
   9895   case Type::Record:
   9896   case Type::Enum:
   9897     return {};
   9898   case Type::Builtin:
   9899     // Only exactly equal builtin types are compatible, which is tested above.
   9900     return {};
   9901   case Type::Complex:
   9902     // Distinct complex types are incompatible.
   9903     return {};
   9904   case Type::Vector:
   9905     // FIXME: The merged type should be an ExtVector!
   9906     if (areCompatVectorTypes(LHSCan->castAs<VectorType>(),
   9907                              RHSCan->castAs<VectorType>()))
   9908       return LHS;
   9909     return {};
   9910   case Type::ConstantMatrix:
   9911     if (areCompatMatrixTypes(LHSCan->castAs<ConstantMatrixType>(),
   9912                              RHSCan->castAs<ConstantMatrixType>()))
   9913       return LHS;
   9914     return {};
   9915   case Type::ObjCObject: {
   9916     // Check if the types are assignment compatible.
   9917     // FIXME: This should be type compatibility, e.g. whether
   9918     // "LHS x; RHS x;" at global scope is legal.
   9919     if (canAssignObjCInterfaces(LHS->castAs<ObjCObjectType>(),
   9920                                 RHS->castAs<ObjCObjectType>()))
   9921       return LHS;
   9922     return {};
   9923   }
   9924   case Type::ObjCObjectPointer:
   9925     if (OfBlockPointer) {
   9926       if (canAssignObjCInterfacesInBlockPointer(
   9927               LHS->castAs<ObjCObjectPointerType>(),
   9928               RHS->castAs<ObjCObjectPointerType>(), BlockReturnType))
   9929         return LHS;
   9930       return {};
   9931     }
   9932     if (canAssignObjCInterfaces(LHS->castAs<ObjCObjectPointerType>(),
   9933                                 RHS->castAs<ObjCObjectPointerType>()))
   9934       return LHS;
   9935     return {};
   9936   case Type::Pipe:
   9937     assert(LHS != RHS &&
   9938            "Equivalent pipe types should have already been handled!");
   9939     return {};
   9940   case Type::ExtInt: {
   9941     // Merge two ext-int types, while trying to preserve typedef info.
   9942     bool LHSUnsigned  = LHS->castAs<ExtIntType>()->isUnsigned();
   9943     bool RHSUnsigned = RHS->castAs<ExtIntType>()->isUnsigned();
   9944     unsigned LHSBits = LHS->castAs<ExtIntType>()->getNumBits();
   9945     unsigned RHSBits = RHS->castAs<ExtIntType>()->getNumBits();
   9946 
   9947     // Like unsigned/int, shouldn't have a type if they dont match.
   9948     if (LHSUnsigned != RHSUnsigned)
   9949       return {};
   9950 
   9951     if (LHSBits != RHSBits)
   9952       return {};
   9953     return LHS;
   9954   }
   9955   }
   9956 
   9957   llvm_unreachable("Invalid Type::Class!");
   9958 }
   9959 
   9960 bool ASTContext::mergeExtParameterInfo(
   9961     const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
   9962     bool &CanUseFirst, bool &CanUseSecond,
   9963     SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos) {
   9964   assert(NewParamInfos.empty() && "param info list not empty");
   9965   CanUseFirst = CanUseSecond = true;
   9966   bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
   9967   bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
   9968 
   9969   // Fast path: if the first type doesn't have ext parameter infos,
   9970   // we match if and only if the second type also doesn't have them.
   9971   if (!FirstHasInfo && !SecondHasInfo)
   9972     return true;
   9973 
   9974   bool NeedParamInfo = false;
   9975   size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
   9976                           : SecondFnType->getExtParameterInfos().size();
   9977 
   9978   for (size_t I = 0; I < E; ++I) {
   9979     FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
   9980     if (FirstHasInfo)
   9981       FirstParam = FirstFnType->getExtParameterInfo(I);
   9982     if (SecondHasInfo)
   9983       SecondParam = SecondFnType->getExtParameterInfo(I);
   9984 
   9985     // Cannot merge unless everything except the noescape flag matches.
   9986     if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false))
   9987       return false;
   9988 
   9989     bool FirstNoEscape = FirstParam.isNoEscape();
   9990     bool SecondNoEscape = SecondParam.isNoEscape();
   9991     bool IsNoEscape = FirstNoEscape && SecondNoEscape;
   9992     NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape));
   9993     if (NewParamInfos.back().getOpaqueValue())
   9994       NeedParamInfo = true;
   9995     if (FirstNoEscape != IsNoEscape)
   9996       CanUseFirst = false;
   9997     if (SecondNoEscape != IsNoEscape)
   9998       CanUseSecond = false;
   9999   }
   10000 
   10001   if (!NeedParamInfo)
   10002     NewParamInfos.clear();
   10003 
   10004   return true;
   10005 }
   10006 
   10007 void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) {
   10008   ObjCLayouts[CD] = nullptr;
   10009 }
   10010 
   10011 /// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
   10012 /// 'RHS' attributes and returns the merged version; including for function
   10013 /// return types.
   10014 QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
   10015   QualType LHSCan = getCanonicalType(LHS),
   10016   RHSCan = getCanonicalType(RHS);
   10017   // If two types are identical, they are compatible.
   10018   if (LHSCan == RHSCan)
   10019     return LHS;
   10020   if (RHSCan->isFunctionType()) {
   10021     if (!LHSCan->isFunctionType())
   10022       return {};
   10023     QualType OldReturnType =
   10024         cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
   10025     QualType NewReturnType =
   10026         cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
   10027     QualType ResReturnType =
   10028       mergeObjCGCQualifiers(NewReturnType, OldReturnType);
   10029     if (ResReturnType.isNull())
   10030       return {};
   10031     if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
   10032       // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
   10033       // In either case, use OldReturnType to build the new function type.
   10034       const auto *F = LHS->castAs<FunctionType>();
   10035       if (const auto *FPT = cast<FunctionProtoType>(F)) {
   10036         FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
   10037         EPI.ExtInfo = getFunctionExtInfo(LHS);
   10038         QualType ResultType =
   10039             getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
   10040         return ResultType;
   10041       }
   10042     }
   10043     return {};
   10044   }
   10045 
   10046   // If the qualifiers are different, the types can still be merged.
   10047   Qualifiers LQuals = LHSCan.getLocalQualifiers();
   10048   Qualifiers RQuals = RHSCan.getLocalQualifiers();
   10049   if (LQuals != RQuals) {
   10050     // If any of these qualifiers are different, we have a type mismatch.
   10051     if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
   10052         LQuals.getAddressSpace() != RQuals.getAddressSpace())
   10053       return {};
   10054 
   10055     // Exactly one GC qualifier difference is allowed: __strong is
   10056     // okay if the other type has no GC qualifier but is an Objective
   10057     // C object pointer (i.e. implicitly strong by default).  We fix
   10058     // this by pretending that the unqualified type was actually
   10059     // qualified __strong.
   10060     Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
   10061     Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
   10062     assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
   10063 
   10064     if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
   10065       return {};
   10066 
   10067     if (GC_L == Qualifiers::Strong)
   10068       return LHS;
   10069     if (GC_R == Qualifiers::Strong)
   10070       return RHS;
   10071     return {};
   10072   }
   10073 
   10074   if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
   10075     QualType LHSBaseQT = LHS->castAs<ObjCObjectPointerType>()->getPointeeType();
   10076     QualType RHSBaseQT = RHS->castAs<ObjCObjectPointerType>()->getPointeeType();
   10077     QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
   10078     if (ResQT == LHSBaseQT)
   10079       return LHS;
   10080     if (ResQT == RHSBaseQT)
   10081       return RHS;
   10082   }
   10083   return {};
   10084 }
   10085 
   10086 //===----------------------------------------------------------------------===//
   10087 //                         Integer Predicates
   10088 //===----------------------------------------------------------------------===//
   10089 
   10090 unsigned ASTContext::getIntWidth(QualType T) const {
   10091   if (const auto *ET = T->getAs<EnumType>())
   10092     T = ET->getDecl()->getIntegerType();
   10093   if (T->isBooleanType())
   10094     return 1;
   10095   if(const auto *EIT = T->getAs<ExtIntType>())
   10096     return EIT->getNumBits();
   10097   // For builtin types, just use the standard type sizing method
   10098   return (unsigned)getTypeSize(T);
   10099 }
   10100 
   10101 QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
   10102   assert((T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) &&
   10103          "Unexpected type");
   10104 
   10105   // Turn <4 x signed int> -> <4 x unsigned int>
   10106   if (const auto *VTy = T->getAs<VectorType>())
   10107     return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
   10108                          VTy->getNumElements(), VTy->getVectorKind());
   10109 
   10110   // For _ExtInt, return an unsigned _ExtInt with same width.
   10111   if (const auto *EITy = T->getAs<ExtIntType>())
   10112     return getExtIntType(/*IsUnsigned=*/true, EITy->getNumBits());
   10113 
   10114   // For enums, get the underlying integer type of the enum, and let the general
   10115   // integer type signchanging code handle it.
   10116   if (const auto *ETy = T->getAs<EnumType>())
   10117     T = ETy->getDecl()->getIntegerType();
   10118 
   10119   switch (T->castAs<BuiltinType>()->getKind()) {
   10120   case BuiltinType::Char_S:
   10121   case BuiltinType::SChar:
   10122     return UnsignedCharTy;
   10123   case BuiltinType::Short:
   10124     return UnsignedShortTy;
   10125   case BuiltinType::Int:
   10126     return UnsignedIntTy;
   10127   case BuiltinType::Long:
   10128     return UnsignedLongTy;
   10129   case BuiltinType::LongLong:
   10130     return UnsignedLongLongTy;
   10131   case BuiltinType::Int128:
   10132     return UnsignedInt128Ty;
   10133   // wchar_t is special. It is either signed or not, but when it's signed,
   10134   // there's no matching "unsigned wchar_t". Therefore we return the unsigned
   10135   // version of it's underlying type instead.
   10136   case BuiltinType::WChar_S:
   10137     return getUnsignedWCharType();
   10138 
   10139   case BuiltinType::ShortAccum:
   10140     return UnsignedShortAccumTy;
   10141   case BuiltinType::Accum:
   10142     return UnsignedAccumTy;
   10143   case BuiltinType::LongAccum:
   10144     return UnsignedLongAccumTy;
   10145   case BuiltinType::SatShortAccum:
   10146     return SatUnsignedShortAccumTy;
   10147   case BuiltinType::SatAccum:
   10148     return SatUnsignedAccumTy;
   10149   case BuiltinType::SatLongAccum:
   10150     return SatUnsignedLongAccumTy;
   10151   case BuiltinType::ShortFract:
   10152     return UnsignedShortFractTy;
   10153   case BuiltinType::Fract:
   10154     return UnsignedFractTy;
   10155   case BuiltinType::LongFract:
   10156     return UnsignedLongFractTy;
   10157   case BuiltinType::SatShortFract:
   10158     return SatUnsignedShortFractTy;
   10159   case BuiltinType::SatFract:
   10160     return SatUnsignedFractTy;
   10161   case BuiltinType::SatLongFract:
   10162     return SatUnsignedLongFractTy;
   10163   default:
   10164     llvm_unreachable("Unexpected signed integer or fixed point type");
   10165   }
   10166 }
   10167 
   10168 QualType ASTContext::getCorrespondingSignedType(QualType T) const {
   10169   assert((T->hasUnsignedIntegerRepresentation() ||
   10170           T->isUnsignedFixedPointType()) &&
   10171          "Unexpected type");
   10172 
   10173   // Turn <4 x unsigned int> -> <4 x signed int>
   10174   if (const auto *VTy = T->getAs<VectorType>())
   10175     return getVectorType(getCorrespondingSignedType(VTy->getElementType()),
   10176                          VTy->getNumElements(), VTy->getVectorKind());
   10177 
   10178   // For _ExtInt, return a signed _ExtInt with same width.
   10179   if (const auto *EITy = T->getAs<ExtIntType>())
   10180     return getExtIntType(/*IsUnsigned=*/false, EITy->getNumBits());
   10181 
   10182   // For enums, get the underlying integer type of the enum, and let the general
   10183   // integer type signchanging code handle it.
   10184   if (const auto *ETy = T->getAs<EnumType>())
   10185     T = ETy->getDecl()->getIntegerType();
   10186 
   10187   switch (T->castAs<BuiltinType>()->getKind()) {
   10188   case BuiltinType::Char_U:
   10189   case BuiltinType::UChar:
   10190     return SignedCharTy;
   10191   case BuiltinType::UShort:
   10192     return ShortTy;
   10193   case BuiltinType::UInt:
   10194     return IntTy;
   10195   case BuiltinType::ULong:
   10196     return LongTy;
   10197   case BuiltinType::ULongLong:
   10198     return LongLongTy;
   10199   case BuiltinType::UInt128:
   10200     return Int128Ty;
   10201   // wchar_t is special. It is either unsigned or not, but when it's unsigned,
   10202   // there's no matching "signed wchar_t". Therefore we return the signed
   10203   // version of it's underlying type instead.
   10204   case BuiltinType::WChar_U:
   10205     return getSignedWCharType();
   10206 
   10207   case BuiltinType::UShortAccum:
   10208     return ShortAccumTy;
   10209   case BuiltinType::UAccum:
   10210     return AccumTy;
   10211   case BuiltinType::ULongAccum:
   10212     return LongAccumTy;
   10213   case BuiltinType::SatUShortAccum:
   10214     return SatShortAccumTy;
   10215   case BuiltinType::SatUAccum:
   10216     return SatAccumTy;
   10217   case BuiltinType::SatULongAccum:
   10218     return SatLongAccumTy;
   10219   case BuiltinType::UShortFract:
   10220     return ShortFractTy;
   10221   case BuiltinType::UFract:
   10222     return FractTy;
   10223   case BuiltinType::ULongFract:
   10224     return LongFractTy;
   10225   case BuiltinType::SatUShortFract:
   10226     return SatShortFractTy;
   10227   case BuiltinType::SatUFract:
   10228     return SatFractTy;
   10229   case BuiltinType::SatULongFract:
   10230     return SatLongFractTy;
   10231   default:
   10232     llvm_unreachable("Unexpected unsigned integer or fixed point type");
   10233   }
   10234 }
   10235 
   10236 ASTMutationListener::~ASTMutationListener() = default;
   10237 
   10238 void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
   10239                                             QualType ReturnType) {}
   10240 
   10241 //===----------------------------------------------------------------------===//
   10242 //                          Builtin Type Computation
   10243 //===----------------------------------------------------------------------===//
   10244 
   10245 /// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
   10246 /// pointer over the consumed characters.  This returns the resultant type.  If
   10247 /// AllowTypeModifiers is false then modifier like * are not parsed, just basic
   10248 /// types.  This allows "v2i*" to be parsed as a pointer to a v2i instead of
   10249 /// a vector of "i*".
   10250 ///
   10251 /// RequiresICE is filled in on return to indicate whether the value is required
   10252 /// to be an Integer Constant Expression.
   10253 static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
   10254                                   ASTContext::GetBuiltinTypeError &Error,
   10255                                   bool &RequiresICE,
   10256                                   bool AllowTypeModifiers) {
   10257   // Modifiers.
   10258   int HowLong = 0;
   10259   bool Signed = false, Unsigned = false;
   10260   RequiresICE = false;
   10261 
   10262   // Read the prefixed modifiers first.
   10263   bool Done = false;
   10264   #ifndef NDEBUG
   10265   bool IsSpecial = false;
   10266   #endif
   10267   while (!Done) {
   10268     switch (*Str++) {
   10269     default: Done = true; --Str; break;
   10270     case 'I':
   10271       RequiresICE = true;
   10272       break;
   10273     case 'S':
   10274       assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
   10275       assert(!Signed && "Can't use 'S' modifier multiple times!");
   10276       Signed = true;
   10277       break;
   10278     case 'U':
   10279       assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
   10280       assert(!Unsigned && "Can't use 'U' modifier multiple times!");
   10281       Unsigned = true;
   10282       break;
   10283     case 'L':
   10284       assert(!IsSpecial && "Can't use 'L' with 'W', 'N', 'Z' or 'O' modifiers");
   10285       assert(HowLong <= 2 && "Can't have LLLL modifier");
   10286       ++HowLong;
   10287       break;
   10288     case 'N':
   10289       // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
   10290       assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
   10291       assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
   10292       #ifndef NDEBUG
   10293       IsSpecial = true;
   10294       #endif
   10295       if (Context.getTargetInfo().getLongWidth() == 32)
   10296         ++HowLong;
   10297       break;
   10298     case 'W':
   10299       // This modifier represents int64 type.
   10300       assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
   10301       assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
   10302       #ifndef NDEBUG
   10303       IsSpecial = true;
   10304       #endif
   10305       switch (Context.getTargetInfo().getInt64Type()) {
   10306       default:
   10307         llvm_unreachable("Unexpected integer type");
   10308       case TargetInfo::SignedLong:
   10309         HowLong = 1;
   10310         break;
   10311       case TargetInfo::SignedLongLong:
   10312         HowLong = 2;
   10313         break;
   10314       }
   10315       break;
   10316     case 'Z':
   10317       // This modifier represents int32 type.
   10318       assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
   10319       assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!");
   10320       #ifndef NDEBUG
   10321       IsSpecial = true;
   10322       #endif
   10323       switch (Context.getTargetInfo().getIntTypeByWidth(32, true)) {
   10324       default:
   10325         llvm_unreachable("Unexpected integer type");
   10326       case TargetInfo::SignedInt:
   10327         HowLong = 0;
   10328         break;
   10329       case TargetInfo::SignedLong:
   10330         HowLong = 1;
   10331         break;
   10332       case TargetInfo::SignedLongLong:
   10333         HowLong = 2;
   10334         break;
   10335       }
   10336       break;
   10337     case 'O':
   10338       assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
   10339       assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!");
   10340       #ifndef NDEBUG
   10341       IsSpecial = true;
   10342       #endif
   10343       if (Context.getLangOpts().OpenCL)
   10344         HowLong = 1;
   10345       else
   10346         HowLong = 2;
   10347       break;
   10348     }
   10349   }
   10350 
   10351   QualType Type;
   10352 
   10353   // Read the base type.
   10354   switch (*Str++) {
   10355   default: llvm_unreachable("Unknown builtin type letter!");
   10356   case 'y':
   10357     assert(HowLong == 0 && !Signed && !Unsigned &&
   10358            "Bad modifiers used with 'y'!");
   10359     Type = Context.BFloat16Ty;
   10360     break;
   10361   case 'v':
   10362     assert(HowLong == 0 && !Signed && !Unsigned &&
   10363            "Bad modifiers used with 'v'!");
   10364     Type = Context.VoidTy;
   10365     break;
   10366   case 'h':
   10367     assert(HowLong == 0 && !Signed && !Unsigned &&
   10368            "Bad modifiers used with 'h'!");
   10369     Type = Context.HalfTy;
   10370     break;
   10371   case 'f':
   10372     assert(HowLong == 0 && !Signed && !Unsigned &&
   10373            "Bad modifiers used with 'f'!");
   10374     Type = Context.FloatTy;
   10375     break;
   10376   case 'd':
   10377     assert(HowLong < 3 && !Signed && !Unsigned &&
   10378            "Bad modifiers used with 'd'!");
   10379     if (HowLong == 1)
   10380       Type = Context.LongDoubleTy;
   10381     else if (HowLong == 2)
   10382       Type = Context.Float128Ty;
   10383     else
   10384       Type = Context.DoubleTy;
   10385     break;
   10386   case 's':
   10387     assert(HowLong == 0 && "Bad modifiers used with 's'!");
   10388     if (Unsigned)
   10389       Type = Context.UnsignedShortTy;
   10390     else
   10391       Type = Context.ShortTy;
   10392     break;
   10393   case 'i':
   10394     if (HowLong == 3)
   10395       Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
   10396     else if (HowLong == 2)
   10397       Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
   10398     else if (HowLong == 1)
   10399       Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
   10400     else
   10401       Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
   10402     break;
   10403   case 'c':
   10404     assert(HowLong == 0 && "Bad modifiers used with 'c'!");
   10405     if (Signed)
   10406       Type = Context.SignedCharTy;
   10407     else if (Unsigned)
   10408       Type = Context.UnsignedCharTy;
   10409     else
   10410       Type = Context.CharTy;
   10411     break;
   10412   case 'b': // boolean
   10413     assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
   10414     Type = Context.BoolTy;
   10415     break;
   10416   case 'z':  // size_t.
   10417     assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
   10418     Type = Context.getSizeType();
   10419     break;
   10420   case 'w':  // wchar_t.
   10421     assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
   10422     Type = Context.getWideCharType();
   10423     break;
   10424   case 'F':
   10425     Type = Context.getCFConstantStringType();
   10426     break;
   10427   case 'G':
   10428     Type = Context.getObjCIdType();
   10429     break;
   10430   case 'H':
   10431     Type = Context.getObjCSelType();
   10432     break;
   10433   case 'M':
   10434     Type = Context.getObjCSuperType();
   10435     break;
   10436   case 'a':
   10437     Type = Context.getBuiltinVaListType();
   10438     assert(!Type.isNull() && "builtin va list type not initialized!");
   10439     break;
   10440   case 'A':
   10441     // This is a "reference" to a va_list; however, what exactly
   10442     // this means depends on how va_list is defined. There are two
   10443     // different kinds of va_list: ones passed by value, and ones
   10444     // passed by reference.  An example of a by-value va_list is
   10445     // x86, where va_list is a char*. An example of by-ref va_list
   10446     // is x86-64, where va_list is a __va_list_tag[1]. For x86,
   10447     // we want this argument to be a char*&; for x86-64, we want
   10448     // it to be a __va_list_tag*.
   10449     Type = Context.getBuiltinVaListType();
   10450     assert(!Type.isNull() && "builtin va list type not initialized!");
   10451     if (Type->isArrayType())
   10452       Type = Context.getArrayDecayedType(Type);
   10453     else
   10454       Type = Context.getLValueReferenceType(Type);
   10455     break;
   10456   case 'q': {
   10457     char *End;
   10458     unsigned NumElements = strtoul(Str, &End, 10);
   10459     assert(End != Str && "Missing vector size");
   10460     Str = End;
   10461 
   10462     QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
   10463                                              RequiresICE, false);
   10464     assert(!RequiresICE && "Can't require vector ICE");
   10465 
   10466     Type = Context.getScalableVectorType(ElementType, NumElements);
   10467     break;
   10468   }
   10469   case 'V': {
   10470     char *End;
   10471     unsigned NumElements = strtoul(Str, &End, 10);
   10472     assert(End != Str && "Missing vector size");
   10473     Str = End;
   10474 
   10475     QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
   10476                                              RequiresICE, false);
   10477     assert(!RequiresICE && "Can't require vector ICE");
   10478 
   10479     // TODO: No way to make AltiVec vectors in builtins yet.
   10480     Type = Context.getVectorType(ElementType, NumElements,
   10481                                  VectorType::GenericVector);
   10482     break;
   10483   }
   10484   case 'E': {
   10485     char *End;
   10486 
   10487     unsigned NumElements = strtoul(Str, &End, 10);
   10488     assert(End != Str && "Missing vector size");
   10489 
   10490     Str = End;
   10491 
   10492     QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
   10493                                              false);
   10494     Type = Context.getExtVectorType(ElementType, NumElements);
   10495     break;
   10496   }
   10497   case 'X': {
   10498     QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
   10499                                              false);
   10500     assert(!RequiresICE && "Can't require complex ICE");
   10501     Type = Context.getComplexType(ElementType);
   10502     break;
   10503   }
   10504   case 'Y':
   10505     Type = Context.getPointerDiffType();
   10506     break;
   10507   case 'P':
   10508     Type = Context.getFILEType();
   10509     if (Type.isNull()) {
   10510       Error = ASTContext::GE_Missing_stdio;
   10511       return {};
   10512     }
   10513     break;
   10514   case 'J':
   10515     if (Signed)
   10516       Type = Context.getsigjmp_bufType();
   10517     else
   10518       Type = Context.getjmp_bufType();
   10519 
   10520     if (Type.isNull()) {
   10521       Error = ASTContext::GE_Missing_setjmp;
   10522       return {};
   10523     }
   10524     break;
   10525   case 'K':
   10526     assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
   10527     Type = Context.getucontext_tType();
   10528 
   10529     if (Type.isNull()) {
   10530       Error = ASTContext::GE_Missing_ucontext;
   10531       return {};
   10532     }
   10533     break;
   10534   case 'p':
   10535     Type = Context.getProcessIDType();
   10536     break;
   10537   }
   10538 
   10539   // If there are modifiers and if we're allowed to parse them, go for it.
   10540   Done = !AllowTypeModifiers;
   10541   while (!Done) {
   10542     switch (char c = *Str++) {
   10543     default: Done = true; --Str; break;
   10544     case '*':
   10545     case '&': {
   10546       // Both pointers and references can have their pointee types
   10547       // qualified with an address space.
   10548       char *End;
   10549       unsigned AddrSpace = strtoul(Str, &End, 10);
   10550       if (End != Str) {
   10551         // Note AddrSpace == 0 is not the same as an unspecified address space.
   10552         Type = Context.getAddrSpaceQualType(
   10553           Type,
   10554           Context.getLangASForBuiltinAddressSpace(AddrSpace));
   10555         Str = End;
   10556       }
   10557       if (c == '*')
   10558         Type = Context.getPointerType(Type);
   10559       else
   10560         Type = Context.getLValueReferenceType(Type);
   10561       break;
   10562     }
   10563     // FIXME: There's no way to have a built-in with an rvalue ref arg.
   10564     case 'C':
   10565       Type = Type.withConst();
   10566       break;
   10567     case 'D':
   10568       Type = Context.getVolatileType(Type);
   10569       break;
   10570     case 'R':
   10571       Type = Type.withRestrict();
   10572       break;
   10573     }
   10574   }
   10575 
   10576   assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
   10577          "Integer constant 'I' type must be an integer");
   10578 
   10579   return Type;
   10580 }
   10581 
   10582 // On some targets such as PowerPC, some of the builtins are defined with custom
   10583 // type decriptors for target-dependent types. These descriptors are decoded in
   10584 // other functions, but it may be useful to be able to fall back to default
   10585 // descriptor decoding to define builtins mixing target-dependent and target-
   10586 // independent types. This function allows decoding one type descriptor with
   10587 // default decoding.
   10588 QualType ASTContext::DecodeTypeStr(const char *&Str, const ASTContext &Context,
   10589                                    GetBuiltinTypeError &Error, bool &RequireICE,
   10590                                    bool AllowTypeModifiers) const {
   10591   return DecodeTypeFromStr(Str, Context, Error, RequireICE, AllowTypeModifiers);
   10592 }
   10593 
   10594 /// GetBuiltinType - Return the type for the specified builtin.
   10595 QualType ASTContext::GetBuiltinType(unsigned Id,
   10596                                     GetBuiltinTypeError &Error,
   10597                                     unsigned *IntegerConstantArgs) const {
   10598   const char *TypeStr = BuiltinInfo.getTypeString(Id);
   10599   if (TypeStr[0] == '\0') {
   10600     Error = GE_Missing_type;
   10601     return {};
   10602   }
   10603 
   10604   SmallVector<QualType, 8> ArgTypes;
   10605 
   10606   bool RequiresICE = false;
   10607   Error = GE_None;
   10608   QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
   10609                                        RequiresICE, true);
   10610   if (Error != GE_None)
   10611     return {};
   10612 
   10613   assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
   10614 
   10615   while (TypeStr[0] && TypeStr[0] != '.') {
   10616     QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
   10617     if (Error != GE_None)
   10618       return {};
   10619 
   10620     // If this argument is required to be an IntegerConstantExpression and the
   10621     // caller cares, fill in the bitmask we return.
   10622     if (RequiresICE && IntegerConstantArgs)
   10623       *IntegerConstantArgs |= 1 << ArgTypes.size();
   10624 
   10625     // Do array -> pointer decay.  The builtin should use the decayed type.
   10626     if (Ty->isArrayType())
   10627       Ty = getArrayDecayedType(Ty);
   10628 
   10629     ArgTypes.push_back(Ty);
   10630   }
   10631 
   10632   if (Id == Builtin::BI__GetExceptionInfo)
   10633     return {};
   10634 
   10635   assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
   10636          "'.' should only occur at end of builtin type list!");
   10637 
   10638   bool Variadic = (TypeStr[0] == '.');
   10639 
   10640   FunctionType::ExtInfo EI(getDefaultCallingConvention(
   10641       Variadic, /*IsCXXMethod=*/false, /*IsBuiltin=*/true));
   10642   if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
   10643 
   10644 
   10645   // We really shouldn't be making a no-proto type here.
   10646   if (ArgTypes.empty() && Variadic && !getLangOpts().CPlusPlus)
   10647     return getFunctionNoProtoType(ResType, EI);
   10648 
   10649   FunctionProtoType::ExtProtoInfo EPI;
   10650   EPI.ExtInfo = EI;
   10651   EPI.Variadic = Variadic;
   10652   if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id))
   10653     EPI.ExceptionSpec.Type =
   10654         getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
   10655 
   10656   return getFunctionType(ResType, ArgTypes, EPI);
   10657 }
   10658 
   10659 static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
   10660                                              const FunctionDecl *FD) {
   10661   if (!FD->isExternallyVisible())
   10662     return GVA_Internal;
   10663 
   10664   // Non-user-provided functions get emitted as weak definitions with every
   10665   // use, no matter whether they've been explicitly instantiated etc.
   10666   if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
   10667     if (!MD->isUserProvided())
   10668       return GVA_DiscardableODR;
   10669 
   10670   GVALinkage External;
   10671   switch (FD->getTemplateSpecializationKind()) {
   10672   case TSK_Undeclared:
   10673   case TSK_ExplicitSpecialization:
   10674     External = GVA_StrongExternal;
   10675     break;
   10676 
   10677   case TSK_ExplicitInstantiationDefinition:
   10678     return GVA_StrongODR;
   10679 
   10680   // C++11 [temp.explicit]p10:
   10681   //   [ Note: The intent is that an inline function that is the subject of
   10682   //   an explicit instantiation declaration will still be implicitly
   10683   //   instantiated when used so that the body can be considered for
   10684   //   inlining, but that no out-of-line copy of the inline function would be
   10685   //   generated in the translation unit. -- end note ]
   10686   case TSK_ExplicitInstantiationDeclaration:
   10687     return GVA_AvailableExternally;
   10688 
   10689   case TSK_ImplicitInstantiation:
   10690     External = GVA_DiscardableODR;
   10691     break;
   10692   }
   10693 
   10694   if (!FD->isInlined())
   10695     return External;
   10696 
   10697   if ((!Context.getLangOpts().CPlusPlus &&
   10698        !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
   10699        !FD->hasAttr<DLLExportAttr>()) ||
   10700       FD->hasAttr<GNUInlineAttr>()) {
   10701     // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
   10702 
   10703     // GNU or C99 inline semantics. Determine whether this symbol should be
   10704     // externally visible.
   10705     if (FD->isInlineDefinitionExternallyVisible())
   10706       return External;
   10707 
   10708     // C99 inline semantics, where the symbol is not externally visible.
   10709     return GVA_AvailableExternally;
   10710   }
   10711 
   10712   // Functions specified with extern and inline in -fms-compatibility mode
   10713   // forcibly get emitted.  While the body of the function cannot be later
   10714   // replaced, the function definition cannot be discarded.
   10715   if (FD->isMSExternInline())
   10716     return GVA_StrongODR;
   10717 
   10718   return GVA_DiscardableODR;
   10719 }
   10720 
   10721 static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context,
   10722                                                 const Decl *D, GVALinkage L) {
   10723   // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
   10724   // dllexport/dllimport on inline functions.
   10725   if (D->hasAttr<DLLImportAttr>()) {
   10726     if (L == GVA_DiscardableODR || L == GVA_StrongODR)
   10727       return GVA_AvailableExternally;
   10728   } else if (D->hasAttr<DLLExportAttr>()) {
   10729     if (L == GVA_DiscardableODR)
   10730       return GVA_StrongODR;
   10731   } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice) {
   10732     // Device-side functions with __global__ attribute must always be
   10733     // visible externally so they can be launched from host.
   10734     if (D->hasAttr<CUDAGlobalAttr>() &&
   10735         (L == GVA_DiscardableODR || L == GVA_Internal))
   10736       return GVA_StrongODR;
   10737     // Single source offloading languages like CUDA/HIP need to be able to
   10738     // access static device variables from host code of the same compilation
   10739     // unit. This is done by externalizing the static variable with a shared
   10740     // name between the host and device compilation which is the same for the
   10741     // same compilation unit whereas different among different compilation
   10742     // units.
   10743     if (Context.shouldExternalizeStaticVar(D))
   10744       return GVA_StrongExternal;
   10745   }
   10746   return L;
   10747 }
   10748 
   10749 /// Adjust the GVALinkage for a declaration based on what an external AST source
   10750 /// knows about whether there can be other definitions of this declaration.
   10751 static GVALinkage
   10752 adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D,
   10753                                           GVALinkage L) {
   10754   ExternalASTSource *Source = Ctx.getExternalSource();
   10755   if (!Source)
   10756     return L;
   10757 
   10758   switch (Source->hasExternalDefinitions(D)) {
   10759   case ExternalASTSource::EK_Never:
   10760     // Other translation units rely on us to provide the definition.
   10761     if (L == GVA_DiscardableODR)
   10762       return GVA_StrongODR;
   10763     break;
   10764 
   10765   case ExternalASTSource::EK_Always:
   10766     return GVA_AvailableExternally;
   10767 
   10768   case ExternalASTSource::EK_ReplyHazy:
   10769     break;
   10770   }
   10771   return L;
   10772 }
   10773 
   10774 GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
   10775   return adjustGVALinkageForExternalDefinitionKind(*this, FD,
   10776            adjustGVALinkageForAttributes(*this, FD,
   10777              basicGVALinkageForFunction(*this, FD)));
   10778 }
   10779 
   10780 static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
   10781                                              const VarDecl *VD) {
   10782   if (!VD->isExternallyVisible())
   10783     return GVA_Internal;
   10784 
   10785   if (VD->isStaticLocal()) {
   10786     const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
   10787     while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
   10788       LexicalContext = LexicalContext->getLexicalParent();
   10789 
   10790     // ObjC Blocks can create local variables that don't have a FunctionDecl
   10791     // LexicalContext.
   10792     if (!LexicalContext)
   10793       return GVA_DiscardableODR;
   10794 
   10795     // Otherwise, let the static local variable inherit its linkage from the
   10796     // nearest enclosing function.
   10797     auto StaticLocalLinkage =
   10798         Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
   10799 
   10800     // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
   10801     // be emitted in any object with references to the symbol for the object it
   10802     // contains, whether inline or out-of-line."
   10803     // Similar behavior is observed with MSVC. An alternative ABI could use
   10804     // StrongODR/AvailableExternally to match the function, but none are
   10805     // known/supported currently.
   10806     if (StaticLocalLinkage == GVA_StrongODR ||
   10807         StaticLocalLinkage == GVA_AvailableExternally)
   10808       return GVA_DiscardableODR;
   10809     return StaticLocalLinkage;
   10810   }
   10811 
   10812   // MSVC treats in-class initialized static data members as definitions.
   10813   // By giving them non-strong linkage, out-of-line definitions won't
   10814   // cause link errors.
   10815   if (Context.isMSStaticDataMemberInlineDefinition(VD))
   10816     return GVA_DiscardableODR;
   10817 
   10818   // Most non-template variables have strong linkage; inline variables are
   10819   // linkonce_odr or (occasionally, for compatibility) weak_odr.
   10820   GVALinkage StrongLinkage;
   10821   switch (Context.getInlineVariableDefinitionKind(VD)) {
   10822   case ASTContext::InlineVariableDefinitionKind::None:
   10823     StrongLinkage = GVA_StrongExternal;
   10824     break;
   10825   case ASTContext::InlineVariableDefinitionKind::Weak:
   10826   case ASTContext::InlineVariableDefinitionKind::WeakUnknown:
   10827     StrongLinkage = GVA_DiscardableODR;
   10828     break;
   10829   case ASTContext::InlineVariableDefinitionKind::Strong:
   10830     StrongLinkage = GVA_StrongODR;
   10831     break;
   10832   }
   10833 
   10834   switch (VD->getTemplateSpecializationKind()) {
   10835   case TSK_Undeclared:
   10836     return StrongLinkage;
   10837 
   10838   case TSK_ExplicitSpecialization:
   10839     return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
   10840                    VD->isStaticDataMember()
   10841                ? GVA_StrongODR
   10842                : StrongLinkage;
   10843 
   10844   case TSK_ExplicitInstantiationDefinition:
   10845     return GVA_StrongODR;
   10846 
   10847   case TSK_ExplicitInstantiationDeclaration:
   10848     return GVA_AvailableExternally;
   10849 
   10850   case TSK_ImplicitInstantiation:
   10851     return GVA_DiscardableODR;
   10852   }
   10853 
   10854   llvm_unreachable("Invalid Linkage!");
   10855 }
   10856 
   10857 GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
   10858   return adjustGVALinkageForExternalDefinitionKind(*this, VD,
   10859            adjustGVALinkageForAttributes(*this, VD,
   10860              basicGVALinkageForVariable(*this, VD)));
   10861 }
   10862 
   10863 bool ASTContext::DeclMustBeEmitted(const Decl *D) {
   10864   if (const auto *VD = dyn_cast<VarDecl>(D)) {
   10865     if (!VD->isFileVarDecl())
   10866       return false;
   10867     // Global named register variables (GNU extension) are never emitted.
   10868     if (VD->getStorageClass() == SC_Register)
   10869       return false;
   10870     if (VD->getDescribedVarTemplate() ||
   10871         isa<VarTemplatePartialSpecializationDecl>(VD))
   10872       return false;
   10873   } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
   10874     // We never need to emit an uninstantiated function template.
   10875     if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
   10876       return false;
   10877   } else if (isa<PragmaCommentDecl>(D))
   10878     return true;
   10879   else if (isa<PragmaDetectMismatchDecl>(D))
   10880     return true;
   10881   else if (isa<OMPRequiresDecl>(D))
   10882     return true;
   10883   else if (isa<OMPThreadPrivateDecl>(D))
   10884     return !D->getDeclContext()->isDependentContext();
   10885   else if (isa<OMPAllocateDecl>(D))
   10886     return !D->getDeclContext()->isDependentContext();
   10887   else if (isa<OMPDeclareReductionDecl>(D) || isa<OMPDeclareMapperDecl>(D))
   10888     return !D->getDeclContext()->isDependentContext();
   10889   else if (isa<ImportDecl>(D))
   10890     return true;
   10891   else
   10892     return false;
   10893 
   10894   // If this is a member of a class template, we do not need to emit it.
   10895   if (D->getDeclContext()->isDependentContext())
   10896     return false;
   10897 
   10898   // Weak references don't produce any output by themselves.
   10899   if (D->hasAttr<WeakRefAttr>())
   10900     return false;
   10901 
   10902   // Aliases and used decls are required.
   10903   if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
   10904     return true;
   10905 
   10906   if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
   10907     // Forward declarations aren't required.
   10908     if (!FD->doesThisDeclarationHaveABody())
   10909       return FD->doesDeclarationForceExternallyVisibleDefinition();
   10910 
   10911     // Constructors and destructors are required.
   10912     if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
   10913       return true;
   10914 
   10915     // The key function for a class is required.  This rule only comes
   10916     // into play when inline functions can be key functions, though.
   10917     if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
   10918       if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
   10919         const CXXRecordDecl *RD = MD->getParent();
   10920         if (MD->isOutOfLine() && RD->isDynamicClass()) {
   10921           const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
   10922           if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
   10923             return true;
   10924         }
   10925       }
   10926     }
   10927 
   10928     GVALinkage Linkage = GetGVALinkageForFunction(FD);
   10929 
   10930     // static, static inline, always_inline, and extern inline functions can
   10931     // always be deferred.  Normal inline functions can be deferred in C99/C++.
   10932     // Implicit template instantiations can also be deferred in C++.
   10933     return !isDiscardableGVALinkage(Linkage);
   10934   }
   10935 
   10936   const auto *VD = cast<VarDecl>(D);
   10937   assert(VD->isFileVarDecl() && "Expected file scoped var");
   10938 
   10939   // If the decl is marked as `declare target to`, it should be emitted for the
   10940   // host and for the device.
   10941   if (LangOpts.OpenMP &&
   10942       OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
   10943     return true;
   10944 
   10945   if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
   10946       !isMSStaticDataMemberInlineDefinition(VD))
   10947     return false;
   10948 
   10949   // Variables that can be needed in other TUs are required.
   10950   auto Linkage = GetGVALinkageForVariable(VD);
   10951   if (!isDiscardableGVALinkage(Linkage))
   10952     return true;
   10953 
   10954   // We never need to emit a variable that is available in another TU.
   10955   if (Linkage == GVA_AvailableExternally)
   10956     return false;
   10957 
   10958   // Variables that have destruction with side-effects are required.
   10959   if (VD->needsDestruction(*this))
   10960     return true;
   10961 
   10962   // Variables that have initialization with side-effects are required.
   10963   if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
   10964       // We can get a value-dependent initializer during error recovery.
   10965       (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
   10966     return true;
   10967 
   10968   // Likewise, variables with tuple-like bindings are required if their
   10969   // bindings have side-effects.
   10970   if (const auto *DD = dyn_cast<DecompositionDecl>(VD))
   10971     for (const auto *BD : DD->bindings())
   10972       if (const auto *BindingVD = BD->getHoldingVar())
   10973         if (DeclMustBeEmitted(BindingVD))
   10974           return true;
   10975 
   10976   return false;
   10977 }
   10978 
   10979 void ASTContext::forEachMultiversionedFunctionVersion(
   10980     const FunctionDecl *FD,
   10981     llvm::function_ref<void(FunctionDecl *)> Pred) const {
   10982   assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
   10983   llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
   10984   FD = FD->getMostRecentDecl();
   10985   // FIXME: The order of traversal here matters and depends on the order of
   10986   // lookup results, which happens to be (mostly) oldest-to-newest, but we
   10987   // shouldn't rely on that.
   10988   for (auto *CurDecl :
   10989        FD->getDeclContext()->getRedeclContext()->lookup(FD->getDeclName())) {
   10990     FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl();
   10991     if (CurFD && hasSameType(CurFD->getType(), FD->getType()) &&
   10992         std::end(SeenDecls) == llvm::find(SeenDecls, CurFD)) {
   10993       SeenDecls.insert(CurFD);
   10994       Pred(CurFD);
   10995     }
   10996   }
   10997 }
   10998 
   10999 CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
   11000                                                     bool IsCXXMethod,
   11001                                                     bool IsBuiltin) const {
   11002   // Pass through to the C++ ABI object
   11003   if (IsCXXMethod)
   11004     return ABI->getDefaultMethodCallConv(IsVariadic);
   11005 
   11006   // Builtins ignore user-specified default calling convention and remain the
   11007   // Target's default calling convention.
   11008   if (!IsBuiltin) {
   11009     switch (LangOpts.getDefaultCallingConv()) {
   11010     case LangOptions::DCC_None:
   11011       break;
   11012     case LangOptions::DCC_CDecl:
   11013       return CC_C;
   11014     case LangOptions::DCC_FastCall:
   11015       if (getTargetInfo().hasFeature("sse2") && !IsVariadic)
   11016         return CC_X86FastCall;
   11017       break;
   11018     case LangOptions::DCC_StdCall:
   11019       if (!IsVariadic)
   11020         return CC_X86StdCall;
   11021       break;
   11022     case LangOptions::DCC_VectorCall:
   11023       // __vectorcall cannot be applied to variadic functions.
   11024       if (!IsVariadic)
   11025         return CC_X86VectorCall;
   11026       break;
   11027     case LangOptions::DCC_RegCall:
   11028       // __regcall cannot be applied to variadic functions.
   11029       if (!IsVariadic)
   11030         return CC_X86RegCall;
   11031       break;
   11032     }
   11033   }
   11034   return Target->getDefaultCallingConv();
   11035 }
   11036 
   11037 bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
   11038   // Pass through to the C++ ABI object
   11039   return ABI->isNearlyEmpty(RD);
   11040 }
   11041 
   11042 VTableContextBase *ASTContext::getVTableContext() {
   11043   if (!VTContext.get()) {
   11044     auto ABI = Target->getCXXABI();
   11045     if (ABI.isMicrosoft())
   11046       VTContext.reset(new MicrosoftVTableContext(*this));
   11047     else {
   11048       auto ComponentLayout = getLangOpts().RelativeCXXABIVTables
   11049                                  ? ItaniumVTableContext::Relative
   11050                                  : ItaniumVTableContext::Pointer;
   11051       VTContext.reset(new ItaniumVTableContext(*this, ComponentLayout));
   11052     }
   11053   }
   11054   return VTContext.get();
   11055 }
   11056 
   11057 MangleContext *ASTContext::createMangleContext(const TargetInfo *T) {
   11058   if (!T)
   11059     T = Target;
   11060   switch (T->getCXXABI().getKind()) {
   11061   case TargetCXXABI::AppleARM64:
   11062   case TargetCXXABI::Fuchsia:
   11063   case TargetCXXABI::GenericAArch64:
   11064   case TargetCXXABI::GenericItanium:
   11065   case TargetCXXABI::GenericARM:
   11066   case TargetCXXABI::GenericMIPS:
   11067   case TargetCXXABI::iOS:
   11068   case TargetCXXABI::WebAssembly:
   11069   case TargetCXXABI::WatchOS:
   11070   case TargetCXXABI::XL:
   11071     return ItaniumMangleContext::create(*this, getDiagnostics());
   11072   case TargetCXXABI::Microsoft:
   11073     return MicrosoftMangleContext::create(*this, getDiagnostics());
   11074   }
   11075   llvm_unreachable("Unsupported ABI");
   11076 }
   11077 
   11078 CXXABI::~CXXABI() = default;
   11079 
   11080 size_t ASTContext::getSideTableAllocatedMemory() const {
   11081   return ASTRecordLayouts.getMemorySize() +
   11082          llvm::capacity_in_bytes(ObjCLayouts) +
   11083          llvm::capacity_in_bytes(KeyFunctions) +
   11084          llvm::capacity_in_bytes(ObjCImpls) +
   11085          llvm::capacity_in_bytes(BlockVarCopyInits) +
   11086          llvm::capacity_in_bytes(DeclAttrs) +
   11087          llvm::capacity_in_bytes(TemplateOrInstantiation) +
   11088          llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
   11089          llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
   11090          llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
   11091          llvm::capacity_in_bytes(OverriddenMethods) +
   11092          llvm::capacity_in_bytes(Types) +
   11093          llvm::capacity_in_bytes(VariableArrayTypes);
   11094 }
   11095 
   11096 /// getIntTypeForBitwidth -
   11097 /// sets integer QualTy according to specified details:
   11098 /// bitwidth, signed/unsigned.
   11099 /// Returns empty type if there is no appropriate target types.
   11100 QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
   11101                                            unsigned Signed) const {
   11102   TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
   11103   CanQualType QualTy = getFromTargetType(Ty);
   11104   if (!QualTy && DestWidth == 128)
   11105     return Signed ? Int128Ty : UnsignedInt128Ty;
   11106   return QualTy;
   11107 }
   11108 
   11109 /// getRealTypeForBitwidth -
   11110 /// sets floating point QualTy according to specified bitwidth.
   11111 /// Returns empty type if there is no appropriate target types.
   11112 QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth,
   11113                                             bool ExplicitIEEE) const {
   11114   TargetInfo::RealType Ty =
   11115       getTargetInfo().getRealTypeByWidth(DestWidth, ExplicitIEEE);
   11116   switch (Ty) {
   11117   case TargetInfo::Float:
   11118     return FloatTy;
   11119   case TargetInfo::Double:
   11120     return DoubleTy;
   11121   case TargetInfo::LongDouble:
   11122     return LongDoubleTy;
   11123   case TargetInfo::Float128:
   11124     return Float128Ty;
   11125   case TargetInfo::NoFloat:
   11126     return {};
   11127   }
   11128 
   11129   llvm_unreachable("Unhandled TargetInfo::RealType value");
   11130 }
   11131 
   11132 void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
   11133   if (Number > 1)
   11134     MangleNumbers[ND] = Number;
   11135 }
   11136 
   11137 unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
   11138   auto I = MangleNumbers.find(ND);
   11139   return I != MangleNumbers.end() ? I->second : 1;
   11140 }
   11141 
   11142 void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
   11143   if (Number > 1)
   11144     StaticLocalNumbers[VD] = Number;
   11145 }
   11146 
   11147 unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
   11148   auto I = StaticLocalNumbers.find(VD);
   11149   return I != StaticLocalNumbers.end() ? I->second : 1;
   11150 }
   11151 
   11152 MangleNumberingContext &
   11153 ASTContext::getManglingNumberContext(const DeclContext *DC) {
   11154   assert(LangOpts.CPlusPlus);  // We don't need mangling numbers for plain C.
   11155   std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
   11156   if (!MCtx)
   11157     MCtx = createMangleNumberingContext();
   11158   return *MCtx;
   11159 }
   11160 
   11161 MangleNumberingContext &
   11162 ASTContext::getManglingNumberContext(NeedExtraManglingDecl_t, const Decl *D) {
   11163   assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
   11164   std::unique_ptr<MangleNumberingContext> &MCtx =
   11165       ExtraMangleNumberingContexts[D];
   11166   if (!MCtx)
   11167     MCtx = createMangleNumberingContext();
   11168   return *MCtx;
   11169 }
   11170 
   11171 std::unique_ptr<MangleNumberingContext>
   11172 ASTContext::createMangleNumberingContext() const {
   11173   return ABI->createMangleNumberingContext();
   11174 }
   11175 
   11176 const CXXConstructorDecl *
   11177 ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
   11178   return ABI->getCopyConstructorForExceptionObject(
   11179       cast<CXXRecordDecl>(RD->getFirstDecl()));
   11180 }
   11181 
   11182 void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
   11183                                                       CXXConstructorDecl *CD) {
   11184   return ABI->addCopyConstructorForExceptionObject(
   11185       cast<CXXRecordDecl>(RD->getFirstDecl()),
   11186       cast<CXXConstructorDecl>(CD->getFirstDecl()));
   11187 }
   11188 
   11189 void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
   11190                                                  TypedefNameDecl *DD) {
   11191   return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
   11192 }
   11193 
   11194 TypedefNameDecl *
   11195 ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
   11196   return ABI->getTypedefNameForUnnamedTagDecl(TD);
   11197 }
   11198 
   11199 void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
   11200                                                 DeclaratorDecl *DD) {
   11201   return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
   11202 }
   11203 
   11204 DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
   11205   return ABI->getDeclaratorForUnnamedTagDecl(TD);
   11206 }
   11207 
   11208 void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
   11209   ParamIndices[D] = index;
   11210 }
   11211 
   11212 unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
   11213   ParameterIndexTable::const_iterator I = ParamIndices.find(D);
   11214   assert(I != ParamIndices.end() &&
   11215          "ParmIndices lacks entry set by ParmVarDecl");
   11216   return I->second;
   11217 }
   11218 
   11219 QualType ASTContext::getStringLiteralArrayType(QualType EltTy,
   11220                                                unsigned Length) const {
   11221   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
   11222   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
   11223     EltTy = EltTy.withConst();
   11224 
   11225   EltTy = adjustStringLiteralBaseType(EltTy);
   11226 
   11227   // Get an array type for the string, according to C99 6.4.5. This includes
   11228   // the null terminator character.
   11229   return getConstantArrayType(EltTy, llvm::APInt(32, Length + 1), nullptr,
   11230                               ArrayType::Normal, /*IndexTypeQuals*/ 0);
   11231 }
   11232 
   11233 StringLiteral *
   11234 ASTContext::getPredefinedStringLiteralFromCache(StringRef Key) const {
   11235   StringLiteral *&Result = StringLiteralCache[Key];
   11236   if (!Result)
   11237     Result = StringLiteral::Create(
   11238         *this, Key, StringLiteral::Ascii,
   11239         /*Pascal*/ false, getStringLiteralArrayType(CharTy, Key.size()),
   11240         SourceLocation());
   11241   return Result;
   11242 }
   11243 
   11244 MSGuidDecl *
   11245 ASTContext::getMSGuidDecl(MSGuidDecl::Parts Parts) const {
   11246   assert(MSGuidTagDecl && "building MS GUID without MS extensions?");
   11247 
   11248   llvm::FoldingSetNodeID ID;
   11249   MSGuidDecl::Profile(ID, Parts);
   11250 
   11251   void *InsertPos;
   11252   if (MSGuidDecl *Existing = MSGuidDecls.FindNodeOrInsertPos(ID, InsertPos))
   11253     return Existing;
   11254 
   11255   QualType GUIDType = getMSGuidType().withConst();
   11256   MSGuidDecl *New = MSGuidDecl::Create(*this, GUIDType, Parts);
   11257   MSGuidDecls.InsertNode(New, InsertPos);
   11258   return New;
   11259 }
   11260 
   11261 TemplateParamObjectDecl *
   11262 ASTContext::getTemplateParamObjectDecl(QualType T, const APValue &V) const {
   11263   assert(T->isRecordType() && "template param object of unexpected type");
   11264 
   11265   // C++ [temp.param]p8:
   11266   //   [...] a static storage duration object of type 'const T' [...]
   11267   T.addConst();
   11268 
   11269   llvm::FoldingSetNodeID ID;
   11270   TemplateParamObjectDecl::Profile(ID, T, V);
   11271 
   11272   void *InsertPos;
   11273   if (TemplateParamObjectDecl *Existing =
   11274           TemplateParamObjectDecls.FindNodeOrInsertPos(ID, InsertPos))
   11275     return Existing;
   11276 
   11277   TemplateParamObjectDecl *New = TemplateParamObjectDecl::Create(*this, T, V);
   11278   TemplateParamObjectDecls.InsertNode(New, InsertPos);
   11279   return New;
   11280 }
   11281 
   11282 bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
   11283   const llvm::Triple &T = getTargetInfo().getTriple();
   11284   if (!T.isOSDarwin())
   11285     return false;
   11286 
   11287   if (!(T.isiOS() && T.isOSVersionLT(7)) &&
   11288       !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
   11289     return false;
   11290 
   11291   QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
   11292   CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
   11293   uint64_t Size = sizeChars.getQuantity();
   11294   CharUnits alignChars = getTypeAlignInChars(AtomicTy);
   11295   unsigned Align = alignChars.getQuantity();
   11296   unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
   11297   return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
   11298 }
   11299 
   11300 bool
   11301 ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
   11302                                 const ObjCMethodDecl *MethodImpl) {
   11303   // No point trying to match an unavailable/deprecated mothod.
   11304   if (MethodDecl->hasAttr<UnavailableAttr>()
   11305       || MethodDecl->hasAttr<DeprecatedAttr>())
   11306     return false;
   11307   if (MethodDecl->getObjCDeclQualifier() !=
   11308       MethodImpl->getObjCDeclQualifier())
   11309     return false;
   11310   if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
   11311     return false;
   11312 
   11313   if (MethodDecl->param_size() != MethodImpl->param_size())
   11314     return false;
   11315 
   11316   for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
   11317        IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
   11318        EF = MethodDecl->param_end();
   11319        IM != EM && IF != EF; ++IM, ++IF) {
   11320     const ParmVarDecl *DeclVar = (*IF);
   11321     const ParmVarDecl *ImplVar = (*IM);
   11322     if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
   11323       return false;
   11324     if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
   11325       return false;
   11326   }
   11327 
   11328   return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
   11329 }
   11330 
   11331 uint64_t ASTContext::getTargetNullPointerValue(QualType QT) const {
   11332   LangAS AS;
   11333   if (QT->getUnqualifiedDesugaredType()->isNullPtrType())
   11334     AS = LangAS::Default;
   11335   else
   11336     AS = QT->getPointeeType().getAddressSpace();
   11337 
   11338   return getTargetInfo().getNullPointerValue(AS);
   11339 }
   11340 
   11341 unsigned ASTContext::getTargetAddressSpace(LangAS AS) const {
   11342   if (isTargetAddressSpace(AS))
   11343     return toTargetAddressSpace(AS);
   11344   else
   11345     return (*AddrSpaceMap)[(unsigned)AS];
   11346 }
   11347 
   11348 QualType ASTContext::getCorrespondingSaturatedType(QualType Ty) const {
   11349   assert(Ty->isFixedPointType());
   11350 
   11351   if (Ty->isSaturatedFixedPointType()) return Ty;
   11352 
   11353   switch (Ty->castAs<BuiltinType>()->getKind()) {
   11354     default:
   11355       llvm_unreachable("Not a fixed point type!");
   11356     case BuiltinType::ShortAccum:
   11357       return SatShortAccumTy;
   11358     case BuiltinType::Accum:
   11359       return SatAccumTy;
   11360     case BuiltinType::LongAccum:
   11361       return SatLongAccumTy;
   11362     case BuiltinType::UShortAccum:
   11363       return SatUnsignedShortAccumTy;
   11364     case BuiltinType::UAccum:
   11365       return SatUnsignedAccumTy;
   11366     case BuiltinType::ULongAccum:
   11367       return SatUnsignedLongAccumTy;
   11368     case BuiltinType::ShortFract:
   11369       return SatShortFractTy;
   11370     case BuiltinType::Fract:
   11371       return SatFractTy;
   11372     case BuiltinType::LongFract:
   11373       return SatLongFractTy;
   11374     case BuiltinType::UShortFract:
   11375       return SatUnsignedShortFractTy;
   11376     case BuiltinType::UFract:
   11377       return SatUnsignedFractTy;
   11378     case BuiltinType::ULongFract:
   11379       return SatUnsignedLongFractTy;
   11380   }
   11381 }
   11382 
   11383 LangAS ASTContext::getLangASForBuiltinAddressSpace(unsigned AS) const {
   11384   if (LangOpts.OpenCL)
   11385     return getTargetInfo().getOpenCLBuiltinAddressSpace(AS);
   11386 
   11387   if (LangOpts.CUDA)
   11388     return getTargetInfo().getCUDABuiltinAddressSpace(AS);
   11389 
   11390   return getLangASFromTargetAS(AS);
   11391 }
   11392 
   11393 // Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
   11394 // doesn't include ASTContext.h
   11395 template
   11396 clang::LazyGenerationalUpdatePtr<
   11397     const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
   11398 clang::LazyGenerationalUpdatePtr<
   11399     const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
   11400         const clang::ASTContext &Ctx, Decl *Value);
   11401 
   11402 unsigned char ASTContext::getFixedPointScale(QualType Ty) const {
   11403   assert(Ty->isFixedPointType());
   11404 
   11405   const TargetInfo &Target = getTargetInfo();
   11406   switch (Ty->castAs<BuiltinType>()->getKind()) {
   11407     default:
   11408       llvm_unreachable("Not a fixed point type!");
   11409     case BuiltinType::ShortAccum:
   11410     case BuiltinType::SatShortAccum:
   11411       return Target.getShortAccumScale();
   11412     case BuiltinType::Accum:
   11413     case BuiltinType::SatAccum:
   11414       return Target.getAccumScale();
   11415     case BuiltinType::LongAccum:
   11416     case BuiltinType::SatLongAccum:
   11417       return Target.getLongAccumScale();
   11418     case BuiltinType::UShortAccum:
   11419     case BuiltinType::SatUShortAccum:
   11420       return Target.getUnsignedShortAccumScale();
   11421     case BuiltinType::UAccum:
   11422     case BuiltinType::SatUAccum:
   11423       return Target.getUnsignedAccumScale();
   11424     case BuiltinType::ULongAccum:
   11425     case BuiltinType::SatULongAccum:
   11426       return Target.getUnsignedLongAccumScale();
   11427     case BuiltinType::ShortFract:
   11428     case BuiltinType::SatShortFract:
   11429       return Target.getShortFractScale();
   11430     case BuiltinType::Fract:
   11431     case BuiltinType::SatFract:
   11432       return Target.getFractScale();
   11433     case BuiltinType::LongFract:
   11434     case BuiltinType::SatLongFract:
   11435       return Target.getLongFractScale();
   11436     case BuiltinType::UShortFract:
   11437     case BuiltinType::SatUShortFract:
   11438       return Target.getUnsignedShortFractScale();
   11439     case BuiltinType::UFract:
   11440     case BuiltinType::SatUFract:
   11441       return Target.getUnsignedFractScale();
   11442     case BuiltinType::ULongFract:
   11443     case BuiltinType::SatULongFract:
   11444       return Target.getUnsignedLongFractScale();
   11445   }
   11446 }
   11447 
   11448 unsigned char ASTContext::getFixedPointIBits(QualType Ty) const {
   11449   assert(Ty->isFixedPointType());
   11450 
   11451   const TargetInfo &Target = getTargetInfo();
   11452   switch (Ty->castAs<BuiltinType>()->getKind()) {
   11453     default:
   11454       llvm_unreachable("Not a fixed point type!");
   11455     case BuiltinType::ShortAccum:
   11456     case BuiltinType::SatShortAccum:
   11457       return Target.getShortAccumIBits();
   11458     case BuiltinType::Accum:
   11459     case BuiltinType::SatAccum:
   11460       return Target.getAccumIBits();
   11461     case BuiltinType::LongAccum:
   11462     case BuiltinType::SatLongAccum:
   11463       return Target.getLongAccumIBits();
   11464     case BuiltinType::UShortAccum:
   11465     case BuiltinType::SatUShortAccum:
   11466       return Target.getUnsignedShortAccumIBits();
   11467     case BuiltinType::UAccum:
   11468     case BuiltinType::SatUAccum:
   11469       return Target.getUnsignedAccumIBits();
   11470     case BuiltinType::ULongAccum:
   11471     case BuiltinType::SatULongAccum:
   11472       return Target.getUnsignedLongAccumIBits();
   11473     case BuiltinType::ShortFract:
   11474     case BuiltinType::SatShortFract:
   11475     case BuiltinType::Fract:
   11476     case BuiltinType::SatFract:
   11477     case BuiltinType::LongFract:
   11478     case BuiltinType::SatLongFract:
   11479     case BuiltinType::UShortFract:
   11480     case BuiltinType::SatUShortFract:
   11481     case BuiltinType::UFract:
   11482     case BuiltinType::SatUFract:
   11483     case BuiltinType::ULongFract:
   11484     case BuiltinType::SatULongFract:
   11485       return 0;
   11486   }
   11487 }
   11488 
   11489 llvm::FixedPointSemantics
   11490 ASTContext::getFixedPointSemantics(QualType Ty) const {
   11491   assert((Ty->isFixedPointType() || Ty->isIntegerType()) &&
   11492          "Can only get the fixed point semantics for a "
   11493          "fixed point or integer type.");
   11494   if (Ty->isIntegerType())
   11495     return llvm::FixedPointSemantics::GetIntegerSemantics(
   11496         getIntWidth(Ty), Ty->isSignedIntegerType());
   11497 
   11498   bool isSigned = Ty->isSignedFixedPointType();
   11499   return llvm::FixedPointSemantics(
   11500       static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned,
   11501       Ty->isSaturatedFixedPointType(),
   11502       !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding());
   11503 }
   11504 
   11505 llvm::APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const {
   11506   assert(Ty->isFixedPointType());
   11507   return llvm::APFixedPoint::getMax(getFixedPointSemantics(Ty));
   11508 }
   11509 
   11510 llvm::APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const {
   11511   assert(Ty->isFixedPointType());
   11512   return llvm::APFixedPoint::getMin(getFixedPointSemantics(Ty));
   11513 }
   11514 
   11515 QualType ASTContext::getCorrespondingSignedFixedPointType(QualType Ty) const {
   11516   assert(Ty->isUnsignedFixedPointType() &&
   11517          "Expected unsigned fixed point type");
   11518 
   11519   switch (Ty->castAs<BuiltinType>()->getKind()) {
   11520   case BuiltinType::UShortAccum:
   11521     return ShortAccumTy;
   11522   case BuiltinType::UAccum:
   11523     return AccumTy;
   11524   case BuiltinType::ULongAccum:
   11525     return LongAccumTy;
   11526   case BuiltinType::SatUShortAccum:
   11527     return SatShortAccumTy;
   11528   case BuiltinType::SatUAccum:
   11529     return SatAccumTy;
   11530   case BuiltinType::SatULongAccum:
   11531     return SatLongAccumTy;
   11532   case BuiltinType::UShortFract:
   11533     return ShortFractTy;
   11534   case BuiltinType::UFract:
   11535     return FractTy;
   11536   case BuiltinType::ULongFract:
   11537     return LongFractTy;
   11538   case BuiltinType::SatUShortFract:
   11539     return SatShortFractTy;
   11540   case BuiltinType::SatUFract:
   11541     return SatFractTy;
   11542   case BuiltinType::SatULongFract:
   11543     return SatLongFractTy;
   11544   default:
   11545     llvm_unreachable("Unexpected unsigned fixed point type");
   11546   }
   11547 }
   11548 
   11549 ParsedTargetAttr
   11550 ASTContext::filterFunctionTargetAttrs(const TargetAttr *TD) const {
   11551   assert(TD != nullptr);
   11552   ParsedTargetAttr ParsedAttr = TD->parse();
   11553 
   11554   ParsedAttr.Features.erase(
   11555       llvm::remove_if(ParsedAttr.Features,
   11556                       [&](const std::string &Feat) {
   11557                         return !Target->isValidFeatureName(
   11558                             StringRef{Feat}.substr(1));
   11559                       }),
   11560       ParsedAttr.Features.end());
   11561   return ParsedAttr;
   11562 }
   11563 
   11564 void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
   11565                                        const FunctionDecl *FD) const {
   11566   if (FD)
   11567     getFunctionFeatureMap(FeatureMap, GlobalDecl().getWithDecl(FD));
   11568   else
   11569     Target->initFeatureMap(FeatureMap, getDiagnostics(),
   11570                            Target->getTargetOpts().CPU,
   11571                            Target->getTargetOpts().Features);
   11572 }
   11573 
   11574 // Fills in the supplied string map with the set of target features for the
   11575 // passed in function.
   11576 void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
   11577                                        GlobalDecl GD) const {
   11578   StringRef TargetCPU = Target->getTargetOpts().CPU;
   11579   const FunctionDecl *FD = GD.getDecl()->getAsFunction();
   11580   if (const auto *TD = FD->getAttr<TargetAttr>()) {
   11581     ParsedTargetAttr ParsedAttr = filterFunctionTargetAttrs(TD);
   11582 
   11583     // Make a copy of the features as passed on the command line into the
   11584     // beginning of the additional features from the function to override.
   11585     ParsedAttr.Features.insert(
   11586         ParsedAttr.Features.begin(),
   11587         Target->getTargetOpts().FeaturesAsWritten.begin(),
   11588         Target->getTargetOpts().FeaturesAsWritten.end());
   11589 
   11590     if (ParsedAttr.Architecture != "" &&
   11591         Target->isValidCPUName(ParsedAttr.Architecture))
   11592       TargetCPU = ParsedAttr.Architecture;
   11593 
   11594     // Now populate the feature map, first with the TargetCPU which is either
   11595     // the default or a new one from the target attribute string. Then we'll use
   11596     // the passed in features (FeaturesAsWritten) along with the new ones from
   11597     // the attribute.
   11598     Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU,
   11599                            ParsedAttr.Features);
   11600   } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) {
   11601     llvm::SmallVector<StringRef, 32> FeaturesTmp;
   11602     Target->getCPUSpecificCPUDispatchFeatures(
   11603         SD->getCPUName(GD.getMultiVersionIndex())->getName(), FeaturesTmp);
   11604     std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end());
   11605     Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
   11606   } else {
   11607     FeatureMap = Target->getTargetOpts().FeatureMap;
   11608   }
   11609 }
   11610 
   11611 OMPTraitInfo &ASTContext::getNewOMPTraitInfo() {
   11612   OMPTraitInfoVector.emplace_back(new OMPTraitInfo());
   11613   return *OMPTraitInfoVector.back();
   11614 }
   11615 
   11616 const StreamingDiagnostic &clang::
   11617 operator<<(const StreamingDiagnostic &DB,
   11618            const ASTContext::SectionInfo &Section) {
   11619   if (Section.Decl)
   11620     return DB << Section.Decl;
   11621   return DB << "a prior #pragma section";
   11622 }
   11623 
   11624 bool ASTContext::mayExternalizeStaticVar(const Decl *D) const {
   11625   bool IsStaticVar =
   11626       isa<VarDecl>(D) && cast<VarDecl>(D)->getStorageClass() == SC_Static;
   11627   bool IsExplicitDeviceVar = (D->hasAttr<CUDADeviceAttr>() &&
   11628                               !D->getAttr<CUDADeviceAttr>()->isImplicit()) ||
   11629                              (D->hasAttr<CUDAConstantAttr>() &&
   11630                               !D->getAttr<CUDAConstantAttr>()->isImplicit());
   11631   // CUDA/HIP: static managed variables need to be externalized since it is
   11632   // a declaration in IR, therefore cannot have internal linkage.
   11633   return IsStaticVar &&
   11634          (D->hasAttr<HIPManagedAttr>() || IsExplicitDeviceVar);
   11635 }
   11636 
   11637 bool ASTContext::shouldExternalizeStaticVar(const Decl *D) const {
   11638   return mayExternalizeStaticVar(D) &&
   11639          (D->hasAttr<HIPManagedAttr>() ||
   11640           CUDADeviceVarODRUsedByHost.count(cast<VarDecl>(D)));
   11641 }
   11642 
   11643 StringRef ASTContext::getCUIDHash() const {
   11644   if (!CUIDHash.empty())
   11645     return CUIDHash;
   11646   if (LangOpts.CUID.empty())
   11647     return StringRef();
   11648   CUIDHash = llvm::utohexstr(llvm::MD5Hash(LangOpts.CUID), /*LowerCase=*/true);
   11649   return CUIDHash;
   11650 }
   11651