brintos

brintos / llvm-project-archived public Read only

0
0
Text · 216.2 KiB · 591457b Raw
6051 lines · cpp
1//===- Decl.cpp - Declaration AST Node Implementation ---------------------===//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-exception6//7//===----------------------------------------------------------------------===//8//9// This file implements the Decl subclasses.10//11//===----------------------------------------------------------------------===//12 13#include "clang/AST/Decl.h"14#include "Linkage.h"15#include "clang/AST/ASTContext.h"16#include "clang/AST/ASTDiagnostic.h"17#include "clang/AST/ASTLambda.h"18#include "clang/AST/ASTMutationListener.h"19#include "clang/AST/Attr.h"20#include "clang/AST/CanonicalType.h"21#include "clang/AST/DeclBase.h"22#include "clang/AST/DeclCXX.h"23#include "clang/AST/DeclObjC.h"24#include "clang/AST/DeclTemplate.h"25#include "clang/AST/DeclarationName.h"26#include "clang/AST/Expr.h"27#include "clang/AST/ExprCXX.h"28#include "clang/AST/ExternalASTSource.h"29#include "clang/AST/ODRHash.h"30#include "clang/AST/PrettyDeclStackTrace.h"31#include "clang/AST/PrettyPrinter.h"32#include "clang/AST/Randstruct.h"33#include "clang/AST/RecordLayout.h"34#include "clang/AST/Redeclarable.h"35#include "clang/AST/Stmt.h"36#include "clang/AST/TemplateBase.h"37#include "clang/AST/Type.h"38#include "clang/AST/TypeLoc.h"39#include "clang/Basic/Builtins.h"40#include "clang/Basic/IdentifierTable.h"41#include "clang/Basic/LLVM.h"42#include "clang/Basic/LangOptions.h"43#include "clang/Basic/Linkage.h"44#include "clang/Basic/Module.h"45#include "clang/Basic/NoSanitizeList.h"46#include "clang/Basic/PartialDiagnostic.h"47#include "clang/Basic/Sanitizers.h"48#include "clang/Basic/SourceLocation.h"49#include "clang/Basic/SourceManager.h"50#include "clang/Basic/Specifiers.h"51#include "clang/Basic/TargetCXXABI.h"52#include "clang/Basic/TargetInfo.h"53#include "clang/Basic/Visibility.h"54#include "llvm/ADT/APSInt.h"55#include "llvm/ADT/ArrayRef.h"56#include "llvm/ADT/STLExtras.h"57#include "llvm/ADT/SmallVector.h"58#include "llvm/ADT/StringRef.h"59#include "llvm/ADT/StringSwitch.h"60#include "llvm/ADT/iterator_range.h"61#include "llvm/Support/Casting.h"62#include "llvm/Support/ErrorHandling.h"63#include "llvm/Support/raw_ostream.h"64#include "llvm/TargetParser/Triple.h"65#include <algorithm>66#include <cassert>67#include <cstddef>68#include <cstring>69#include <optional>70#include <string>71#include <tuple>72#include <type_traits>73 74using namespace clang;75 76Decl *clang::getPrimaryMergedDecl(Decl *D) {77  return D->getASTContext().getPrimaryMergedDecl(D);78}79 80void PrettyDeclStackTraceEntry::print(raw_ostream &OS) const {81  SourceLocation Loc = this->Loc;82  if (!Loc.isValid() && TheDecl) Loc = TheDecl->getLocation();83  if (Loc.isValid()) {84    Loc.print(OS, Context.getSourceManager());85    OS << ": ";86  }87  OS << Message;88 89  if (auto *ND = dyn_cast_if_present<NamedDecl>(TheDecl)) {90    OS << " '";91    ND->getNameForDiagnostic(OS, Context.getPrintingPolicy(), true);92    OS << "'";93  }94 95  OS << '\n';96}97 98// Defined here so that it can be inlined into its direct callers.99bool Decl::isOutOfLine() const {100  return !getLexicalDeclContext()->Equals(getDeclContext());101}102 103TranslationUnitDecl::TranslationUnitDecl(ASTContext &ctx)104    : Decl(TranslationUnit, nullptr, SourceLocation()),105      DeclContext(TranslationUnit), redeclarable_base(ctx), Ctx(ctx) {}106 107//===----------------------------------------------------------------------===//108// NamedDecl Implementation109//===----------------------------------------------------------------------===//110 111// Visibility rules aren't rigorously externally specified, but here112// are the basic principles behind what we implement:113//114// 1. An explicit visibility attribute is generally a direct expression115// of the user's intent and should be honored.  Only the innermost116// visibility attribute applies.  If no visibility attribute applies,117// global visibility settings are considered.118//119// 2. There is one caveat to the above: on or in a template pattern,120// an explicit visibility attribute is just a default rule, and121// visibility can be decreased by the visibility of template122// arguments.  But this, too, has an exception: an attribute on an123// explicit specialization or instantiation causes all the visibility124// restrictions of the template arguments to be ignored.125//126// 3. A variable that does not otherwise have explicit visibility can127// be restricted by the visibility of its type.128//129// 4. A visibility restriction is explicit if it comes from an130// attribute (or something like it), not a global visibility setting.131// When emitting a reference to an external symbol, visibility132// restrictions are ignored unless they are explicit.133//134// 5. When computing the visibility of a non-type, including a135// non-type member of a class, only non-type visibility restrictions136// are considered: the 'visibility' attribute, global value-visibility137// settings, and a few special cases like __private_extern.138//139// 6. When computing the visibility of a type, including a type member140// of a class, only type visibility restrictions are considered:141// the 'type_visibility' attribute and global type-visibility settings.142// However, a 'visibility' attribute counts as a 'type_visibility'143// attribute on any declaration that only has the former.144//145// The visibility of a "secondary" entity, like a template argument,146// is computed using the kind of that entity, not the kind of the147// primary entity for which we are computing visibility.  For example,148// the visibility of a specialization of either of these templates:149//   template <class T, bool (&compare)(T, X)> bool has_match(list<T>, X);150//   template <class T, bool (&compare)(T, X)> class matcher;151// is restricted according to the type visibility of the argument 'T',152// the type visibility of 'bool(&)(T,X)', and the value visibility of153// the argument function 'compare'.  That 'has_match' is a value154// and 'matcher' is a type only matters when looking for attributes155// and settings from the immediate context.156 157/// Does this computation kind permit us to consider additional158/// visibility settings from attributes and the like?159static bool hasExplicitVisibilityAlready(LVComputationKind computation) {160  return computation.IgnoreExplicitVisibility;161}162 163/// Given an LVComputationKind, return one of the same type/value sort164/// that records that it already has explicit visibility.165static LVComputationKind166withExplicitVisibilityAlready(LVComputationKind Kind) {167  Kind.IgnoreExplicitVisibility = true;168  return Kind;169}170 171static std::optional<Visibility> getExplicitVisibility(const NamedDecl *D,172                                                       LVComputationKind kind) {173  assert(!kind.IgnoreExplicitVisibility &&174         "asking for explicit visibility when we shouldn't be");175  return D->getExplicitVisibility(kind.getExplicitVisibilityKind());176}177 178/// Is the given declaration a "type" or a "value" for the purposes of179/// visibility computation?180static bool usesTypeVisibility(const NamedDecl *D) {181  return isa<TypeDecl>(D) ||182         isa<ClassTemplateDecl>(D) ||183         isa<ObjCInterfaceDecl>(D);184}185 186/// Does the given declaration have member specialization information,187/// and if so, is it an explicit specialization?188template <class T>189static std::enable_if_t<!std::is_base_of_v<RedeclarableTemplateDecl, T>, bool>190isExplicitMemberSpecialization(const T *D) {191  if (const MemberSpecializationInfo *member =192        D->getMemberSpecializationInfo()) {193    return member->isExplicitSpecialization();194  }195  return false;196}197 198/// For templates, this question is easier: a member template can't be199/// explicitly instantiated, so there's a single bit indicating whether200/// or not this is an explicit member specialization.201static bool isExplicitMemberSpecialization(const RedeclarableTemplateDecl *D) {202  return D->isMemberSpecialization();203}204 205/// Given a visibility attribute, return the explicit visibility206/// associated with it.207template <class T>208static Visibility getVisibilityFromAttr(const T *attr) {209  switch (attr->getVisibility()) {210  case T::Default:211    return DefaultVisibility;212  case T::Hidden:213    return HiddenVisibility;214  case T::Protected:215    return ProtectedVisibility;216  }217  llvm_unreachable("bad visibility kind");218}219 220/// Return the explicit visibility of the given declaration.221static std::optional<Visibility>222getVisibilityOf(const NamedDecl *D, NamedDecl::ExplicitVisibilityKind kind) {223  // If we're ultimately computing the visibility of a type, look for224  // a 'type_visibility' attribute before looking for 'visibility'.225  if (kind == NamedDecl::VisibilityForType) {226    if (const auto *A = D->getAttr<TypeVisibilityAttr>()) {227      return getVisibilityFromAttr(A);228    }229  }230 231  // If this declaration has an explicit visibility attribute, use it.232  if (const auto *A = D->getAttr<VisibilityAttr>()) {233    return getVisibilityFromAttr(A);234  }235 236  return std::nullopt;237}238 239LinkageInfo LinkageComputer::getLVForType(const Type &T,240                                          LVComputationKind computation) {241  if (computation.IgnoreAllVisibility)242    return LinkageInfo(T.getLinkage(), DefaultVisibility, true);243  return getTypeLinkageAndVisibility(&T);244}245 246/// Get the most restrictive linkage for the types in the given247/// template parameter list.  For visibility purposes, template248/// parameters are part of the signature of a template.249LinkageInfo LinkageComputer::getLVForTemplateParameterList(250    const TemplateParameterList *Params, LVComputationKind computation) {251  LinkageInfo LV;252  for (const NamedDecl *P : *Params) {253    // Template type parameters are the most common and never254    // contribute to visibility, pack or not.255    if (isa<TemplateTypeParmDecl>(P))256      continue;257 258    // Non-type template parameters can be restricted by the value type, e.g.259    //   template <enum X> class A { ... };260    // We have to be careful here, though, because we can be dealing with261    // dependent types.262    if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {263      // Handle the non-pack case first.264      if (!NTTP->isExpandedParameterPack()) {265        if (!NTTP->getType()->isDependentType()) {266          LV.merge(getLVForType(*NTTP->getType(), computation));267        }268        continue;269      }270 271      // Look at all the types in an expanded pack.272      for (unsigned i = 0, n = NTTP->getNumExpansionTypes(); i != n; ++i) {273        QualType type = NTTP->getExpansionType(i);274        if (!type->isDependentType())275          LV.merge(getTypeLinkageAndVisibility(type));276      }277      continue;278    }279 280    // Template template parameters can be restricted by their281    // template parameters, recursively.282    const auto *TTP = cast<TemplateTemplateParmDecl>(P);283 284    // Handle the non-pack case first.285    if (!TTP->isExpandedParameterPack()) {286      LV.merge(getLVForTemplateParameterList(TTP->getTemplateParameters(),287                                             computation));288      continue;289    }290 291    // Look at all expansions in an expanded pack.292    for (unsigned i = 0, n = TTP->getNumExpansionTemplateParameters();293           i != n; ++i) {294      LV.merge(getLVForTemplateParameterList(295          TTP->getExpansionTemplateParameters(i), computation));296    }297  }298 299  return LV;300}301 302static const Decl *getOutermostFuncOrBlockContext(const Decl *D) {303  const Decl *Ret = nullptr;304  const DeclContext *DC = D->getDeclContext();305  while (DC->getDeclKind() != Decl::TranslationUnit) {306    if (isa<FunctionDecl>(DC) || isa<BlockDecl>(DC))307      Ret = cast<Decl>(DC);308    DC = DC->getParent();309  }310  return Ret;311}312 313/// Get the most restrictive linkage for the types and314/// declarations in the given template argument list.315///316/// Note that we don't take an LVComputationKind because we always317/// want to honor the visibility of template arguments in the same way.318LinkageInfo319LinkageComputer::getLVForTemplateArgumentList(ArrayRef<TemplateArgument> Args,320                                              LVComputationKind computation) {321  LinkageInfo LV;322 323  for (const TemplateArgument &Arg : Args) {324    switch (Arg.getKind()) {325    case TemplateArgument::Null:326    case TemplateArgument::Integral:327    case TemplateArgument::Expression:328      continue;329 330    case TemplateArgument::Type:331      LV.merge(getLVForType(*Arg.getAsType(), computation));332      continue;333 334    case TemplateArgument::Declaration: {335      const NamedDecl *ND = Arg.getAsDecl();336      assert(!usesTypeVisibility(ND));337      LV.merge(getLVForDecl(ND, computation));338      continue;339    }340 341    case TemplateArgument::NullPtr:342      LV.merge(getTypeLinkageAndVisibility(Arg.getNullPtrType()));343      continue;344 345    case TemplateArgument::StructuralValue:346      LV.merge(getLVForValue(Arg.getAsStructuralValue(), computation));347      continue;348 349    case TemplateArgument::Template:350    case TemplateArgument::TemplateExpansion:351      if (TemplateDecl *Template =352              Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl(353                  /*IgnoreDeduced=*/true))354        LV.merge(getLVForDecl(Template, computation));355      continue;356 357    case TemplateArgument::Pack:358      LV.merge(getLVForTemplateArgumentList(Arg.getPackAsArray(), computation));359      continue;360    }361    llvm_unreachable("bad template argument kind");362  }363 364  return LV;365}366 367LinkageInfo368LinkageComputer::getLVForTemplateArgumentList(const TemplateArgumentList &TArgs,369                                              LVComputationKind computation) {370  return getLVForTemplateArgumentList(TArgs.asArray(), computation);371}372 373static bool shouldConsiderTemplateVisibility(const FunctionDecl *fn,374                        const FunctionTemplateSpecializationInfo *specInfo) {375  // Include visibility from the template parameters and arguments376  // only if this is not an explicit instantiation or specialization377  // with direct explicit visibility.  (Implicit instantiations won't378  // have a direct attribute.)379  if (!specInfo->isExplicitInstantiationOrSpecialization())380    return true;381 382  return !fn->hasAttr<VisibilityAttr>();383}384 385/// Merge in template-related linkage and visibility for the given386/// function template specialization.387///388/// We don't need a computation kind here because we can assume389/// LVForValue.390///391/// \param[out] LV the computation to use for the parent392void LinkageComputer::mergeTemplateLV(393    LinkageInfo &LV, const FunctionDecl *fn,394    const FunctionTemplateSpecializationInfo *specInfo,395    LVComputationKind computation) {396  bool considerVisibility =397    shouldConsiderTemplateVisibility(fn, specInfo);398 399  FunctionTemplateDecl *temp = specInfo->getTemplate();400  // Merge information from the template declaration.401  LinkageInfo tempLV = getLVForDecl(temp, computation);402  // The linkage and visibility of the specialization should be403  // consistent with the template declaration.404  LV.mergeMaybeWithVisibility(tempLV, considerVisibility);405 406  // Merge information from the template parameters.407  LinkageInfo paramsLV =408      getLVForTemplateParameterList(temp->getTemplateParameters(), computation);409  LV.mergeMaybeWithVisibility(paramsLV, considerVisibility);410 411  // Merge information from the template arguments.412  const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments;413  LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);414  LV.mergeMaybeWithVisibility(argsLV, considerVisibility);415}416 417/// Does the given declaration have a direct visibility attribute418/// that would match the given rules?419static bool hasDirectVisibilityAttribute(const NamedDecl *D,420                                         LVComputationKind computation) {421  if (computation.IgnoreAllVisibility)422    return false;423 424  return (computation.isTypeVisibility() && D->hasAttr<TypeVisibilityAttr>()) ||425         D->hasAttr<VisibilityAttr>();426}427 428/// Should we consider visibility associated with the template429/// arguments and parameters of the given class template specialization?430static bool shouldConsiderTemplateVisibility(431                                 const ClassTemplateSpecializationDecl *spec,432                                 LVComputationKind computation) {433  // Include visibility from the template parameters and arguments434  // only if this is not an explicit instantiation or specialization435  // with direct explicit visibility (and note that implicit436  // instantiations won't have a direct attribute).437  //438  // Furthermore, we want to ignore template parameters and arguments439  // for an explicit specialization when computing the visibility of a440  // member thereof with explicit visibility.441  //442  // This is a bit complex; let's unpack it.443  //444  // An explicit class specialization is an independent, top-level445  // declaration.  As such, if it or any of its members has an446  // explicit visibility attribute, that must directly express the447  // user's intent, and we should honor it.  The same logic applies to448  // an explicit instantiation of a member of such a thing.449 450  // Fast path: if this is not an explicit instantiation or451  // specialization, we always want to consider template-related452  // visibility restrictions.453  if (!spec->isExplicitInstantiationOrSpecialization())454    return true;455 456  // This is the 'member thereof' check.457  if (spec->isExplicitSpecialization() &&458      hasExplicitVisibilityAlready(computation))459    return false;460 461  return !hasDirectVisibilityAttribute(spec, computation);462}463 464/// Merge in template-related linkage and visibility for the given465/// class template specialization.466void LinkageComputer::mergeTemplateLV(467    LinkageInfo &LV, const ClassTemplateSpecializationDecl *spec,468    LVComputationKind computation) {469  bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);470 471  // Merge information from the template parameters, but ignore472  // visibility if we're only considering template arguments.473  ClassTemplateDecl *temp = spec->getSpecializedTemplate();474  // Merge information from the template declaration.475  LinkageInfo tempLV = getLVForDecl(temp, computation);476  // The linkage of the specialization should be consistent with the477  // template declaration.478  LV.setLinkage(tempLV.getLinkage());479 480  LinkageInfo paramsLV =481    getLVForTemplateParameterList(temp->getTemplateParameters(), computation);482  LV.mergeMaybeWithVisibility(paramsLV,483           considerVisibility && !hasExplicitVisibilityAlready(computation));484 485  // Merge information from the template arguments.  We ignore486  // template-argument visibility if we've got an explicit487  // instantiation with a visibility attribute.488  const TemplateArgumentList &templateArgs = spec->getTemplateArgs();489  LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);490  if (considerVisibility)491    LV.mergeVisibility(argsLV);492  LV.mergeExternalVisibility(argsLV);493}494 495/// Should we consider visibility associated with the template496/// arguments and parameters of the given variable template497/// specialization? As usual, follow class template specialization498/// logic up to initialization.499static bool shouldConsiderTemplateVisibility(500                                 const VarTemplateSpecializationDecl *spec,501                                 LVComputationKind computation) {502  // Include visibility from the template parameters and arguments503  // only if this is not an explicit instantiation or specialization504  // with direct explicit visibility (and note that implicit505  // instantiations won't have a direct attribute).506  if (!spec->isExplicitInstantiationOrSpecialization())507    return true;508 509  // An explicit variable specialization is an independent, top-level510  // declaration.  As such, if it has an explicit visibility attribute,511  // that must directly express the user's intent, and we should honor512  // it.513  if (spec->isExplicitSpecialization() &&514      hasExplicitVisibilityAlready(computation))515    return false;516 517  return !hasDirectVisibilityAttribute(spec, computation);518}519 520/// Merge in template-related linkage and visibility for the given521/// variable template specialization. As usual, follow class template522/// specialization logic up to initialization.523void LinkageComputer::mergeTemplateLV(LinkageInfo &LV,524                                      const VarTemplateSpecializationDecl *spec,525                                      LVComputationKind computation) {526  bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);527 528  // Merge information from the template parameters, but ignore529  // visibility if we're only considering template arguments.530  VarTemplateDecl *temp = spec->getSpecializedTemplate();531  LinkageInfo tempLV =532    getLVForTemplateParameterList(temp->getTemplateParameters(), computation);533  LV.mergeMaybeWithVisibility(tempLV,534           considerVisibility && !hasExplicitVisibilityAlready(computation));535 536  // Merge information from the template arguments.  We ignore537  // template-argument visibility if we've got an explicit538  // instantiation with a visibility attribute.539  const TemplateArgumentList &templateArgs = spec->getTemplateArgs();540  LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);541  if (considerVisibility)542    LV.mergeVisibility(argsLV);543  LV.mergeExternalVisibility(argsLV);544}545 546static bool useInlineVisibilityHidden(const NamedDecl *D) {547  // FIXME: we should warn if -fvisibility-inlines-hidden is used with c.548  const LangOptions &Opts = D->getASTContext().getLangOpts();549  if (!Opts.CPlusPlus || !Opts.InlineVisibilityHidden)550    return false;551 552  const auto *FD = dyn_cast<FunctionDecl>(D);553  if (!FD)554    return false;555 556  TemplateSpecializationKind TSK = TSK_Undeclared;557  if (FunctionTemplateSpecializationInfo *spec558      = FD->getTemplateSpecializationInfo()) {559    TSK = spec->getTemplateSpecializationKind();560  } else if (MemberSpecializationInfo *MSI =561             FD->getMemberSpecializationInfo()) {562    TSK = MSI->getTemplateSpecializationKind();563  }564 565  const FunctionDecl *Def = nullptr;566  // InlineVisibilityHidden only applies to definitions, and567  // isInlined() only gives meaningful answers on definitions568  // anyway.569  return TSK != TSK_ExplicitInstantiationDeclaration &&570    TSK != TSK_ExplicitInstantiationDefinition &&571    FD->hasBody(Def) && Def->isInlined() && !Def->hasAttr<GNUInlineAttr>();572}573 574template <typename T> static bool isFirstInExternCContext(T *D) {575  const T *First = D->getFirstDecl();576  return First->isInExternCContext();577}578 579static bool isSingleLineLanguageLinkage(const Decl &D) {580  if (const auto *SD = dyn_cast<LinkageSpecDecl>(D.getDeclContext()))581    if (!SD->hasBraces())582      return true;583  return false;584}585 586static LinkageInfo getExternalLinkageFor(const NamedDecl *D) {587  return LinkageInfo::external();588}589 590static StorageClass getStorageClass(const Decl *D) {591  if (auto *TD = dyn_cast<TemplateDecl>(D))592    D = TD->getTemplatedDecl();593  if (D) {594    if (auto *VD = dyn_cast<VarDecl>(D))595      return VD->getStorageClass();596    if (auto *FD = dyn_cast<FunctionDecl>(D))597      return FD->getStorageClass();598  }599  return SC_None;600}601 602LinkageInfo603LinkageComputer::getLVForNamespaceScopeDecl(const NamedDecl *D,604                                            LVComputationKind computation,605                                            bool IgnoreVarTypeLinkage) {606  assert(D->getDeclContext()->getRedeclContext()->isFileContext() &&607         "Not a name having namespace scope");608  ASTContext &Context = D->getASTContext();609  const auto *Var = dyn_cast<VarDecl>(D);610 611  // C++ [basic.link]p3:612  //   A name having namespace scope (3.3.6) has internal linkage if it613  //   is the name of614 615  if ((getStorageClass(D->getCanonicalDecl()) == SC_Static) ||616      (Context.getLangOpts().C23 && Var && Var->isConstexpr())) {617    // - a variable, variable template, function, or function template618    //   that is explicitly declared static; or619    // (This bullet corresponds to C99 6.2.2p3.)620 621    // C23 6.2.2p3622    // If the declaration of a file scope identifier for623    // an object contains any of the storage-class specifiers static or624    // constexpr then the identifier has internal linkage.625    return LinkageInfo::internal();626  }627 628  if (Var) {629    // - a non-template variable of non-volatile const-qualified type, unless630    //   - it is explicitly declared extern, or631    //   - it is declared in the purview of a module interface unit632    //     (outside the private-module-fragment, if any) or module partition, or633    //   - it is inline, or634    //   - it was previously declared and the prior declaration did not have635    //     internal linkage636    // (There is no equivalent in C99.)637    if (Context.getLangOpts().CPlusPlus && Var->getType().isConstQualified() &&638        !Var->getType().isVolatileQualified() && !Var->isInline() &&639        ![Var]() {640          // Check if it is module purview except private module fragment641          // and implementation unit.642          if (auto *M = Var->getOwningModule())643            return M->isInterfaceOrPartition() || M->isImplicitGlobalModule();644          return false;645        }() &&646        !isa<VarTemplateSpecializationDecl>(Var) &&647        !Var->getDescribedVarTemplate()) {648      const VarDecl *PrevVar = Var->getPreviousDecl();649      if (PrevVar)650        return getLVForDecl(PrevVar, computation);651 652      if (Var->getStorageClass() != SC_Extern &&653          Var->getStorageClass() != SC_PrivateExtern &&654          !isSingleLineLanguageLinkage(*Var))655        return LinkageInfo::internal();656    }657 658    for (const VarDecl *PrevVar = Var->getPreviousDecl(); PrevVar;659         PrevVar = PrevVar->getPreviousDecl()) {660      if (PrevVar->getStorageClass() == SC_PrivateExtern &&661          Var->getStorageClass() == SC_None)662        return getDeclLinkageAndVisibility(PrevVar);663      // Explicitly declared static.664      if (PrevVar->getStorageClass() == SC_Static)665        return LinkageInfo::internal();666    }667  } else if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D)) {668    //   - a data member of an anonymous union.669    const VarDecl *VD = IFD->getVarDecl();670    assert(VD && "Expected a VarDecl in this IndirectFieldDecl!");671    return getLVForNamespaceScopeDecl(VD, computation, IgnoreVarTypeLinkage);672  }673  assert(!isa<FieldDecl>(D) && "Didn't expect a FieldDecl!");674 675  // FIXME: This gives internal linkage to names that should have no linkage676  // (those not covered by [basic.link]p6).677  if (D->isInAnonymousNamespace()) {678    const auto *Var = dyn_cast<VarDecl>(D);679    const auto *Func = dyn_cast<FunctionDecl>(D);680    // FIXME: The check for extern "C" here is not justified by the standard681    // wording, but we retain it from the pre-DR1113 model to avoid breaking682    // code.683    //684    // C++11 [basic.link]p4:685    //   An unnamed namespace or a namespace declared directly or indirectly686    //   within an unnamed namespace has internal linkage.687    if ((!Var || !isFirstInExternCContext(Var)) &&688        (!Func || !isFirstInExternCContext(Func)))689      return LinkageInfo::internal();690  }691 692  // Set up the defaults.693 694  // C99 6.2.2p5:695  //   If the declaration of an identifier for an object has file696  //   scope and no storage-class specifier, its linkage is697  //   external.698  LinkageInfo LV = getExternalLinkageFor(D);699 700  if (!hasExplicitVisibilityAlready(computation)) {701    if (std::optional<Visibility> Vis = getExplicitVisibility(D, computation)) {702      LV.mergeVisibility(*Vis, true);703    } else {704      // If we're declared in a namespace with a visibility attribute,705      // use that namespace's visibility, and it still counts as explicit.706      for (const DeclContext *DC = D->getDeclContext();707           !isa<TranslationUnitDecl>(DC);708           DC = DC->getParent()) {709        const auto *ND = dyn_cast<NamespaceDecl>(DC);710        if (!ND) continue;711        if (std::optional<Visibility> Vis =712                getExplicitVisibility(ND, computation)) {713          LV.mergeVisibility(*Vis, true);714          break;715        }716      }717    }718 719    // Add in global settings if the above didn't give us direct visibility.720    if (!LV.isVisibilityExplicit()) {721      // Use global type/value visibility as appropriate.722      Visibility globalVisibility =723          computation.isValueVisibility()724              ? Context.getLangOpts().getValueVisibilityMode()725              : Context.getLangOpts().getTypeVisibilityMode();726      LV.mergeVisibility(globalVisibility, /*explicit*/ false);727 728      // If we're paying attention to global visibility, apply729      // -finline-visibility-hidden if this is an inline method.730      if (useInlineVisibilityHidden(D))731        LV.mergeVisibility(HiddenVisibility, /*visibilityExplicit=*/false);732    }733  }734 735  // C++ [basic.link]p4:736 737  //   A name having namespace scope that has not been given internal linkage738  //   above and that is the name of739  //   [...bullets...]740  //   has its linkage determined as follows:741  //     - if the enclosing namespace has internal linkage, the name has742  //       internal linkage; [handled above]743  //     - otherwise, if the declaration of the name is attached to a named744  //       module and is not exported, the name has module linkage;745  //     - otherwise, the name has external linkage.746  // LV is currently set up to handle the last two bullets.747  //748  //   The bullets are:749 750  //     - a variable; or751  if (const auto *Var = dyn_cast<VarDecl>(D)) {752    // GCC applies the following optimization to variables and static753    // data members, but not to functions:754    //755    // Modify the variable's LV by the LV of its type unless this is756    // C or extern "C".  This follows from [basic.link]p9:757    //   A type without linkage shall not be used as the type of a758    //   variable or function with external linkage unless759    //    - the entity has C language linkage, or760    //    - the entity is declared within an unnamed namespace, or761    //    - the entity is not used or is defined in the same762    //      translation unit.763    // and [basic.link]p10:764    //   ...the types specified by all declarations referring to a765    //   given variable or function shall be identical...766    // C does not have an equivalent rule.767    //768    // Ignore this if we've got an explicit attribute;  the user769    // probably knows what they're doing.770    //771    // Note that we don't want to make the variable non-external772    // because of this, but unique-external linkage suits us.773 774    if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Var) &&775        !IgnoreVarTypeLinkage) {776      LinkageInfo TypeLV = getLVForType(*Var->getType(), computation);777      if (!isExternallyVisible(TypeLV.getLinkage()))778        return LinkageInfo::uniqueExternal();779      if (!LV.isVisibilityExplicit())780        LV.mergeVisibility(TypeLV);781    }782 783    if (Var->getStorageClass() == SC_PrivateExtern)784      LV.mergeVisibility(HiddenVisibility, true);785 786    // Note that Sema::MergeVarDecl already takes care of implementing787    // C99 6.2.2p4 and propagating the visibility attribute, so we don't have788    // to do it here.789 790    // As per function and class template specializations (below),791    // consider LV for the template and template arguments.  We're at file792    // scope, so we do not need to worry about nested specializations.793    if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(Var)) {794      mergeTemplateLV(LV, spec, computation);795    }796 797  //     - a function; or798  } else if (const auto *Function = dyn_cast<FunctionDecl>(D)) {799    // In theory, we can modify the function's LV by the LV of its800    // type unless it has C linkage (see comment above about variables801    // for justification).  In practice, GCC doesn't do this, so it's802    // just too painful to make work.803 804    if (Function->getStorageClass() == SC_PrivateExtern)805      LV.mergeVisibility(HiddenVisibility, true);806 807    // OpenMP target declare device functions are not callable from the host so808    // they should not be exported from the device image. This applies to all809    // functions as the host-callable kernel functions are emitted at codegen.810    if (Context.getLangOpts().OpenMP &&811        Context.getLangOpts().OpenMPIsTargetDevice &&812        (Context.getTargetInfo().getTriple().isGPU() ||813         OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Function)))814      LV.mergeVisibility(HiddenVisibility, /*newExplicit=*/false);815 816    // Note that Sema::MergeCompatibleFunctionDecls already takes care of817    // merging storage classes and visibility attributes, so we don't have to818    // look at previous decls in here.819 820    // In C++, then if the type of the function uses a type with821    // unique-external linkage, it's not legally usable from outside822    // this translation unit.  However, we should use the C linkage823    // rules instead for extern "C" declarations.824    if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Function)) {825      // Only look at the type-as-written. Otherwise, deducing the return type826      // of a function could change its linkage.827      QualType TypeAsWritten = Function->getType();828      if (TypeSourceInfo *TSI = Function->getTypeSourceInfo())829        TypeAsWritten = TSI->getType();830      if (!isExternallyVisible(TypeAsWritten->getLinkage()))831        return LinkageInfo::uniqueExternal();832    }833 834    // Consider LV from the template and the template arguments.835    // We're at file scope, so we do not need to worry about nested836    // specializations.837    if (FunctionTemplateSpecializationInfo *specInfo838                               = Function->getTemplateSpecializationInfo()) {839      mergeTemplateLV(LV, Function, specInfo, computation);840    }841 842  //     - a named class (Clause 9), or an unnamed class defined in a843  //       typedef declaration in which the class has the typedef name844  //       for linkage purposes (7.1.3); or845  //     - a named enumeration (7.2), or an unnamed enumeration846  //       defined in a typedef declaration in which the enumeration847  //       has the typedef name for linkage purposes (7.1.3); or848  } else if (const auto *Tag = dyn_cast<TagDecl>(D)) {849    // Unnamed tags have no linkage.850    if (!Tag->hasNameForLinkage())851      return LinkageInfo::none();852 853    // If this is a class template specialization, consider the854    // linkage of the template and template arguments.  We're at file855    // scope, so we do not need to worry about nested specializations.856    if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {857      mergeTemplateLV(LV, spec, computation);858    }859 860  // FIXME: This is not part of the C++ standard any more.861  //     - an enumerator belonging to an enumeration with external linkage; or862  } else if (isa<EnumConstantDecl>(D)) {863    LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()),864                                      computation);865    if (!isExternalFormalLinkage(EnumLV.getLinkage()))866      return LinkageInfo::none();867    LV.merge(EnumLV);868 869  //     - a template870  } else if (const auto *temp = dyn_cast<TemplateDecl>(D)) {871    bool considerVisibility = !hasExplicitVisibilityAlready(computation);872    LinkageInfo tempLV =873      getLVForTemplateParameterList(temp->getTemplateParameters(), computation);874    LV.mergeMaybeWithVisibility(tempLV, considerVisibility);875 876  //     An unnamed namespace or a namespace declared directly or indirectly877  //     within an unnamed namespace has internal linkage. All other namespaces878  //     have external linkage.879  //880  // We handled names in anonymous namespaces above.881  } else if (isa<NamespaceDecl>(D)) {882    return LV;883 884  // By extension, we assign external linkage to Objective-C885  // interfaces.886  } else if (isa<ObjCInterfaceDecl>(D)) {887    // fallout888 889  } else if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {890    // A typedef declaration has linkage if it gives a type a name for891    // linkage purposes.892    if (!TD->getAnonDeclWithTypedefName(/*AnyRedecl*/true))893      return LinkageInfo::none();894 895  } else if (isa<MSGuidDecl>(D)) {896    // A GUID behaves like an inline variable with external linkage. Fall897    // through.898 899  // Everything not covered here has no linkage.900  } else {901    return LinkageInfo::none();902  }903 904  // If we ended up with non-externally-visible linkage, visibility should905  // always be default.906  if (!isExternallyVisible(LV.getLinkage()))907    return LinkageInfo(LV.getLinkage(), DefaultVisibility, false);908 909  return LV;910}911 912LinkageInfo913LinkageComputer::getLVForClassMember(const NamedDecl *D,914                                     LVComputationKind computation,915                                     bool IgnoreVarTypeLinkage) {916  // Only certain class members have linkage.  Note that fields don't917  // really have linkage, but it's convenient to say they do for the918  // purposes of calculating linkage of pointer-to-data-member919  // template arguments.920  //921  // Templates also don't officially have linkage, but since we ignore922  // the C++ standard and look at template arguments when determining923  // linkage and visibility of a template specialization, we might hit924  // a template template argument that way. If we do, we need to925  // consider its linkage.926  if (!(isa<CXXMethodDecl>(D) ||927        isa<VarDecl>(D) ||928        isa<FieldDecl>(D) ||929        isa<IndirectFieldDecl>(D) ||930        isa<TagDecl>(D) ||931        isa<TemplateDecl>(D)))932    return LinkageInfo::none();933 934  LinkageInfo LV;935 936  // If we have an explicit visibility attribute, merge that in.937  if (!hasExplicitVisibilityAlready(computation)) {938    if (std::optional<Visibility> Vis = getExplicitVisibility(D, computation))939      LV.mergeVisibility(*Vis, true);940    // If we're paying attention to global visibility, apply941    // -finline-visibility-hidden if this is an inline method.942    //943    // Note that we do this before merging information about944    // the class visibility.945    if (!LV.isVisibilityExplicit() && useInlineVisibilityHidden(D))946      LV.mergeVisibility(HiddenVisibility, /*visibilityExplicit=*/false);947  }948 949  // If this class member has an explicit visibility attribute, the only950  // thing that can change its visibility is the template arguments, so951  // only look for them when processing the class.952  LVComputationKind classComputation = computation;953  if (LV.isVisibilityExplicit())954    classComputation = withExplicitVisibilityAlready(computation);955 956  LinkageInfo classLV =957    getLVForDecl(cast<RecordDecl>(D->getDeclContext()), classComputation);958  // The member has the same linkage as the class. If that's not externally959  // visible, we don't need to compute anything about the linkage.960  // FIXME: If we're only computing linkage, can we bail out here?961  if (!isExternallyVisible(classLV.getLinkage()))962    return classLV;963 964 965  // Otherwise, don't merge in classLV yet, because in certain cases966  // we need to completely ignore the visibility from it.967 968  // Specifically, if this decl exists and has an explicit attribute.969  const NamedDecl *explicitSpecSuppressor = nullptr;970 971  if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {972    // Only look at the type-as-written. Otherwise, deducing the return type973    // of a function could change its linkage.974    QualType TypeAsWritten = MD->getType();975    if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())976      TypeAsWritten = TSI->getType();977    if (!isExternallyVisible(TypeAsWritten->getLinkage()))978      return LinkageInfo::uniqueExternal();979 980    // If this is a method template specialization, use the linkage for981    // the template parameters and arguments.982    if (FunctionTemplateSpecializationInfo *spec983           = MD->getTemplateSpecializationInfo()) {984      mergeTemplateLV(LV, MD, spec, computation);985      if (spec->isExplicitSpecialization()) {986        explicitSpecSuppressor = MD;987      } else if (isExplicitMemberSpecialization(spec->getTemplate())) {988        explicitSpecSuppressor = spec->getTemplate()->getTemplatedDecl();989      }990    } else if (isExplicitMemberSpecialization(MD)) {991      explicitSpecSuppressor = MD;992    }993 994    // OpenMP target declare device functions are not callable from the host so995    // they should not be exported from the device image. This applies to all996    // functions as the host-callable kernel functions are emitted at codegen.997    ASTContext &Context = D->getASTContext();998    if (Context.getLangOpts().OpenMP &&999        Context.getLangOpts().OpenMPIsTargetDevice &&1000        ((Context.getTargetInfo().getTriple().isAMDGPU() ||1001          Context.getTargetInfo().getTriple().isNVPTX()) ||1002         OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(MD)))1003      LV.mergeVisibility(HiddenVisibility, /*newExplicit=*/false);1004 1005  } else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {1006    if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {1007      mergeTemplateLV(LV, spec, computation);1008      if (spec->isExplicitSpecialization()) {1009        explicitSpecSuppressor = spec;1010      } else {1011        const ClassTemplateDecl *temp = spec->getSpecializedTemplate();1012        if (isExplicitMemberSpecialization(temp)) {1013          explicitSpecSuppressor = temp->getTemplatedDecl();1014        }1015      }1016    } else if (isExplicitMemberSpecialization(RD)) {1017      explicitSpecSuppressor = RD;1018    }1019 1020  // Static data members.1021  } else if (const auto *VD = dyn_cast<VarDecl>(D)) {1022    if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(VD))1023      mergeTemplateLV(LV, spec, computation);1024 1025    // Modify the variable's linkage by its type, but ignore the1026    // type's visibility unless it's a definition.1027    if (!IgnoreVarTypeLinkage) {1028      LinkageInfo typeLV = getLVForType(*VD->getType(), computation);1029      // FIXME: If the type's linkage is not externally visible, we can1030      // give this static data member UniqueExternalLinkage.1031      if (!LV.isVisibilityExplicit() && !classLV.isVisibilityExplicit())1032        LV.mergeVisibility(typeLV);1033      LV.mergeExternalVisibility(typeLV);1034    }1035 1036    if (isExplicitMemberSpecialization(VD)) {1037      explicitSpecSuppressor = VD;1038    }1039 1040  // Template members.1041  } else if (const auto *temp = dyn_cast<TemplateDecl>(D)) {1042    bool considerVisibility =1043      (!LV.isVisibilityExplicit() &&1044       !classLV.isVisibilityExplicit() &&1045       !hasExplicitVisibilityAlready(computation));1046    LinkageInfo tempLV =1047      getLVForTemplateParameterList(temp->getTemplateParameters(), computation);1048    LV.mergeMaybeWithVisibility(tempLV, considerVisibility);1049 1050    if (const auto *redeclTemp = dyn_cast<RedeclarableTemplateDecl>(temp)) {1051      if (isExplicitMemberSpecialization(redeclTemp)) {1052        explicitSpecSuppressor = temp->getTemplatedDecl();1053      } else if (const RedeclarableTemplateDecl *from =1054                     redeclTemp->getInstantiatedFromMemberTemplate()) {1055        // If no explicit visibility is specified yet, and this is an1056        // instantiated member of a template, look up visibility there1057        // as well.1058        LinkageInfo fromLV = from->getLinkageAndVisibility();1059        LV.mergeMaybeWithVisibility(fromLV, considerVisibility);1060      }1061    }1062  }1063 1064  // We should never be looking for an attribute directly on a template.1065  assert(!explicitSpecSuppressor || !isa<TemplateDecl>(explicitSpecSuppressor));1066 1067  // If this member is an explicit member specialization, and it has1068  // an explicit attribute, ignore visibility from the parent.1069  bool considerClassVisibility = true;1070  if (explicitSpecSuppressor &&1071      // optimization: hasDVA() is true only with explicit visibility.1072      LV.isVisibilityExplicit() &&1073      classLV.getVisibility() != DefaultVisibility &&1074      hasDirectVisibilityAttribute(explicitSpecSuppressor, computation)) {1075    considerClassVisibility = false;1076  }1077 1078  // Finally, merge in information from the class.1079  LV.mergeMaybeWithVisibility(classLV, considerClassVisibility);1080  return LV;1081}1082 1083void NamedDecl::anchor() {}1084 1085bool NamedDecl::isLinkageValid() const {1086  if (!hasCachedLinkage())1087    return true;1088 1089  Linkage L = LinkageComputer{}1090                  .computeLVForDecl(this, LVComputationKind::forLinkageOnly())1091                  .getLinkage();1092  return L == getCachedLinkage();1093}1094 1095bool NamedDecl::isPlaceholderVar(const LangOptions &LangOpts) const {1096  // [C++2c] [basic.scope.scope]/p51097  // A declaration is name-independent if its name is _ and it declares1098  // - a variable with automatic storage duration,1099  // - a structured binding not inhabiting a namespace scope,1100  // - the variable introduced by an init-capture1101  // - or a non-static data member.1102 1103  if (!LangOpts.CPlusPlus || !getIdentifier() ||1104      !getIdentifier()->isPlaceholder())1105    return false;1106  if (isa<FieldDecl>(this))1107    return true;1108  if (const auto *IFD = dyn_cast<IndirectFieldDecl>(this)) {1109    if (!getDeclContext()->isFunctionOrMethod() &&1110        !getDeclContext()->isRecord())1111      return false;1112    const VarDecl *VD = IFD->getVarDecl();1113    return !VD || VD->getStorageDuration() == SD_Automatic;1114  }1115  // and it declares a variable with automatic storage duration1116  if (const auto *VD = dyn_cast<VarDecl>(this)) {1117    if (isa<ParmVarDecl>(VD))1118      return false;1119    if (VD->isInitCapture())1120      return true;1121    return VD->getStorageDuration() == StorageDuration::SD_Automatic;1122  }1123  if (const auto *BD = dyn_cast<BindingDecl>(this);1124      BD && getDeclContext()->isFunctionOrMethod()) {1125    const VarDecl *VD = BD->getHoldingVar();1126    return !VD || VD->getStorageDuration() == StorageDuration::SD_Automatic;1127  }1128  return false;1129}1130 1131ReservedIdentifierStatus1132NamedDecl::isReserved(const LangOptions &LangOpts) const {1133  const IdentifierInfo *II = getIdentifier();1134 1135  // This triggers at least for CXXLiteralIdentifiers, which we already checked1136  // at lexing time.1137  if (!II)1138    return ReservedIdentifierStatus::NotReserved;1139 1140  ReservedIdentifierStatus Status = II->isReserved(LangOpts);1141  if (isReservedAtGlobalScope(Status) && !isReservedInAllContexts(Status)) {1142    // This name is only reserved at global scope. Check if this declaration1143    // conflicts with a global scope declaration.1144    if (isa<ParmVarDecl>(this) || isTemplateParameter())1145      return ReservedIdentifierStatus::NotReserved;1146 1147    // C++ [dcl.link]/7:1148    //   Two declarations [conflict] if [...] one declares a function or1149    //   variable with C language linkage, and the other declares [...] a1150    //   variable that belongs to the global scope.1151    //1152    // Therefore names that are reserved at global scope are also reserved as1153    // names of variables and functions with C language linkage.1154    const DeclContext *DC = getDeclContext()->getRedeclContext();1155    if (DC->isTranslationUnit())1156      return Status;1157    if (auto *VD = dyn_cast<VarDecl>(this))1158      if (VD->isExternC())1159        return ReservedIdentifierStatus::StartsWithUnderscoreAndIsExternC;1160    if (auto *FD = dyn_cast<FunctionDecl>(this))1161      if (FD->isExternC())1162        return ReservedIdentifierStatus::StartsWithUnderscoreAndIsExternC;1163    return ReservedIdentifierStatus::NotReserved;1164  }1165 1166  return Status;1167}1168 1169ObjCStringFormatFamily NamedDecl::getObjCFStringFormattingFamily() const {1170  StringRef name = getName();1171  if (name.empty()) return SFF_None;1172 1173  if (name.front() == 'C')1174    if (name == "CFStringCreateWithFormat" ||1175        name == "CFStringCreateWithFormatAndArguments" ||1176        name == "CFStringAppendFormat" ||1177        name == "CFStringAppendFormatAndArguments")1178      return SFF_CFString;1179  return SFF_None;1180}1181 1182Linkage NamedDecl::getLinkageInternal() const {1183  // We don't care about visibility here, so ask for the cheapest1184  // possible visibility analysis.1185  return LinkageComputer{}1186      .getLVForDecl(this, LVComputationKind::forLinkageOnly())1187      .getLinkage();1188}1189 1190static bool isExportedFromModuleInterfaceUnit(const NamedDecl *D) {1191  // FIXME: Handle isModulePrivate.1192  switch (D->getModuleOwnershipKind()) {1193  case Decl::ModuleOwnershipKind::Unowned:1194  case Decl::ModuleOwnershipKind::ReachableWhenImported:1195  case Decl::ModuleOwnershipKind::ModulePrivate:1196    return false;1197  case Decl::ModuleOwnershipKind::Visible:1198  case Decl::ModuleOwnershipKind::VisibleWhenImported:1199    return D->isInNamedModule();1200  }1201  llvm_unreachable("unexpected module ownership kind");1202}1203 1204/// Get the linkage from a semantic point of view. Entities in1205/// anonymous namespaces are external (in c++98).1206Linkage NamedDecl::getFormalLinkage() const {1207  Linkage InternalLinkage = getLinkageInternal();1208 1209  // C++ [basic.link]p4.8:1210  //   - if the declaration of the name is attached to a named module and is not1211  //   exported1212  //     the name has module linkage;1213  //1214  // [basic.namespace.general]/p21215  //   A namespace is never attached to a named module and never has a name with1216  //   module linkage.1217  if (isInNamedModule() && InternalLinkage == Linkage::External &&1218      !isExportedFromModuleInterfaceUnit(1219          cast<NamedDecl>(this->getCanonicalDecl())) &&1220      !isa<NamespaceDecl>(this))1221    InternalLinkage = Linkage::Module;1222 1223  return clang::getFormalLinkage(InternalLinkage);1224}1225 1226LinkageInfo NamedDecl::getLinkageAndVisibility() const {1227  return LinkageComputer{}.getDeclLinkageAndVisibility(this);1228}1229 1230static std::optional<Visibility>1231getExplicitVisibilityAux(const NamedDecl *ND,1232                         NamedDecl::ExplicitVisibilityKind kind,1233                         bool IsMostRecent) {1234  assert(!IsMostRecent || ND == ND->getMostRecentDecl());1235 1236  if (isa<ConceptDecl>(ND))1237    return {};1238 1239  // Check the declaration itself first.1240  if (std::optional<Visibility> V = getVisibilityOf(ND, kind))1241    return V;1242 1243  // If this is a member class of a specialization of a class template1244  // and the corresponding decl has explicit visibility, use that.1245  if (const auto *RD = dyn_cast<CXXRecordDecl>(ND)) {1246    CXXRecordDecl *InstantiatedFrom = RD->getInstantiatedFromMemberClass();1247    if (InstantiatedFrom)1248      return getVisibilityOf(InstantiatedFrom, kind);1249  }1250 1251  // If there wasn't explicit visibility there, and this is a1252  // specialization of a class template, check for visibility1253  // on the pattern.1254  if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(ND)) {1255    // Walk all the template decl till this point to see if there are1256    // explicit visibility attributes.1257    const auto *TD = spec->getSpecializedTemplate()->getTemplatedDecl();1258    while (TD != nullptr) {1259      auto Vis = getVisibilityOf(TD, kind);1260      if (Vis != std::nullopt)1261        return Vis;1262      TD = TD->getPreviousDecl();1263    }1264    return std::nullopt;1265  }1266 1267  // Use the most recent declaration.1268  if (!IsMostRecent && !isa<NamespaceDecl>(ND)) {1269    const NamedDecl *MostRecent = ND->getMostRecentDecl();1270    if (MostRecent != ND)1271      return getExplicitVisibilityAux(MostRecent, kind, true);1272  }1273 1274  if (const auto *Var = dyn_cast<VarDecl>(ND)) {1275    if (Var->isStaticDataMember()) {1276      VarDecl *InstantiatedFrom = Var->getInstantiatedFromStaticDataMember();1277      if (InstantiatedFrom)1278        return getVisibilityOf(InstantiatedFrom, kind);1279    }1280 1281    if (const auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Var))1282      return getVisibilityOf(VTSD->getSpecializedTemplate()->getTemplatedDecl(),1283                             kind);1284 1285    return std::nullopt;1286  }1287  // Also handle function template specializations.1288  if (const auto *fn = dyn_cast<FunctionDecl>(ND)) {1289    // If the function is a specialization of a template with an1290    // explicit visibility attribute, use that.1291    if (FunctionTemplateSpecializationInfo *templateInfo1292          = fn->getTemplateSpecializationInfo())1293      return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl(),1294                             kind);1295 1296    // If the function is a member of a specialization of a class template1297    // and the corresponding decl has explicit visibility, use that.1298    FunctionDecl *InstantiatedFrom = fn->getInstantiatedFromMemberFunction();1299    if (InstantiatedFrom)1300      return getVisibilityOf(InstantiatedFrom, kind);1301 1302    return std::nullopt;1303  }1304 1305  // The visibility of a template is stored in the templated decl.1306  if (const auto *TD = dyn_cast<TemplateDecl>(ND))1307    return getVisibilityOf(TD->getTemplatedDecl(), kind);1308 1309  return std::nullopt;1310}1311 1312std::optional<Visibility>1313NamedDecl::getExplicitVisibility(ExplicitVisibilityKind kind) const {1314  return getExplicitVisibilityAux(this, kind, false);1315}1316 1317LinkageInfo LinkageComputer::getLVForClosure(const DeclContext *DC,1318                                             Decl *ContextDecl,1319                                             LVComputationKind computation) {1320  // This lambda has its linkage/visibility determined by its owner.1321  const NamedDecl *Owner;1322  if (!ContextDecl)1323    Owner = dyn_cast<NamedDecl>(DC);1324  else if (isa<ParmVarDecl>(ContextDecl))1325    Owner =1326        dyn_cast<NamedDecl>(ContextDecl->getDeclContext()->getRedeclContext());1327  else if (isa<ImplicitConceptSpecializationDecl>(ContextDecl)) {1328    // Replace with the concept's owning decl, which is either a namespace or a1329    // TU, so this needs a dyn_cast.1330    Owner = dyn_cast<NamedDecl>(ContextDecl->getDeclContext());1331  } else {1332    Owner = cast<NamedDecl>(ContextDecl);1333  }1334 1335  if (!Owner)1336    return LinkageInfo::none();1337 1338  // If the owner has a deduced type, we need to skip querying the linkage and1339  // visibility of that type, because it might involve this closure type.  The1340  // only effect of this is that we might give a lambda VisibleNoLinkage rather1341  // than NoLinkage when we don't strictly need to, which is benign.1342  auto *VD = dyn_cast<VarDecl>(Owner);1343  LinkageInfo OwnerLV =1344      VD && VD->getType()->getContainedDeducedType()1345          ? computeLVForDecl(Owner, computation, /*IgnoreVarTypeLinkage*/true)1346          : getLVForDecl(Owner, computation);1347 1348  // A lambda never formally has linkage. But if the owner is externally1349  // visible, then the lambda is too. We apply the same rules to blocks.1350  if (!isExternallyVisible(OwnerLV.getLinkage()))1351    return LinkageInfo::none();1352  return LinkageInfo(Linkage::VisibleNone, OwnerLV.getVisibility(),1353                     OwnerLV.isVisibilityExplicit());1354}1355 1356LinkageInfo LinkageComputer::getLVForLocalDecl(const NamedDecl *D,1357                                               LVComputationKind computation) {1358  if (const auto *Function = dyn_cast<FunctionDecl>(D)) {1359    if (Function->isInAnonymousNamespace() &&1360        !isFirstInExternCContext(Function))1361      return LinkageInfo::internal();1362 1363    // This is a "void f();" which got merged with a file static.1364    if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)1365      return LinkageInfo::internal();1366 1367    LinkageInfo LV;1368    if (!hasExplicitVisibilityAlready(computation)) {1369      if (std::optional<Visibility> Vis =1370              getExplicitVisibility(Function, computation))1371        LV.mergeVisibility(*Vis, true);1372    }1373 1374    // Note that Sema::MergeCompatibleFunctionDecls already takes care of1375    // merging storage classes and visibility attributes, so we don't have to1376    // look at previous decls in here.1377 1378    return LV;1379  }1380 1381  if (const auto *Var = dyn_cast<VarDecl>(D)) {1382    if (Var->hasExternalStorage()) {1383      if (Var->isInAnonymousNamespace() && !isFirstInExternCContext(Var))1384        return LinkageInfo::internal();1385 1386      LinkageInfo LV;1387      if (Var->getStorageClass() == SC_PrivateExtern)1388        LV.mergeVisibility(HiddenVisibility, true);1389      else if (!hasExplicitVisibilityAlready(computation)) {1390        if (std::optional<Visibility> Vis =1391                getExplicitVisibility(Var, computation))1392          LV.mergeVisibility(*Vis, true);1393      }1394 1395      if (const VarDecl *Prev = Var->getPreviousDecl()) {1396        LinkageInfo PrevLV = getLVForDecl(Prev, computation);1397        if (PrevLV.getLinkage() != Linkage::Invalid)1398          LV.setLinkage(PrevLV.getLinkage());1399        LV.mergeVisibility(PrevLV);1400      }1401 1402      return LV;1403    }1404 1405    if (!Var->isStaticLocal())1406      return LinkageInfo::none();1407  }1408 1409  ASTContext &Context = D->getASTContext();1410  if (!Context.getLangOpts().CPlusPlus)1411    return LinkageInfo::none();1412 1413  const Decl *OuterD = getOutermostFuncOrBlockContext(D);1414  if (!OuterD || OuterD->isInvalidDecl())1415    return LinkageInfo::none();1416 1417  LinkageInfo LV;1418  if (const auto *BD = dyn_cast<BlockDecl>(OuterD)) {1419    if (!BD->getBlockManglingNumber())1420      return LinkageInfo::none();1421 1422    LV = getLVForClosure(BD->getDeclContext()->getRedeclContext(),1423                         BD->getBlockManglingContextDecl(), computation);1424  } else {1425    const auto *FD = cast<FunctionDecl>(OuterD);1426    if (!FD->isInlined() &&1427        !isTemplateInstantiation(FD->getTemplateSpecializationKind()))1428      return LinkageInfo::none();1429 1430    // If a function is hidden by -fvisibility-inlines-hidden option and1431    // is not explicitly attributed as a hidden function,1432    // we should not make static local variables in the function hidden.1433    LV = getLVForDecl(FD, computation);1434    if (isa<VarDecl>(D) && useInlineVisibilityHidden(FD) &&1435        !LV.isVisibilityExplicit() &&1436        !Context.getLangOpts().VisibilityInlinesHiddenStaticLocalVar) {1437      assert(cast<VarDecl>(D)->isStaticLocal());1438      // If this was an implicitly hidden inline method, check again for1439      // explicit visibility on the parent class, and use that for static locals1440      // if present.1441      if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))1442        LV = getLVForDecl(MD->getParent(), computation);1443      if (!LV.isVisibilityExplicit()) {1444        Visibility globalVisibility =1445            computation.isValueVisibility()1446                ? Context.getLangOpts().getValueVisibilityMode()1447                : Context.getLangOpts().getTypeVisibilityMode();1448        return LinkageInfo(Linkage::VisibleNone, globalVisibility,1449                           /*visibilityExplicit=*/false);1450      }1451    }1452  }1453  if (!isExternallyVisible(LV.getLinkage()))1454    return LinkageInfo::none();1455  return LinkageInfo(Linkage::VisibleNone, LV.getVisibility(),1456                     LV.isVisibilityExplicit());1457}1458 1459LinkageInfo LinkageComputer::computeLVForDecl(const NamedDecl *D,1460                                              LVComputationKind computation,1461                                              bool IgnoreVarTypeLinkage) {1462  // Internal_linkage attribute overrides other considerations.1463  if (D->hasAttr<InternalLinkageAttr>())1464    return LinkageInfo::internal();1465 1466  // Objective-C: treat all Objective-C declarations as having external1467  // linkage.1468  switch (D->getKind()) {1469    default:1470      break;1471 1472    // Per C++ [basic.link]p2, only the names of objects, references,1473    // functions, types, templates, namespaces, and values ever have linkage.1474    //1475    // Note that the name of a typedef, namespace alias, using declaration,1476    // and so on are not the name of the corresponding type, namespace, or1477    // declaration, so they do *not* have linkage.1478    case Decl::ImplicitParam:1479    case Decl::Label:1480    case Decl::NamespaceAlias:1481    case Decl::ParmVar:1482    case Decl::Using:1483    case Decl::UsingEnum:1484    case Decl::UsingShadow:1485    case Decl::UsingDirective:1486      return LinkageInfo::none();1487 1488    case Decl::EnumConstant:1489      // C++ [basic.link]p4: an enumerator has the linkage of its enumeration.1490      if (D->getASTContext().getLangOpts().CPlusPlus)1491        return getLVForDecl(cast<EnumDecl>(D->getDeclContext()), computation);1492      return LinkageInfo::visible_none();1493 1494    case Decl::Typedef:1495    case Decl::TypeAlias:1496      // A typedef declaration has linkage if it gives a type a name for1497      // linkage purposes.1498      if (!cast<TypedefNameDecl>(D)1499               ->getAnonDeclWithTypedefName(/*AnyRedecl*/true))1500        return LinkageInfo::none();1501      break;1502 1503    case Decl::TemplateTemplateParm: // count these as external1504    case Decl::NonTypeTemplateParm:1505    case Decl::ObjCAtDefsField:1506    case Decl::ObjCCategory:1507    case Decl::ObjCCategoryImpl:1508    case Decl::ObjCCompatibleAlias:1509    case Decl::ObjCImplementation:1510    case Decl::ObjCMethod:1511    case Decl::ObjCProperty:1512    case Decl::ObjCPropertyImpl:1513    case Decl::ObjCProtocol:1514      return getExternalLinkageFor(D);1515 1516    case Decl::CXXRecord: {1517      const auto *Record = cast<CXXRecordDecl>(D);1518      if (Record->isLambda()) {1519        if (Record->hasKnownLambdaInternalLinkage() ||1520            !Record->getLambdaManglingNumber()) {1521          // This lambda has no mangling number, so it's internal.1522          return LinkageInfo::internal();1523        }1524 1525        return getLVForClosure(1526                  Record->getDeclContext()->getRedeclContext(),1527                  Record->getLambdaContextDecl(), computation);1528      }1529 1530      break;1531    }1532 1533    case Decl::TemplateParamObject: {1534      // The template parameter object can be referenced from anywhere its type1535      // and value can be referenced.1536      auto *TPO = cast<TemplateParamObjectDecl>(D);1537      LinkageInfo LV = getLVForType(*TPO->getType(), computation);1538      LV.merge(getLVForValue(TPO->getValue(), computation));1539      return LV;1540    }1541  }1542 1543  // Handle linkage for namespace-scope names.1544  if (D->getDeclContext()->getRedeclContext()->isFileContext())1545    return getLVForNamespaceScopeDecl(D, computation, IgnoreVarTypeLinkage);1546 1547  // C++ [basic.link]p5:1548  //   In addition, a member function, static data member, a named1549  //   class or enumeration of class scope, or an unnamed class or1550  //   enumeration defined in a class-scope typedef declaration such1551  //   that the class or enumeration has the typedef name for linkage1552  //   purposes (7.1.3), has external linkage if the name of the class1553  //   has external linkage.1554  if (D->getDeclContext()->isRecord())1555    return getLVForClassMember(D, computation, IgnoreVarTypeLinkage);1556 1557  // C++ [basic.link]p6:1558  //   The name of a function declared in block scope and the name of1559  //   an object declared by a block scope extern declaration have1560  //   linkage. If there is a visible declaration of an entity with1561  //   linkage having the same name and type, ignoring entities1562  //   declared outside the innermost enclosing namespace scope, the1563  //   block scope declaration declares that same entity and receives1564  //   the linkage of the previous declaration. If there is more than1565  //   one such matching entity, the program is ill-formed. Otherwise,1566  //   if no matching entity is found, the block scope entity receives1567  //   external linkage.1568  if (D->getDeclContext()->isFunctionOrMethod())1569    return getLVForLocalDecl(D, computation);1570 1571  // C++ [basic.link]p6:1572  //   Names not covered by these rules have no linkage.1573  return LinkageInfo::none();1574}1575 1576/// getLVForDecl - Get the linkage and visibility for the given declaration.1577LinkageInfo LinkageComputer::getLVForDecl(const NamedDecl *D,1578                                          LVComputationKind computation) {1579  // Internal_linkage attribute overrides other considerations.1580  if (D->hasAttr<InternalLinkageAttr>())1581    return LinkageInfo::internal();1582 1583  if (computation.IgnoreAllVisibility && D->hasCachedLinkage())1584    return LinkageInfo(D->getCachedLinkage(), DefaultVisibility, false);1585 1586  if (std::optional<LinkageInfo> LI = lookup(D, computation))1587    return *LI;1588 1589  LinkageInfo LV = computeLVForDecl(D, computation);1590  if (D->hasCachedLinkage())1591    assert(D->getCachedLinkage() == LV.getLinkage());1592 1593  D->setCachedLinkage(LV.getLinkage());1594  cache(D, computation, LV);1595 1596#ifndef NDEBUG1597  // In C (because of gnu inline) and in c++ with microsoft extensions an1598  // static can follow an extern, so we can have two decls with different1599  // linkages.1600  const LangOptions &Opts = D->getASTContext().getLangOpts();1601  if (!Opts.CPlusPlus || Opts.MicrosoftExt)1602    return LV;1603 1604  // We have just computed the linkage for this decl. By induction we know1605  // that all other computed linkages match, check that the one we just1606  // computed also does.1607  // We can't assume the redecl chain is well formed at this point,1608  // so keep track of already visited declarations.1609  for (llvm::SmallPtrSet<const Decl *, 4> AlreadyVisited{D}; /**/; /**/) {1610    D = cast<NamedDecl>(const_cast<NamedDecl *>(D)->getNextRedeclarationImpl());1611    if (!AlreadyVisited.insert(D).second)1612      break;1613    if (D->isInvalidDecl())1614      continue;1615    if (auto OldLinkage = D->getCachedLinkage();1616        OldLinkage != Linkage::Invalid) {1617      assert(LV.getLinkage() == OldLinkage);1618      break;1619    }1620  }1621#endif1622 1623  return LV;1624}1625 1626LinkageInfo LinkageComputer::getDeclLinkageAndVisibility(const NamedDecl *D) {1627  NamedDecl::ExplicitVisibilityKind EK = usesTypeVisibility(D)1628                                             ? NamedDecl::VisibilityForType1629                                             : NamedDecl::VisibilityForValue;1630  LVComputationKind CK(EK);1631  return getLVForDecl(D, D->getASTContext().getLangOpts().IgnoreXCOFFVisibility1632                             ? CK.forLinkageOnly()1633                             : CK);1634}1635 1636Module *Decl::getOwningModuleForLinkage() const {1637  if (isa<NamespaceDecl>(this))1638    // Namespaces never have module linkage.  It is the entities within them1639    // that [may] do.1640    return nullptr;1641 1642  Module *M = getOwningModule();1643  if (!M)1644    return nullptr;1645 1646  switch (M->Kind) {1647  case Module::ModuleMapModule:1648    // Module map modules have no special linkage semantics.1649    return nullptr;1650 1651  case Module::ModuleInterfaceUnit:1652  case Module::ModuleImplementationUnit:1653  case Module::ModulePartitionInterface:1654  case Module::ModulePartitionImplementation:1655    return M;1656 1657  case Module::ModuleHeaderUnit:1658  case Module::ExplicitGlobalModuleFragment:1659  case Module::ImplicitGlobalModuleFragment:1660    // The global module shouldn't change the linkage.1661    return nullptr;1662 1663  case Module::PrivateModuleFragment:1664    // The private module fragment is part of its containing module for linkage1665    // purposes.1666    return M->Parent;1667  }1668 1669  llvm_unreachable("unknown module kind");1670}1671 1672void NamedDecl::printName(raw_ostream &OS, const PrintingPolicy &Policy) const {1673  Name.print(OS, Policy);1674}1675 1676void NamedDecl::printName(raw_ostream &OS) const {1677  printName(OS, getASTContext().getPrintingPolicy());1678}1679 1680std::string NamedDecl::getQualifiedNameAsString() const {1681  std::string QualName;1682  llvm::raw_string_ostream OS(QualName);1683  printQualifiedName(OS, getASTContext().getPrintingPolicy());1684  return QualName;1685}1686 1687void NamedDecl::printQualifiedName(raw_ostream &OS) const {1688  printQualifiedName(OS, getASTContext().getPrintingPolicy());1689}1690 1691void NamedDecl::printQualifiedName(raw_ostream &OS,1692                                   const PrintingPolicy &P) const {1693  if (getDeclContext()->isFunctionOrMethod()) {1694    // We do not print '(anonymous)' for function parameters without name.1695    printName(OS, P);1696    return;1697  }1698  printNestedNameSpecifier(OS, P);1699  if (getDeclName()) {1700    printName(OS, P);1701  } else {1702    // Give the printName override a chance to pick a different name before we1703    // fall back to "(anonymous)".1704    SmallString<64> NameBuffer;1705    llvm::raw_svector_ostream NameOS(NameBuffer);1706    printName(NameOS, P);1707    if (NameBuffer.empty())1708      OS << "(anonymous)";1709    else1710      OS << NameBuffer;1711  }1712}1713 1714void NamedDecl::printNestedNameSpecifier(raw_ostream &OS) const {1715  printNestedNameSpecifier(OS, getASTContext().getPrintingPolicy());1716}1717 1718void NamedDecl::printNestedNameSpecifier(raw_ostream &OS,1719                                         const PrintingPolicy &P) const {1720  const DeclContext *Ctx = getDeclContext();1721 1722  // For ObjC methods and properties, look through categories and use the1723  // interface as context.1724  if (auto *MD = dyn_cast<ObjCMethodDecl>(this)) {1725    if (auto *ID = MD->getClassInterface())1726      Ctx = ID;1727  } else if (auto *PD = dyn_cast<ObjCPropertyDecl>(this)) {1728    if (auto *MD = PD->getGetterMethodDecl())1729      if (auto *ID = MD->getClassInterface())1730        Ctx = ID;1731  } else if (auto *ID = dyn_cast<ObjCIvarDecl>(this)) {1732    if (auto *CI = ID->getContainingInterface())1733      Ctx = CI;1734  }1735 1736  if (Ctx->isFunctionOrMethod())1737    return;1738 1739  using ContextsTy = SmallVector<const DeclContext *, 8>;1740  ContextsTy Contexts;1741 1742  // Collect named contexts.1743  DeclarationName NameInScope = getDeclName();1744  for (; Ctx; Ctx = Ctx->getParent()) {1745    if (P.Callbacks && P.Callbacks->isScopeVisible(Ctx))1746      continue;1747 1748    // Suppress anonymous namespace if requested.1749    if (P.SuppressUnwrittenScope && isa<NamespaceDecl>(Ctx) &&1750        cast<NamespaceDecl>(Ctx)->isAnonymousNamespace())1751      continue;1752 1753    // Suppress inline namespace if it doesn't make the result ambiguous.1754    if (Ctx->isInlineNamespace() && NameInScope) {1755      if (P.SuppressInlineNamespace ==1756              PrintingPolicy::SuppressInlineNamespaceMode::All ||1757          (P.SuppressInlineNamespace ==1758               PrintingPolicy::SuppressInlineNamespaceMode::Redundant &&1759           cast<NamespaceDecl>(Ctx)->isRedundantInlineQualifierFor(1760               NameInScope))) {1761        continue;1762      }1763    }1764 1765    // Suppress transparent contexts like export or HLSLBufferDecl context1766    if (Ctx->isTransparentContext())1767      continue;1768 1769    // Skip non-named contexts such as linkage specifications and ExportDecls.1770    const NamedDecl *ND = dyn_cast<NamedDecl>(Ctx);1771    if (!ND)1772      continue;1773 1774    Contexts.push_back(Ctx);1775    NameInScope = ND->getDeclName();1776  }1777 1778  for (const DeclContext *DC : llvm::reverse(Contexts)) {1779    if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {1780      OS << Spec->getName();1781      const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();1782      printTemplateArgumentList(1783          OS, TemplateArgs.asArray(), P,1784          Spec->getSpecializedTemplate()->getTemplateParameters());1785    } else if (const auto *ND = dyn_cast<NamespaceDecl>(DC)) {1786      if (ND->isAnonymousNamespace()) {1787        OS << (P.MSVCFormatting ? "`anonymous namespace\'"1788                                : "(anonymous namespace)");1789      }1790      else1791        OS << *ND;1792    } else if (const auto *RD = dyn_cast<RecordDecl>(DC)) {1793      if (TypedefNameDecl *TD = RD->getTypedefNameForAnonDecl())1794        OS << *TD;1795      else if (!RD->getIdentifier())1796        OS << "(anonymous " << RD->getKindName() << ')';1797      else1798        OS << *RD;1799    } else if (const auto *FD = dyn_cast<FunctionDecl>(DC)) {1800      const FunctionProtoType *FT = nullptr;1801      if (FD->hasWrittenPrototype())1802        FT = dyn_cast<FunctionProtoType>(FD->getType()->castAs<FunctionType>());1803 1804      OS << *FD << '(';1805      if (FT) {1806        unsigned NumParams = FD->getNumParams();1807        for (unsigned i = 0; i < NumParams; ++i) {1808          if (i)1809            OS << ", ";1810          OS << FD->getParamDecl(i)->getType().stream(P);1811        }1812 1813        if (FT->isVariadic()) {1814          if (NumParams > 0)1815            OS << ", ";1816          OS << "...";1817        }1818      }1819      OS << ')';1820    } else if (const auto *ED = dyn_cast<EnumDecl>(DC)) {1821      // C++ [dcl.enum]p10: Each enum-name and each unscoped1822      // enumerator is declared in the scope that immediately contains1823      // the enum-specifier. Each scoped enumerator is declared in the1824      // scope of the enumeration.1825      // For the case of unscoped enumerator, do not include in the qualified1826      // name any information about its enum enclosing scope, as its visibility1827      // is global.1828      if (ED->isScoped())1829        OS << *ED;1830      else1831        continue;1832    } else {1833      OS << *cast<NamedDecl>(DC);1834    }1835    OS << "::";1836  }1837}1838 1839void NamedDecl::getNameForDiagnostic(raw_ostream &OS,1840                                     const PrintingPolicy &Policy,1841                                     bool Qualified) const {1842  if (Qualified)1843    printQualifiedName(OS, Policy);1844  else1845    printName(OS, Policy);1846}1847 1848template<typename T> static bool isRedeclarableImpl(Redeclarable<T> *) {1849  return true;1850}1851static bool isRedeclarableImpl(...) { return false; }1852static bool isRedeclarable(Decl::Kind K) {1853  switch (K) {1854#define DECL(Type, Base) \1855  case Decl::Type: \1856    return isRedeclarableImpl((Type##Decl *)nullptr);1857#define ABSTRACT_DECL(DECL)1858#include "clang/AST/DeclNodes.inc"1859  }1860  llvm_unreachable("unknown decl kind");1861}1862 1863bool NamedDecl::declarationReplaces(const NamedDecl *OldD,1864                                    bool IsKnownNewer) const {1865  assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");1866 1867  // Never replace one imported declaration with another; we need both results1868  // when re-exporting.1869  if (OldD->isFromASTFile() && isFromASTFile())1870    return false;1871 1872  // A kind mismatch implies that the declaration is not replaced.1873  if (OldD->getKind() != getKind())1874    return false;1875 1876  // For method declarations, we never replace. (Why?)1877  if (isa<ObjCMethodDecl>(this))1878    return false;1879 1880  // For parameters, pick the newer one. This is either an error or (in1881  // Objective-C) permitted as an extension.1882  if (isa<ParmVarDecl>(this))1883    return true;1884 1885  // Inline namespaces can give us two declarations with the same1886  // name and kind in the same scope but different contexts; we should1887  // keep both declarations in this case.1888  if (!this->getDeclContext()->getRedeclContext()->Equals(1889          OldD->getDeclContext()->getRedeclContext()))1890    return false;1891 1892  // Using declarations can be replaced if they import the same name from the1893  // same context.1894  if (const auto *UD = dyn_cast<UsingDecl>(this))1895    return UD->getQualifier().getCanonical() ==1896 1897           cast<UsingDecl>(OldD)->getQualifier().getCanonical();1898  if (const auto *UUVD = dyn_cast<UnresolvedUsingValueDecl>(this))1899    return UUVD->getQualifier().getCanonical() ==1900           cast<UnresolvedUsingValueDecl>(OldD)->getQualifier().getCanonical();1901 1902  if (isRedeclarable(getKind())) {1903    if (getCanonicalDecl() != OldD->getCanonicalDecl())1904      return false;1905 1906    if (IsKnownNewer)1907      return true;1908 1909    // Check whether this is actually newer than OldD. We want to keep the1910    // newer declaration. This loop will usually only iterate once, because1911    // OldD is usually the previous declaration.1912    for (const auto *D : redecls()) {1913      if (D == OldD)1914        break;1915 1916      // If we reach the canonical declaration, then OldD is not actually older1917      // than this one.1918      //1919      // FIXME: In this case, we should not add this decl to the lookup table.1920      if (D->isCanonicalDecl())1921        return false;1922    }1923 1924    // It's a newer declaration of the same kind of declaration in the same1925    // scope: we want this decl instead of the existing one.1926    return true;1927  }1928 1929  // In all other cases, we need to keep both declarations in case they have1930  // different visibility. Any attempt to use the name will result in an1931  // ambiguity if more than one is visible.1932  return false;1933}1934 1935bool NamedDecl::hasLinkage() const {1936  switch (getFormalLinkage()) {1937  case Linkage::Invalid:1938    llvm_unreachable("Linkage hasn't been computed!");1939  case Linkage::None:1940    return false;1941  case Linkage::Internal:1942    return true;1943  case Linkage::UniqueExternal:1944  case Linkage::VisibleNone:1945    llvm_unreachable("Non-formal linkage is not allowed here!");1946  case Linkage::Module:1947  case Linkage::External:1948    return true;1949  }1950  llvm_unreachable("Unhandled Linkage enum");1951}1952 1953NamedDecl *NamedDecl::getUnderlyingDeclImpl() {1954  NamedDecl *ND = this;1955  if (auto *UD = dyn_cast<UsingShadowDecl>(ND))1956    ND = UD->getTargetDecl();1957 1958  if (auto *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND))1959    return AD->getClassInterface();1960 1961  if (auto *AD = dyn_cast<NamespaceAliasDecl>(ND))1962    return AD->getNamespace();1963 1964  return ND;1965}1966 1967bool NamedDecl::isCXXInstanceMember() const {1968  if (!isCXXClassMember())1969    return false;1970 1971  const NamedDecl *D = this;1972  if (isa<UsingShadowDecl>(D))1973    D = cast<UsingShadowDecl>(D)->getTargetDecl();1974 1975  if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<MSPropertyDecl>(D))1976    return true;1977  if (const auto *MD = dyn_cast_if_present<CXXMethodDecl>(D->getAsFunction()))1978    return MD->isInstance();1979  return false;1980}1981 1982//===----------------------------------------------------------------------===//1983// DeclaratorDecl Implementation1984//===----------------------------------------------------------------------===//1985 1986template <typename DeclT>1987static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {1988  if (decl->getNumTemplateParameterLists() > 0)1989    return decl->getTemplateParameterList(0)->getTemplateLoc();1990  return decl->getInnerLocStart();1991}1992 1993SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {1994  TypeSourceInfo *TSI = getTypeSourceInfo();1995  if (TSI) return TSI->getTypeLoc().getBeginLoc();1996  return SourceLocation();1997}1998 1999SourceLocation DeclaratorDecl::getTypeSpecEndLoc() const {2000  TypeSourceInfo *TSI = getTypeSourceInfo();2001  if (TSI) return TSI->getTypeLoc().getEndLoc();2002  return SourceLocation();2003}2004 2005void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {2006  if (QualifierLoc) {2007    // Make sure the extended decl info is allocated.2008    if (!hasExtInfo()) {2009      // Save (non-extended) type source info pointer.2010      auto *savedTInfo = cast<TypeSourceInfo *>(DeclInfo);2011      // Allocate external info struct.2012      DeclInfo = new (getASTContext()) ExtInfo;2013      // Restore savedTInfo into (extended) decl info.2014      getExtInfo()->TInfo = savedTInfo;2015    }2016    // Set qualifier info.2017    getExtInfo()->QualifierLoc = QualifierLoc;2018  } else if (hasExtInfo()) {2019    // Here Qualifier == 0, i.e., we are removing the qualifier (if any).2020    getExtInfo()->QualifierLoc = QualifierLoc;2021  }2022}2023 2024void DeclaratorDecl::setTrailingRequiresClause(const AssociatedConstraint &AC) {2025  assert(AC);2026  // Make sure the extended decl info is allocated.2027  if (!hasExtInfo()) {2028    // Save (non-extended) type source info pointer.2029    auto *savedTInfo = cast<TypeSourceInfo *>(DeclInfo);2030    // Allocate external info struct.2031    DeclInfo = new (getASTContext()) ExtInfo;2032    // Restore savedTInfo into (extended) decl info.2033    getExtInfo()->TInfo = savedTInfo;2034  }2035  // Set requires clause info.2036  getExtInfo()->TrailingRequiresClause = AC;2037}2038 2039void DeclaratorDecl::setTemplateParameterListsInfo(2040    ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {2041  assert(!TPLists.empty());2042  // Make sure the extended decl info is allocated.2043  if (!hasExtInfo()) {2044    // Save (non-extended) type source info pointer.2045    auto *savedTInfo = cast<TypeSourceInfo *>(DeclInfo);2046    // Allocate external info struct.2047    DeclInfo = new (getASTContext()) ExtInfo;2048    // Restore savedTInfo into (extended) decl info.2049    getExtInfo()->TInfo = savedTInfo;2050  }2051  // Set the template parameter lists info.2052  getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);2053}2054 2055SourceLocation DeclaratorDecl::getOuterLocStart() const {2056  return getTemplateOrInnerLocStart(this);2057}2058 2059// Helper function: returns true if QT is or contains a type2060// having a postfix component.2061static bool typeIsPostfix(QualType QT) {2062  while (true) {2063    const Type* T = QT.getTypePtr();2064    switch (T->getTypeClass()) {2065    default:2066      return false;2067    case Type::Pointer:2068      QT = cast<PointerType>(T)->getPointeeType();2069      break;2070    case Type::BlockPointer:2071      QT = cast<BlockPointerType>(T)->getPointeeType();2072      break;2073    case Type::MemberPointer:2074      QT = cast<MemberPointerType>(T)->getPointeeType();2075      break;2076    case Type::LValueReference:2077    case Type::RValueReference:2078      QT = cast<ReferenceType>(T)->getPointeeType();2079      break;2080    case Type::PackExpansion:2081      QT = cast<PackExpansionType>(T)->getPattern();2082      break;2083    case Type::Paren:2084    case Type::ConstantArray:2085    case Type::DependentSizedArray:2086    case Type::IncompleteArray:2087    case Type::VariableArray:2088    case Type::FunctionProto:2089    case Type::FunctionNoProto:2090      return true;2091    }2092  }2093}2094 2095SourceRange DeclaratorDecl::getSourceRange() const {2096  SourceLocation RangeEnd = getLocation();2097  if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {2098    // If the declaration has no name or the type extends past the name take the2099    // end location of the type.2100    if (!getDeclName() || typeIsPostfix(TInfo->getType()))2101      RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();2102  }2103  return SourceRange(getOuterLocStart(), RangeEnd);2104}2105 2106void QualifierInfo::setTemplateParameterListsInfo(2107    ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {2108  // Free previous template parameters (if any).2109  if (NumTemplParamLists > 0) {2110    Context.Deallocate(TemplParamLists);2111    TemplParamLists = nullptr;2112    NumTemplParamLists = 0;2113  }2114  // Set info on matched template parameter lists (if any).2115  if (!TPLists.empty()) {2116    TemplParamLists = new (Context) TemplateParameterList *[TPLists.size()];2117    NumTemplParamLists = TPLists.size();2118    llvm::copy(TPLists, TemplParamLists);2119  }2120}2121 2122//===----------------------------------------------------------------------===//2123// VarDecl Implementation2124//===----------------------------------------------------------------------===//2125 2126const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {2127  switch (SC) {2128  case SC_None:                 break;2129  case SC_Auto:                 return "auto";2130  case SC_Extern:               return "extern";2131  case SC_PrivateExtern:        return "__private_extern__";2132  case SC_Register:             return "register";2133  case SC_Static:               return "static";2134  }2135 2136  llvm_unreachable("Invalid storage class");2137}2138 2139VarDecl::VarDecl(Kind DK, ASTContext &C, DeclContext *DC,2140                 SourceLocation StartLoc, SourceLocation IdLoc,2141                 const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,2142                 StorageClass SC)2143    : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),2144      redeclarable_base(C) {2145  static_assert(sizeof(VarDeclBitfields) <= sizeof(unsigned),2146                "VarDeclBitfields too large!");2147  static_assert(sizeof(ParmVarDeclBitfields) <= sizeof(unsigned),2148                "ParmVarDeclBitfields too large!");2149  static_assert(sizeof(NonParmVarDeclBitfields) <= sizeof(unsigned),2150                "NonParmVarDeclBitfields too large!");2151  AllBits = 0;2152  VarDeclBits.SClass = SC;2153  // Everything else is implicitly initialized to false.2154}2155 2156VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation StartL,2157                         SourceLocation IdL, const IdentifierInfo *Id,2158                         QualType T, TypeSourceInfo *TInfo, StorageClass S) {2159  return new (C, DC) VarDecl(Var, C, DC, StartL, IdL, Id, T, TInfo, S);2160}2161 2162VarDecl *VarDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) {2163  return new (C, ID)2164      VarDecl(Var, C, nullptr, SourceLocation(), SourceLocation(), nullptr,2165              QualType(), nullptr, SC_None);2166}2167 2168void VarDecl::setStorageClass(StorageClass SC) {2169  assert(isLegalForVariable(SC));2170  VarDeclBits.SClass = SC;2171}2172 2173VarDecl::TLSKind VarDecl::getTLSKind() const {2174  switch (VarDeclBits.TSCSpec) {2175  case TSCS_unspecified:2176    if (!hasAttr<ThreadAttr>() &&2177        !(getASTContext().getLangOpts().OpenMPUseTLS &&2178          getASTContext().getTargetInfo().isTLSSupported() &&2179          hasAttr<OMPThreadPrivateDeclAttr>()))2180      return TLS_None;2181    return ((getASTContext().getLangOpts().isCompatibleWithMSVC(2182                LangOptions::MSVC2015)) ||2183            hasAttr<OMPThreadPrivateDeclAttr>())2184               ? TLS_Dynamic2185               : TLS_Static;2186  case TSCS___thread: // Fall through.2187  case TSCS__Thread_local:2188    return TLS_Static;2189  case TSCS_thread_local:2190    return TLS_Dynamic;2191  }2192  llvm_unreachable("Unknown thread storage class specifier!");2193}2194 2195SourceRange VarDecl::getSourceRange() const {2196  if (const Expr *Init = getInit()) {2197    SourceLocation InitEnd = Init->getEndLoc();2198    // If Init is implicit, ignore its source range and fallback on2199    // DeclaratorDecl::getSourceRange() to handle postfix elements.2200    if (InitEnd.isValid() && InitEnd != getLocation())2201      return SourceRange(getOuterLocStart(), InitEnd);2202  }2203  return DeclaratorDecl::getSourceRange();2204}2205 2206template<typename T>2207static LanguageLinkage getDeclLanguageLinkage(const T &D) {2208  // C++ [dcl.link]p1: All function types, function names with external linkage,2209  // and variable names with external linkage have a language linkage.2210  if (!D.hasExternalFormalLinkage())2211    return NoLanguageLinkage;2212 2213  // Language linkage is a C++ concept, but saying that everything else in C has2214  // C language linkage fits the implementation nicely.2215  if (!D.getASTContext().getLangOpts().CPlusPlus)2216    return CLanguageLinkage;2217 2218  // C++ [dcl.link]p4: A C language linkage is ignored in determining the2219  // language linkage of the names of class members and the function type of2220  // class member functions.2221  const DeclContext *DC = D.getDeclContext();2222  if (DC->isRecord())2223    return CXXLanguageLinkage;2224 2225  // If the first decl is in an extern "C" context, any other redeclaration2226  // will have C language linkage. If the first one is not in an extern "C"2227  // context, we would have reported an error for any other decl being in one.2228  if (isFirstInExternCContext(&D))2229    return CLanguageLinkage;2230  return CXXLanguageLinkage;2231}2232 2233template<typename T>2234static bool isDeclExternC(const T &D) {2235  // Since the context is ignored for class members, they can only have C++2236  // language linkage or no language linkage.2237  const DeclContext *DC = D.getDeclContext();2238  if (DC->isRecord()) {2239    assert(D.getASTContext().getLangOpts().CPlusPlus);2240    return false;2241  }2242 2243  return D.getLanguageLinkage() == CLanguageLinkage;2244}2245 2246LanguageLinkage VarDecl::getLanguageLinkage() const {2247  return getDeclLanguageLinkage(*this);2248}2249 2250bool VarDecl::isExternC() const {2251  return isDeclExternC(*this);2252}2253 2254bool VarDecl::isInExternCContext() const {2255  return getLexicalDeclContext()->isExternCContext();2256}2257 2258bool VarDecl::isInExternCXXContext() const {2259  return getLexicalDeclContext()->isExternCXXContext();2260}2261 2262VarDecl *VarDecl::getCanonicalDecl() { return getFirstDecl(); }2263 2264VarDecl::DefinitionKind2265VarDecl::isThisDeclarationADefinition(ASTContext &C) const {2266  if (isThisDeclarationADemotedDefinition())2267    return DeclarationOnly;2268 2269  // C++ [basic.def]p2:2270  //   A declaration is a definition unless [...] it contains the 'extern'2271  //   specifier or a linkage-specification and neither an initializer [...],2272  //   it declares a non-inline static data member in a class declaration [...],2273  //   it declares a static data member outside a class definition and the variable2274  //   was defined within the class with the constexpr specifier [...],2275  // C++1y [temp.expl.spec]p15:2276  //   An explicit specialization of a static data member or an explicit2277  //   specialization of a static data member template is a definition if the2278  //   declaration includes an initializer; otherwise, it is a declaration.2279  //2280  // FIXME: How do you declare (but not define) a partial specialization of2281  // a static data member template outside the containing class?2282  if (isStaticDataMember()) {2283    if (isOutOfLine() &&2284        !(getCanonicalDecl()->isInline() &&2285          getCanonicalDecl()->isConstexpr()) &&2286        (hasInit() ||2287         // If the first declaration is out-of-line, this may be an2288         // instantiation of an out-of-line partial specialization of a variable2289         // template for which we have not yet instantiated the initializer.2290         (getFirstDecl()->isOutOfLine()2291              ? getTemplateSpecializationKind() == TSK_Undeclared2292              : getTemplateSpecializationKind() !=2293                    TSK_ExplicitSpecialization) ||2294         isa<VarTemplatePartialSpecializationDecl>(this)))2295      return Definition;2296    if (!isOutOfLine() && isInline())2297      return Definition;2298    return DeclarationOnly;2299  }2300  // C99 6.7p5:2301  //   A definition of an identifier is a declaration for that identifier that2302  //   [...] causes storage to be reserved for that object.2303  // Note: that applies for all non-file-scope objects.2304  // C99 6.9.2p1:2305  //   If the declaration of an identifier for an object has file scope and an2306  //   initializer, the declaration is an external definition for the identifier2307  if (hasInit())2308    return Definition;2309 2310  if (hasDefiningAttr())2311    return Definition;2312 2313  if (const auto *SAA = getAttr<SelectAnyAttr>())2314    if (!SAA->isInherited())2315      return Definition;2316 2317  // A variable template specialization (other than a static data member2318  // template or an explicit specialization) is a declaration until we2319  // instantiate its initializer.2320  if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(this)) {2321    if (VTSD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization &&2322        !isa<VarTemplatePartialSpecializationDecl>(VTSD) &&2323        !VTSD->IsCompleteDefinition)2324      return DeclarationOnly;2325  }2326 2327  if (hasExternalStorage())2328    return DeclarationOnly;2329 2330  // [dcl.link] p7:2331  //   A declaration directly contained in a linkage-specification is treated2332  //   as if it contains the extern specifier for the purpose of determining2333  //   the linkage of the declared name and whether it is a definition.2334  if (isSingleLineLanguageLinkage(*this))2335    return DeclarationOnly;2336 2337  // C99 6.9.2p2:2338  //   A declaration of an object that has file scope without an initializer,2339  //   and without a storage class specifier or the scs 'static', constitutes2340  //   a tentative definition.2341  // No such thing in C++.2342  if (!C.getLangOpts().CPlusPlus && isFileVarDecl())2343    return TentativeDefinition;2344 2345  // What's left is (in C, block-scope) declarations without initializers or2346  // external storage. These are definitions.2347  return Definition;2348}2349 2350VarDecl *VarDecl::getActingDefinition() {2351  DefinitionKind Kind = isThisDeclarationADefinition();2352  if (Kind != TentativeDefinition)2353    return nullptr;2354 2355  VarDecl *LastTentative = nullptr;2356 2357  // Loop through the declaration chain, starting with the most recent.2358  for (VarDecl *Decl = getMostRecentDecl(); Decl;2359       Decl = Decl->getPreviousDecl()) {2360    Kind = Decl->isThisDeclarationADefinition();2361    if (Kind == Definition)2362      return nullptr;2363    // Record the first (most recent) TentativeDefinition that is encountered.2364    if (Kind == TentativeDefinition && !LastTentative)2365      LastTentative = Decl;2366  }2367 2368  return LastTentative;2369}2370 2371VarDecl *VarDecl::getDefinition(ASTContext &C) {2372  VarDecl *First = getFirstDecl();2373  for (auto *I : First->redecls()) {2374    if (I->isThisDeclarationADefinition(C) == Definition)2375      return I;2376  }2377  return nullptr;2378}2379 2380VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const {2381  DefinitionKind Kind = DeclarationOnly;2382 2383  const VarDecl *First = getFirstDecl();2384  for (auto *I : First->redecls()) {2385    Kind = std::max(Kind, I->isThisDeclarationADefinition(C));2386    if (Kind == Definition)2387      break;2388  }2389 2390  return Kind;2391}2392 2393const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {2394  for (auto *I : redecls()) {2395    if (auto Expr = I->getInit()) {2396      D = I;2397      return Expr;2398    }2399  }2400  return nullptr;2401}2402 2403bool VarDecl::hasInit() const {2404  if (auto *P = dyn_cast<ParmVarDecl>(this))2405    if (P->hasUnparsedDefaultArg() || P->hasUninstantiatedDefaultArg())2406      return false;2407 2408  if (auto *Eval = getEvaluatedStmt())2409    return Eval->Value.isValid();2410 2411  return !Init.isNull();2412}2413 2414Expr *VarDecl::getInit() {2415  if (!hasInit())2416    return nullptr;2417 2418  if (auto *S = dyn_cast<Stmt *>(Init))2419    return cast<Expr>(S);2420 2421  auto *Eval = getEvaluatedStmt();2422 2423  return cast<Expr>(Eval->Value.get(2424      Eval->Value.isOffset() ? getASTContext().getExternalSource() : nullptr));2425}2426 2427Stmt **VarDecl::getInitAddress() {2428  if (auto *ES = Init.dyn_cast<EvaluatedStmt *>())2429    return ES->Value.getAddressOfPointer(getASTContext().getExternalSource());2430 2431  return Init.getAddrOfPtr1();2432}2433 2434VarDecl *VarDecl::getInitializingDeclaration() {2435  VarDecl *Def = nullptr;2436  for (auto *I : redecls()) {2437    if (I->hasInit())2438      return I;2439 2440    if (I->isThisDeclarationADefinition()) {2441      if (isStaticDataMember())2442        return I;2443      Def = I;2444    }2445  }2446  return Def;2447}2448 2449bool VarDecl::hasInitWithSideEffects() const {2450  if (!hasInit())2451    return false;2452 2453  EvaluatedStmt *ES = ensureEvaluatedStmt();2454  if (!ES->CheckedForSideEffects) {2455    const Expr *E = getInit();2456    ES->HasSideEffects =2457        E->HasSideEffects(getASTContext()) &&2458        // We can get a value-dependent initializer during error recovery.2459        (E->isValueDependent() || getType()->isDependentType() ||2460         !evaluateValue());2461    ES->CheckedForSideEffects = true;2462  }2463  return ES->HasSideEffects;2464}2465 2466bool VarDecl::isOutOfLine() const {2467  if (Decl::isOutOfLine())2468    return true;2469 2470  if (!isStaticDataMember())2471    return false;2472 2473  // If this static data member was instantiated from a static data member of2474  // a class template, check whether that static data member was defined2475  // out-of-line.2476  if (VarDecl *VD = getInstantiatedFromStaticDataMember())2477    return VD->isOutOfLine();2478 2479  return false;2480}2481 2482void VarDecl::setInit(Expr *I) {2483  if (auto *Eval = dyn_cast_if_present<EvaluatedStmt *>(Init)) {2484    Eval->~EvaluatedStmt();2485    getASTContext().Deallocate(Eval);2486  }2487 2488  Init = I;2489}2490 2491bool VarDecl::mightBeUsableInConstantExpressions(const ASTContext &C) const {2492  const LangOptions &Lang = C.getLangOpts();2493 2494  // OpenCL permits const integral variables to be used in constant2495  // expressions, like in C++98.2496  if (!Lang.CPlusPlus && !Lang.OpenCL && !Lang.C23)2497    return false;2498 2499  // Function parameters are never usable in constant expressions.2500  if (isa<ParmVarDecl>(this))2501    return false;2502 2503  // The values of weak variables are never usable in constant expressions.2504  if (isWeak())2505    return false;2506 2507  // In C++11, any variable of reference type can be used in a constant2508  // expression if it is initialized by a constant expression.2509  if (Lang.CPlusPlus11 && getType()->isReferenceType())2510    return true;2511 2512  // Only const objects can be used in constant expressions in C++. C++98 does2513  // not require the variable to be non-volatile, but we consider this to be a2514  // defect.2515  if (!getType().isConstant(C) || getType().isVolatileQualified())2516    return false;2517 2518  // In C++, but not in C, const, non-volatile variables of integral or2519  // enumeration types can be used in constant expressions.2520  if (getType()->isIntegralOrEnumerationType() && !Lang.C23)2521    return true;2522 2523  // C23 6.6p7: An identifier that is:2524  // ...2525  // - declared with storage-class specifier constexpr and has an object type,2526  // is a named constant, ... such a named constant is a constant expression2527  // with the type and value of the declared object.2528  // Additionally, in C++11, non-volatile constexpr variables can be used in2529  // constant expressions.2530  return (Lang.CPlusPlus11 || Lang.C23) && isConstexpr();2531}2532 2533bool VarDecl::isUsableInConstantExpressions(const ASTContext &Context) const {2534  // C++2a [expr.const]p3:2535  //   A variable is usable in constant expressions after its initializing2536  //   declaration is encountered...2537  const VarDecl *DefVD = nullptr;2538  const Expr *Init = getAnyInitializer(DefVD);2539  if (!Init || Init->isValueDependent() || getType()->isDependentType())2540    return false;2541  //   ... if it is a constexpr variable, or it is of reference type or of2542  //   const-qualified integral or enumeration type, ...2543  if (!DefVD->mightBeUsableInConstantExpressions(Context))2544    return false;2545  //   ... and its initializer is a constant initializer.2546  if ((Context.getLangOpts().CPlusPlus || getLangOpts().C23) &&2547      !DefVD->hasConstantInitialization())2548    return false;2549  // C++98 [expr.const]p1:2550  //   An integral constant-expression can involve only [...] const variables2551  //   or static data members of integral or enumeration types initialized with2552  //   [integer] constant expressions (dcl.init)2553  if ((Context.getLangOpts().CPlusPlus || Context.getLangOpts().OpenCL) &&2554      !Context.getLangOpts().CPlusPlus11 && !DefVD->hasICEInitializer(Context))2555    return false;2556  return true;2557}2558 2559/// Convert the initializer for this declaration to the elaborated EvaluatedStmt2560/// form, which contains extra information on the evaluated value of the2561/// initializer.2562EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const {2563  auto *Eval = dyn_cast_if_present<EvaluatedStmt *>(Init);2564  if (!Eval) {2565    // Note: EvaluatedStmt contains an APValue, which usually holds2566    // resources not allocated from the ASTContext.  We need to do some2567    // work to avoid leaking those, but we do so in VarDecl::evaluateValue2568    // where we can detect whether there's anything to clean up or not.2569    Eval = new (getASTContext()) EvaluatedStmt;2570    Eval->Value = cast<Stmt *>(Init);2571    Init = Eval;2572  }2573  return Eval;2574}2575 2576EvaluatedStmt *VarDecl::getEvaluatedStmt() const {2577  return dyn_cast_if_present<EvaluatedStmt *>(Init);2578}2579 2580APValue *VarDecl::evaluateValue() const {2581  SmallVector<PartialDiagnosticAt, 8> Notes;2582  return evaluateValueImpl(Notes, hasConstantInitialization());2583}2584 2585APValue *VarDecl::evaluateValueImpl(SmallVectorImpl<PartialDiagnosticAt> &Notes,2586                                    bool IsConstantInitialization) const {2587  EvaluatedStmt *Eval = ensureEvaluatedStmt();2588 2589  const auto *Init = getInit();2590  assert(!Init->isValueDependent());2591 2592  // We only produce notes indicating why an initializer is non-constant the2593  // first time it is evaluated. FIXME: The notes won't always be emitted the2594  // first time we try evaluation, so might not be produced at all.2595  if (Eval->WasEvaluated)2596    return Eval->Evaluated.isAbsent() ? nullptr : &Eval->Evaluated;2597 2598  if (Eval->IsEvaluating) {2599    // FIXME: Produce a diagnostic for self-initialization.2600    return nullptr;2601  }2602 2603  Eval->IsEvaluating = true;2604 2605  ASTContext &Ctx = getASTContext();2606  bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, Ctx, this, Notes,2607                                            IsConstantInitialization);2608 2609  // In C++, or in C23 if we're initialising a 'constexpr' variable, this isn't2610  // a constant initializer if we produced notes. In that case, we can't keep2611  // the result, because it may only be correct under the assumption that the2612  // initializer is a constant context.2613  if (IsConstantInitialization &&2614      (Ctx.getLangOpts().CPlusPlus ||2615       (isConstexpr() && Ctx.getLangOpts().C23)) &&2616      !Notes.empty())2617    Result = false;2618 2619  // Ensure the computed APValue is cleaned up later if evaluation succeeded,2620  // or that it's empty (so that there's nothing to clean up) if evaluation2621  // failed.2622  if (!Result)2623    Eval->Evaluated = APValue();2624  else if (Eval->Evaluated.needsCleanup())2625    Ctx.addDestruction(&Eval->Evaluated);2626 2627  Eval->IsEvaluating = false;2628  Eval->WasEvaluated = true;2629 2630  return Result ? &Eval->Evaluated : nullptr;2631}2632 2633APValue *VarDecl::getEvaluatedValue() const {2634  if (EvaluatedStmt *Eval = getEvaluatedStmt())2635    if (Eval->WasEvaluated)2636      return &Eval->Evaluated;2637 2638  return nullptr;2639}2640 2641bool VarDecl::hasICEInitializer(const ASTContext &Context) const {2642  const Expr *Init = getInit();2643  assert(Init && "no initializer");2644 2645  EvaluatedStmt *Eval = ensureEvaluatedStmt();2646  if (!Eval->CheckedForICEInit) {2647    Eval->CheckedForICEInit = true;2648    Eval->HasICEInit = Init->isIntegerConstantExpr(Context);2649  }2650  return Eval->HasICEInit;2651}2652 2653bool VarDecl::hasConstantInitialization() const {2654  // In C, all globals and constexpr variables should have constant2655  // initialization. For constexpr variables in C check that initializer is a2656  // constant initializer because they can be used in constant expressions.2657  if (hasGlobalStorage() && !getASTContext().getLangOpts().CPlusPlus &&2658      !isConstexpr())2659    return true;2660 2661  // In C++, it depends on whether the evaluation at the point of definition2662  // was evaluatable as a constant initializer.2663  if (EvaluatedStmt *Eval = getEvaluatedStmt())2664    return Eval->HasConstantInitialization;2665 2666  return false;2667}2668 2669bool VarDecl::checkForConstantInitialization(2670    SmallVectorImpl<PartialDiagnosticAt> &Notes) const {2671  EvaluatedStmt *Eval = ensureEvaluatedStmt();2672  // If we ask for the value before we know whether we have a constant2673  // initializer, we can compute the wrong value (for example, due to2674  // std::is_constant_evaluated()).2675  assert(!Eval->WasEvaluated &&2676         "already evaluated var value before checking for constant init");2677  assert((getASTContext().getLangOpts().CPlusPlus ||2678          getASTContext().getLangOpts().C23) &&2679         "only meaningful in C++/C23");2680 2681  assert(!getInit()->isValueDependent());2682 2683  // Evaluate the initializer to check whether it's a constant expression.2684  Eval->HasConstantInitialization =2685      evaluateValueImpl(Notes, true) && Notes.empty();2686 2687  // If evaluation as a constant initializer failed, allow re-evaluation as a2688  // non-constant initializer if we later find we want the value.2689  if (!Eval->HasConstantInitialization)2690    Eval->WasEvaluated = false;2691 2692  return Eval->HasConstantInitialization;2693}2694 2695template<typename DeclT>2696static DeclT *getDefinitionOrSelf(DeclT *D) {2697  assert(D);2698  if (auto *Def = D->getDefinition())2699    return Def;2700  return D;2701}2702 2703bool VarDecl::isEscapingByref() const {2704  return hasAttr<BlocksAttr>() && NonParmVarDeclBits.EscapingByref;2705}2706 2707bool VarDecl::isNonEscapingByref() const {2708  return hasAttr<BlocksAttr>() && !NonParmVarDeclBits.EscapingByref;2709}2710 2711bool VarDecl::hasDependentAlignment() const {2712  QualType T = getType();2713  return T->isDependentType() || T->isUndeducedType() ||2714         llvm::any_of(specific_attrs<AlignedAttr>(), [](const AlignedAttr *AA) {2715           return AA->isAlignmentDependent();2716         });2717}2718 2719VarDecl *VarDecl::getTemplateInstantiationPattern() const {2720  const VarDecl *VD = this;2721 2722  // If this is an instantiated member, walk back to the template from which2723  // it was instantiated.2724  if (MemberSpecializationInfo *MSInfo = VD->getMemberSpecializationInfo()) {2725    if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) {2726      VD = VD->getInstantiatedFromStaticDataMember();2727      while (auto *NewVD = VD->getInstantiatedFromStaticDataMember())2728        VD = NewVD;2729    }2730  }2731 2732  // If it's an instantiated variable template specialization, find the2733  // template or partial specialization from which it was instantiated.2734  if (auto *VDTemplSpec = dyn_cast<VarTemplateSpecializationDecl>(VD)) {2735    if (isTemplateInstantiation(VDTemplSpec->getTemplateSpecializationKind())) {2736      auto From = VDTemplSpec->getInstantiatedFrom();2737      if (auto *VTD = From.dyn_cast<VarTemplateDecl *>()) {2738        while (!VTD->isMemberSpecialization()) {2739          auto *NewVTD = VTD->getInstantiatedFromMemberTemplate();2740          if (!NewVTD)2741            break;2742          VTD = NewVTD;2743        }2744        return getDefinitionOrSelf(VTD->getTemplatedDecl());2745      }2746      if (auto *VTPSD =2747              From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {2748        while (!VTPSD->isMemberSpecialization()) {2749          auto *NewVTPSD = VTPSD->getInstantiatedFromMember();2750          if (!NewVTPSD)2751            break;2752          VTPSD = NewVTPSD;2753        }2754        return getDefinitionOrSelf<VarDecl>(VTPSD);2755      }2756    }2757  }2758 2759  // If this is the pattern of a variable template, find where it was2760  // instantiated from. FIXME: Is this necessary?2761  if (VarTemplateDecl *VarTemplate = VD->getDescribedVarTemplate()) {2762    while (!VarTemplate->isMemberSpecialization()) {2763      auto *NewVT = VarTemplate->getInstantiatedFromMemberTemplate();2764      if (!NewVT)2765        break;2766      VarTemplate = NewVT;2767    }2768 2769    return getDefinitionOrSelf(VarTemplate->getTemplatedDecl());2770  }2771 2772  if (VD == this)2773    return nullptr;2774  return getDefinitionOrSelf(const_cast<VarDecl*>(VD));2775}2776 2777VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {2778  if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())2779    return cast<VarDecl>(MSI->getInstantiatedFrom());2780 2781  return nullptr;2782}2783 2784TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {2785  if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))2786    return Spec->getSpecializationKind();2787 2788  if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())2789    return MSI->getTemplateSpecializationKind();2790 2791  return TSK_Undeclared;2792}2793 2794TemplateSpecializationKind2795VarDecl::getTemplateSpecializationKindForInstantiation() const {2796  if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())2797    return MSI->getTemplateSpecializationKind();2798 2799  if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))2800    return Spec->getSpecializationKind();2801 2802  return TSK_Undeclared;2803}2804 2805SourceLocation VarDecl::getPointOfInstantiation() const {2806  if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))2807    return Spec->getPointOfInstantiation();2808 2809  if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())2810    return MSI->getPointOfInstantiation();2811 2812  return SourceLocation();2813}2814 2815VarTemplateDecl *VarDecl::getDescribedVarTemplate() const {2816  return dyn_cast_if_present<VarTemplateDecl *>(2817      getASTContext().getTemplateOrSpecializationInfo(this));2818}2819 2820void VarDecl::setDescribedVarTemplate(VarTemplateDecl *Template) {2821  getASTContext().setTemplateOrSpecializationInfo(this, Template);2822}2823 2824bool VarDecl::isKnownToBeDefined() const {2825  const auto &LangOpts = getASTContext().getLangOpts();2826  // In CUDA mode without relocatable device code, variables of form 'extern2827  // __shared__ Foo foo[]' are pointers to the base of the GPU core's shared2828  // memory pool.  These are never undefined variables, even if they appear2829  // inside of an anon namespace or static function.2830  //2831  // With CUDA relocatable device code enabled, these variables don't get2832  // special handling; they're treated like regular extern variables.2833  if (LangOpts.CUDA && !LangOpts.GPURelocatableDeviceCode &&2834      hasExternalStorage() && hasAttr<CUDASharedAttr>() &&2835      isa<IncompleteArrayType>(getType()))2836    return true;2837 2838  return hasDefinition();2839}2840 2841bool VarDecl::isNoDestroy(const ASTContext &Ctx) const {2842  if (!hasGlobalStorage())2843    return false;2844  if (hasAttr<NoDestroyAttr>())2845    return true;2846  if (hasAttr<AlwaysDestroyAttr>())2847    return false;2848 2849  using RSDKind = LangOptions::RegisterStaticDestructorsKind;2850  RSDKind K = Ctx.getLangOpts().getRegisterStaticDestructors();2851  return K == RSDKind::None ||2852         (K == RSDKind::ThreadLocal && getTLSKind() == TLS_None);2853}2854 2855QualType::DestructionKind2856VarDecl::needsDestruction(const ASTContext &Ctx) const {2857  if (EvaluatedStmt *Eval = getEvaluatedStmt())2858    if (Eval->HasConstantDestruction)2859      return QualType::DK_none;2860 2861  if (isNoDestroy(Ctx))2862    return QualType::DK_none;2863 2864  return getType().isDestructedType();2865}2866 2867bool VarDecl::hasFlexibleArrayInit(const ASTContext &Ctx) const {2868  assert(hasInit() && "Expect initializer to check for flexible array init");2869  auto *D = getType()->getAsRecordDecl();2870  if (!D || !D->hasFlexibleArrayMember())2871    return false;2872  auto *List = dyn_cast<InitListExpr>(getInit()->IgnoreParens());2873  if (!List)2874    return false;2875  const Expr *FlexibleInit = List->getInit(List->getNumInits() - 1);2876  auto InitTy = Ctx.getAsConstantArrayType(FlexibleInit->getType());2877  if (!InitTy)2878    return false;2879  return !InitTy->isZeroSize();2880}2881 2882CharUnits VarDecl::getFlexibleArrayInitChars(const ASTContext &Ctx) const {2883  assert(hasInit() && "Expect initializer to check for flexible array init");2884  auto *RD = getType()->getAsRecordDecl();2885  if (!RD || !RD->hasFlexibleArrayMember())2886    return CharUnits::Zero();2887  auto *List = dyn_cast<InitListExpr>(getInit()->IgnoreParens());2888  if (!List || List->getNumInits() == 0)2889    return CharUnits::Zero();2890  const Expr *FlexibleInit = List->getInit(List->getNumInits() - 1);2891  auto InitTy = Ctx.getAsConstantArrayType(FlexibleInit->getType());2892  if (!InitTy)2893    return CharUnits::Zero();2894  CharUnits FlexibleArraySize = Ctx.getTypeSizeInChars(InitTy);2895  const ASTRecordLayout &RL = Ctx.getASTRecordLayout(RD);2896  CharUnits FlexibleArrayOffset =2897      Ctx.toCharUnitsFromBits(RL.getFieldOffset(RL.getFieldCount() - 1));2898  if (FlexibleArrayOffset + FlexibleArraySize < RL.getSize())2899    return CharUnits::Zero();2900  return FlexibleArrayOffset + FlexibleArraySize - RL.getSize();2901}2902 2903MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {2904  if (isStaticDataMember())2905    // FIXME: Remove ?2906    // return getASTContext().getInstantiatedFromStaticDataMember(this);2907    return dyn_cast_if_present<MemberSpecializationInfo *>(2908        getASTContext().getTemplateOrSpecializationInfo(this));2909  return nullptr;2910}2911 2912void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,2913                                         SourceLocation PointOfInstantiation) {2914  assert((isa<VarTemplateSpecializationDecl>(this) ||2915          getMemberSpecializationInfo()) &&2916         "not a variable or static data member template specialization");2917 2918  if (VarTemplateSpecializationDecl *Spec =2919          dyn_cast<VarTemplateSpecializationDecl>(this)) {2920    Spec->setSpecializationKind(TSK);2921    if (TSK != TSK_ExplicitSpecialization &&2922        PointOfInstantiation.isValid() &&2923        Spec->getPointOfInstantiation().isInvalid()) {2924      Spec->setPointOfInstantiation(PointOfInstantiation);2925      if (ASTMutationListener *L = getASTContext().getASTMutationListener())2926        L->InstantiationRequested(this);2927    }2928  } else if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) {2929    MSI->setTemplateSpecializationKind(TSK);2930    if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&2931        MSI->getPointOfInstantiation().isInvalid()) {2932      MSI->setPointOfInstantiation(PointOfInstantiation);2933      if (ASTMutationListener *L = getASTContext().getASTMutationListener())2934        L->InstantiationRequested(this);2935    }2936  }2937}2938 2939void2940VarDecl::setInstantiationOfStaticDataMember(VarDecl *VD,2941                                            TemplateSpecializationKind TSK) {2942  assert(getASTContext().getTemplateOrSpecializationInfo(this).isNull() &&2943         "Previous template or instantiation?");2944  getASTContext().setInstantiatedFromStaticDataMember(this, VD, TSK);2945}2946 2947//===----------------------------------------------------------------------===//2948// ParmVarDecl Implementation2949//===----------------------------------------------------------------------===//2950 2951ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,2952                                 SourceLocation StartLoc, SourceLocation IdLoc,2953                                 const IdentifierInfo *Id, QualType T,2954                                 TypeSourceInfo *TInfo, StorageClass S,2955                                 Expr *DefArg) {2956  return new (C, DC) ParmVarDecl(ParmVar, C, DC, StartLoc, IdLoc, Id, T, TInfo,2957                                 S, DefArg);2958}2959 2960QualType ParmVarDecl::getOriginalType() const {2961  TypeSourceInfo *TSI = getTypeSourceInfo();2962  QualType T = TSI ? TSI->getType() : getType();2963  if (const auto *DT = dyn_cast<DecayedType>(T))2964    return DT->getOriginalType();2965  return T;2966}2967 2968ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) {2969  return new (C, ID)2970      ParmVarDecl(ParmVar, C, nullptr, SourceLocation(), SourceLocation(),2971                  nullptr, QualType(), nullptr, SC_None, nullptr);2972}2973 2974SourceRange ParmVarDecl::getSourceRange() const {2975  if (!hasInheritedDefaultArg()) {2976    SourceRange ArgRange = getDefaultArgRange();2977    if (ArgRange.isValid())2978      return SourceRange(getOuterLocStart(), ArgRange.getEnd());2979  }2980 2981  // DeclaratorDecl considers the range of postfix types as overlapping with the2982  // declaration name, but this is not the case with parameters in ObjC methods.2983  if (isa<ObjCMethodDecl>(getDeclContext()))2984    return SourceRange(DeclaratorDecl::getBeginLoc(), getLocation());2985 2986  return DeclaratorDecl::getSourceRange();2987}2988 2989bool ParmVarDecl::isDestroyedInCallee() const {2990  // ns_consumed only affects code generation in ARC2991  if (hasAttr<NSConsumedAttr>())2992    return getASTContext().getLangOpts().ObjCAutoRefCount;2993 2994  // FIXME: isParamDestroyedInCallee() should probably imply2995  // isDestructedType()2996  const auto *RT = getType()->getAsCanonical<RecordType>();2997  if (RT && RT->getDecl()->getDefinitionOrSelf()->isParamDestroyedInCallee() &&2998      getType().isDestructedType())2999    return true;3000 3001  return false;3002}3003 3004Expr *ParmVarDecl::getDefaultArg() {3005  assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");3006  assert(!hasUninstantiatedDefaultArg() &&3007         "Default argument is not yet instantiated!");3008 3009  Expr *Arg = getInit();3010  if (auto *E = dyn_cast_if_present<FullExpr>(Arg))3011    return E->getSubExpr();3012 3013  return Arg;3014}3015 3016void ParmVarDecl::setDefaultArg(Expr *defarg) {3017  ParmVarDeclBits.DefaultArgKind = DAK_Normal;3018  Init = defarg;3019}3020 3021SourceRange ParmVarDecl::getDefaultArgRange() const {3022  switch (ParmVarDeclBits.DefaultArgKind) {3023  case DAK_None:3024  case DAK_Unparsed:3025    // Nothing we can do here.3026    return SourceRange();3027 3028  case DAK_Uninstantiated:3029    return getUninstantiatedDefaultArg()->getSourceRange();3030 3031  case DAK_Normal:3032    if (const Expr *E = getInit())3033      return E->getSourceRange();3034 3035    // Missing an actual expression, may be invalid.3036    return SourceRange();3037  }3038  llvm_unreachable("Invalid default argument kind.");3039}3040 3041void ParmVarDecl::setUninstantiatedDefaultArg(Expr *arg) {3042  ParmVarDeclBits.DefaultArgKind = DAK_Uninstantiated;3043  Init = arg;3044}3045 3046Expr *ParmVarDecl::getUninstantiatedDefaultArg() {3047  assert(hasUninstantiatedDefaultArg() &&3048         "Wrong kind of initialization expression!");3049  return cast_if_present<Expr>(cast<Stmt *>(Init));3050}3051 3052bool ParmVarDecl::hasDefaultArg() const {3053  // FIXME: We should just return false for DAK_None here once callers are3054  // prepared for the case that we encountered an invalid default argument and3055  // were unable to even build an invalid expression.3056  return hasUnparsedDefaultArg() || hasUninstantiatedDefaultArg() ||3057         !Init.isNull();3058}3059 3060void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {3061  getASTContext().setParameterIndex(this, parameterIndex);3062  ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;3063}3064 3065unsigned ParmVarDecl::getParameterIndexLarge() const {3066  return getASTContext().getParameterIndex(this);3067}3068 3069//===----------------------------------------------------------------------===//3070// FunctionDecl Implementation3071//===----------------------------------------------------------------------===//3072 3073FunctionDecl::FunctionDecl(Kind DK, ASTContext &C, DeclContext *DC,3074                           SourceLocation StartLoc,3075                           const DeclarationNameInfo &NameInfo, QualType T,3076                           TypeSourceInfo *TInfo, StorageClass S,3077                           bool UsesFPIntrin, bool isInlineSpecified,3078                           ConstexprSpecKind ConstexprKind,3079                           const AssociatedConstraint &TrailingRequiresClause)3080    : DeclaratorDecl(DK, DC, NameInfo.getLoc(), NameInfo.getName(), T, TInfo,3081                     StartLoc),3082      DeclContext(DK), redeclarable_base(C), Body(), ODRHash(0),3083      EndRangeLoc(NameInfo.getEndLoc()), DNLoc(NameInfo.getInfo()) {3084  assert(T.isNull() || T->isFunctionType());3085  FunctionDeclBits.SClass = S;3086  FunctionDeclBits.IsInline = isInlineSpecified;3087  FunctionDeclBits.IsInlineSpecified = isInlineSpecified;3088  FunctionDeclBits.IsVirtualAsWritten = false;3089  FunctionDeclBits.IsPureVirtual = false;3090  FunctionDeclBits.HasInheritedPrototype = false;3091  FunctionDeclBits.HasWrittenPrototype = true;3092  FunctionDeclBits.IsDeleted = false;3093  FunctionDeclBits.IsTrivial = false;3094  FunctionDeclBits.IsTrivialForCall = false;3095  FunctionDeclBits.IsDefaulted = false;3096  FunctionDeclBits.IsExplicitlyDefaulted = false;3097  FunctionDeclBits.HasDefaultedOrDeletedInfo = false;3098  FunctionDeclBits.IsIneligibleOrNotSelected = false;3099  FunctionDeclBits.HasImplicitReturnZero = false;3100  FunctionDeclBits.IsLateTemplateParsed = false;3101  FunctionDeclBits.IsInstantiatedFromMemberTemplate = false;3102  FunctionDeclBits.ConstexprKind = static_cast<uint64_t>(ConstexprKind);3103  FunctionDeclBits.BodyContainsImmediateEscalatingExpression = false;3104  FunctionDeclBits.InstantiationIsPending = false;3105  FunctionDeclBits.UsesSEHTry = false;3106  FunctionDeclBits.UsesFPIntrin = UsesFPIntrin;3107  FunctionDeclBits.HasSkippedBody = false;3108  FunctionDeclBits.WillHaveBody = false;3109  FunctionDeclBits.IsMultiVersion = false;3110  FunctionDeclBits.DeductionCandidateKind =3111      static_cast<unsigned char>(DeductionCandidate::Normal);3112  FunctionDeclBits.HasODRHash = false;3113  FunctionDeclBits.FriendConstraintRefersToEnclosingTemplate = false;3114 3115  if (TrailingRequiresClause)3116    setTrailingRequiresClause(TrailingRequiresClause);3117}3118 3119void FunctionDecl::getNameForDiagnostic(3120    raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const {3121  NamedDecl::getNameForDiagnostic(OS, Policy, Qualified);3122  const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();3123  if (TemplateArgs)3124    printTemplateArgumentList(OS, TemplateArgs->asArray(), Policy);3125}3126 3127bool FunctionDecl::isVariadic() const {3128  if (const auto *FT = getType()->getAs<FunctionProtoType>())3129    return FT->isVariadic();3130  return false;3131}3132 3133FunctionDecl::DefaultedOrDeletedFunctionInfo *3134FunctionDecl::DefaultedOrDeletedFunctionInfo::Create(3135    ASTContext &Context, ArrayRef<DeclAccessPair> Lookups,3136    StringLiteral *DeletedMessage) {3137  static constexpr size_t Alignment =3138      std::max({alignof(DefaultedOrDeletedFunctionInfo),3139                alignof(DeclAccessPair), alignof(StringLiteral *)});3140  size_t Size = totalSizeToAlloc<DeclAccessPair, StringLiteral *>(3141      Lookups.size(), DeletedMessage != nullptr);3142 3143  DefaultedOrDeletedFunctionInfo *Info =3144      new (Context.Allocate(Size, Alignment)) DefaultedOrDeletedFunctionInfo;3145  Info->NumLookups = Lookups.size();3146  Info->HasDeletedMessage = DeletedMessage != nullptr;3147 3148  llvm::uninitialized_copy(Lookups, Info->getTrailingObjects<DeclAccessPair>());3149  if (DeletedMessage)3150    *Info->getTrailingObjects<StringLiteral *>() = DeletedMessage;3151  return Info;3152}3153 3154void FunctionDecl::setDefaultedOrDeletedInfo(3155    DefaultedOrDeletedFunctionInfo *Info) {3156  assert(!FunctionDeclBits.HasDefaultedOrDeletedInfo && "already have this");3157  assert(!Body && "can't replace function body with defaulted function info");3158 3159  FunctionDeclBits.HasDefaultedOrDeletedInfo = true;3160  DefaultedOrDeletedInfo = Info;3161}3162 3163void FunctionDecl::setDeletedAsWritten(bool D, StringLiteral *Message) {3164  FunctionDeclBits.IsDeleted = D;3165 3166  if (Message) {3167    assert(isDeletedAsWritten() && "Function must be deleted");3168    if (FunctionDeclBits.HasDefaultedOrDeletedInfo)3169      DefaultedOrDeletedInfo->setDeletedMessage(Message);3170    else3171      setDefaultedOrDeletedInfo(DefaultedOrDeletedFunctionInfo::Create(3172          getASTContext(), /*Lookups=*/{}, Message));3173  }3174}3175 3176void FunctionDecl::DefaultedOrDeletedFunctionInfo::setDeletedMessage(3177    StringLiteral *Message) {3178  // We should never get here with the DefaultedOrDeletedInfo populated, but3179  // no space allocated for the deleted message, since that would require3180  // recreating this, but setDefaultedOrDeletedInfo() disallows overwriting3181  // an already existing DefaultedOrDeletedFunctionInfo.3182  assert(HasDeletedMessage &&3183         "No space to store a delete message in this DefaultedOrDeletedInfo");3184  *getTrailingObjects<StringLiteral *>() = Message;3185}3186 3187FunctionDecl::DefaultedOrDeletedFunctionInfo *3188FunctionDecl::getDefaultedOrDeletedInfo() const {3189  return FunctionDeclBits.HasDefaultedOrDeletedInfo ? DefaultedOrDeletedInfo3190                                                    : nullptr;3191}3192 3193bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {3194  for (const auto *I : redecls()) {3195    if (I->doesThisDeclarationHaveABody()) {3196      Definition = I;3197      return true;3198    }3199  }3200 3201  return false;3202}3203 3204bool FunctionDecl::hasTrivialBody() const {3205  const Stmt *S = getBody();3206  if (!S) {3207    // Since we don't have a body for this function, we don't know if it's3208    // trivial or not.3209    return false;3210  }3211 3212  if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())3213    return true;3214  return false;3215}3216 3217bool FunctionDecl::isThisDeclarationInstantiatedFromAFriendDefinition() const {3218  if (!getFriendObjectKind())3219    return false;3220 3221  // Check for a friend function instantiated from a friend function3222  // definition in a templated class.3223  if (const FunctionDecl *InstantiatedFrom =3224          getInstantiatedFromMemberFunction())3225    return InstantiatedFrom->getFriendObjectKind() &&3226           InstantiatedFrom->isThisDeclarationADefinition();3227 3228  // Check for a friend function template instantiated from a friend3229  // function template definition in a templated class.3230  if (const FunctionTemplateDecl *Template = getDescribedFunctionTemplate()) {3231    if (const FunctionTemplateDecl *InstantiatedFrom =3232            Template->getInstantiatedFromMemberTemplate())3233      return InstantiatedFrom->getFriendObjectKind() &&3234             InstantiatedFrom->isThisDeclarationADefinition();3235  }3236 3237  return false;3238}3239 3240bool FunctionDecl::isDefined(const FunctionDecl *&Definition,3241                             bool CheckForPendingFriendDefinition) const {3242  for (const FunctionDecl *FD : redecls()) {3243    if (FD->isThisDeclarationADefinition()) {3244      Definition = FD;3245      return true;3246    }3247 3248    // If this is a friend function defined in a class template, it does not3249    // have a body until it is used, nevertheless it is a definition, see3250    // [temp.inst]p2:3251    //3252    // ... for the purpose of determining whether an instantiated redeclaration3253    // is valid according to [basic.def.odr] and [class.mem], a declaration that3254    // corresponds to a definition in the template is considered to be a3255    // definition.3256    //3257    // The following code must produce redefinition error:3258    //3259    //     template<typename T> struct C20 { friend void func_20() {} };3260    //     C20<int> c20i;3261    //     void func_20() {}3262    //3263    if (CheckForPendingFriendDefinition &&3264        FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {3265      Definition = FD;3266      return true;3267    }3268  }3269 3270  return false;3271}3272 3273Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {3274  if (!hasBody(Definition))3275    return nullptr;3276 3277  assert(!Definition->FunctionDeclBits.HasDefaultedOrDeletedInfo &&3278         "definition should not have a body");3279  if (Definition->Body)3280    return Definition->Body.get(getASTContext().getExternalSource());3281 3282  return nullptr;3283}3284 3285void FunctionDecl::setBody(Stmt *B) {3286  FunctionDeclBits.HasDefaultedOrDeletedInfo = false;3287  Body = LazyDeclStmtPtr(B);3288  if (B)3289    EndRangeLoc = B->getEndLoc();3290}3291 3292void FunctionDecl::setIsPureVirtual(bool P) {3293  FunctionDeclBits.IsPureVirtual = P;3294  if (P)3295    if (auto *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))3296      Parent->markedVirtualFunctionPure();3297}3298 3299template<std::size_t Len>3300static bool isNamed(const NamedDecl *ND, const char (&Str)[Len]) {3301  const IdentifierInfo *II = ND->getIdentifier();3302  return II && II->isStr(Str);3303}3304 3305bool FunctionDecl::isImmediateEscalating() const {3306  // C++23 [expr.const]/p173307  // An immediate-escalating function is3308  //  - the call operator of a lambda that is not declared with the consteval3309  //  specifier,3310  if (isLambdaCallOperator(this) && !isConsteval())3311    return true;3312  // - a defaulted special member function that is not declared with the3313  // consteval specifier,3314  if (isDefaulted() && !isConsteval())3315    return true;3316 3317  if (auto *CD = dyn_cast<CXXConstructorDecl>(this);3318      CD && CD->isInheritingConstructor())3319    return CD->getInheritedConstructor().getConstructor();3320 3321  // Destructors are not immediate escalating.3322  if (isa<CXXDestructorDecl>(this))3323    return false;3324 3325  // - a function that results from the instantiation of a templated entity3326  // defined with the constexpr specifier.3327  TemplatedKind TK = getTemplatedKind();3328  if (TK != TK_NonTemplate && TK != TK_DependentNonTemplate &&3329      isConstexprSpecified())3330    return true;3331  return false;3332}3333 3334bool FunctionDecl::isImmediateFunction() const {3335  // C++23 [expr.const]/p183336  // An immediate function is a function or constructor that is3337  // - declared with the consteval specifier3338  if (isConsteval())3339    return true;3340  // - an immediate-escalating function F whose function body contains an3341  // immediate-escalating expression3342  if (isImmediateEscalating() && BodyContainsImmediateEscalatingExpressions())3343    return true;3344 3345  if (auto *CD = dyn_cast<CXXConstructorDecl>(this);3346      CD && CD->isInheritingConstructor())3347    return CD->getInheritedConstructor()3348        .getConstructor()3349        ->isImmediateFunction();3350 3351  if (FunctionDecl *P = getTemplateInstantiationPattern();3352      P && P->isImmediateFunction())3353    return true;3354 3355  if (const auto *MD = dyn_cast<CXXMethodDecl>(this);3356      MD && MD->isLambdaStaticInvoker())3357    return MD->getParent()->getLambdaCallOperator()->isImmediateFunction();3358 3359  return false;3360}3361 3362bool FunctionDecl::isMain() const {3363  return isNamed(this, "main") && !getLangOpts().Freestanding &&3364         !getLangOpts().HLSL &&3365         (getDeclContext()->getRedeclContext()->isTranslationUnit() ||3366          isExternC());3367}3368 3369bool FunctionDecl::isMSVCRTEntryPoint() const {3370  const TranslationUnitDecl *TUnit =3371      dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());3372  if (!TUnit)3373    return false;3374 3375  // Even though we aren't really targeting MSVCRT if we are freestanding,3376  // semantic analysis for these functions remains the same.3377 3378  // MSVCRT entry points only exist on MSVCRT targets.3379  if (!TUnit->getASTContext().getTargetInfo().getTriple().isOSMSVCRT() &&3380      !TUnit->getASTContext().getTargetInfo().getTriple().isUEFI())3381    return false;3382 3383  // Nameless functions like constructors cannot be entry points.3384  if (!getIdentifier())3385    return false;3386 3387  return llvm::StringSwitch<bool>(getName())3388      .Cases({"main",     // an ANSI console app3389              "wmain",    // a Unicode console App3390              "WinMain",  // an ANSI GUI app3391              "wWinMain", // a Unicode GUI app3392              "DllMain"}, // a DLL3393             true)3394      .Default(false);3395}3396 3397bool FunctionDecl::isReservedGlobalPlacementOperator() const {3398  if (!getDeclName().isAnyOperatorNewOrDelete())3399    return false;3400 3401  if (!getDeclContext()->getRedeclContext()->isTranslationUnit())3402    return false;3403 3404  if (isTypeAwareOperatorNewOrDelete())3405    return false;3406 3407  const auto *proto = getType()->castAs<FunctionProtoType>();3408  if (proto->getNumParams() != 2 || proto->isVariadic())3409    return false;3410 3411  const ASTContext &Context =3412      cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())3413          ->getASTContext();3414 3415  // The result type and first argument type are constant across all3416  // these operators.  The second argument must be exactly void*.3417  return (proto->getParamType(1).getCanonicalType() == Context.VoidPtrTy);3418}3419 3420bool FunctionDecl::isUsableAsGlobalAllocationFunctionInConstantEvaluation(3421    UnsignedOrNone *AlignmentParam, bool *IsNothrow) const {3422  if (!getDeclName().isAnyOperatorNewOrDelete())3423    return false;3424 3425  if (isa<CXXRecordDecl>(getDeclContext()))3426    return false;3427 3428  // This can only fail for an invalid 'operator new' declaration.3429  if (!getDeclContext()->getRedeclContext()->isTranslationUnit())3430    return false;3431 3432  if (isVariadic())3433    return false;3434 3435  if (isTypeAwareOperatorNewOrDelete()) {3436    bool IsDelete = getDeclName().isAnyOperatorDelete();3437    unsigned RequiredParameterCount =3438        IsDelete ? FunctionDecl::RequiredTypeAwareDeleteParameterCount3439                 : FunctionDecl::RequiredTypeAwareNewParameterCount;3440    if (AlignmentParam)3441      *AlignmentParam =3442          /* type identity */ 1U + /* address */ IsDelete + /* size */ 1U;3443    if (RequiredParameterCount == getNumParams())3444      return true;3445    if (getNumParams() > RequiredParameterCount + 1)3446      return false;3447    if (!getParamDecl(RequiredParameterCount)->getType()->isNothrowT())3448      return false;3449 3450    if (IsNothrow)3451      *IsNothrow = true;3452    return true;3453  }3454 3455  const auto *FPT = getType()->castAs<FunctionProtoType>();3456  if (FPT->getNumParams() == 0 || FPT->getNumParams() > 4)3457    return false;3458 3459  // If this is a single-parameter function, it must be a replaceable global3460  // allocation or deallocation function.3461  if (FPT->getNumParams() == 1)3462    return true;3463 3464  unsigned Params = 1;3465  QualType Ty = FPT->getParamType(Params);3466  const ASTContext &Ctx = getASTContext();3467 3468  auto Consume = [&] {3469    ++Params;3470    Ty = Params < FPT->getNumParams() ? FPT->getParamType(Params) : QualType();3471  };3472 3473  // In C++14, the next parameter can be a 'std::size_t' for sized delete.3474  bool IsSizedDelete = false;3475  if (Ctx.getLangOpts().SizedDeallocation &&3476      getDeclName().isAnyOperatorDelete() &&3477      Ctx.hasSameType(Ty, Ctx.getSizeType())) {3478    IsSizedDelete = true;3479    Consume();3480  }3481 3482  // In C++17, the next parameter can be a 'std::align_val_t' for aligned3483  // new/delete.3484  if (Ctx.getLangOpts().AlignedAllocation && !Ty.isNull() && Ty->isAlignValT()) {3485    Consume();3486    if (AlignmentParam)3487      *AlignmentParam = Params;3488  }3489 3490  // If this is not a sized delete, the next parameter can be a3491  // 'const std::nothrow_t&'.3492  if (!IsSizedDelete && !Ty.isNull() && Ty->isReferenceType()) {3493    Ty = Ty->getPointeeType();3494    if (Ty.getCVRQualifiers() != Qualifiers::Const)3495      return false;3496    if (Ty->isNothrowT()) {3497      if (IsNothrow)3498        *IsNothrow = true;3499      Consume();3500    }3501  }3502 3503  // Finally, recognize the not yet standard versions of new that take a3504  // hot/cold allocation hint (__hot_cold_t). These are currently supported by3505  // tcmalloc (see3506  // https://github.com/google/tcmalloc/blob/220043886d4e2efff7a5702d5172cb8065253664/tcmalloc/malloc_extension.h#L53).3507  if (!IsSizedDelete && !Ty.isNull() && Ty->isEnumeralType()) {3508    QualType T = Ty;3509    while (const auto *TD = T->getAs<TypedefType>())3510      T = TD->getDecl()->getUnderlyingType();3511    const IdentifierInfo *II =3512        T->castAsCanonical<EnumType>()->getDecl()->getIdentifier();3513    if (II && II->isStr("__hot_cold_t"))3514      Consume();3515  }3516 3517  return Params == FPT->getNumParams();3518}3519 3520bool FunctionDecl::isInlineBuiltinDeclaration() const {3521  if (!getBuiltinID())3522    return false;3523 3524  const FunctionDecl *Definition;3525  if (!hasBody(Definition))3526    return false;3527 3528  if (!Definition->isInlineSpecified() ||3529      !Definition->hasAttr<AlwaysInlineAttr>())3530    return false;3531 3532  ASTContext &Context = getASTContext();3533  switch (Context.GetGVALinkageForFunction(Definition)) {3534  case GVA_Internal:3535  case GVA_DiscardableODR:3536  case GVA_StrongODR:3537    return false;3538  case GVA_AvailableExternally:3539  case GVA_StrongExternal:3540    return true;3541  }3542  llvm_unreachable("Unknown GVALinkage");3543}3544 3545bool FunctionDecl::isDestroyingOperatorDelete() const {3546  return getASTContext().isDestroyingOperatorDelete(this);3547}3548 3549void FunctionDecl::setIsDestroyingOperatorDelete(bool IsDestroyingDelete) {3550  getASTContext().setIsDestroyingOperatorDelete(this, IsDestroyingDelete);3551}3552 3553bool FunctionDecl::isTypeAwareOperatorNewOrDelete() const {3554  return getASTContext().isTypeAwareOperatorNewOrDelete(this);3555}3556 3557void FunctionDecl::setIsTypeAwareOperatorNewOrDelete(bool IsTypeAware) {3558  getASTContext().setIsTypeAwareOperatorNewOrDelete(this, IsTypeAware);3559}3560 3561UsualDeleteParams FunctionDecl::getUsualDeleteParams() const {3562  UsualDeleteParams Params;3563 3564  // This function should only be called for operator delete declarations.3565  assert(getDeclName().isAnyOperatorDelete());3566  if (!getDeclName().isAnyOperatorDelete())3567    return Params;3568 3569  const FunctionProtoType *FPT = getType()->castAs<FunctionProtoType>();3570  auto AI = FPT->param_type_begin(), AE = FPT->param_type_end();3571 3572  if (isTypeAwareOperatorNewOrDelete()) {3573    Params.TypeAwareDelete = TypeAwareAllocationMode::Yes;3574    assert(AI != AE);3575    ++AI;3576  }3577 3578  // The first argument after the type-identity parameter (if any) is3579  // always a void* (or C* for a destroying operator delete for class3580  // type C).3581  ++AI;3582 3583  // The next parameter may be a std::destroying_delete_t.3584  if (isDestroyingOperatorDelete()) {3585    assert(!isTypeAwareAllocation(Params.TypeAwareDelete));3586    Params.DestroyingDelete = true;3587    assert(AI != AE);3588    ++AI;3589  }3590 3591  // Figure out what other parameters we should be implicitly passing.3592  if (AI != AE && (*AI)->isIntegerType()) {3593    Params.Size = true;3594    ++AI;3595  } else3596    assert(!isTypeAwareAllocation(Params.TypeAwareDelete));3597 3598  if (AI != AE && (*AI)->isAlignValT()) {3599    Params.Alignment = AlignedAllocationMode::Yes;3600    ++AI;3601  } else3602    assert(!isTypeAwareAllocation(Params.TypeAwareDelete));3603 3604  assert(AI == AE && "unexpected usual deallocation function parameter");3605  return Params;3606}3607 3608LanguageLinkage FunctionDecl::getLanguageLinkage() const {3609  return getDeclLanguageLinkage(*this);3610}3611 3612bool FunctionDecl::isExternC() const {3613  return isDeclExternC(*this);3614}3615 3616bool FunctionDecl::isInExternCContext() const {3617  if (DeviceKernelAttr::isOpenCLSpelling(getAttr<DeviceKernelAttr>()))3618    return true;3619  return getLexicalDeclContext()->isExternCContext();3620}3621 3622bool FunctionDecl::isInExternCXXContext() const {3623  return getLexicalDeclContext()->isExternCXXContext();3624}3625 3626bool FunctionDecl::isGlobal() const {3627  if (const auto *Method = dyn_cast<CXXMethodDecl>(this))3628    return Method->isStatic();3629 3630  if (getCanonicalDecl()->getStorageClass() == SC_Static)3631    return false;3632 3633  for (const DeclContext *DC = getDeclContext();3634       DC->isNamespace();3635       DC = DC->getParent()) {3636    if (const auto *Namespace = cast<NamespaceDecl>(DC)) {3637      if (!Namespace->getDeclName())3638        return false;3639    }3640  }3641 3642  return true;3643}3644 3645bool FunctionDecl::isNoReturn() const {3646  if (hasAttr<NoReturnAttr>() || hasAttr<CXX11NoReturnAttr>() ||3647      hasAttr<C11NoReturnAttr>())3648    return true;3649 3650  if (auto *FnTy = getType()->getAs<FunctionType>())3651    return FnTy->getNoReturnAttr();3652 3653  return false;3654}3655 3656bool FunctionDecl::isAnalyzerNoReturn() const {3657  return hasAttr<AnalyzerNoReturnAttr>();3658}3659 3660bool FunctionDecl::isMemberLikeConstrainedFriend() const {3661  // C++20 [temp.friend]p9:3662  //   A non-template friend declaration with a requires-clause [or]3663  //   a friend function template with a constraint that depends on a template3664  //   parameter from an enclosing template [...] does not declare the same3665  //   function or function template as a declaration in any other scope.3666 3667  // If this isn't a friend then it's not a member-like constrained friend.3668  if (!getFriendObjectKind()) {3669    return false;3670  }3671 3672  if (!getDescribedFunctionTemplate()) {3673    // If these friends don't have constraints, they aren't constrained, and3674    // thus don't fall under temp.friend p9. Else the simple presence of a3675    // constraint makes them unique.3676    return !getTrailingRequiresClause().isNull();3677  }3678 3679  return FriendConstraintRefersToEnclosingTemplate();3680}3681 3682MultiVersionKind FunctionDecl::getMultiVersionKind() const {3683  if (hasAttr<TargetAttr>())3684    return MultiVersionKind::Target;3685  if (hasAttr<TargetVersionAttr>())3686    return MultiVersionKind::TargetVersion;3687  if (hasAttr<CPUDispatchAttr>())3688    return MultiVersionKind::CPUDispatch;3689  if (hasAttr<CPUSpecificAttr>())3690    return MultiVersionKind::CPUSpecific;3691  if (hasAttr<TargetClonesAttr>())3692    return MultiVersionKind::TargetClones;3693  return MultiVersionKind::None;3694}3695 3696bool FunctionDecl::isCPUDispatchMultiVersion() const {3697  return isMultiVersion() && hasAttr<CPUDispatchAttr>();3698}3699 3700bool FunctionDecl::isCPUSpecificMultiVersion() const {3701  return isMultiVersion() && hasAttr<CPUSpecificAttr>();3702}3703 3704bool FunctionDecl::isTargetMultiVersion() const {3705  return isMultiVersion() &&3706         (hasAttr<TargetAttr>() || hasAttr<TargetVersionAttr>());3707}3708 3709bool FunctionDecl::isTargetMultiVersionDefault() const {3710  if (!isMultiVersion())3711    return false;3712  if (hasAttr<TargetAttr>())3713    return getAttr<TargetAttr>()->isDefaultVersion();3714  return hasAttr<TargetVersionAttr>() &&3715         getAttr<TargetVersionAttr>()->isDefaultVersion();3716}3717 3718bool FunctionDecl::isTargetClonesMultiVersion() const {3719  return isMultiVersion() && hasAttr<TargetClonesAttr>();3720}3721 3722bool FunctionDecl::isTargetVersionMultiVersion() const {3723  return isMultiVersion() && hasAttr<TargetVersionAttr>();3724}3725 3726void3727FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {3728  redeclarable_base::setPreviousDecl(PrevDecl);3729 3730  if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {3731    FunctionTemplateDecl *PrevFunTmpl3732      = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : nullptr;3733    assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");3734    FunTmpl->setPreviousDecl(PrevFunTmpl);3735  }3736 3737  if (PrevDecl && PrevDecl->isInlined())3738    setImplicitlyInline(true);3739}3740 3741FunctionDecl *FunctionDecl::getCanonicalDecl() { return getFirstDecl(); }3742 3743/// Returns a value indicating whether this function corresponds to a builtin3744/// function.3745///3746/// The function corresponds to a built-in function if it is declared at3747/// translation scope or within an extern "C" block and its name matches with3748/// the name of a builtin. The returned value will be 0 for functions that do3749/// not correspond to a builtin, a value of type \c Builtin::ID if in the3750/// target-independent range \c [1,Builtin::First), or a target-specific builtin3751/// value.3752///3753/// \param ConsiderWrapperFunctions If true, we should consider wrapper3754/// functions as their wrapped builtins. This shouldn't be done in general, but3755/// it's useful in Sema to diagnose calls to wrappers based on their semantics.3756unsigned FunctionDecl::getBuiltinID(bool ConsiderWrapperFunctions) const {3757  unsigned BuiltinID = 0;3758 3759  if (const auto *ABAA = getAttr<ArmBuiltinAliasAttr>()) {3760    BuiltinID = ABAA->getBuiltinName()->getBuiltinID();3761  } else if (const auto *BAA = getAttr<BuiltinAliasAttr>()) {3762    BuiltinID = BAA->getBuiltinName()->getBuiltinID();3763  } else if (const auto *A = getAttr<BuiltinAttr>()) {3764    BuiltinID = A->getID();3765  }3766 3767  if (!BuiltinID)3768    return 0;3769 3770  // If the function is marked "overloadable", it has a different mangled name3771  // and is not the C library function.3772  if (!ConsiderWrapperFunctions && hasAttr<OverloadableAttr>() &&3773      (!hasAttr<ArmBuiltinAliasAttr>() && !hasAttr<BuiltinAliasAttr>()))3774    return 0;3775 3776  if (getASTContext().getLangOpts().CPlusPlus &&3777      BuiltinID == Builtin::BI__builtin_counted_by_ref)3778    return 0;3779 3780  const ASTContext &Context = getASTContext();3781  if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))3782    return BuiltinID;3783 3784  // This function has the name of a known C library3785  // function. Determine whether it actually refers to the C library3786  // function or whether it just has the same name.3787 3788  // If this is a static function, it's not a builtin.3789  if (!ConsiderWrapperFunctions && getStorageClass() == SC_Static)3790    return 0;3791 3792  // OpenCL v1.2 s6.9.f - The library functions defined in3793  // the C99 standard headers are not available.3794  if (Context.getLangOpts().OpenCL &&3795      Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))3796    return 0;3797 3798  // CUDA does not have device-side standard library. printf and malloc are the3799  // only special cases that are supported by device-side runtime.3800  if (Context.getLangOpts().CUDA && hasAttr<CUDADeviceAttr>() &&3801      !hasAttr<CUDAHostAttr>() &&3802      !(BuiltinID == Builtin::BIprintf || BuiltinID == Builtin::BImalloc))3803    return 0;3804 3805  // As AMDGCN implementation of OpenMP does not have a device-side standard3806  // library, none of the predefined library functions except printf and malloc3807  // should be treated as a builtin i.e. 0 should be returned for them.3808  if (Context.getTargetInfo().getTriple().isAMDGCN() &&3809      Context.getLangOpts().OpenMPIsTargetDevice &&3810      Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&3811      !(BuiltinID == Builtin::BIprintf || BuiltinID == Builtin::BImalloc))3812    return 0;3813 3814  return BuiltinID;3815}3816 3817/// getNumParams - Return the number of parameters this function must have3818/// based on its FunctionType.  This is the length of the ParamInfo array3819/// after it has been created.3820unsigned FunctionDecl::getNumParams() const {3821  const auto *FPT = getType()->getAs<FunctionProtoType>();3822  return FPT ? FPT->getNumParams() : 0;3823}3824 3825void FunctionDecl::setParams(ASTContext &C,3826                             ArrayRef<ParmVarDecl *> NewParamInfo) {3827  assert(!ParamInfo && "Already has param info!");3828  assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");3829 3830  // Zero params -> null pointer.3831  if (!NewParamInfo.empty()) {3832    ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];3833    llvm::copy(NewParamInfo, ParamInfo);3834  }3835}3836 3837/// getMinRequiredArguments - Returns the minimum number of arguments3838/// needed to call this function. This may be fewer than the number of3839/// function parameters, if some of the parameters have default3840/// arguments (in C++) or are parameter packs (C++11).3841unsigned FunctionDecl::getMinRequiredArguments() const {3842  if (!getASTContext().getLangOpts().CPlusPlus)3843    return getNumParams();3844 3845  // Note that it is possible for a parameter with no default argument to3846  // follow a parameter with a default argument.3847  unsigned NumRequiredArgs = 0;3848  unsigned MinParamsSoFar = 0;3849  for (auto *Param : parameters()) {3850    if (!Param->isParameterPack()) {3851      ++MinParamsSoFar;3852      if (!Param->hasDefaultArg())3853        NumRequiredArgs = MinParamsSoFar;3854    }3855  }3856  return NumRequiredArgs;3857}3858 3859bool FunctionDecl::hasCXXExplicitFunctionObjectParameter() const {3860  return getNumParams() != 0 && getParamDecl(0)->isExplicitObjectParameter();3861}3862 3863unsigned FunctionDecl::getNumNonObjectParams() const {3864  return getNumParams() -3865         static_cast<unsigned>(hasCXXExplicitFunctionObjectParameter());3866}3867 3868unsigned FunctionDecl::getMinRequiredExplicitArguments() const {3869  return getMinRequiredArguments() -3870         static_cast<unsigned>(hasCXXExplicitFunctionObjectParameter());3871}3872 3873bool FunctionDecl::hasOneParamOrDefaultArgs() const {3874  return getNumParams() == 1 ||3875         (getNumParams() > 1 &&3876          llvm::all_of(llvm::drop_begin(parameters()),3877                       [](ParmVarDecl *P) { return P->hasDefaultArg(); }));3878}3879 3880/// The combination of the extern and inline keywords under MSVC forces3881/// the function to be required.3882///3883/// Note: This function assumes that we will only get called when isInlined()3884/// would return true for this FunctionDecl.3885bool FunctionDecl::isMSExternInline() const {3886  assert(isInlined() && "expected to get called on an inlined function!");3887 3888  const ASTContext &Context = getASTContext();3889  if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&3890      !hasAttr<DLLExportAttr>())3891    return false;3892 3893  for (const FunctionDecl *FD = getMostRecentDecl(); FD;3894       FD = FD->getPreviousDecl())3895    if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)3896      return true;3897 3898  return false;3899}3900 3901static bool redeclForcesDefMSVC(const FunctionDecl *Redecl) {3902  if (Redecl->getStorageClass() != SC_Extern)3903    return false;3904 3905  for (const FunctionDecl *FD = Redecl->getPreviousDecl(); FD;3906       FD = FD->getPreviousDecl())3907    if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)3908      return false;3909 3910  return true;3911}3912 3913static bool RedeclForcesDefC99(const FunctionDecl *Redecl) {3914  // Only consider file-scope declarations in this test.3915  if (!Redecl->getLexicalDeclContext()->isTranslationUnit())3916    return false;3917 3918  // Only consider explicit declarations; the presence of a builtin for a3919  // libcall shouldn't affect whether a definition is externally visible.3920  if (Redecl->isImplicit())3921    return false;3922 3923  if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)3924    return true; // Not an inline definition3925 3926  return false;3927}3928 3929/// For a function declaration in C or C++, determine whether this3930/// declaration causes the definition to be externally visible.3931///3932/// For instance, this determines if adding the current declaration to the set3933/// of redeclarations of the given functions causes3934/// isInlineDefinitionExternallyVisible to change from false to true.3935bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const {3936  assert(!doesThisDeclarationHaveABody() &&3937         "Must have a declaration without a body.");3938 3939  const ASTContext &Context = getASTContext();3940 3941  if (Context.getLangOpts().MSVCCompat) {3942    const FunctionDecl *Definition;3943    if (hasBody(Definition) && Definition->isInlined() &&3944        redeclForcesDefMSVC(this))3945      return true;3946  }3947 3948  if (Context.getLangOpts().CPlusPlus)3949    return false;3950 3951  if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {3952    // With GNU inlining, a declaration with 'inline' but not 'extern', forces3953    // an externally visible definition.3954    //3955    // FIXME: What happens if gnu_inline gets added on after the first3956    // declaration?3957    if (!isInlineSpecified() || getStorageClass() == SC_Extern)3958      return false;3959 3960    const FunctionDecl *Prev = this;3961    bool FoundBody = false;3962    while ((Prev = Prev->getPreviousDecl())) {3963      FoundBody |= Prev->doesThisDeclarationHaveABody();3964 3965      if (Prev->doesThisDeclarationHaveABody()) {3966        // If it's not the case that both 'inline' and 'extern' are3967        // specified on the definition, then it is always externally visible.3968        if (!Prev->isInlineSpecified() ||3969            Prev->getStorageClass() != SC_Extern)3970          return false;3971      } else if (Prev->isInlineSpecified() &&3972                 Prev->getStorageClass() != SC_Extern) {3973        return false;3974      }3975    }3976    return FoundBody;3977  }3978 3979  // C99 6.7.4p6:3980  //   [...] If all of the file scope declarations for a function in a3981  //   translation unit include the inline function specifier without extern,3982  //   then the definition in that translation unit is an inline definition.3983  if (isInlineSpecified() && getStorageClass() != SC_Extern)3984    return false;3985  const FunctionDecl *Prev = this;3986  bool FoundBody = false;3987  while ((Prev = Prev->getPreviousDecl())) {3988    FoundBody |= Prev->doesThisDeclarationHaveABody();3989    if (RedeclForcesDefC99(Prev))3990      return false;3991  }3992  return FoundBody;3993}3994 3995FunctionTypeLoc FunctionDecl::getFunctionTypeLoc() const {3996  const TypeSourceInfo *TSI = getTypeSourceInfo();3997 3998  if (!TSI)3999    return FunctionTypeLoc();4000 4001  TypeLoc TL = TSI->getTypeLoc();4002  FunctionTypeLoc FTL;4003 4004  while (!(FTL = TL.getAs<FunctionTypeLoc>())) {4005    if (const auto PTL = TL.getAs<ParenTypeLoc>())4006      TL = PTL.getInnerLoc();4007    else if (const auto ATL = TL.getAs<AttributedTypeLoc>())4008      TL = ATL.getEquivalentTypeLoc();4009    else if (const auto MQTL = TL.getAs<MacroQualifiedTypeLoc>())4010      TL = MQTL.getInnerLoc();4011    else4012      break;4013  }4014 4015  return FTL;4016}4017 4018SourceRange FunctionDecl::getReturnTypeSourceRange() const {4019  FunctionTypeLoc FTL = getFunctionTypeLoc();4020  if (!FTL)4021    return SourceRange();4022 4023  // Skip self-referential return types.4024  const SourceManager &SM = getASTContext().getSourceManager();4025  SourceRange RTRange = FTL.getReturnLoc().getSourceRange();4026  SourceLocation Boundary = getNameInfo().getBeginLoc();4027  if (RTRange.isInvalid() || Boundary.isInvalid() ||4028      !SM.isBeforeInTranslationUnit(RTRange.getEnd(), Boundary))4029    return SourceRange();4030 4031  return RTRange;4032}4033 4034SourceRange FunctionDecl::getParametersSourceRange() const {4035  unsigned NP = getNumParams();4036  SourceLocation EllipsisLoc = getEllipsisLoc();4037 4038  if (NP == 0 && EllipsisLoc.isInvalid())4039    return SourceRange();4040 4041  SourceLocation Begin =4042      NP > 0 ? ParamInfo[0]->getSourceRange().getBegin() : EllipsisLoc;4043  SourceLocation End = EllipsisLoc.isValid()4044                           ? EllipsisLoc4045                           : ParamInfo[NP - 1]->getSourceRange().getEnd();4046 4047  return SourceRange(Begin, End);4048}4049 4050SourceRange FunctionDecl::getExceptionSpecSourceRange() const {4051  FunctionTypeLoc FTL = getFunctionTypeLoc();4052  return FTL ? FTL.getExceptionSpecRange() : SourceRange();4053}4054 4055/// For an inline function definition in C, or for a gnu_inline function4056/// in C++, determine whether the definition will be externally visible.4057///4058/// Inline function definitions are always available for inlining optimizations.4059/// However, depending on the language dialect, declaration specifiers, and4060/// attributes, the definition of an inline function may or may not be4061/// "externally" visible to other translation units in the program.4062///4063/// In C99, inline definitions are not externally visible by default. However,4064/// if even one of the global-scope declarations is marked "extern inline", the4065/// inline definition becomes externally visible (C99 6.7.4p6).4066///4067/// In GNU89 mode, or if the gnu_inline attribute is attached to the function4068/// definition, we use the GNU semantics for inline, which are nearly the4069/// opposite of C99 semantics. In particular, "inline" by itself will create4070/// an externally visible symbol, but "extern inline" will not create an4071/// externally visible symbol.4072bool FunctionDecl::isInlineDefinitionExternallyVisible() const {4073  assert((doesThisDeclarationHaveABody() || willHaveBody() ||4074          hasAttr<AliasAttr>()) &&4075         "Must be a function definition");4076  assert(isInlined() && "Function must be inline");4077  ASTContext &Context = getASTContext();4078 4079  if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {4080    // Note: If you change the logic here, please change4081    // doesDeclarationForceExternallyVisibleDefinition as well.4082    //4083    // If it's not the case that both 'inline' and 'extern' are4084    // specified on the definition, then this inline definition is4085    // externally visible.4086    if (Context.getLangOpts().CPlusPlus)4087      return false;4088    if (!(isInlineSpecified() && getStorageClass() == SC_Extern))4089      return true;4090 4091    // If any declaration is 'inline' but not 'extern', then this definition4092    // is externally visible.4093    for (auto *Redecl : redecls()) {4094      if (Redecl->isInlineSpecified() &&4095          Redecl->getStorageClass() != SC_Extern)4096        return true;4097    }4098 4099    return false;4100  }4101 4102  // The rest of this function is C-only.4103  assert(!Context.getLangOpts().CPlusPlus &&4104         "should not use C inline rules in C++");4105 4106  // C99 6.7.4p6:4107  //   [...] If all of the file scope declarations for a function in a4108  //   translation unit include the inline function specifier without extern,4109  //   then the definition in that translation unit is an inline definition.4110  for (auto *Redecl : redecls()) {4111    if (RedeclForcesDefC99(Redecl))4112      return true;4113  }4114 4115  // C99 6.7.4p6:4116  //   An inline definition does not provide an external definition for the4117  //   function, and does not forbid an external definition in another4118  //   translation unit.4119  return false;4120}4121 4122/// getOverloadedOperator - Which C++ overloaded operator this4123/// function represents, if any.4124OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {4125  if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)4126    return getDeclName().getCXXOverloadedOperator();4127  return OO_None;4128}4129 4130/// getLiteralIdentifier - The literal suffix identifier this function4131/// represents, if any.4132const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {4133  if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)4134    return getDeclName().getCXXLiteralIdentifier();4135  return nullptr;4136}4137 4138FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {4139  if (TemplateOrSpecialization.isNull())4140    return TK_NonTemplate;4141  if (const auto *ND = dyn_cast<NamedDecl *>(TemplateOrSpecialization)) {4142    if (isa<FunctionDecl>(ND))4143      return TK_DependentNonTemplate;4144    assert(isa<FunctionTemplateDecl>(ND) &&4145           "No other valid types in NamedDecl");4146    return TK_FunctionTemplate;4147  }4148  if (isa<MemberSpecializationInfo *>(TemplateOrSpecialization))4149    return TK_MemberSpecialization;4150  if (isa<FunctionTemplateSpecializationInfo *>(TemplateOrSpecialization))4151    return TK_FunctionTemplateSpecialization;4152  if (isa<DependentFunctionTemplateSpecializationInfo *>(4153          TemplateOrSpecialization))4154    return TK_DependentFunctionTemplateSpecialization;4155 4156  llvm_unreachable("Did we miss a TemplateOrSpecialization type?");4157}4158 4159FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {4160  if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())4161    return cast<FunctionDecl>(Info->getInstantiatedFrom());4162 4163  return nullptr;4164}4165 4166MemberSpecializationInfo *FunctionDecl::getMemberSpecializationInfo() const {4167  if (auto *MSI = dyn_cast_if_present<MemberSpecializationInfo *>(4168          TemplateOrSpecialization))4169    return MSI;4170  if (auto *FTSI = dyn_cast_if_present<FunctionTemplateSpecializationInfo *>(4171          TemplateOrSpecialization))4172    return FTSI->getMemberSpecializationInfo();4173  return nullptr;4174}4175 4176void4177FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,4178                                               FunctionDecl *FD,4179                                               TemplateSpecializationKind TSK) {4180  assert(TemplateOrSpecialization.isNull() &&4181         "Member function is already a specialization");4182  MemberSpecializationInfo *Info4183    = new (C) MemberSpecializationInfo(FD, TSK);4184  TemplateOrSpecialization = Info;4185}4186 4187FunctionTemplateDecl *FunctionDecl::getDescribedFunctionTemplate() const {4188  return dyn_cast_if_present<FunctionTemplateDecl>(4189      dyn_cast_if_present<NamedDecl *>(TemplateOrSpecialization));4190}4191 4192void FunctionDecl::setDescribedFunctionTemplate(4193    FunctionTemplateDecl *Template) {4194  assert(TemplateOrSpecialization.isNull() &&4195         "Member function is already a specialization");4196  TemplateOrSpecialization = Template;4197}4198 4199bool FunctionDecl::isFunctionTemplateSpecialization() const {4200  return isa<FunctionTemplateSpecializationInfo *>(TemplateOrSpecialization) ||4201         isa<DependentFunctionTemplateSpecializationInfo *>(4202             TemplateOrSpecialization);4203}4204 4205void FunctionDecl::setInstantiatedFromDecl(FunctionDecl *FD) {4206  assert(TemplateOrSpecialization.isNull() &&4207         "Function is already a specialization");4208  TemplateOrSpecialization = FD;4209}4210 4211FunctionDecl *FunctionDecl::getInstantiatedFromDecl() const {4212  return dyn_cast_if_present<FunctionDecl>(4213      TemplateOrSpecialization.dyn_cast<NamedDecl *>());4214}4215 4216bool FunctionDecl::isImplicitlyInstantiable() const {4217  // If the function is invalid, it can't be implicitly instantiated.4218  if (isInvalidDecl())4219    return false;4220 4221  switch (getTemplateSpecializationKindForInstantiation()) {4222  case TSK_Undeclared:4223  case TSK_ExplicitInstantiationDefinition:4224  case TSK_ExplicitSpecialization:4225    return false;4226 4227  case TSK_ImplicitInstantiation:4228    return true;4229 4230  case TSK_ExplicitInstantiationDeclaration:4231    // Handled below.4232    break;4233  }4234 4235  // Find the actual template from which we will instantiate.4236  const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();4237  bool HasPattern = false;4238  if (PatternDecl)4239    HasPattern = PatternDecl->hasBody(PatternDecl);4240 4241  // C++0x [temp.explicit]p9:4242  //   Except for inline functions, other explicit instantiation declarations4243  //   have the effect of suppressing the implicit instantiation of the entity4244  //   to which they refer.4245  if (!HasPattern || !PatternDecl)4246    return true;4247 4248  return PatternDecl->isInlined();4249}4250 4251bool FunctionDecl::isTemplateInstantiation() const {4252  // FIXME: Remove this, it's not clear what it means. (Which template4253  // specialization kind?)4254  return clang::isTemplateInstantiation(getTemplateSpecializationKind());4255}4256 4257FunctionDecl *4258FunctionDecl::getTemplateInstantiationPattern(bool ForDefinition) const {4259  // If this is a generic lambda call operator specialization, its4260  // instantiation pattern is always its primary template's pattern4261  // even if its primary template was instantiated from another4262  // member template (which happens with nested generic lambdas).4263  // Since a lambda's call operator's body is transformed eagerly,4264  // we don't have to go hunting for a prototype definition template4265  // (i.e. instantiated-from-member-template) to use as an instantiation4266  // pattern.4267 4268  if (isGenericLambdaCallOperatorSpecialization(4269          dyn_cast<CXXMethodDecl>(this))) {4270    assert(getPrimaryTemplate() && "not a generic lambda call operator?");4271    return getDefinitionOrSelf(getPrimaryTemplate()->getTemplatedDecl());4272  }4273 4274  // Check for a declaration of this function that was instantiated from a4275  // friend definition.4276  const FunctionDecl *FD = nullptr;4277  if (!isDefined(FD, /*CheckForPendingFriendDefinition=*/true))4278    FD = this;4279 4280  if (MemberSpecializationInfo *Info = FD->getMemberSpecializationInfo()) {4281    if (ForDefinition &&4282        !clang::isTemplateInstantiation(Info->getTemplateSpecializationKind()))4283      return nullptr;4284    return getDefinitionOrSelf(cast<FunctionDecl>(Info->getInstantiatedFrom()));4285  }4286 4287  if (ForDefinition &&4288      !clang::isTemplateInstantiation(getTemplateSpecializationKind()))4289    return nullptr;4290 4291  if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {4292    // If we hit a point where the user provided a specialization of this4293    // template, we're done looking.4294    while (!ForDefinition || !Primary->isMemberSpecialization()) {4295      auto *NewPrimary = Primary->getInstantiatedFromMemberTemplate();4296      if (!NewPrimary)4297        break;4298      Primary = NewPrimary;4299    }4300 4301    return getDefinitionOrSelf(Primary->getTemplatedDecl());4302  }4303 4304  return nullptr;4305}4306 4307FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {4308  if (FunctionTemplateSpecializationInfo *Info =4309          dyn_cast_if_present<FunctionTemplateSpecializationInfo *>(4310              TemplateOrSpecialization)) {4311    return Info->getTemplate();4312  }4313  return nullptr;4314}4315 4316FunctionTemplateSpecializationInfo *4317FunctionDecl::getTemplateSpecializationInfo() const {4318  return dyn_cast_if_present<FunctionTemplateSpecializationInfo *>(4319      TemplateOrSpecialization);4320}4321 4322const TemplateArgumentList *4323FunctionDecl::getTemplateSpecializationArgs() const {4324  if (FunctionTemplateSpecializationInfo *Info =4325          dyn_cast_if_present<FunctionTemplateSpecializationInfo *>(4326              TemplateOrSpecialization)) {4327    return Info->TemplateArguments;4328  }4329  return nullptr;4330}4331 4332const ASTTemplateArgumentListInfo *4333FunctionDecl::getTemplateSpecializationArgsAsWritten() const {4334  if (FunctionTemplateSpecializationInfo *Info =4335          dyn_cast_if_present<FunctionTemplateSpecializationInfo *>(4336              TemplateOrSpecialization)) {4337    return Info->TemplateArgumentsAsWritten;4338  }4339  if (DependentFunctionTemplateSpecializationInfo *Info =4340          dyn_cast_if_present<DependentFunctionTemplateSpecializationInfo *>(4341              TemplateOrSpecialization)) {4342    return Info->TemplateArgumentsAsWritten;4343  }4344  return nullptr;4345}4346 4347void FunctionDecl::setFunctionTemplateSpecialization(4348    ASTContext &C, FunctionTemplateDecl *Template,4349    TemplateArgumentList *TemplateArgs, void *InsertPos,4350    TemplateSpecializationKind TSK,4351    const TemplateArgumentListInfo *TemplateArgsAsWritten,4352    SourceLocation PointOfInstantiation) {4353  assert((TemplateOrSpecialization.isNull() ||4354          isa<MemberSpecializationInfo *>(TemplateOrSpecialization)) &&4355         "Member function is already a specialization");4356  assert(TSK != TSK_Undeclared &&4357         "Must specify the type of function template specialization");4358  assert((TemplateOrSpecialization.isNull() ||4359          getFriendObjectKind() != FOK_None ||4360          TSK == TSK_ExplicitSpecialization) &&4361         "Member specialization must be an explicit specialization");4362  FunctionTemplateSpecializationInfo *Info =4363      FunctionTemplateSpecializationInfo::Create(4364          C, this, Template, TSK, TemplateArgs, TemplateArgsAsWritten,4365          PointOfInstantiation,4366          dyn_cast_if_present<MemberSpecializationInfo *>(4367              TemplateOrSpecialization));4368  TemplateOrSpecialization = Info;4369  Template->addSpecialization(Info, InsertPos);4370}4371 4372void FunctionDecl::setDependentTemplateSpecialization(4373    ASTContext &Context, const UnresolvedSetImpl &Templates,4374    const TemplateArgumentListInfo *TemplateArgs) {4375  assert(TemplateOrSpecialization.isNull());4376  DependentFunctionTemplateSpecializationInfo *Info =4377      DependentFunctionTemplateSpecializationInfo::Create(Context, Templates,4378                                                          TemplateArgs);4379  TemplateOrSpecialization = Info;4380}4381 4382DependentFunctionTemplateSpecializationInfo *4383FunctionDecl::getDependentSpecializationInfo() const {4384  return dyn_cast_if_present<DependentFunctionTemplateSpecializationInfo *>(4385      TemplateOrSpecialization);4386}4387 4388DependentFunctionTemplateSpecializationInfo *4389DependentFunctionTemplateSpecializationInfo::Create(4390    ASTContext &Context, const UnresolvedSetImpl &Candidates,4391    const TemplateArgumentListInfo *TArgs) {4392  const auto *TArgsWritten =4393      TArgs ? ASTTemplateArgumentListInfo::Create(Context, *TArgs) : nullptr;4394  return new (Context.Allocate(4395      totalSizeToAlloc<FunctionTemplateDecl *>(Candidates.size())))4396      DependentFunctionTemplateSpecializationInfo(Candidates, TArgsWritten);4397}4398 4399DependentFunctionTemplateSpecializationInfo::4400    DependentFunctionTemplateSpecializationInfo(4401        const UnresolvedSetImpl &Candidates,4402        const ASTTemplateArgumentListInfo *TemplateArgsWritten)4403    : NumCandidates(Candidates.size()),4404      TemplateArgumentsAsWritten(TemplateArgsWritten) {4405  std::transform(Candidates.begin(), Candidates.end(), getTrailingObjects(),4406                 [](NamedDecl *ND) {4407                   return cast<FunctionTemplateDecl>(ND->getUnderlyingDecl());4408                 });4409}4410 4411TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {4412  // For a function template specialization, query the specialization4413  // information object.4414  if (FunctionTemplateSpecializationInfo *FTSInfo =4415          dyn_cast_if_present<FunctionTemplateSpecializationInfo *>(4416              TemplateOrSpecialization))4417    return FTSInfo->getTemplateSpecializationKind();4418 4419  if (MemberSpecializationInfo *MSInfo =4420          dyn_cast_if_present<MemberSpecializationInfo *>(4421              TemplateOrSpecialization))4422    return MSInfo->getTemplateSpecializationKind();4423 4424  // A dependent function template specialization is an explicit specialization,4425  // except when it's a friend declaration.4426  if (isa<DependentFunctionTemplateSpecializationInfo *>(4427          TemplateOrSpecialization) &&4428      getFriendObjectKind() == FOK_None)4429    return TSK_ExplicitSpecialization;4430 4431  return TSK_Undeclared;4432}4433 4434TemplateSpecializationKind4435FunctionDecl::getTemplateSpecializationKindForInstantiation() const {4436  // This is the same as getTemplateSpecializationKind(), except that for a4437  // function that is both a function template specialization and a member4438  // specialization, we prefer the member specialization information. Eg:4439  //4440  // template<typename T> struct A {4441  //   template<typename U> void f() {}4442  //   template<> void f<int>() {}4443  // };4444  //4445  // Within the templated CXXRecordDecl, A<T>::f<int> is a dependent function4446  // template specialization; both getTemplateSpecializationKind() and4447  // getTemplateSpecializationKindForInstantiation() will return4448  // TSK_ExplicitSpecialization.4449  //4450  // For A<int>::f<int>():4451  // * getTemplateSpecializationKind() will return TSK_ExplicitSpecialization4452  // * getTemplateSpecializationKindForInstantiation() will return4453  //       TSK_ImplicitInstantiation4454  //4455  // This reflects the facts that A<int>::f<int> is an explicit specialization4456  // of A<int>::f, and that A<int>::f<int> should be implicitly instantiated4457  // from A::f<int> if a definition is needed.4458  if (FunctionTemplateSpecializationInfo *FTSInfo =4459          dyn_cast_if_present<FunctionTemplateSpecializationInfo *>(4460              TemplateOrSpecialization)) {4461    if (auto *MSInfo = FTSInfo->getMemberSpecializationInfo())4462      return MSInfo->getTemplateSpecializationKind();4463    return FTSInfo->getTemplateSpecializationKind();4464  }4465 4466  if (MemberSpecializationInfo *MSInfo =4467          dyn_cast_if_present<MemberSpecializationInfo *>(4468              TemplateOrSpecialization))4469    return MSInfo->getTemplateSpecializationKind();4470 4471  if (isa<DependentFunctionTemplateSpecializationInfo *>(4472          TemplateOrSpecialization) &&4473      getFriendObjectKind() == FOK_None)4474    return TSK_ExplicitSpecialization;4475 4476  return TSK_Undeclared;4477}4478 4479void4480FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,4481                                          SourceLocation PointOfInstantiation) {4482  if (FunctionTemplateSpecializationInfo *FTSInfo =4483          dyn_cast<FunctionTemplateSpecializationInfo *>(4484              TemplateOrSpecialization)) {4485    FTSInfo->setTemplateSpecializationKind(TSK);4486    if (TSK != TSK_ExplicitSpecialization &&4487        PointOfInstantiation.isValid() &&4488        FTSInfo->getPointOfInstantiation().isInvalid()) {4489      FTSInfo->setPointOfInstantiation(PointOfInstantiation);4490      if (ASTMutationListener *L = getASTContext().getASTMutationListener())4491        L->InstantiationRequested(this);4492    }4493  } else if (MemberSpecializationInfo *MSInfo =4494                 dyn_cast<MemberSpecializationInfo *>(4495                     TemplateOrSpecialization)) {4496    MSInfo->setTemplateSpecializationKind(TSK);4497    if (TSK != TSK_ExplicitSpecialization &&4498        PointOfInstantiation.isValid() &&4499        MSInfo->getPointOfInstantiation().isInvalid()) {4500      MSInfo->setPointOfInstantiation(PointOfInstantiation);4501      if (ASTMutationListener *L = getASTContext().getASTMutationListener())4502        L->InstantiationRequested(this);4503    }4504  } else4505    llvm_unreachable("Function cannot have a template specialization kind");4506}4507 4508SourceLocation FunctionDecl::getPointOfInstantiation() const {4509  if (FunctionTemplateSpecializationInfo *FTSInfo4510        = TemplateOrSpecialization.dyn_cast<4511                                        FunctionTemplateSpecializationInfo*>())4512    return FTSInfo->getPointOfInstantiation();4513  if (MemberSpecializationInfo *MSInfo =4514          TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>())4515    return MSInfo->getPointOfInstantiation();4516 4517  return SourceLocation();4518}4519 4520bool FunctionDecl::isOutOfLine() const {4521  if (Decl::isOutOfLine())4522    return true;4523 4524  // If this function was instantiated from a member function of a4525  // class template, check whether that member function was defined out-of-line.4526  if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {4527    const FunctionDecl *Definition;4528    if (FD->hasBody(Definition))4529      return Definition->isOutOfLine();4530  }4531 4532  // If this function was instantiated from a function template,4533  // check whether that function template was defined out-of-line.4534  if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {4535    const FunctionDecl *Definition;4536    if (FunTmpl->getTemplatedDecl()->hasBody(Definition))4537      return Definition->isOutOfLine();4538  }4539 4540  return false;4541}4542 4543SourceRange FunctionDecl::getSourceRange() const {4544  return SourceRange(getOuterLocStart(), EndRangeLoc);4545}4546 4547unsigned FunctionDecl::getMemoryFunctionKind() const {4548  IdentifierInfo *FnInfo = getIdentifier();4549 4550  if (!FnInfo)4551    return 0;4552 4553  // Builtin handling.4554  switch (getBuiltinID()) {4555  case Builtin::BI__builtin_memset:4556  case Builtin::BI__builtin___memset_chk:4557  case Builtin::BImemset:4558    return Builtin::BImemset;4559 4560  case Builtin::BI__builtin_memcpy:4561  case Builtin::BI__builtin___memcpy_chk:4562  case Builtin::BImemcpy:4563    return Builtin::BImemcpy;4564 4565  case Builtin::BI__builtin_mempcpy:4566  case Builtin::BI__builtin___mempcpy_chk:4567  case Builtin::BImempcpy:4568    return Builtin::BImempcpy;4569 4570  case Builtin::BI__builtin_trivially_relocate:4571  case Builtin::BI__builtin_memmove:4572  case Builtin::BI__builtin___memmove_chk:4573  case Builtin::BImemmove:4574    return Builtin::BImemmove;4575 4576  case Builtin::BIstrlcpy:4577  case Builtin::BI__builtin___strlcpy_chk:4578    return Builtin::BIstrlcpy;4579 4580  case Builtin::BIstrlcat:4581  case Builtin::BI__builtin___strlcat_chk:4582    return Builtin::BIstrlcat;4583 4584  case Builtin::BI__builtin_memcmp:4585  case Builtin::BImemcmp:4586    return Builtin::BImemcmp;4587 4588  case Builtin::BI__builtin_bcmp:4589  case Builtin::BIbcmp:4590    return Builtin::BIbcmp;4591 4592  case Builtin::BI__builtin_strncpy:4593  case Builtin::BI__builtin___strncpy_chk:4594  case Builtin::BIstrncpy:4595    return Builtin::BIstrncpy;4596 4597  case Builtin::BI__builtin_strncmp:4598  case Builtin::BIstrncmp:4599    return Builtin::BIstrncmp;4600 4601  case Builtin::BI__builtin_strncasecmp:4602  case Builtin::BIstrncasecmp:4603    return Builtin::BIstrncasecmp;4604 4605  case Builtin::BI__builtin_strncat:4606  case Builtin::BI__builtin___strncat_chk:4607  case Builtin::BIstrncat:4608    return Builtin::BIstrncat;4609 4610  case Builtin::BI__builtin_strndup:4611  case Builtin::BIstrndup:4612    return Builtin::BIstrndup;4613 4614  case Builtin::BI__builtin_strlen:4615  case Builtin::BIstrlen:4616    return Builtin::BIstrlen;4617 4618  case Builtin::BI__builtin_bzero:4619  case Builtin::BIbzero:4620    return Builtin::BIbzero;4621 4622  case Builtin::BI__builtin_bcopy:4623  case Builtin::BIbcopy:4624    return Builtin::BIbcopy;4625 4626  case Builtin::BIfree:4627    return Builtin::BIfree;4628 4629  default:4630    if (isExternC()) {4631      if (FnInfo->isStr("memset"))4632        return Builtin::BImemset;4633      if (FnInfo->isStr("memcpy"))4634        return Builtin::BImemcpy;4635      if (FnInfo->isStr("mempcpy"))4636        return Builtin::BImempcpy;4637      if (FnInfo->isStr("memmove"))4638        return Builtin::BImemmove;4639      if (FnInfo->isStr("memcmp"))4640        return Builtin::BImemcmp;4641      if (FnInfo->isStr("bcmp"))4642        return Builtin::BIbcmp;4643      if (FnInfo->isStr("strncpy"))4644        return Builtin::BIstrncpy;4645      if (FnInfo->isStr("strncmp"))4646        return Builtin::BIstrncmp;4647      if (FnInfo->isStr("strncasecmp"))4648        return Builtin::BIstrncasecmp;4649      if (FnInfo->isStr("strncat"))4650        return Builtin::BIstrncat;4651      if (FnInfo->isStr("strndup"))4652        return Builtin::BIstrndup;4653      if (FnInfo->isStr("strlen"))4654        return Builtin::BIstrlen;4655      if (FnInfo->isStr("bzero"))4656        return Builtin::BIbzero;4657      if (FnInfo->isStr("bcopy"))4658        return Builtin::BIbcopy;4659    } else if (isInStdNamespace()) {4660      if (FnInfo->isStr("free"))4661        return Builtin::BIfree;4662    }4663    break;4664  }4665  return 0;4666}4667 4668unsigned FunctionDecl::getODRHash() const {4669  assert(hasODRHash());4670  return ODRHash;4671}4672 4673unsigned FunctionDecl::getODRHash() {4674  if (hasODRHash())4675    return ODRHash;4676 4677  if (auto *FT = getInstantiatedFromMemberFunction()) {4678    setHasODRHash(true);4679    ODRHash = FT->getODRHash();4680    return ODRHash;4681  }4682 4683  class ODRHash Hash;4684  Hash.AddFunctionDecl(this);4685  setHasODRHash(true);4686  ODRHash = Hash.CalculateHash();4687  return ODRHash;4688}4689 4690//===----------------------------------------------------------------------===//4691// FieldDecl Implementation4692//===----------------------------------------------------------------------===//4693 4694FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC,4695                             SourceLocation StartLoc, SourceLocation IdLoc,4696                             const IdentifierInfo *Id, QualType T,4697                             TypeSourceInfo *TInfo, Expr *BW, bool Mutable,4698                             InClassInitStyle InitStyle) {4699  return new (C, DC) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,4700                               BW, Mutable, InitStyle);4701}4702 4703FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) {4704  return new (C, ID) FieldDecl(Field, nullptr, SourceLocation(),4705                               SourceLocation(), nullptr, QualType(), nullptr,4706                               nullptr, false, ICIS_NoInit);4707}4708 4709bool FieldDecl::isAnonymousStructOrUnion() const {4710  if (!isImplicit() || getDeclName())4711    return false;4712 4713  if (const auto *Record = getType()->getAsCanonical<RecordType>())4714    return Record->getDecl()->isAnonymousStructOrUnion();4715 4716  return false;4717}4718 4719Expr *FieldDecl::getInClassInitializer() const {4720  if (!hasInClassInitializer())4721    return nullptr;4722 4723  LazyDeclStmtPtr InitPtr = BitField ? InitAndBitWidth->Init : Init;4724  return cast_if_present<Expr>(4725      InitPtr.isOffset() ? InitPtr.get(getASTContext().getExternalSource())4726                         : InitPtr.get(nullptr));4727}4728 4729void FieldDecl::setInClassInitializer(Expr *NewInit) {4730  setLazyInClassInitializer(LazyDeclStmtPtr(NewInit));4731}4732 4733void FieldDecl::setLazyInClassInitializer(LazyDeclStmtPtr NewInit) {4734  assert(hasInClassInitializer() && !getInClassInitializer());4735  if (BitField)4736    InitAndBitWidth->Init = NewInit;4737  else4738    Init = NewInit;4739}4740 4741bool FieldDecl::hasConstantIntegerBitWidth() const {4742  const auto *CE = dyn_cast_if_present<ConstantExpr>(getBitWidth());4743  return CE && CE->getAPValueResult().isInt();4744}4745 4746unsigned FieldDecl::getBitWidthValue() const {4747  assert(isBitField() && "not a bitfield");4748  assert(hasConstantIntegerBitWidth());4749  return cast<ConstantExpr>(getBitWidth())4750      ->getAPValueResult()4751      .getInt()4752      .getZExtValue();4753}4754 4755bool FieldDecl::isZeroLengthBitField() const {4756  return isUnnamedBitField() && !getBitWidth()->isValueDependent() &&4757         getBitWidthValue() == 0;4758}4759 4760bool FieldDecl::isZeroSize(const ASTContext &Ctx) const {4761  if (isZeroLengthBitField())4762    return true;4763 4764  // C++2a [intro.object]p7:4765  //   An object has nonzero size if it4766  //     -- is not a potentially-overlapping subobject, or4767  if (!hasAttr<NoUniqueAddressAttr>())4768    return false;4769 4770  //     -- is not of class type, or4771  const auto *RT = getType()->getAsCanonical<RecordType>();4772  if (!RT)4773    return false;4774  const RecordDecl *RD = RT->getDecl()->getDefinition();4775  if (!RD) {4776    assert(isInvalidDecl() && "valid field has incomplete type");4777    return false;4778  }4779 4780  //     -- [has] virtual member functions or virtual base classes, or4781  //     -- has subobjects of nonzero size or bit-fields of nonzero length4782  const auto *CXXRD = cast<CXXRecordDecl>(RD);4783  if (!CXXRD->isEmpty())4784    return false;4785 4786  // Otherwise, [...] the circumstances under which the object has zero size4787  // are implementation-defined.4788  if (!Ctx.getTargetInfo().getCXXABI().isMicrosoft())4789    return true;4790 4791  // MS ABI: has nonzero size if it is a class type with class type fields,4792  // whether or not they have nonzero size4793  return !llvm::any_of(CXXRD->fields(), [](const FieldDecl *Field) {4794    return Field->getType()->isRecordType();4795  });4796}4797 4798bool FieldDecl::isPotentiallyOverlapping() const {4799  return hasAttr<NoUniqueAddressAttr>() && getType()->getAsCXXRecordDecl();4800}4801 4802void FieldDecl::setCachedFieldIndex() const {4803  assert(this == getCanonicalDecl() &&4804         "should be called on the canonical decl");4805 4806  unsigned Index = 0;4807  const RecordDecl *RD = getParent()->getDefinition();4808  assert(RD && "requested index for field of struct with no definition");4809 4810  for (auto *Field : RD->fields()) {4811    Field->getCanonicalDecl()->CachedFieldIndex = Index + 1;4812    assert(Field->getCanonicalDecl()->CachedFieldIndex == Index + 1 &&4813           "overflow in field numbering");4814    ++Index;4815  }4816 4817  assert(CachedFieldIndex && "failed to find field in parent");4818}4819 4820SourceRange FieldDecl::getSourceRange() const {4821  const Expr *FinalExpr = getInClassInitializer();4822  if (!FinalExpr)4823    FinalExpr = getBitWidth();4824  if (FinalExpr)4825    return SourceRange(getInnerLocStart(), FinalExpr->getEndLoc());4826  return DeclaratorDecl::getSourceRange();4827}4828 4829void FieldDecl::setCapturedVLAType(const VariableArrayType *VLAType) {4830  assert((getParent()->isLambda() || getParent()->isCapturedRecord()) &&4831         "capturing type in non-lambda or captured record.");4832  assert(StorageKind == ISK_NoInit && !BitField &&4833         "bit-field or field with default member initializer cannot capture "4834         "VLA type");4835  StorageKind = ISK_CapturedVLAType;4836  CapturedVLAType = VLAType;4837}4838 4839void FieldDecl::printName(raw_ostream &OS, const PrintingPolicy &Policy) const {4840  // Print unnamed members using name of their type.4841  if (isAnonymousStructOrUnion()) {4842    this->getType().print(OS, Policy);4843    return;4844  }4845  // Otherwise, do the normal printing.4846  DeclaratorDecl::printName(OS, Policy);4847}4848 4849const FieldDecl *FieldDecl::findCountedByField() const {4850  const auto *CAT = getType()->getAs<CountAttributedType>();4851  if (!CAT)4852    return nullptr;4853 4854  const auto *CountDRE = cast<DeclRefExpr>(CAT->getCountExpr());4855  const auto *CountDecl = CountDRE->getDecl();4856  if (const auto *IFD = dyn_cast<IndirectFieldDecl>(CountDecl))4857    CountDecl = IFD->getAnonField();4858 4859  return dyn_cast<FieldDecl>(CountDecl);4860}4861 4862//===----------------------------------------------------------------------===//4863// TagDecl Implementation4864//===----------------------------------------------------------------------===//4865 4866TagDecl::TagDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC,4867                 SourceLocation L, IdentifierInfo *Id, TagDecl *PrevDecl,4868                 SourceLocation StartL)4869    : TypeDecl(DK, DC, L, Id, StartL), DeclContext(DK), redeclarable_base(C),4870      TypedefNameDeclOrQualifier((TypedefNameDecl *)nullptr) {4871  assert((DK != Enum || TK == TagTypeKind::Enum) &&4872         "EnumDecl not matched with TagTypeKind::Enum");4873  setPreviousDecl(PrevDecl);4874  setTagKind(TK);4875  setCompleteDefinition(false);4876  setBeingDefined(false);4877  setEmbeddedInDeclarator(false);4878  setFreeStanding(false);4879  setCompleteDefinitionRequired(false);4880  TagDeclBits.IsThisDeclarationADemotedDefinition = false;4881}4882 4883SourceLocation TagDecl::getOuterLocStart() const {4884  return getTemplateOrInnerLocStart(this);4885}4886 4887SourceRange TagDecl::getSourceRange() const {4888  SourceLocation RBraceLoc = BraceRange.getEnd();4889  SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();4890  return SourceRange(getOuterLocStart(), E);4891}4892 4893TagDecl *TagDecl::getCanonicalDecl() { return getFirstDecl(); }4894 4895void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) {4896  TypedefNameDeclOrQualifier = TDD;4897  assert(isLinkageValid());4898}4899 4900void TagDecl::startDefinition() {4901  setBeingDefined(true);4902 4903  if (auto *D = dyn_cast<CXXRecordDecl>(this)) {4904    struct CXXRecordDecl::DefinitionData *Data =4905      new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);4906    for (auto *I : redecls())4907      cast<CXXRecordDecl>(I)->DefinitionData = Data;4908  }4909}4910 4911void TagDecl::completeDefinition() {4912  assert((!isa<CXXRecordDecl>(this) ||4913          cast<CXXRecordDecl>(this)->hasDefinition()) &&4914         "definition completed but not started");4915 4916  setCompleteDefinition(true);4917  setBeingDefined(false);4918 4919  if (ASTMutationListener *L = getASTMutationListener())4920    L->CompletedTagDefinition(this);4921}4922 4923TagDecl *TagDecl::getDefinition() const {4924  if (isCompleteDefinition() || isBeingDefined())4925    return const_cast<TagDecl *>(this);4926 4927  if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(this))4928    return CXXRD->getDefinition();4929 4930  for (TagDecl *R :4931       redecl_range(redecl_iterator(getNextRedeclaration()), redecl_iterator()))4932    if (R->isCompleteDefinition() || R->isBeingDefined())4933      return R;4934  return nullptr;4935}4936 4937void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {4938  if (QualifierLoc) {4939    // Make sure the extended qualifier info is allocated.4940    if (!hasExtInfo())4941      TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;4942    // Set qualifier info.4943    getExtInfo()->QualifierLoc = QualifierLoc;4944  } else {4945    // Here Qualifier == 0, i.e., we are removing the qualifier (if any).4946    if (hasExtInfo()) {4947      if (getExtInfo()->NumTemplParamLists == 0) {4948        getASTContext().Deallocate(getExtInfo());4949        TypedefNameDeclOrQualifier = (TypedefNameDecl *)nullptr;4950      }4951      else4952        getExtInfo()->QualifierLoc = QualifierLoc;4953    }4954  }4955}4956 4957void TagDecl::printName(raw_ostream &OS, const PrintingPolicy &Policy) const {4958  DeclarationName Name = getDeclName();4959  // If the name is supposed to have an identifier but does not have one, then4960  // the tag is anonymous and we should print it differently.4961  if (Name.isIdentifier() && !Name.getAsIdentifierInfo()) {4962    // If the caller wanted to print a qualified name, they've already printed4963    // the scope. And if the caller doesn't want that, the scope information4964    // is already printed as part of the type.4965    PrintingPolicy Copy(Policy);4966    Copy.SuppressScope = true;4967    QualType(getASTContext().getCanonicalTagType(this)).print(OS, Copy);4968    return;4969  }4970  // Otherwise, do the normal printing.4971  Name.print(OS, Policy);4972}4973 4974void TagDecl::setTemplateParameterListsInfo(4975    ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {4976  assert(!TPLists.empty());4977  // Make sure the extended decl info is allocated.4978  if (!hasExtInfo())4979    // Allocate external info struct.4980    TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;4981  // Set the template parameter lists info.4982  getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);4983}4984 4985//===----------------------------------------------------------------------===//4986// EnumDecl Implementation4987//===----------------------------------------------------------------------===//4988 4989EnumDecl::EnumDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,4990                   SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl,4991                   bool Scoped, bool ScopedUsingClassTag, bool Fixed)4992    : TagDecl(Enum, TagTypeKind::Enum, C, DC, IdLoc, Id, PrevDecl, StartLoc) {4993  assert(Scoped || !ScopedUsingClassTag);4994  IntegerType = nullptr;4995  setNumPositiveBits(0);4996  setNumNegativeBits(0);4997  setScoped(Scoped);4998  setScopedUsingClassTag(ScopedUsingClassTag);4999  setFixed(Fixed);5000  setHasODRHash(false);5001  ODRHash = 0;5002}5003 5004void EnumDecl::anchor() {}5005 5006EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC,5007                           SourceLocation StartLoc, SourceLocation IdLoc,5008                           IdentifierInfo *Id,5009                           EnumDecl *PrevDecl, bool IsScoped,5010                           bool IsScopedUsingClassTag, bool IsFixed) {5011  return new (C, DC) EnumDecl(C, DC, StartLoc, IdLoc, Id, PrevDecl, IsScoped,5012                              IsScopedUsingClassTag, IsFixed);5013}5014 5015EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) {5016  return new (C, ID) EnumDecl(C, nullptr, SourceLocation(), SourceLocation(),5017                              nullptr, nullptr, false, false, false);5018}5019 5020SourceRange EnumDecl::getIntegerTypeRange() const {5021  if (const TypeSourceInfo *TI = getIntegerTypeSourceInfo())5022    return TI->getTypeLoc().getSourceRange();5023  return SourceRange();5024}5025 5026void EnumDecl::completeDefinition(QualType NewType,5027                                  QualType NewPromotionType,5028                                  unsigned NumPositiveBits,5029                                  unsigned NumNegativeBits) {5030  assert(!isCompleteDefinition() && "Cannot redefine enums!");5031  if (!IntegerType)5032    IntegerType = NewType.getTypePtr();5033  PromotionType = NewPromotionType;5034  setNumPositiveBits(NumPositiveBits);5035  setNumNegativeBits(NumNegativeBits);5036  TagDecl::completeDefinition();5037}5038 5039bool EnumDecl::isClosed() const {5040  if (const auto *A = getAttr<EnumExtensibilityAttr>())5041    return A->getExtensibility() == EnumExtensibilityAttr::Closed;5042  return true;5043}5044 5045bool EnumDecl::isClosedFlag() const {5046  return isClosed() && hasAttr<FlagEnumAttr>();5047}5048 5049bool EnumDecl::isClosedNonFlag() const {5050  return isClosed() && !hasAttr<FlagEnumAttr>();5051}5052 5053TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const {5054  if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())5055    return MSI->getTemplateSpecializationKind();5056 5057  return TSK_Undeclared;5058}5059 5060void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,5061                                         SourceLocation PointOfInstantiation) {5062  MemberSpecializationInfo *MSI = getMemberSpecializationInfo();5063  assert(MSI && "Not an instantiated member enumeration?");5064  MSI->setTemplateSpecializationKind(TSK);5065  if (TSK != TSK_ExplicitSpecialization &&5066      PointOfInstantiation.isValid() &&5067      MSI->getPointOfInstantiation().isInvalid())5068    MSI->setPointOfInstantiation(PointOfInstantiation);5069}5070 5071EnumDecl *EnumDecl::getTemplateInstantiationPattern() const {5072  if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) {5073    if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) {5074      EnumDecl *ED = getInstantiatedFromMemberEnum();5075      while (auto *NewED = ED->getInstantiatedFromMemberEnum())5076        ED = NewED;5077      return ::getDefinitionOrSelf(ED);5078    }5079  }5080 5081  assert(!isTemplateInstantiation(getTemplateSpecializationKind()) &&5082         "couldn't find pattern for enum instantiation");5083  return nullptr;5084}5085 5086EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const {5087  if (SpecializationInfo)5088    return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom());5089 5090  return nullptr;5091}5092 5093void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,5094                                            TemplateSpecializationKind TSK) {5095  assert(!SpecializationInfo && "Member enum is already a specialization");5096  SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK);5097}5098 5099unsigned EnumDecl::getODRHash() {5100  if (hasODRHash())5101    return ODRHash;5102 5103  class ODRHash Hash;5104  Hash.AddEnumDecl(this);5105  setHasODRHash(true);5106  ODRHash = Hash.CalculateHash();5107  return ODRHash;5108}5109 5110SourceRange EnumDecl::getSourceRange() const {5111  auto Res = TagDecl::getSourceRange();5112  // Set end-point to enum-base, e.g. enum foo : ^bar5113  if (auto *TSI = getIntegerTypeSourceInfo()) {5114    // TagDecl doesn't know about the enum base.5115    if (!getBraceRange().getEnd().isValid())5116      Res.setEnd(TSI->getTypeLoc().getEndLoc());5117  }5118  return Res;5119}5120 5121void EnumDecl::getValueRange(llvm::APInt &Max, llvm::APInt &Min) const {5122  unsigned Bitwidth = getASTContext().getIntWidth(getIntegerType());5123  unsigned NumNegativeBits = getNumNegativeBits();5124  unsigned NumPositiveBits = getNumPositiveBits();5125 5126  if (NumNegativeBits) {5127    unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1);5128    Max = llvm::APInt(Bitwidth, 1) << (NumBits - 1);5129    Min = -Max;5130  } else {5131    Max = llvm::APInt(Bitwidth, 1) << NumPositiveBits;5132    Min = llvm::APInt::getZero(Bitwidth);5133  }5134}5135 5136//===----------------------------------------------------------------------===//5137// RecordDecl Implementation5138//===----------------------------------------------------------------------===//5139 5140RecordDecl::RecordDecl(Kind DK, TagKind TK, const ASTContext &C,5141                       DeclContext *DC, SourceLocation StartLoc,5142                       SourceLocation IdLoc, IdentifierInfo *Id,5143                       RecordDecl *PrevDecl)5144    : TagDecl(DK, TK, C, DC, IdLoc, Id, PrevDecl, StartLoc) {5145  assert(classof(static_cast<Decl *>(this)) && "Invalid Kind!");5146  setHasFlexibleArrayMember(false);5147  setAnonymousStructOrUnion(false);5148  setHasObjectMember(false);5149  setHasVolatileMember(false);5150  setHasLoadedFieldsFromExternalStorage(false);5151  setNonTrivialToPrimitiveDefaultInitialize(false);5152  setNonTrivialToPrimitiveCopy(false);5153  setNonTrivialToPrimitiveDestroy(false);5154  setHasNonTrivialToPrimitiveDefaultInitializeCUnion(false);5155  setHasNonTrivialToPrimitiveDestructCUnion(false);5156  setHasNonTrivialToPrimitiveCopyCUnion(false);5157  setHasUninitializedExplicitInitFields(false);5158  setParamDestroyedInCallee(false);5159  setArgPassingRestrictions(RecordArgPassingKind::CanPassInRegs);5160  setIsRandomized(false);5161  setODRHash(0);5162}5163 5164RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC,5165                               SourceLocation StartLoc, SourceLocation IdLoc,5166                               IdentifierInfo *Id, RecordDecl* PrevDecl) {5167  return new (C, DC)5168      RecordDecl(Record, TK, C, DC, StartLoc, IdLoc, Id, PrevDecl);5169}5170 5171RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C,5172                                           GlobalDeclID ID) {5173  return new (C, ID)5174      RecordDecl(Record, TagTypeKind::Struct, C, nullptr, SourceLocation(),5175                 SourceLocation(), nullptr, nullptr);5176}5177 5178bool RecordDecl::isLambda() const {5179  if (auto RD = dyn_cast<CXXRecordDecl>(this))5180    return RD->isLambda();5181  return false;5182}5183 5184bool RecordDecl::isCapturedRecord() const {5185  return hasAttr<CapturedRecordAttr>();5186}5187 5188void RecordDecl::setCapturedRecord() {5189  addAttr(CapturedRecordAttr::CreateImplicit(getASTContext()));5190}5191 5192bool RecordDecl::isOrContainsUnion() const {5193  if (isUnion())5194    return true;5195 5196  if (const RecordDecl *Def = getDefinition()) {5197    for (const FieldDecl *FD : Def->fields()) {5198      const RecordType *RT = FD->getType()->getAsCanonical<RecordType>();5199      if (RT && RT->getDecl()->isOrContainsUnion())5200        return true;5201    }5202  }5203 5204  return false;5205}5206 5207RecordDecl::field_iterator RecordDecl::field_begin() const {5208  if (hasExternalLexicalStorage() && !hasLoadedFieldsFromExternalStorage())5209    LoadFieldsFromExternalStorage();5210  // This is necessary for correctness for C++ with modules.5211  // FIXME: Come up with a test case that breaks without definition.5212  if (RecordDecl *D = getDefinition(); D && D != this)5213    return D->field_begin();5214  return field_iterator(decl_iterator(FirstDecl));5215}5216 5217RecordDecl::field_iterator RecordDecl::noload_field_begin() const {5218  return field_iterator(decl_iterator(getDefinitionOrSelf()->FirstDecl));5219}5220 5221/// completeDefinition - Notes that the definition of this type is now5222/// complete.5223void RecordDecl::completeDefinition() {5224  assert(!isCompleteDefinition() && "Cannot redefine record!");5225  TagDecl::completeDefinition();5226 5227  ASTContext &Ctx = getASTContext();5228 5229  // Layouts are dumped when computed, so if we are dumping for all complete5230  // types, we need to force usage to get types that wouldn't be used elsewhere.5231  //5232  // If the type is dependent, then we can't compute its layout because there5233  // is no way for us to know the size or alignment of a dependent type. Also5234  // ignore declarations marked as invalid since 'getASTRecordLayout()' asserts5235  // on that.5236  if (Ctx.getLangOpts().DumpRecordLayoutsComplete && !isDependentType() &&5237      !isInvalidDecl())5238    (void)Ctx.getASTRecordLayout(this);5239}5240 5241/// isMsStruct - Get whether or not this record uses ms_struct layout.5242/// This which can be turned on with an attribute, pragma, or the5243/// -mms-bitfields command-line option.5244bool RecordDecl::isMsStruct(const ASTContext &C) const {5245  return hasAttr<MSStructAttr>() || C.getLangOpts().MSBitfields == 1;5246}5247 5248void RecordDecl::reorderDecls(const SmallVectorImpl<Decl *> &Decls) {5249  std::tie(FirstDecl, LastDecl) = DeclContext::BuildDeclChain(Decls, false);5250  LastDecl->NextInContextAndBits.setPointer(nullptr);5251  setIsRandomized(true);5252}5253 5254void RecordDecl::LoadFieldsFromExternalStorage() const {5255  ExternalASTSource *Source = getASTContext().getExternalSource();5256  assert(hasExternalLexicalStorage() && Source && "No external storage?");5257 5258  // Notify that we have a RecordDecl doing some initialization.5259  ExternalASTSource::Deserializing TheFields(Source);5260 5261  SmallVector<Decl*, 64> Decls;5262  setHasLoadedFieldsFromExternalStorage(true);5263  Source->FindExternalLexicalDecls(this, [](Decl::Kind K) {5264    return FieldDecl::classofKind(K) || IndirectFieldDecl::classofKind(K);5265  }, Decls);5266 5267#ifndef NDEBUG5268  // Check that all decls we got were FieldDecls.5269  for (unsigned i=0, e=Decls.size(); i != e; ++i)5270    assert(isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>(Decls[i]));5271#endif5272 5273  if (Decls.empty())5274    return;5275 5276  auto [ExternalFirst, ExternalLast] =5277      BuildDeclChain(Decls,5278                     /*FieldsAlreadyLoaded=*/false);5279  ExternalLast->NextInContextAndBits.setPointer(FirstDecl);5280  FirstDecl = ExternalFirst;5281  if (!LastDecl)5282    LastDecl = ExternalLast;5283}5284 5285bool RecordDecl::mayInsertExtraPadding(bool EmitRemark) const {5286  ASTContext &Context = getASTContext();5287  const SanitizerMask EnabledAsanMask = Context.getLangOpts().Sanitize.Mask &5288      (SanitizerKind::Address | SanitizerKind::KernelAddress);5289  if (!EnabledAsanMask || !Context.getLangOpts().SanitizeAddressFieldPadding)5290    return false;5291  const auto &NoSanitizeList = Context.getNoSanitizeList();5292  const auto *CXXRD = dyn_cast<CXXRecordDecl>(this);5293  // We may be able to relax some of these requirements.5294  int ReasonToReject = -1;5295  if (!CXXRD || CXXRD->isExternCContext())5296    ReasonToReject = 0;  // is not C++.5297  else if (CXXRD->hasAttr<PackedAttr>())5298    ReasonToReject = 1;  // is packed.5299  else if (CXXRD->isUnion())5300    ReasonToReject = 2;  // is a union.5301  else if (CXXRD->isTriviallyCopyable())5302    ReasonToReject = 3;  // is trivially copyable.5303  else if (CXXRD->hasTrivialDestructor())5304    ReasonToReject = 4;  // has trivial destructor.5305  else if (CXXRD->isStandardLayout())5306    ReasonToReject = 5;  // is standard layout.5307  else if (NoSanitizeList.containsLocation(EnabledAsanMask, getLocation(),5308                                           "field-padding"))5309    ReasonToReject = 6;  // is in an excluded file.5310  else if (NoSanitizeList.containsType(5311               EnabledAsanMask, getQualifiedNameAsString(), "field-padding"))5312    ReasonToReject = 7;  // The type is excluded.5313 5314  if (EmitRemark) {5315    if (ReasonToReject >= 0)5316      Context.getDiagnostics().Report(5317          getLocation(),5318          diag::remark_sanitize_address_insert_extra_padding_rejected)5319          << getQualifiedNameAsString() << ReasonToReject;5320    else5321      Context.getDiagnostics().Report(5322          getLocation(),5323          diag::remark_sanitize_address_insert_extra_padding_accepted)5324          << getQualifiedNameAsString();5325  }5326  return ReasonToReject < 0;5327}5328 5329const FieldDecl *RecordDecl::findFirstNamedDataMember() const {5330  for (const auto *I : fields()) {5331    if (I->getIdentifier())5332      return I;5333 5334    if (const auto *RD = I->getType()->getAsRecordDecl())5335      if (const FieldDecl *NamedDataMember = RD->findFirstNamedDataMember())5336        return NamedDataMember;5337  }5338 5339  // We didn't find a named data member.5340  return nullptr;5341}5342 5343unsigned RecordDecl::getODRHash() {5344  if (hasODRHash())5345    return RecordDeclBits.ODRHash;5346 5347  // Only calculate hash on first call of getODRHash per record.5348  ODRHash Hash;5349  Hash.AddRecordDecl(this);5350  // For RecordDecl the ODRHash is stored in the remaining5351  // bits of RecordDeclBits, adjust the hash to accommodate.5352  static_assert(sizeof(Hash.CalculateHash()) * CHAR_BIT == 32);5353  setODRHash(Hash.CalculateHash() >> (32 - NumOdrHashBits));5354  return RecordDeclBits.ODRHash;5355}5356 5357//===----------------------------------------------------------------------===//5358// BlockDecl Implementation5359//===----------------------------------------------------------------------===//5360 5361BlockDecl::BlockDecl(DeclContext *DC, SourceLocation CaretLoc)5362    : Decl(Block, DC, CaretLoc), DeclContext(Block) {5363  setIsVariadic(false);5364  setCapturesCXXThis(false);5365  setBlockMissingReturnType(true);5366  setIsConversionFromLambda(false);5367  setDoesNotEscape(false);5368  setCanAvoidCopyToHeap(false);5369}5370 5371void BlockDecl::setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {5372  assert(!ParamInfo && "Already has param info!");5373 5374  // Zero params -> null pointer.5375  if (!NewParamInfo.empty()) {5376    NumParams = NewParamInfo.size();5377    ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];5378    llvm::copy(NewParamInfo, ParamInfo);5379  }5380}5381 5382void BlockDecl::setCaptures(ASTContext &Context, ArrayRef<Capture> Captures,5383                            bool CapturesCXXThis) {5384  this->setCapturesCXXThis(CapturesCXXThis);5385  this->NumCaptures = Captures.size();5386 5387  if (Captures.empty()) {5388    this->Captures = nullptr;5389    return;5390  }5391 5392  this->Captures = Captures.copy(Context).data();5393}5394 5395bool BlockDecl::capturesVariable(const VarDecl *variable) const {5396  for (const auto &I : captures())5397    // Only auto vars can be captured, so no redeclaration worries.5398    if (I.getVariable() == variable)5399      return true;5400 5401  return false;5402}5403 5404SourceRange BlockDecl::getSourceRange() const {5405  return SourceRange(getLocation(), Body ? Body->getEndLoc() : getLocation());5406}5407 5408//===----------------------------------------------------------------------===//5409// Other Decl Allocation/Deallocation Method Implementations5410//===----------------------------------------------------------------------===//5411 5412void TranslationUnitDecl::anchor() {}5413 5414TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {5415  return new (C, (DeclContext *)nullptr) TranslationUnitDecl(C);5416}5417 5418void TranslationUnitDecl::setAnonymousNamespace(NamespaceDecl *D) {5419  AnonymousNamespace = D;5420 5421  if (ASTMutationListener *Listener = Ctx.getASTMutationListener())5422    Listener->AddedAnonymousNamespace(this, D);5423}5424 5425void PragmaCommentDecl::anchor() {}5426 5427PragmaCommentDecl *PragmaCommentDecl::Create(const ASTContext &C,5428                                             TranslationUnitDecl *DC,5429                                             SourceLocation CommentLoc,5430                                             PragmaMSCommentKind CommentKind,5431                                             StringRef Arg) {5432  PragmaCommentDecl *PCD =5433      new (C, DC, additionalSizeToAlloc<char>(Arg.size() + 1))5434          PragmaCommentDecl(DC, CommentLoc, CommentKind);5435  llvm::copy(Arg, PCD->getTrailingObjects());5436  PCD->getTrailingObjects()[Arg.size()] = '\0';5437  return PCD;5438}5439 5440PragmaCommentDecl *PragmaCommentDecl::CreateDeserialized(ASTContext &C,5441                                                         GlobalDeclID ID,5442                                                         unsigned ArgSize) {5443  return new (C, ID, additionalSizeToAlloc<char>(ArgSize + 1))5444      PragmaCommentDecl(nullptr, SourceLocation(), PCK_Unknown);5445}5446 5447void PragmaDetectMismatchDecl::anchor() {}5448 5449PragmaDetectMismatchDecl *5450PragmaDetectMismatchDecl::Create(const ASTContext &C, TranslationUnitDecl *DC,5451                                 SourceLocation Loc, StringRef Name,5452                                 StringRef Value) {5453  size_t ValueStart = Name.size() + 1;5454  PragmaDetectMismatchDecl *PDMD =5455      new (C, DC, additionalSizeToAlloc<char>(ValueStart + Value.size() + 1))5456          PragmaDetectMismatchDecl(DC, Loc, ValueStart);5457  llvm::copy(Name, PDMD->getTrailingObjects());5458  PDMD->getTrailingObjects()[Name.size()] = '\0';5459  llvm::copy(Value, PDMD->getTrailingObjects() + ValueStart);5460  PDMD->getTrailingObjects()[ValueStart + Value.size()] = '\0';5461  return PDMD;5462}5463 5464PragmaDetectMismatchDecl *5465PragmaDetectMismatchDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID,5466                                             unsigned NameValueSize) {5467  return new (C, ID, additionalSizeToAlloc<char>(NameValueSize + 1))5468      PragmaDetectMismatchDecl(nullptr, SourceLocation(), 0);5469}5470 5471void ExternCContextDecl::anchor() {}5472 5473ExternCContextDecl *ExternCContextDecl::Create(const ASTContext &C,5474                                               TranslationUnitDecl *DC) {5475  return new (C, DC) ExternCContextDecl(DC);5476}5477 5478void LabelDecl::anchor() {}5479 5480LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,5481                             SourceLocation IdentL, IdentifierInfo *II) {5482  return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, IdentL);5483}5484 5485LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,5486                             SourceLocation IdentL, IdentifierInfo *II,5487                             SourceLocation GnuLabelL) {5488  assert(GnuLabelL != IdentL && "Use this only for GNU local labels");5489  return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, GnuLabelL);5490}5491 5492LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) {5493  return new (C, ID) LabelDecl(nullptr, SourceLocation(), nullptr, nullptr,5494                               SourceLocation());5495}5496 5497void LabelDecl::setMSAsmLabel(StringRef Name) {5498char *Buffer = new (getASTContext(), 1) char[Name.size() + 1];5499llvm::copy(Name, Buffer);5500Buffer[Name.size()] = '\0';5501MSAsmName = Buffer;5502}5503 5504void ValueDecl::anchor() {}5505 5506bool ValueDecl::isWeak() const {5507  auto *MostRecent = getMostRecentDecl();5508  return MostRecent->hasAttr<WeakAttr>() ||5509         MostRecent->hasAttr<WeakRefAttr>() || isWeakImported();5510}5511 5512bool ValueDecl::isInitCapture() const {5513  if (auto *Var = llvm::dyn_cast<VarDecl>(this))5514    return Var->isInitCapture();5515  return false;5516}5517 5518bool ValueDecl::isParameterPack() const {5519  if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(this))5520    return NTTP->isParameterPack();5521 5522  return isa_and_nonnull<PackExpansionType>(getType().getTypePtrOrNull());5523}5524 5525void ImplicitParamDecl::anchor() {}5526 5527ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,5528                                             SourceLocation IdLoc,5529                                             IdentifierInfo *Id, QualType Type,5530                                             ImplicitParamKind ParamKind) {5531  return new (C, DC) ImplicitParamDecl(C, DC, IdLoc, Id, Type, ParamKind);5532}5533 5534ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, QualType Type,5535                                             ImplicitParamKind ParamKind) {5536  return new (C, nullptr) ImplicitParamDecl(C, Type, ParamKind);5537}5538 5539ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C,5540                                                         GlobalDeclID ID) {5541  return new (C, ID) ImplicitParamDecl(C, QualType(), ImplicitParamKind::Other);5542}5543 5544FunctionDecl *5545FunctionDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,5546                     const DeclarationNameInfo &NameInfo, QualType T,5547                     TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin,5548                     bool isInlineSpecified, bool hasWrittenPrototype,5549                     ConstexprSpecKind ConstexprKind,5550                     const AssociatedConstraint &TrailingRequiresClause) {5551  FunctionDecl *New = new (C, DC) FunctionDecl(5552      Function, C, DC, StartLoc, NameInfo, T, TInfo, SC, UsesFPIntrin,5553      isInlineSpecified, ConstexprKind, TrailingRequiresClause);5554  New->setHasWrittenPrototype(hasWrittenPrototype);5555  return New;5556}5557 5558FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) {5559  return new (C, ID) FunctionDecl(5560      Function, C, nullptr, SourceLocation(), DeclarationNameInfo(), QualType(),5561      nullptr, SC_None, false, false, ConstexprSpecKind::Unspecified,5562      /*TrailingRequiresClause=*/{});5563}5564 5565bool FunctionDecl::isReferenceableKernel() const {5566  return hasAttr<CUDAGlobalAttr>() ||5567         DeviceKernelAttr::isOpenCLSpelling(getAttr<DeviceKernelAttr>());5568}5569 5570BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {5571  return new (C, DC) BlockDecl(DC, L);5572}5573 5574BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) {5575  return new (C, ID) BlockDecl(nullptr, SourceLocation());5576}5577 5578OutlinedFunctionDecl::OutlinedFunctionDecl(DeclContext *DC, unsigned NumParams)5579    : Decl(OutlinedFunction, DC, SourceLocation()),5580      DeclContext(OutlinedFunction), NumParams(NumParams),5581      BodyAndNothrow(nullptr, false) {}5582 5583OutlinedFunctionDecl *OutlinedFunctionDecl::Create(ASTContext &C,5584                                                   DeclContext *DC,5585                                                   unsigned NumParams) {5586  return new (C, DC, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))5587      OutlinedFunctionDecl(DC, NumParams);5588}5589 5590OutlinedFunctionDecl *5591OutlinedFunctionDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID,5592                                         unsigned NumParams) {5593  return new (C, ID, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))5594      OutlinedFunctionDecl(nullptr, NumParams);5595}5596 5597Stmt *OutlinedFunctionDecl::getBody() const {5598  return BodyAndNothrow.getPointer();5599}5600void OutlinedFunctionDecl::setBody(Stmt *B) { BodyAndNothrow.setPointer(B); }5601 5602bool OutlinedFunctionDecl::isNothrow() const { return BodyAndNothrow.getInt(); }5603void OutlinedFunctionDecl::setNothrow(bool Nothrow) {5604  BodyAndNothrow.setInt(Nothrow);5605}5606 5607CapturedDecl::CapturedDecl(DeclContext *DC, unsigned NumParams)5608    : Decl(Captured, DC, SourceLocation()), DeclContext(Captured),5609      NumParams(NumParams), ContextParam(0), BodyAndNothrow(nullptr, false) {}5610 5611CapturedDecl *CapturedDecl::Create(ASTContext &C, DeclContext *DC,5612                                   unsigned NumParams) {5613  return new (C, DC, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))5614      CapturedDecl(DC, NumParams);5615}5616 5617CapturedDecl *CapturedDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID,5618                                               unsigned NumParams) {5619  return new (C, ID, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))5620      CapturedDecl(nullptr, NumParams);5621}5622 5623Stmt *CapturedDecl::getBody() const { return BodyAndNothrow.getPointer(); }5624void CapturedDecl::setBody(Stmt *B) { BodyAndNothrow.setPointer(B); }5625 5626bool CapturedDecl::isNothrow() const { return BodyAndNothrow.getInt(); }5627void CapturedDecl::setNothrow(bool Nothrow) { BodyAndNothrow.setInt(Nothrow); }5628 5629EnumConstantDecl::EnumConstantDecl(const ASTContext &C, DeclContext *DC,5630                                   SourceLocation L, IdentifierInfo *Id,5631                                   QualType T, Expr *E, const llvm::APSInt &V)5632    : ValueDecl(EnumConstant, DC, L, Id, T), Init((Stmt *)E) {5633  setInitVal(C, V);5634}5635 5636EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,5637                                           SourceLocation L,5638                                           IdentifierInfo *Id, QualType T,5639                                           Expr *E, const llvm::APSInt &V) {5640  return new (C, CD) EnumConstantDecl(C, CD, L, Id, T, E, V);5641}5642 5643EnumConstantDecl *EnumConstantDecl::CreateDeserialized(ASTContext &C,5644                                                       GlobalDeclID ID) {5645  return new (C, ID) EnumConstantDecl(C, nullptr, SourceLocation(), nullptr,5646                                      QualType(), nullptr, llvm::APSInt());5647}5648 5649void IndirectFieldDecl::anchor() {}5650 5651IndirectFieldDecl::IndirectFieldDecl(ASTContext &C, DeclContext *DC,5652                                     SourceLocation L, DeclarationName N,5653                                     QualType T,5654                                     MutableArrayRef<NamedDecl *> CH)5655    : ValueDecl(IndirectField, DC, L, N, T), Chaining(CH.data()),5656      ChainingSize(CH.size()) {5657  // In C++, indirect field declarations conflict with tag declarations in the5658  // same scope, so add them to IDNS_Tag so that tag redeclaration finds them.5659  if (C.getLangOpts().CPlusPlus)5660    IdentifierNamespace |= IDNS_Tag;5661}5662 5663IndirectFieldDecl *IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC,5664                                             SourceLocation L,5665                                             const IdentifierInfo *Id,5666                                             QualType T,5667                                             MutableArrayRef<NamedDecl *> CH) {5668  return new (C, DC) IndirectFieldDecl(C, DC, L, Id, T, CH);5669}5670 5671IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C,5672                                                         GlobalDeclID ID) {5673  return new (C, ID) IndirectFieldDecl(C, nullptr, SourceLocation(),5674                                       DeclarationName(), QualType(), {});5675}5676 5677SourceRange EnumConstantDecl::getSourceRange() const {5678  SourceLocation End = getLocation();5679  if (Init)5680    End = Init->getEndLoc();5681  return SourceRange(getLocation(), End);5682}5683 5684void TypeDecl::anchor() {}5685 5686TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,5687                                 SourceLocation StartLoc, SourceLocation IdLoc,5688                                 const IdentifierInfo *Id,5689                                 TypeSourceInfo *TInfo) {5690  return new (C, DC) TypedefDecl(C, DC, StartLoc, IdLoc, Id, TInfo);5691}5692 5693void TypedefNameDecl::anchor() {}5694 5695TagDecl *TypedefNameDecl::getAnonDeclWithTypedefName(bool AnyRedecl) const {5696  if (auto *TT = getTypeSourceInfo()->getType()->getAs<TagType>()) {5697    auto *OwningTypedef = TT->getDecl()->getTypedefNameForAnonDecl();5698    auto *ThisTypedef = this;5699    if (AnyRedecl && OwningTypedef) {5700      OwningTypedef = OwningTypedef->getCanonicalDecl();5701      ThisTypedef = ThisTypedef->getCanonicalDecl();5702    }5703    if (OwningTypedef == ThisTypedef)5704      return TT->getDecl()->getDefinitionOrSelf();5705  }5706 5707  return nullptr;5708}5709 5710bool TypedefNameDecl::isTransparentTagSlow() const {5711  auto determineIsTransparent = [&]() {5712    if (auto *TT = getUnderlyingType()->getAs<TagType>()) {5713      if (auto *TD = TT->getDecl()) {5714        if (TD->getName() != getName())5715          return false;5716        SourceLocation TTLoc = getLocation();5717        SourceLocation TDLoc = TD->getLocation();5718        if (!TTLoc.isMacroID() || !TDLoc.isMacroID())5719          return false;5720        SourceManager &SM = getASTContext().getSourceManager();5721        return SM.getSpellingLoc(TTLoc) == SM.getSpellingLoc(TDLoc);5722      }5723    }5724    return false;5725  };5726 5727  bool isTransparent = determineIsTransparent();5728  MaybeModedTInfo.setInt((isTransparent << 1) | 1);5729  return isTransparent;5730}5731 5732TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) {5733  return new (C, ID) TypedefDecl(C, nullptr, SourceLocation(), SourceLocation(),5734                                 nullptr, nullptr);5735}5736 5737TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC,5738                                     SourceLocation StartLoc,5739                                     SourceLocation IdLoc,5740                                     const IdentifierInfo *Id,5741                                     TypeSourceInfo *TInfo) {5742  return new (C, DC) TypeAliasDecl(C, DC, StartLoc, IdLoc, Id, TInfo);5743}5744 5745TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C,5746                                                 GlobalDeclID ID) {5747  return new (C, ID) TypeAliasDecl(C, nullptr, SourceLocation(),5748                                   SourceLocation(), nullptr, nullptr);5749}5750 5751SourceRange TypedefDecl::getSourceRange() const {5752  SourceLocation RangeEnd = getLocation();5753  if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {5754    if (typeIsPostfix(TInfo->getType()))5755      RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();5756  }5757  return SourceRange(getBeginLoc(), RangeEnd);5758}5759 5760SourceRange TypeAliasDecl::getSourceRange() const {5761  SourceLocation RangeEnd = getBeginLoc();5762  if (TypeSourceInfo *TInfo = getTypeSourceInfo())5763    RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();5764  return SourceRange(getBeginLoc(), RangeEnd);5765}5766 5767void FileScopeAsmDecl::anchor() {}5768 5769FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,5770                                           Expr *Str, SourceLocation AsmLoc,5771                                           SourceLocation RParenLoc) {5772  return new (C, DC) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);5773}5774 5775FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C,5776                                                       GlobalDeclID ID) {5777  return new (C, ID) FileScopeAsmDecl(nullptr, nullptr, SourceLocation(),5778                                      SourceLocation());5779}5780 5781std::string FileScopeAsmDecl::getAsmString() const {5782  return GCCAsmStmt::ExtractStringFromGCCAsmStmtComponent(getAsmStringExpr());5783}5784 5785void TopLevelStmtDecl::anchor() {}5786 5787TopLevelStmtDecl *TopLevelStmtDecl::Create(ASTContext &C, Stmt *Statement) {5788  assert(C.getLangOpts().IncrementalExtensions &&5789         "Must be used only in incremental mode");5790 5791  SourceLocation Loc = Statement ? Statement->getBeginLoc() : SourceLocation();5792  DeclContext *DC = C.getTranslationUnitDecl();5793 5794  return new (C, DC) TopLevelStmtDecl(DC, Loc, Statement);5795}5796 5797TopLevelStmtDecl *TopLevelStmtDecl::CreateDeserialized(ASTContext &C,5798                                                       GlobalDeclID ID) {5799  return new (C, ID)5800      TopLevelStmtDecl(/*DC=*/nullptr, SourceLocation(), /*S=*/nullptr);5801}5802 5803SourceRange TopLevelStmtDecl::getSourceRange() const {5804  return SourceRange(getLocation(), Statement->getEndLoc());5805}5806 5807void TopLevelStmtDecl::setStmt(Stmt *S) {5808  assert(S);5809  Statement = S;5810  setLocation(Statement->getBeginLoc());5811}5812 5813void EmptyDecl::anchor() {}5814 5815EmptyDecl *EmptyDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {5816  return new (C, DC) EmptyDecl(DC, L);5817}5818 5819EmptyDecl *EmptyDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) {5820  return new (C, ID) EmptyDecl(nullptr, SourceLocation());5821}5822 5823HLSLBufferDecl::HLSLBufferDecl(DeclContext *DC, bool CBuffer,5824                               SourceLocation KwLoc, IdentifierInfo *ID,5825                               SourceLocation IDLoc, SourceLocation LBrace)5826    : NamedDecl(Decl::Kind::HLSLBuffer, DC, IDLoc, DeclarationName(ID)),5827      DeclContext(Decl::Kind::HLSLBuffer), LBraceLoc(LBrace), KwLoc(KwLoc),5828      IsCBuffer(CBuffer), HasValidPackoffset(false), LayoutStruct(nullptr) {}5829 5830HLSLBufferDecl *HLSLBufferDecl::Create(ASTContext &C,5831                                       DeclContext *LexicalParent, bool CBuffer,5832                                       SourceLocation KwLoc, IdentifierInfo *ID,5833                                       SourceLocation IDLoc,5834                                       SourceLocation LBrace) {5835  // For hlsl like this5836  // cbuffer A {5837  //     cbuffer B {5838  //     }5839  // }5840  // compiler should treat it as5841  // cbuffer A {5842  // }5843  // cbuffer B {5844  // }5845  // FIXME: support nested buffers if required for back-compat.5846  DeclContext *DC = LexicalParent;5847  HLSLBufferDecl *Result =5848      new (C, DC) HLSLBufferDecl(DC, CBuffer, KwLoc, ID, IDLoc, LBrace);5849  return Result;5850}5851 5852HLSLBufferDecl *5853HLSLBufferDecl::CreateDefaultCBuffer(ASTContext &C, DeclContext *LexicalParent,5854                                     ArrayRef<Decl *> DefaultCBufferDecls) {5855  DeclContext *DC = LexicalParent;5856  IdentifierInfo *II = &C.Idents.get("$Globals", tok::TokenKind::identifier);5857  HLSLBufferDecl *Result = new (C, DC) HLSLBufferDecl(5858      DC, true, SourceLocation(), II, SourceLocation(), SourceLocation());5859  Result->setImplicit(true);5860  Result->setDefaultBufferDecls(DefaultCBufferDecls);5861  return Result;5862}5863 5864HLSLBufferDecl *HLSLBufferDecl::CreateDeserialized(ASTContext &C,5865                                                   GlobalDeclID ID) {5866  return new (C, ID) HLSLBufferDecl(nullptr, false, SourceLocation(), nullptr,5867                                    SourceLocation(), SourceLocation());5868}5869 5870void HLSLBufferDecl::addLayoutStruct(CXXRecordDecl *LS) {5871  assert(LayoutStruct == nullptr && "layout struct has already been set");5872  LayoutStruct = LS;5873  addDecl(LS);5874}5875 5876void HLSLBufferDecl::setDefaultBufferDecls(ArrayRef<Decl *> Decls) {5877  assert(!Decls.empty());5878  assert(DefaultBufferDecls.empty() && "default decls are already set");5879  assert(isImplicit() &&5880         "default decls can only be added to the implicit/default constant "5881         "buffer $Globals");5882 5883  // allocate array for default decls with ASTContext allocator5884  Decl **DeclsArray = new (getASTContext()) Decl *[Decls.size()];5885  llvm::copy(Decls, DeclsArray);5886  DefaultBufferDecls = ArrayRef<Decl *>(DeclsArray, Decls.size());5887}5888 5889HLSLBufferDecl::buffer_decl_iterator5890HLSLBufferDecl::buffer_decls_begin() const {5891  return buffer_decl_iterator(llvm::iterator_range(DefaultBufferDecls.begin(),5892                                                   DefaultBufferDecls.end()),5893                              decl_range(decls_begin(), decls_end()));5894}5895 5896HLSLBufferDecl::buffer_decl_iterator HLSLBufferDecl::buffer_decls_end() const {5897  return buffer_decl_iterator(5898      llvm::iterator_range(DefaultBufferDecls.end(), DefaultBufferDecls.end()),5899      decl_range(decls_end(), decls_end()));5900}5901 5902bool HLSLBufferDecl::buffer_decls_empty() {5903  return DefaultBufferDecls.empty() && decls_empty();5904}5905 5906//===----------------------------------------------------------------------===//5907// HLSLRootSignatureDecl Implementation5908//===----------------------------------------------------------------------===//5909 5910HLSLRootSignatureDecl::HLSLRootSignatureDecl(5911    DeclContext *DC, SourceLocation Loc, IdentifierInfo *ID,5912    llvm::dxbc::RootSignatureVersion Version, unsigned NumElems)5913    : NamedDecl(Decl::Kind::HLSLRootSignature, DC, Loc, DeclarationName(ID)),5914      Version(Version), NumElems(NumElems) {}5915 5916HLSLRootSignatureDecl *HLSLRootSignatureDecl::Create(5917    ASTContext &C, DeclContext *DC, SourceLocation Loc, IdentifierInfo *ID,5918    llvm::dxbc::RootSignatureVersion Version,5919    ArrayRef<llvm::hlsl::rootsig::RootElement> RootElements) {5920  HLSLRootSignatureDecl *RSDecl =5921      new (C, DC,5922           additionalSizeToAlloc<llvm::hlsl::rootsig::RootElement>(5923               RootElements.size()))5924          HLSLRootSignatureDecl(DC, Loc, ID, Version, RootElements.size());5925  auto *StoredElems = RSDecl->getElems();5926  llvm::uninitialized_copy(RootElements, StoredElems);5927  return RSDecl;5928}5929 5930HLSLRootSignatureDecl *5931HLSLRootSignatureDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) {5932  HLSLRootSignatureDecl *Result = new (C, ID)5933      HLSLRootSignatureDecl(nullptr, SourceLocation(), nullptr,5934                            /*Version*/ llvm::dxbc::RootSignatureVersion::V1_1,5935                            /*NumElems=*/0);5936  return Result;5937}5938 5939//===----------------------------------------------------------------------===//5940// ImportDecl Implementation5941//===----------------------------------------------------------------------===//5942 5943/// Retrieve the number of module identifiers needed to name the given5944/// module.5945static unsigned getNumModuleIdentifiers(Module *Mod) {5946  unsigned Result = 1;5947  while (Mod->Parent) {5948    Mod = Mod->Parent;5949    ++Result;5950  }5951  return Result;5952}5953 5954ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,5955                       Module *Imported,5956                       ArrayRef<SourceLocation> IdentifierLocs)5957    : Decl(Import, DC, StartLoc), ImportedModule(Imported),5958      NextLocalImportAndComplete(nullptr, true) {5959  assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size());5960  auto *StoredLocs = getTrailingObjects();5961  llvm::uninitialized_copy(IdentifierLocs, StoredLocs);5962}5963 5964ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,5965                       Module *Imported, SourceLocation EndLoc)5966    : Decl(Import, DC, StartLoc), ImportedModule(Imported),5967      NextLocalImportAndComplete(nullptr, false) {5968  *getTrailingObjects() = EndLoc;5969}5970 5971ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC,5972                               SourceLocation StartLoc, Module *Imported,5973                               ArrayRef<SourceLocation> IdentifierLocs) {5974  return new (C, DC,5975              additionalSizeToAlloc<SourceLocation>(IdentifierLocs.size()))5976      ImportDecl(DC, StartLoc, Imported, IdentifierLocs);5977}5978 5979ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC,5980                                       SourceLocation StartLoc,5981                                       Module *Imported,5982                                       SourceLocation EndLoc) {5983  ImportDecl *Import = new (C, DC, additionalSizeToAlloc<SourceLocation>(1))5984      ImportDecl(DC, StartLoc, Imported, EndLoc);5985  Import->setImplicit();5986  return Import;5987}5988 5989ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID,5990                                           unsigned NumLocations) {5991  return new (C, ID, additionalSizeToAlloc<SourceLocation>(NumLocations))5992      ImportDecl(EmptyShell());5993}5994 5995ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const {5996  if (!isImportComplete())5997    return {};5998 5999  return getTrailingObjects(getNumModuleIdentifiers(getImportedModule()));6000}6001 6002SourceRange ImportDecl::getSourceRange() const {6003  if (!isImportComplete())6004    return SourceRange(getLocation(), *getTrailingObjects());6005 6006  return SourceRange(getLocation(), getIdentifierLocs().back());6007}6008 6009//===----------------------------------------------------------------------===//6010// ExportDecl Implementation6011//===----------------------------------------------------------------------===//6012 6013void ExportDecl::anchor() {}6014 6015ExportDecl *ExportDecl::Create(ASTContext &C, DeclContext *DC,6016                               SourceLocation ExportLoc) {6017  return new (C, DC) ExportDecl(DC, ExportLoc);6018}6019 6020ExportDecl *ExportDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) {6021  return new (C, ID) ExportDecl(nullptr, SourceLocation());6022}6023 6024bool clang::IsArmStreamingFunction(const FunctionDecl *FD,6025                                   bool IncludeLocallyStreaming) {6026  if (IncludeLocallyStreaming)6027    if (FD->hasAttr<ArmLocallyStreamingAttr>())6028      return true;6029 6030  assert(!FD->getType().isNull() && "Expected a valid FunctionDecl");6031  if (const auto *FPT = FD->getType()->getAs<FunctionProtoType>())6032    if (FPT->getAArch64SMEAttributes() & FunctionType::SME_PStateSMEnabledMask)6033      return true;6034 6035  return false;6036}6037 6038bool clang::hasArmZAState(const FunctionDecl *FD) {6039  const auto *T = FD->getType()->getAs<FunctionProtoType>();6040  return (T && FunctionType::getArmZAState(T->getAArch64SMEAttributes()) !=6041                   FunctionType::ARM_None) ||6042         (FD->hasAttr<ArmNewAttr>() && FD->getAttr<ArmNewAttr>()->isNewZA());6043}6044 6045bool clang::hasArmZT0State(const FunctionDecl *FD) {6046  const auto *T = FD->getType()->getAs<FunctionProtoType>();6047  return (T && FunctionType::getArmZT0State(T->getAArch64SMEAttributes()) !=6048                   FunctionType::ARM_None) ||6049         (FD->hasAttr<ArmNewAttr>() && FD->getAttr<ArmNewAttr>()->isNewZT0());6050}6051