Path: blob/main/contrib/llvm-project/clang/lib/AST/Decl.cpp
35260 views
//===- Decl.cpp - Declaration AST Node Implementation ---------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file implements the Decl subclasses.9//10//===----------------------------------------------------------------------===//1112#include "clang/AST/Decl.h"13#include "Linkage.h"14#include "clang/AST/ASTContext.h"15#include "clang/AST/ASTDiagnostic.h"16#include "clang/AST/ASTLambda.h"17#include "clang/AST/ASTMutationListener.h"18#include "clang/AST/Attr.h"19#include "clang/AST/CanonicalType.h"20#include "clang/AST/DeclBase.h"21#include "clang/AST/DeclCXX.h"22#include "clang/AST/DeclObjC.h"23#include "clang/AST/DeclOpenMP.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/Support/Casting.h"61#include "llvm/Support/ErrorHandling.h"62#include "llvm/Support/raw_ostream.h"63#include "llvm/TargetParser/Triple.h"64#include <algorithm>65#include <cassert>66#include <cstddef>67#include <cstring>68#include <memory>69#include <optional>70#include <string>71#include <tuple>72#include <type_traits>7374using namespace clang;7576Decl *clang::getPrimaryMergedDecl(Decl *D) {77return D->getASTContext().getPrimaryMergedDecl(D);78}7980void PrettyDeclStackTraceEntry::print(raw_ostream &OS) const {81SourceLocation Loc = this->Loc;82if (!Loc.isValid() && TheDecl) Loc = TheDecl->getLocation();83if (Loc.isValid()) {84Loc.print(OS, Context.getSourceManager());85OS << ": ";86}87OS << Message;8889if (auto *ND = dyn_cast_if_present<NamedDecl>(TheDecl)) {90OS << " '";91ND->getNameForDiagnostic(OS, Context.getPrintingPolicy(), true);92OS << "'";93}9495OS << '\n';96}9798// Defined here so that it can be inlined into its direct callers.99bool Decl::isOutOfLine() const {100return !getLexicalDeclContext()->Equals(getDeclContext());101}102103TranslationUnitDecl::TranslationUnitDecl(ASTContext &ctx)104: Decl(TranslationUnit, nullptr, SourceLocation()),105DeclContext(TranslationUnit), redeclarable_base(ctx), Ctx(ctx) {}106107//===----------------------------------------------------------------------===//108// NamedDecl Implementation109//===----------------------------------------------------------------------===//110111// 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.156157/// Does this computation kind permit us to consider additional158/// visibility settings from attributes and the like?159static bool hasExplicitVisibilityAlready(LVComputationKind computation) {160return computation.IgnoreExplicitVisibility;161}162163/// Given an LVComputationKind, return one of the same type/value sort164/// that records that it already has explicit visibility.165static LVComputationKind166withExplicitVisibilityAlready(LVComputationKind Kind) {167Kind.IgnoreExplicitVisibility = true;168return Kind;169}170171static std::optional<Visibility> getExplicitVisibility(const NamedDecl *D,172LVComputationKind kind) {173assert(!kind.IgnoreExplicitVisibility &&174"asking for explicit visibility when we shouldn't be");175return D->getExplicitVisibility(kind.getExplicitVisibilityKind());176}177178/// Is the given declaration a "type" or a "value" for the purposes of179/// visibility computation?180static bool usesTypeVisibility(const NamedDecl *D) {181return isa<TypeDecl>(D) ||182isa<ClassTemplateDecl>(D) ||183isa<ObjCInterfaceDecl>(D);184}185186/// 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) {191if (const MemberSpecializationInfo *member =192D->getMemberSpecializationInfo()) {193return member->isExplicitSpecialization();194}195return false;196}197198/// 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) {202return D->isMemberSpecialization();203}204205/// Given a visibility attribute, return the explicit visibility206/// associated with it.207template <class T>208static Visibility getVisibilityFromAttr(const T *attr) {209switch (attr->getVisibility()) {210case T::Default:211return DefaultVisibility;212case T::Hidden:213return HiddenVisibility;214case T::Protected:215return ProtectedVisibility;216}217llvm_unreachable("bad visibility kind");218}219220/// 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'.225if (kind == NamedDecl::VisibilityForType) {226if (const auto *A = D->getAttr<TypeVisibilityAttr>()) {227return getVisibilityFromAttr(A);228}229}230231// If this declaration has an explicit visibility attribute, use it.232if (const auto *A = D->getAttr<VisibilityAttr>()) {233return getVisibilityFromAttr(A);234}235236return std::nullopt;237}238239LinkageInfo LinkageComputer::getLVForType(const Type &T,240LVComputationKind computation) {241if (computation.IgnoreAllVisibility)242return LinkageInfo(T.getLinkage(), DefaultVisibility, true);243return getTypeLinkageAndVisibility(&T);244}245246/// 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(250const TemplateParameterList *Params, LVComputationKind computation) {251LinkageInfo LV;252for (const NamedDecl *P : *Params) {253// Template type parameters are the most common and never254// contribute to visibility, pack or not.255if (isa<TemplateTypeParmDecl>(P))256continue;257258// 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.262if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {263// Handle the non-pack case first.264if (!NTTP->isExpandedParameterPack()) {265if (!NTTP->getType()->isDependentType()) {266LV.merge(getLVForType(*NTTP->getType(), computation));267}268continue;269}270271// Look at all the types in an expanded pack.272for (unsigned i = 0, n = NTTP->getNumExpansionTypes(); i != n; ++i) {273QualType type = NTTP->getExpansionType(i);274if (!type->isDependentType())275LV.merge(getTypeLinkageAndVisibility(type));276}277continue;278}279280// Template template parameters can be restricted by their281// template parameters, recursively.282const auto *TTP = cast<TemplateTemplateParmDecl>(P);283284// Handle the non-pack case first.285if (!TTP->isExpandedParameterPack()) {286LV.merge(getLVForTemplateParameterList(TTP->getTemplateParameters(),287computation));288continue;289}290291// Look at all expansions in an expanded pack.292for (unsigned i = 0, n = TTP->getNumExpansionTemplateParameters();293i != n; ++i) {294LV.merge(getLVForTemplateParameterList(295TTP->getExpansionTemplateParameters(i), computation));296}297}298299return LV;300}301302static const Decl *getOutermostFuncOrBlockContext(const Decl *D) {303const Decl *Ret = nullptr;304const DeclContext *DC = D->getDeclContext();305while (DC->getDeclKind() != Decl::TranslationUnit) {306if (isa<FunctionDecl>(DC) || isa<BlockDecl>(DC))307Ret = cast<Decl>(DC);308DC = DC->getParent();309}310return Ret;311}312313/// 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,320LVComputationKind computation) {321LinkageInfo LV;322323for (const TemplateArgument &Arg : Args) {324switch (Arg.getKind()) {325case TemplateArgument::Null:326case TemplateArgument::Integral:327case TemplateArgument::Expression:328continue;329330case TemplateArgument::Type:331LV.merge(getLVForType(*Arg.getAsType(), computation));332continue;333334case TemplateArgument::Declaration: {335const NamedDecl *ND = Arg.getAsDecl();336assert(!usesTypeVisibility(ND));337LV.merge(getLVForDecl(ND, computation));338continue;339}340341case TemplateArgument::NullPtr:342LV.merge(getTypeLinkageAndVisibility(Arg.getNullPtrType()));343continue;344345case TemplateArgument::StructuralValue:346LV.merge(getLVForValue(Arg.getAsStructuralValue(), computation));347continue;348349case TemplateArgument::Template:350case TemplateArgument::TemplateExpansion:351if (TemplateDecl *Template =352Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl())353LV.merge(getLVForDecl(Template, computation));354continue;355356case TemplateArgument::Pack:357LV.merge(getLVForTemplateArgumentList(Arg.getPackAsArray(), computation));358continue;359}360llvm_unreachable("bad template argument kind");361}362363return LV;364}365366LinkageInfo367LinkageComputer::getLVForTemplateArgumentList(const TemplateArgumentList &TArgs,368LVComputationKind computation) {369return getLVForTemplateArgumentList(TArgs.asArray(), computation);370}371372static bool shouldConsiderTemplateVisibility(const FunctionDecl *fn,373const FunctionTemplateSpecializationInfo *specInfo) {374// Include visibility from the template parameters and arguments375// only if this is not an explicit instantiation or specialization376// with direct explicit visibility. (Implicit instantiations won't377// have a direct attribute.)378if (!specInfo->isExplicitInstantiationOrSpecialization())379return true;380381return !fn->hasAttr<VisibilityAttr>();382}383384/// Merge in template-related linkage and visibility for the given385/// function template specialization.386///387/// We don't need a computation kind here because we can assume388/// LVForValue.389///390/// \param[out] LV the computation to use for the parent391void LinkageComputer::mergeTemplateLV(392LinkageInfo &LV, const FunctionDecl *fn,393const FunctionTemplateSpecializationInfo *specInfo,394LVComputationKind computation) {395bool considerVisibility =396shouldConsiderTemplateVisibility(fn, specInfo);397398FunctionTemplateDecl *temp = specInfo->getTemplate();399// Merge information from the template declaration.400LinkageInfo tempLV = getLVForDecl(temp, computation);401// The linkage of the specialization should be consistent with the402// template declaration.403LV.setLinkage(tempLV.getLinkage());404405// Merge information from the template parameters.406LinkageInfo paramsLV =407getLVForTemplateParameterList(temp->getTemplateParameters(), computation);408LV.mergeMaybeWithVisibility(paramsLV, considerVisibility);409410// Merge information from the template arguments.411const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments;412LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);413LV.mergeMaybeWithVisibility(argsLV, considerVisibility);414}415416/// Does the given declaration have a direct visibility attribute417/// that would match the given rules?418static bool hasDirectVisibilityAttribute(const NamedDecl *D,419LVComputationKind computation) {420if (computation.IgnoreAllVisibility)421return false;422423return (computation.isTypeVisibility() && D->hasAttr<TypeVisibilityAttr>()) ||424D->hasAttr<VisibilityAttr>();425}426427/// Should we consider visibility associated with the template428/// arguments and parameters of the given class template specialization?429static bool shouldConsiderTemplateVisibility(430const ClassTemplateSpecializationDecl *spec,431LVComputationKind computation) {432// Include visibility from the template parameters and arguments433// only if this is not an explicit instantiation or specialization434// with direct explicit visibility (and note that implicit435// instantiations won't have a direct attribute).436//437// Furthermore, we want to ignore template parameters and arguments438// for an explicit specialization when computing the visibility of a439// member thereof with explicit visibility.440//441// This is a bit complex; let's unpack it.442//443// An explicit class specialization is an independent, top-level444// declaration. As such, if it or any of its members has an445// explicit visibility attribute, that must directly express the446// user's intent, and we should honor it. The same logic applies to447// an explicit instantiation of a member of such a thing.448449// Fast path: if this is not an explicit instantiation or450// specialization, we always want to consider template-related451// visibility restrictions.452if (!spec->isExplicitInstantiationOrSpecialization())453return true;454455// This is the 'member thereof' check.456if (spec->isExplicitSpecialization() &&457hasExplicitVisibilityAlready(computation))458return false;459460return !hasDirectVisibilityAttribute(spec, computation);461}462463/// Merge in template-related linkage and visibility for the given464/// class template specialization.465void LinkageComputer::mergeTemplateLV(466LinkageInfo &LV, const ClassTemplateSpecializationDecl *spec,467LVComputationKind computation) {468bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);469470// Merge information from the template parameters, but ignore471// visibility if we're only considering template arguments.472ClassTemplateDecl *temp = spec->getSpecializedTemplate();473// Merge information from the template declaration.474LinkageInfo tempLV = getLVForDecl(temp, computation);475// The linkage of the specialization should be consistent with the476// template declaration.477LV.setLinkage(tempLV.getLinkage());478479LinkageInfo paramsLV =480getLVForTemplateParameterList(temp->getTemplateParameters(), computation);481LV.mergeMaybeWithVisibility(paramsLV,482considerVisibility && !hasExplicitVisibilityAlready(computation));483484// Merge information from the template arguments. We ignore485// template-argument visibility if we've got an explicit486// instantiation with a visibility attribute.487const TemplateArgumentList &templateArgs = spec->getTemplateArgs();488LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);489if (considerVisibility)490LV.mergeVisibility(argsLV);491LV.mergeExternalVisibility(argsLV);492}493494/// Should we consider visibility associated with the template495/// arguments and parameters of the given variable template496/// specialization? As usual, follow class template specialization497/// logic up to initialization.498static bool shouldConsiderTemplateVisibility(499const VarTemplateSpecializationDecl *spec,500LVComputationKind computation) {501// Include visibility from the template parameters and arguments502// only if this is not an explicit instantiation or specialization503// with direct explicit visibility (and note that implicit504// instantiations won't have a direct attribute).505if (!spec->isExplicitInstantiationOrSpecialization())506return true;507508// An explicit variable specialization is an independent, top-level509// declaration. As such, if it has an explicit visibility attribute,510// that must directly express the user's intent, and we should honor511// it.512if (spec->isExplicitSpecialization() &&513hasExplicitVisibilityAlready(computation))514return false;515516return !hasDirectVisibilityAttribute(spec, computation);517}518519/// Merge in template-related linkage and visibility for the given520/// variable template specialization. As usual, follow class template521/// specialization logic up to initialization.522void LinkageComputer::mergeTemplateLV(LinkageInfo &LV,523const VarTemplateSpecializationDecl *spec,524LVComputationKind computation) {525bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);526527// Merge information from the template parameters, but ignore528// visibility if we're only considering template arguments.529VarTemplateDecl *temp = spec->getSpecializedTemplate();530LinkageInfo tempLV =531getLVForTemplateParameterList(temp->getTemplateParameters(), computation);532LV.mergeMaybeWithVisibility(tempLV,533considerVisibility && !hasExplicitVisibilityAlready(computation));534535// Merge information from the template arguments. We ignore536// template-argument visibility if we've got an explicit537// instantiation with a visibility attribute.538const TemplateArgumentList &templateArgs = spec->getTemplateArgs();539LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);540if (considerVisibility)541LV.mergeVisibility(argsLV);542LV.mergeExternalVisibility(argsLV);543}544545static bool useInlineVisibilityHidden(const NamedDecl *D) {546// FIXME: we should warn if -fvisibility-inlines-hidden is used with c.547const LangOptions &Opts = D->getASTContext().getLangOpts();548if (!Opts.CPlusPlus || !Opts.InlineVisibilityHidden)549return false;550551const auto *FD = dyn_cast<FunctionDecl>(D);552if (!FD)553return false;554555TemplateSpecializationKind TSK = TSK_Undeclared;556if (FunctionTemplateSpecializationInfo *spec557= FD->getTemplateSpecializationInfo()) {558TSK = spec->getTemplateSpecializationKind();559} else if (MemberSpecializationInfo *MSI =560FD->getMemberSpecializationInfo()) {561TSK = MSI->getTemplateSpecializationKind();562}563564const FunctionDecl *Def = nullptr;565// InlineVisibilityHidden only applies to definitions, and566// isInlined() only gives meaningful answers on definitions567// anyway.568return TSK != TSK_ExplicitInstantiationDeclaration &&569TSK != TSK_ExplicitInstantiationDefinition &&570FD->hasBody(Def) && Def->isInlined() && !Def->hasAttr<GNUInlineAttr>();571}572573template <typename T> static bool isFirstInExternCContext(T *D) {574const T *First = D->getFirstDecl();575return First->isInExternCContext();576}577578static bool isSingleLineLanguageLinkage(const Decl &D) {579if (const auto *SD = dyn_cast<LinkageSpecDecl>(D.getDeclContext()))580if (!SD->hasBraces())581return true;582return false;583}584585static bool isDeclaredInModuleInterfaceOrPartition(const NamedDecl *D) {586if (auto *M = D->getOwningModule())587return M->isInterfaceOrPartition();588return false;589}590591static LinkageInfo getExternalLinkageFor(const NamedDecl *D) {592return LinkageInfo::external();593}594595static StorageClass getStorageClass(const Decl *D) {596if (auto *TD = dyn_cast<TemplateDecl>(D))597D = TD->getTemplatedDecl();598if (D) {599if (auto *VD = dyn_cast<VarDecl>(D))600return VD->getStorageClass();601if (auto *FD = dyn_cast<FunctionDecl>(D))602return FD->getStorageClass();603}604return SC_None;605}606607LinkageInfo608LinkageComputer::getLVForNamespaceScopeDecl(const NamedDecl *D,609LVComputationKind computation,610bool IgnoreVarTypeLinkage) {611assert(D->getDeclContext()->getRedeclContext()->isFileContext() &&612"Not a name having namespace scope");613ASTContext &Context = D->getASTContext();614const auto *Var = dyn_cast<VarDecl>(D);615616// C++ [basic.link]p3:617// A name having namespace scope (3.3.6) has internal linkage if it618// is the name of619620if ((getStorageClass(D->getCanonicalDecl()) == SC_Static) ||621(Context.getLangOpts().C23 && Var && Var->isConstexpr())) {622// - a variable, variable template, function, or function template623// that is explicitly declared static; or624// (This bullet corresponds to C99 6.2.2p3.)625626// C23 6.2.2p3627// If the declaration of a file scope identifier for628// an object contains any of the storage-class specifiers static or629// constexpr then the identifier has internal linkage.630return LinkageInfo::internal();631}632633if (Var) {634// - a non-template variable of non-volatile const-qualified type, unless635// - it is explicitly declared extern, or636// - it is declared in the purview of a module interface unit637// (outside the private-module-fragment, if any) or module partition, or638// - it is inline, or639// - it was previously declared and the prior declaration did not have640// internal linkage641// (There is no equivalent in C99.)642if (Context.getLangOpts().CPlusPlus && Var->getType().isConstQualified() &&643!Var->getType().isVolatileQualified() && !Var->isInline() &&644!isDeclaredInModuleInterfaceOrPartition(Var) &&645!isa<VarTemplateSpecializationDecl>(Var) &&646!Var->getDescribedVarTemplate()) {647const VarDecl *PrevVar = Var->getPreviousDecl();648if (PrevVar)649return getLVForDecl(PrevVar, computation);650651if (Var->getStorageClass() != SC_Extern &&652Var->getStorageClass() != SC_PrivateExtern &&653!isSingleLineLanguageLinkage(*Var))654return LinkageInfo::internal();655}656657for (const VarDecl *PrevVar = Var->getPreviousDecl(); PrevVar;658PrevVar = PrevVar->getPreviousDecl()) {659if (PrevVar->getStorageClass() == SC_PrivateExtern &&660Var->getStorageClass() == SC_None)661return getDeclLinkageAndVisibility(PrevVar);662// Explicitly declared static.663if (PrevVar->getStorageClass() == SC_Static)664return LinkageInfo::internal();665}666} else if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D)) {667// - a data member of an anonymous union.668const VarDecl *VD = IFD->getVarDecl();669assert(VD && "Expected a VarDecl in this IndirectFieldDecl!");670return getLVForNamespaceScopeDecl(VD, computation, IgnoreVarTypeLinkage);671}672assert(!isa<FieldDecl>(D) && "Didn't expect a FieldDecl!");673674// FIXME: This gives internal linkage to names that should have no linkage675// (those not covered by [basic.link]p6).676if (D->isInAnonymousNamespace()) {677const auto *Var = dyn_cast<VarDecl>(D);678const auto *Func = dyn_cast<FunctionDecl>(D);679// FIXME: The check for extern "C" here is not justified by the standard680// wording, but we retain it from the pre-DR1113 model to avoid breaking681// code.682//683// C++11 [basic.link]p4:684// An unnamed namespace or a namespace declared directly or indirectly685// within an unnamed namespace has internal linkage.686if ((!Var || !isFirstInExternCContext(Var)) &&687(!Func || !isFirstInExternCContext(Func)))688return LinkageInfo::internal();689}690691// Set up the defaults.692693// C99 6.2.2p5:694// If the declaration of an identifier for an object has file695// scope and no storage-class specifier, its linkage is696// external.697LinkageInfo LV = getExternalLinkageFor(D);698699if (!hasExplicitVisibilityAlready(computation)) {700if (std::optional<Visibility> Vis = getExplicitVisibility(D, computation)) {701LV.mergeVisibility(*Vis, true);702} else {703// If we're declared in a namespace with a visibility attribute,704// use that namespace's visibility, and it still counts as explicit.705for (const DeclContext *DC = D->getDeclContext();706!isa<TranslationUnitDecl>(DC);707DC = DC->getParent()) {708const auto *ND = dyn_cast<NamespaceDecl>(DC);709if (!ND) continue;710if (std::optional<Visibility> Vis =711getExplicitVisibility(ND, computation)) {712LV.mergeVisibility(*Vis, true);713break;714}715}716}717718// Add in global settings if the above didn't give us direct visibility.719if (!LV.isVisibilityExplicit()) {720// Use global type/value visibility as appropriate.721Visibility globalVisibility =722computation.isValueVisibility()723? Context.getLangOpts().getValueVisibilityMode()724: Context.getLangOpts().getTypeVisibilityMode();725LV.mergeVisibility(globalVisibility, /*explicit*/ false);726727// If we're paying attention to global visibility, apply728// -finline-visibility-hidden if this is an inline method.729if (useInlineVisibilityHidden(D))730LV.mergeVisibility(HiddenVisibility, /*visibilityExplicit=*/false);731}732}733734// C++ [basic.link]p4:735736// A name having namespace scope that has not been given internal linkage737// above and that is the name of738// [...bullets...]739// has its linkage determined as follows:740// - if the enclosing namespace has internal linkage, the name has741// internal linkage; [handled above]742// - otherwise, if the declaration of the name is attached to a named743// module and is not exported, the name has module linkage;744// - otherwise, the name has external linkage.745// LV is currently set up to handle the last two bullets.746//747// The bullets are:748749// - a variable; or750if (const auto *Var = dyn_cast<VarDecl>(D)) {751// GCC applies the following optimization to variables and static752// data members, but not to functions:753//754// Modify the variable's LV by the LV of its type unless this is755// C or extern "C". This follows from [basic.link]p9:756// A type without linkage shall not be used as the type of a757// variable or function with external linkage unless758// - the entity has C language linkage, or759// - the entity is declared within an unnamed namespace, or760// - the entity is not used or is defined in the same761// translation unit.762// and [basic.link]p10:763// ...the types specified by all declarations referring to a764// given variable or function shall be identical...765// C does not have an equivalent rule.766//767// Ignore this if we've got an explicit attribute; the user768// probably knows what they're doing.769//770// Note that we don't want to make the variable non-external771// because of this, but unique-external linkage suits us.772773if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Var) &&774!IgnoreVarTypeLinkage) {775LinkageInfo TypeLV = getLVForType(*Var->getType(), computation);776if (!isExternallyVisible(TypeLV.getLinkage()))777return LinkageInfo::uniqueExternal();778if (!LV.isVisibilityExplicit())779LV.mergeVisibility(TypeLV);780}781782if (Var->getStorageClass() == SC_PrivateExtern)783LV.mergeVisibility(HiddenVisibility, true);784785// Note that Sema::MergeVarDecl already takes care of implementing786// C99 6.2.2p4 and propagating the visibility attribute, so we don't have787// to do it here.788789// As per function and class template specializations (below),790// consider LV for the template and template arguments. We're at file791// scope, so we do not need to worry about nested specializations.792if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(Var)) {793mergeTemplateLV(LV, spec, computation);794}795796// - a function; or797} else if (const auto *Function = dyn_cast<FunctionDecl>(D)) {798// In theory, we can modify the function's LV by the LV of its799// type unless it has C linkage (see comment above about variables800// for justification). In practice, GCC doesn't do this, so it's801// just too painful to make work.802803if (Function->getStorageClass() == SC_PrivateExtern)804LV.mergeVisibility(HiddenVisibility, true);805806// OpenMP target declare device functions are not callable from the host so807// they should not be exported from the device image. This applies to all808// functions as the host-callable kernel functions are emitted at codegen.809if (Context.getLangOpts().OpenMP &&810Context.getLangOpts().OpenMPIsTargetDevice &&811((Context.getTargetInfo().getTriple().isAMDGPU() ||812Context.getTargetInfo().getTriple().isNVPTX()) ||813OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Function)))814LV.mergeVisibility(HiddenVisibility, /*newExplicit=*/false);815816// 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.819820// 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.824if (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.827QualType TypeAsWritten = Function->getType();828if (TypeSourceInfo *TSI = Function->getTypeSourceInfo())829TypeAsWritten = TSI->getType();830if (!isExternallyVisible(TypeAsWritten->getLinkage()))831return LinkageInfo::uniqueExternal();832}833834// 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.837if (FunctionTemplateSpecializationInfo *specInfo838= Function->getTemplateSpecializationInfo()) {839mergeTemplateLV(LV, Function, specInfo, computation);840}841842// - 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.850if (!Tag->hasNameForLinkage())851return LinkageInfo::none();852853// 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.856if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {857mergeTemplateLV(LV, spec, computation);858}859860// 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)) {863LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()),864computation);865if (!isExternalFormalLinkage(EnumLV.getLinkage()))866return LinkageInfo::none();867LV.merge(EnumLV);868869// - a template870} else if (const auto *temp = dyn_cast<TemplateDecl>(D)) {871bool considerVisibility = !hasExplicitVisibilityAlready(computation);872LinkageInfo tempLV =873getLVForTemplateParameterList(temp->getTemplateParameters(), computation);874LV.mergeMaybeWithVisibility(tempLV, considerVisibility);875876// 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)) {882return LV;883884// By extension, we assign external linkage to Objective-C885// interfaces.886} else if (isa<ObjCInterfaceDecl>(D)) {887// fallout888889} else if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {890// A typedef declaration has linkage if it gives a type a name for891// linkage purposes.892if (!TD->getAnonDeclWithTypedefName(/*AnyRedecl*/true))893return LinkageInfo::none();894895} else if (isa<MSGuidDecl>(D)) {896// A GUID behaves like an inline variable with external linkage. Fall897// through.898899// Everything not covered here has no linkage.900} else {901return LinkageInfo::none();902}903904// If we ended up with non-externally-visible linkage, visibility should905// always be default.906if (!isExternallyVisible(LV.getLinkage()))907return LinkageInfo(LV.getLinkage(), DefaultVisibility, false);908909return LV;910}911912LinkageInfo913LinkageComputer::getLVForClassMember(const NamedDecl *D,914LVComputationKind computation,915bool 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.926if (!(isa<CXXMethodDecl>(D) ||927isa<VarDecl>(D) ||928isa<FieldDecl>(D) ||929isa<IndirectFieldDecl>(D) ||930isa<TagDecl>(D) ||931isa<TemplateDecl>(D)))932return LinkageInfo::none();933934LinkageInfo LV;935936// If we have an explicit visibility attribute, merge that in.937if (!hasExplicitVisibilityAlready(computation)) {938if (std::optional<Visibility> Vis = getExplicitVisibility(D, computation))939LV.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.945if (!LV.isVisibilityExplicit() && useInlineVisibilityHidden(D))946LV.mergeVisibility(HiddenVisibility, /*visibilityExplicit=*/false);947}948949// 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.952LVComputationKind classComputation = computation;953if (LV.isVisibilityExplicit())954classComputation = withExplicitVisibilityAlready(computation);955956LinkageInfo classLV =957getLVForDecl(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?961if (!isExternallyVisible(classLV.getLinkage()))962return classLV;963964965// Otherwise, don't merge in classLV yet, because in certain cases966// we need to completely ignore the visibility from it.967968// Specifically, if this decl exists and has an explicit attribute.969const NamedDecl *explicitSpecSuppressor = nullptr;970971if (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.974QualType TypeAsWritten = MD->getType();975if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())976TypeAsWritten = TSI->getType();977if (!isExternallyVisible(TypeAsWritten->getLinkage()))978return LinkageInfo::uniqueExternal();979980// If this is a method template specialization, use the linkage for981// the template parameters and arguments.982if (FunctionTemplateSpecializationInfo *spec983= MD->getTemplateSpecializationInfo()) {984mergeTemplateLV(LV, MD, spec, computation);985if (spec->isExplicitSpecialization()) {986explicitSpecSuppressor = MD;987} else if (isExplicitMemberSpecialization(spec->getTemplate())) {988explicitSpecSuppressor = spec->getTemplate()->getTemplatedDecl();989}990} else if (isExplicitMemberSpecialization(MD)) {991explicitSpecSuppressor = MD;992}993994// 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.997ASTContext &Context = D->getASTContext();998if (Context.getLangOpts().OpenMP &&999Context.getLangOpts().OpenMPIsTargetDevice &&1000((Context.getTargetInfo().getTriple().isAMDGPU() ||1001Context.getTargetInfo().getTriple().isNVPTX()) ||1002OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(MD)))1003LV.mergeVisibility(HiddenVisibility, /*newExplicit=*/false);10041005} else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {1006if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {1007mergeTemplateLV(LV, spec, computation);1008if (spec->isExplicitSpecialization()) {1009explicitSpecSuppressor = spec;1010} else {1011const ClassTemplateDecl *temp = spec->getSpecializedTemplate();1012if (isExplicitMemberSpecialization(temp)) {1013explicitSpecSuppressor = temp->getTemplatedDecl();1014}1015}1016} else if (isExplicitMemberSpecialization(RD)) {1017explicitSpecSuppressor = RD;1018}10191020// Static data members.1021} else if (const auto *VD = dyn_cast<VarDecl>(D)) {1022if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(VD))1023mergeTemplateLV(LV, spec, computation);10241025// Modify the variable's linkage by its type, but ignore the1026// type's visibility unless it's a definition.1027if (!IgnoreVarTypeLinkage) {1028LinkageInfo typeLV = getLVForType(*VD->getType(), computation);1029// FIXME: If the type's linkage is not externally visible, we can1030// give this static data member UniqueExternalLinkage.1031if (!LV.isVisibilityExplicit() && !classLV.isVisibilityExplicit())1032LV.mergeVisibility(typeLV);1033LV.mergeExternalVisibility(typeLV);1034}10351036if (isExplicitMemberSpecialization(VD)) {1037explicitSpecSuppressor = VD;1038}10391040// Template members.1041} else if (const auto *temp = dyn_cast<TemplateDecl>(D)) {1042bool considerVisibility =1043(!LV.isVisibilityExplicit() &&1044!classLV.isVisibilityExplicit() &&1045!hasExplicitVisibilityAlready(computation));1046LinkageInfo tempLV =1047getLVForTemplateParameterList(temp->getTemplateParameters(), computation);1048LV.mergeMaybeWithVisibility(tempLV, considerVisibility);10491050if (const auto *redeclTemp = dyn_cast<RedeclarableTemplateDecl>(temp)) {1051if (isExplicitMemberSpecialization(redeclTemp)) {1052explicitSpecSuppressor = temp->getTemplatedDecl();1053}1054}1055}10561057// We should never be looking for an attribute directly on a template.1058assert(!explicitSpecSuppressor || !isa<TemplateDecl>(explicitSpecSuppressor));10591060// If this member is an explicit member specialization, and it has1061// an explicit attribute, ignore visibility from the parent.1062bool considerClassVisibility = true;1063if (explicitSpecSuppressor &&1064// optimization: hasDVA() is true only with explicit visibility.1065LV.isVisibilityExplicit() &&1066classLV.getVisibility() != DefaultVisibility &&1067hasDirectVisibilityAttribute(explicitSpecSuppressor, computation)) {1068considerClassVisibility = false;1069}10701071// Finally, merge in information from the class.1072LV.mergeMaybeWithVisibility(classLV, considerClassVisibility);1073return LV;1074}10751076void NamedDecl::anchor() {}10771078bool NamedDecl::isLinkageValid() const {1079if (!hasCachedLinkage())1080return true;10811082Linkage L = LinkageComputer{}1083.computeLVForDecl(this, LVComputationKind::forLinkageOnly())1084.getLinkage();1085return L == getCachedLinkage();1086}10871088bool NamedDecl::isPlaceholderVar(const LangOptions &LangOpts) const {1089// [C++2c] [basic.scope.scope]/p51090// A declaration is name-independent if its name is _ and it declares1091// - a variable with automatic storage duration,1092// - a structured binding not inhabiting a namespace scope,1093// - the variable introduced by an init-capture1094// - or a non-static data member.10951096if (!LangOpts.CPlusPlus || !getIdentifier() ||1097!getIdentifier()->isPlaceholder())1098return false;1099if (isa<FieldDecl>(this))1100return true;1101if (const auto *IFD = dyn_cast<IndirectFieldDecl>(this)) {1102if (!getDeclContext()->isFunctionOrMethod() &&1103!getDeclContext()->isRecord())1104return false;1105const VarDecl *VD = IFD->getVarDecl();1106return !VD || VD->getStorageDuration() == SD_Automatic;1107}1108// and it declares a variable with automatic storage duration1109if (const auto *VD = dyn_cast<VarDecl>(this)) {1110if (isa<ParmVarDecl>(VD))1111return false;1112if (VD->isInitCapture())1113return true;1114return VD->getStorageDuration() == StorageDuration::SD_Automatic;1115}1116if (const auto *BD = dyn_cast<BindingDecl>(this);1117BD && getDeclContext()->isFunctionOrMethod()) {1118const VarDecl *VD = BD->getHoldingVar();1119return !VD || VD->getStorageDuration() == StorageDuration::SD_Automatic;1120}1121return false;1122}11231124ReservedIdentifierStatus1125NamedDecl::isReserved(const LangOptions &LangOpts) const {1126const IdentifierInfo *II = getIdentifier();11271128// This triggers at least for CXXLiteralIdentifiers, which we already checked1129// at lexing time.1130if (!II)1131return ReservedIdentifierStatus::NotReserved;11321133ReservedIdentifierStatus Status = II->isReserved(LangOpts);1134if (isReservedAtGlobalScope(Status) && !isReservedInAllContexts(Status)) {1135// This name is only reserved at global scope. Check if this declaration1136// conflicts with a global scope declaration.1137if (isa<ParmVarDecl>(this) || isTemplateParameter())1138return ReservedIdentifierStatus::NotReserved;11391140// C++ [dcl.link]/7:1141// Two declarations [conflict] if [...] one declares a function or1142// variable with C language linkage, and the other declares [...] a1143// variable that belongs to the global scope.1144//1145// Therefore names that are reserved at global scope are also reserved as1146// names of variables and functions with C language linkage.1147const DeclContext *DC = getDeclContext()->getRedeclContext();1148if (DC->isTranslationUnit())1149return Status;1150if (auto *VD = dyn_cast<VarDecl>(this))1151if (VD->isExternC())1152return ReservedIdentifierStatus::StartsWithUnderscoreAndIsExternC;1153if (auto *FD = dyn_cast<FunctionDecl>(this))1154if (FD->isExternC())1155return ReservedIdentifierStatus::StartsWithUnderscoreAndIsExternC;1156return ReservedIdentifierStatus::NotReserved;1157}11581159return Status;1160}11611162ObjCStringFormatFamily NamedDecl::getObjCFStringFormattingFamily() const {1163StringRef name = getName();1164if (name.empty()) return SFF_None;11651166if (name.front() == 'C')1167if (name == "CFStringCreateWithFormat" ||1168name == "CFStringCreateWithFormatAndArguments" ||1169name == "CFStringAppendFormat" ||1170name == "CFStringAppendFormatAndArguments")1171return SFF_CFString;1172return SFF_None;1173}11741175Linkage NamedDecl::getLinkageInternal() const {1176// We don't care about visibility here, so ask for the cheapest1177// possible visibility analysis.1178return LinkageComputer{}1179.getLVForDecl(this, LVComputationKind::forLinkageOnly())1180.getLinkage();1181}11821183static bool isExportedFromModuleInterfaceUnit(const NamedDecl *D) {1184// FIXME: Handle isModulePrivate.1185switch (D->getModuleOwnershipKind()) {1186case Decl::ModuleOwnershipKind::Unowned:1187case Decl::ModuleOwnershipKind::ReachableWhenImported:1188case Decl::ModuleOwnershipKind::ModulePrivate:1189return false;1190case Decl::ModuleOwnershipKind::Visible:1191case Decl::ModuleOwnershipKind::VisibleWhenImported:1192return D->isInNamedModule();1193}1194llvm_unreachable("unexpected module ownership kind");1195}11961197/// Get the linkage from a semantic point of view. Entities in1198/// anonymous namespaces are external (in c++98).1199Linkage NamedDecl::getFormalLinkage() const {1200Linkage InternalLinkage = getLinkageInternal();12011202// C++ [basic.link]p4.8:1203// - if the declaration of the name is attached to a named module and is not1204// exported1205// the name has module linkage;1206//1207// [basic.namespace.general]/p21208// A namespace is never attached to a named module and never has a name with1209// module linkage.1210if (isInNamedModule() && InternalLinkage == Linkage::External &&1211!isExportedFromModuleInterfaceUnit(1212cast<NamedDecl>(this->getCanonicalDecl())) &&1213!isa<NamespaceDecl>(this))1214InternalLinkage = Linkage::Module;12151216return clang::getFormalLinkage(InternalLinkage);1217}12181219LinkageInfo NamedDecl::getLinkageAndVisibility() const {1220return LinkageComputer{}.getDeclLinkageAndVisibility(this);1221}12221223static std::optional<Visibility>1224getExplicitVisibilityAux(const NamedDecl *ND,1225NamedDecl::ExplicitVisibilityKind kind,1226bool IsMostRecent) {1227assert(!IsMostRecent || ND == ND->getMostRecentDecl());12281229// Check the declaration itself first.1230if (std::optional<Visibility> V = getVisibilityOf(ND, kind))1231return V;12321233// If this is a member class of a specialization of a class template1234// and the corresponding decl has explicit visibility, use that.1235if (const auto *RD = dyn_cast<CXXRecordDecl>(ND)) {1236CXXRecordDecl *InstantiatedFrom = RD->getInstantiatedFromMemberClass();1237if (InstantiatedFrom)1238return getVisibilityOf(InstantiatedFrom, kind);1239}12401241// If there wasn't explicit visibility there, and this is a1242// specialization of a class template, check for visibility1243// on the pattern.1244if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(ND)) {1245// Walk all the template decl till this point to see if there are1246// explicit visibility attributes.1247const auto *TD = spec->getSpecializedTemplate()->getTemplatedDecl();1248while (TD != nullptr) {1249auto Vis = getVisibilityOf(TD, kind);1250if (Vis != std::nullopt)1251return Vis;1252TD = TD->getPreviousDecl();1253}1254return std::nullopt;1255}12561257// Use the most recent declaration.1258if (!IsMostRecent && !isa<NamespaceDecl>(ND)) {1259const NamedDecl *MostRecent = ND->getMostRecentDecl();1260if (MostRecent != ND)1261return getExplicitVisibilityAux(MostRecent, kind, true);1262}12631264if (const auto *Var = dyn_cast<VarDecl>(ND)) {1265if (Var->isStaticDataMember()) {1266VarDecl *InstantiatedFrom = Var->getInstantiatedFromStaticDataMember();1267if (InstantiatedFrom)1268return getVisibilityOf(InstantiatedFrom, kind);1269}12701271if (const auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Var))1272return getVisibilityOf(VTSD->getSpecializedTemplate()->getTemplatedDecl(),1273kind);12741275return std::nullopt;1276}1277// Also handle function template specializations.1278if (const auto *fn = dyn_cast<FunctionDecl>(ND)) {1279// If the function is a specialization of a template with an1280// explicit visibility attribute, use that.1281if (FunctionTemplateSpecializationInfo *templateInfo1282= fn->getTemplateSpecializationInfo())1283return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl(),1284kind);12851286// If the function is a member of a specialization of a class template1287// and the corresponding decl has explicit visibility, use that.1288FunctionDecl *InstantiatedFrom = fn->getInstantiatedFromMemberFunction();1289if (InstantiatedFrom)1290return getVisibilityOf(InstantiatedFrom, kind);12911292return std::nullopt;1293}12941295// The visibility of a template is stored in the templated decl.1296if (const auto *TD = dyn_cast<TemplateDecl>(ND))1297return getVisibilityOf(TD->getTemplatedDecl(), kind);12981299return std::nullopt;1300}13011302std::optional<Visibility>1303NamedDecl::getExplicitVisibility(ExplicitVisibilityKind kind) const {1304return getExplicitVisibilityAux(this, kind, false);1305}13061307LinkageInfo LinkageComputer::getLVForClosure(const DeclContext *DC,1308Decl *ContextDecl,1309LVComputationKind computation) {1310// This lambda has its linkage/visibility determined by its owner.1311const NamedDecl *Owner;1312if (!ContextDecl)1313Owner = dyn_cast<NamedDecl>(DC);1314else if (isa<ParmVarDecl>(ContextDecl))1315Owner =1316dyn_cast<NamedDecl>(ContextDecl->getDeclContext()->getRedeclContext());1317else if (isa<ImplicitConceptSpecializationDecl>(ContextDecl)) {1318// Replace with the concept's owning decl, which is either a namespace or a1319// TU, so this needs a dyn_cast.1320Owner = dyn_cast<NamedDecl>(ContextDecl->getDeclContext());1321} else {1322Owner = cast<NamedDecl>(ContextDecl);1323}13241325if (!Owner)1326return LinkageInfo::none();13271328// If the owner has a deduced type, we need to skip querying the linkage and1329// visibility of that type, because it might involve this closure type. The1330// only effect of this is that we might give a lambda VisibleNoLinkage rather1331// than NoLinkage when we don't strictly need to, which is benign.1332auto *VD = dyn_cast<VarDecl>(Owner);1333LinkageInfo OwnerLV =1334VD && VD->getType()->getContainedDeducedType()1335? computeLVForDecl(Owner, computation, /*IgnoreVarTypeLinkage*/true)1336: getLVForDecl(Owner, computation);13371338// A lambda never formally has linkage. But if the owner is externally1339// visible, then the lambda is too. We apply the same rules to blocks.1340if (!isExternallyVisible(OwnerLV.getLinkage()))1341return LinkageInfo::none();1342return LinkageInfo(Linkage::VisibleNone, OwnerLV.getVisibility(),1343OwnerLV.isVisibilityExplicit());1344}13451346LinkageInfo LinkageComputer::getLVForLocalDecl(const NamedDecl *D,1347LVComputationKind computation) {1348if (const auto *Function = dyn_cast<FunctionDecl>(D)) {1349if (Function->isInAnonymousNamespace() &&1350!isFirstInExternCContext(Function))1351return LinkageInfo::internal();13521353// This is a "void f();" which got merged with a file static.1354if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)1355return LinkageInfo::internal();13561357LinkageInfo LV;1358if (!hasExplicitVisibilityAlready(computation)) {1359if (std::optional<Visibility> Vis =1360getExplicitVisibility(Function, computation))1361LV.mergeVisibility(*Vis, true);1362}13631364// Note that Sema::MergeCompatibleFunctionDecls already takes care of1365// merging storage classes and visibility attributes, so we don't have to1366// look at previous decls in here.13671368return LV;1369}13701371if (const auto *Var = dyn_cast<VarDecl>(D)) {1372if (Var->hasExternalStorage()) {1373if (Var->isInAnonymousNamespace() && !isFirstInExternCContext(Var))1374return LinkageInfo::internal();13751376LinkageInfo LV;1377if (Var->getStorageClass() == SC_PrivateExtern)1378LV.mergeVisibility(HiddenVisibility, true);1379else if (!hasExplicitVisibilityAlready(computation)) {1380if (std::optional<Visibility> Vis =1381getExplicitVisibility(Var, computation))1382LV.mergeVisibility(*Vis, true);1383}13841385if (const VarDecl *Prev = Var->getPreviousDecl()) {1386LinkageInfo PrevLV = getLVForDecl(Prev, computation);1387if (PrevLV.getLinkage() != Linkage::Invalid)1388LV.setLinkage(PrevLV.getLinkage());1389LV.mergeVisibility(PrevLV);1390}13911392return LV;1393}13941395if (!Var->isStaticLocal())1396return LinkageInfo::none();1397}13981399ASTContext &Context = D->getASTContext();1400if (!Context.getLangOpts().CPlusPlus)1401return LinkageInfo::none();14021403const Decl *OuterD = getOutermostFuncOrBlockContext(D);1404if (!OuterD || OuterD->isInvalidDecl())1405return LinkageInfo::none();14061407LinkageInfo LV;1408if (const auto *BD = dyn_cast<BlockDecl>(OuterD)) {1409if (!BD->getBlockManglingNumber())1410return LinkageInfo::none();14111412LV = getLVForClosure(BD->getDeclContext()->getRedeclContext(),1413BD->getBlockManglingContextDecl(), computation);1414} else {1415const auto *FD = cast<FunctionDecl>(OuterD);1416if (!FD->isInlined() &&1417!isTemplateInstantiation(FD->getTemplateSpecializationKind()))1418return LinkageInfo::none();14191420// If a function is hidden by -fvisibility-inlines-hidden option and1421// is not explicitly attributed as a hidden function,1422// we should not make static local variables in the function hidden.1423LV = getLVForDecl(FD, computation);1424if (isa<VarDecl>(D) && useInlineVisibilityHidden(FD) &&1425!LV.isVisibilityExplicit() &&1426!Context.getLangOpts().VisibilityInlinesHiddenStaticLocalVar) {1427assert(cast<VarDecl>(D)->isStaticLocal());1428// If this was an implicitly hidden inline method, check again for1429// explicit visibility on the parent class, and use that for static locals1430// if present.1431if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))1432LV = getLVForDecl(MD->getParent(), computation);1433if (!LV.isVisibilityExplicit()) {1434Visibility globalVisibility =1435computation.isValueVisibility()1436? Context.getLangOpts().getValueVisibilityMode()1437: Context.getLangOpts().getTypeVisibilityMode();1438return LinkageInfo(Linkage::VisibleNone, globalVisibility,1439/*visibilityExplicit=*/false);1440}1441}1442}1443if (!isExternallyVisible(LV.getLinkage()))1444return LinkageInfo::none();1445return LinkageInfo(Linkage::VisibleNone, LV.getVisibility(),1446LV.isVisibilityExplicit());1447}14481449LinkageInfo LinkageComputer::computeLVForDecl(const NamedDecl *D,1450LVComputationKind computation,1451bool IgnoreVarTypeLinkage) {1452// Internal_linkage attribute overrides other considerations.1453if (D->hasAttr<InternalLinkageAttr>())1454return LinkageInfo::internal();14551456// Objective-C: treat all Objective-C declarations as having external1457// linkage.1458switch (D->getKind()) {1459default:1460break;14611462// Per C++ [basic.link]p2, only the names of objects, references,1463// functions, types, templates, namespaces, and values ever have linkage.1464//1465// Note that the name of a typedef, namespace alias, using declaration,1466// and so on are not the name of the corresponding type, namespace, or1467// declaration, so they do *not* have linkage.1468case Decl::ImplicitParam:1469case Decl::Label:1470case Decl::NamespaceAlias:1471case Decl::ParmVar:1472case Decl::Using:1473case Decl::UsingEnum:1474case Decl::UsingShadow:1475case Decl::UsingDirective:1476return LinkageInfo::none();14771478case Decl::EnumConstant:1479// C++ [basic.link]p4: an enumerator has the linkage of its enumeration.1480if (D->getASTContext().getLangOpts().CPlusPlus)1481return getLVForDecl(cast<EnumDecl>(D->getDeclContext()), computation);1482return LinkageInfo::visible_none();14831484case Decl::Typedef:1485case Decl::TypeAlias:1486// A typedef declaration has linkage if it gives a type a name for1487// linkage purposes.1488if (!cast<TypedefNameDecl>(D)1489->getAnonDeclWithTypedefName(/*AnyRedecl*/true))1490return LinkageInfo::none();1491break;14921493case Decl::TemplateTemplateParm: // count these as external1494case Decl::NonTypeTemplateParm:1495case Decl::ObjCAtDefsField:1496case Decl::ObjCCategory:1497case Decl::ObjCCategoryImpl:1498case Decl::ObjCCompatibleAlias:1499case Decl::ObjCImplementation:1500case Decl::ObjCMethod:1501case Decl::ObjCProperty:1502case Decl::ObjCPropertyImpl:1503case Decl::ObjCProtocol:1504return getExternalLinkageFor(D);15051506case Decl::CXXRecord: {1507const auto *Record = cast<CXXRecordDecl>(D);1508if (Record->isLambda()) {1509if (Record->hasKnownLambdaInternalLinkage() ||1510!Record->getLambdaManglingNumber()) {1511// This lambda has no mangling number, so it's internal.1512return LinkageInfo::internal();1513}15141515return getLVForClosure(1516Record->getDeclContext()->getRedeclContext(),1517Record->getLambdaContextDecl(), computation);1518}15191520break;1521}15221523case Decl::TemplateParamObject: {1524// The template parameter object can be referenced from anywhere its type1525// and value can be referenced.1526auto *TPO = cast<TemplateParamObjectDecl>(D);1527LinkageInfo LV = getLVForType(*TPO->getType(), computation);1528LV.merge(getLVForValue(TPO->getValue(), computation));1529return LV;1530}1531}15321533// Handle linkage for namespace-scope names.1534if (D->getDeclContext()->getRedeclContext()->isFileContext())1535return getLVForNamespaceScopeDecl(D, computation, IgnoreVarTypeLinkage);15361537// C++ [basic.link]p5:1538// In addition, a member function, static data member, a named1539// class or enumeration of class scope, or an unnamed class or1540// enumeration defined in a class-scope typedef declaration such1541// that the class or enumeration has the typedef name for linkage1542// purposes (7.1.3), has external linkage if the name of the class1543// has external linkage.1544if (D->getDeclContext()->isRecord())1545return getLVForClassMember(D, computation, IgnoreVarTypeLinkage);15461547// C++ [basic.link]p6:1548// The name of a function declared in block scope and the name of1549// an object declared by a block scope extern declaration have1550// linkage. If there is a visible declaration of an entity with1551// linkage having the same name and type, ignoring entities1552// declared outside the innermost enclosing namespace scope, the1553// block scope declaration declares that same entity and receives1554// the linkage of the previous declaration. If there is more than1555// one such matching entity, the program is ill-formed. Otherwise,1556// if no matching entity is found, the block scope entity receives1557// external linkage.1558if (D->getDeclContext()->isFunctionOrMethod())1559return getLVForLocalDecl(D, computation);15601561// C++ [basic.link]p6:1562// Names not covered by these rules have no linkage.1563return LinkageInfo::none();1564}15651566/// getLVForDecl - Get the linkage and visibility for the given declaration.1567LinkageInfo LinkageComputer::getLVForDecl(const NamedDecl *D,1568LVComputationKind computation) {1569// Internal_linkage attribute overrides other considerations.1570if (D->hasAttr<InternalLinkageAttr>())1571return LinkageInfo::internal();15721573if (computation.IgnoreAllVisibility && D->hasCachedLinkage())1574return LinkageInfo(D->getCachedLinkage(), DefaultVisibility, false);15751576if (std::optional<LinkageInfo> LI = lookup(D, computation))1577return *LI;15781579LinkageInfo LV = computeLVForDecl(D, computation);1580if (D->hasCachedLinkage())1581assert(D->getCachedLinkage() == LV.getLinkage());15821583D->setCachedLinkage(LV.getLinkage());1584cache(D, computation, LV);15851586#ifndef NDEBUG1587// In C (because of gnu inline) and in c++ with microsoft extensions an1588// static can follow an extern, so we can have two decls with different1589// linkages.1590const LangOptions &Opts = D->getASTContext().getLangOpts();1591if (!Opts.CPlusPlus || Opts.MicrosoftExt)1592return LV;15931594// We have just computed the linkage for this decl. By induction we know1595// that all other computed linkages match, check that the one we just1596// computed also does.1597NamedDecl *Old = nullptr;1598for (auto *I : D->redecls()) {1599auto *T = cast<NamedDecl>(I);1600if (T == D)1601continue;1602if (!T->isInvalidDecl() && T->hasCachedLinkage()) {1603Old = T;1604break;1605}1606}1607assert(!Old || Old->getCachedLinkage() == D->getCachedLinkage());1608#endif16091610return LV;1611}16121613LinkageInfo LinkageComputer::getDeclLinkageAndVisibility(const NamedDecl *D) {1614NamedDecl::ExplicitVisibilityKind EK = usesTypeVisibility(D)1615? NamedDecl::VisibilityForType1616: NamedDecl::VisibilityForValue;1617LVComputationKind CK(EK);1618return getLVForDecl(D, D->getASTContext().getLangOpts().IgnoreXCOFFVisibility1619? CK.forLinkageOnly()1620: CK);1621}16221623Module *Decl::getOwningModuleForLinkage() const {1624if (isa<NamespaceDecl>(this))1625// Namespaces never have module linkage. It is the entities within them1626// that [may] do.1627return nullptr;16281629Module *M = getOwningModule();1630if (!M)1631return nullptr;16321633switch (M->Kind) {1634case Module::ModuleMapModule:1635// Module map modules have no special linkage semantics.1636return nullptr;16371638case Module::ModuleInterfaceUnit:1639case Module::ModuleImplementationUnit:1640case Module::ModulePartitionInterface:1641case Module::ModulePartitionImplementation:1642return M;16431644case Module::ModuleHeaderUnit:1645case Module::ExplicitGlobalModuleFragment:1646case Module::ImplicitGlobalModuleFragment:1647// The global module shouldn't change the linkage.1648return nullptr;16491650case Module::PrivateModuleFragment:1651// The private module fragment is part of its containing module for linkage1652// purposes.1653return M->Parent;1654}16551656llvm_unreachable("unknown module kind");1657}16581659void NamedDecl::printName(raw_ostream &OS, const PrintingPolicy &Policy) const {1660Name.print(OS, Policy);1661}16621663void NamedDecl::printName(raw_ostream &OS) const {1664printName(OS, getASTContext().getPrintingPolicy());1665}16661667std::string NamedDecl::getQualifiedNameAsString() const {1668std::string QualName;1669llvm::raw_string_ostream OS(QualName);1670printQualifiedName(OS, getASTContext().getPrintingPolicy());1671return QualName;1672}16731674void NamedDecl::printQualifiedName(raw_ostream &OS) const {1675printQualifiedName(OS, getASTContext().getPrintingPolicy());1676}16771678void NamedDecl::printQualifiedName(raw_ostream &OS,1679const PrintingPolicy &P) const {1680if (getDeclContext()->isFunctionOrMethod()) {1681// We do not print '(anonymous)' for function parameters without name.1682printName(OS, P);1683return;1684}1685printNestedNameSpecifier(OS, P);1686if (getDeclName())1687OS << *this;1688else {1689// Give the printName override a chance to pick a different name before we1690// fall back to "(anonymous)".1691SmallString<64> NameBuffer;1692llvm::raw_svector_ostream NameOS(NameBuffer);1693printName(NameOS, P);1694if (NameBuffer.empty())1695OS << "(anonymous)";1696else1697OS << NameBuffer;1698}1699}17001701void NamedDecl::printNestedNameSpecifier(raw_ostream &OS) const {1702printNestedNameSpecifier(OS, getASTContext().getPrintingPolicy());1703}17041705void NamedDecl::printNestedNameSpecifier(raw_ostream &OS,1706const PrintingPolicy &P) const {1707const DeclContext *Ctx = getDeclContext();17081709// For ObjC methods and properties, look through categories and use the1710// interface as context.1711if (auto *MD = dyn_cast<ObjCMethodDecl>(this)) {1712if (auto *ID = MD->getClassInterface())1713Ctx = ID;1714} else if (auto *PD = dyn_cast<ObjCPropertyDecl>(this)) {1715if (auto *MD = PD->getGetterMethodDecl())1716if (auto *ID = MD->getClassInterface())1717Ctx = ID;1718} else if (auto *ID = dyn_cast<ObjCIvarDecl>(this)) {1719if (auto *CI = ID->getContainingInterface())1720Ctx = CI;1721}17221723if (Ctx->isFunctionOrMethod())1724return;17251726using ContextsTy = SmallVector<const DeclContext *, 8>;1727ContextsTy Contexts;17281729// Collect named contexts.1730DeclarationName NameInScope = getDeclName();1731for (; Ctx; Ctx = Ctx->getParent()) {1732// Suppress anonymous namespace if requested.1733if (P.SuppressUnwrittenScope && isa<NamespaceDecl>(Ctx) &&1734cast<NamespaceDecl>(Ctx)->isAnonymousNamespace())1735continue;17361737// Suppress inline namespace if it doesn't make the result ambiguous.1738if (P.SuppressInlineNamespace && Ctx->isInlineNamespace() && NameInScope &&1739cast<NamespaceDecl>(Ctx)->isRedundantInlineQualifierFor(NameInScope))1740continue;17411742// Skip non-named contexts such as linkage specifications and ExportDecls.1743const NamedDecl *ND = dyn_cast<NamedDecl>(Ctx);1744if (!ND)1745continue;17461747Contexts.push_back(Ctx);1748NameInScope = ND->getDeclName();1749}17501751for (const DeclContext *DC : llvm::reverse(Contexts)) {1752if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {1753OS << Spec->getName();1754const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();1755printTemplateArgumentList(1756OS, TemplateArgs.asArray(), P,1757Spec->getSpecializedTemplate()->getTemplateParameters());1758} else if (const auto *ND = dyn_cast<NamespaceDecl>(DC)) {1759if (ND->isAnonymousNamespace()) {1760OS << (P.MSVCFormatting ? "`anonymous namespace\'"1761: "(anonymous namespace)");1762}1763else1764OS << *ND;1765} else if (const auto *RD = dyn_cast<RecordDecl>(DC)) {1766if (!RD->getIdentifier())1767OS << "(anonymous " << RD->getKindName() << ')';1768else1769OS << *RD;1770} else if (const auto *FD = dyn_cast<FunctionDecl>(DC)) {1771const FunctionProtoType *FT = nullptr;1772if (FD->hasWrittenPrototype())1773FT = dyn_cast<FunctionProtoType>(FD->getType()->castAs<FunctionType>());17741775OS << *FD << '(';1776if (FT) {1777unsigned NumParams = FD->getNumParams();1778for (unsigned i = 0; i < NumParams; ++i) {1779if (i)1780OS << ", ";1781OS << FD->getParamDecl(i)->getType().stream(P);1782}17831784if (FT->isVariadic()) {1785if (NumParams > 0)1786OS << ", ";1787OS << "...";1788}1789}1790OS << ')';1791} else if (const auto *ED = dyn_cast<EnumDecl>(DC)) {1792// C++ [dcl.enum]p10: Each enum-name and each unscoped1793// enumerator is declared in the scope that immediately contains1794// the enum-specifier. Each scoped enumerator is declared in the1795// scope of the enumeration.1796// For the case of unscoped enumerator, do not include in the qualified1797// name any information about its enum enclosing scope, as its visibility1798// is global.1799if (ED->isScoped())1800OS << *ED;1801else1802continue;1803} else {1804OS << *cast<NamedDecl>(DC);1805}1806OS << "::";1807}1808}18091810void NamedDecl::getNameForDiagnostic(raw_ostream &OS,1811const PrintingPolicy &Policy,1812bool Qualified) const {1813if (Qualified)1814printQualifiedName(OS, Policy);1815else1816printName(OS, Policy);1817}18181819template<typename T> static bool isRedeclarableImpl(Redeclarable<T> *) {1820return true;1821}1822static bool isRedeclarableImpl(...) { return false; }1823static bool isRedeclarable(Decl::Kind K) {1824switch (K) {1825#define DECL(Type, Base) \1826case Decl::Type: \1827return isRedeclarableImpl((Type##Decl *)nullptr);1828#define ABSTRACT_DECL(DECL)1829#include "clang/AST/DeclNodes.inc"1830}1831llvm_unreachable("unknown decl kind");1832}18331834bool NamedDecl::declarationReplaces(const NamedDecl *OldD,1835bool IsKnownNewer) const {1836assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");18371838// Never replace one imported declaration with another; we need both results1839// when re-exporting.1840if (OldD->isFromASTFile() && isFromASTFile())1841return false;18421843// A kind mismatch implies that the declaration is not replaced.1844if (OldD->getKind() != getKind())1845return false;18461847// For method declarations, we never replace. (Why?)1848if (isa<ObjCMethodDecl>(this))1849return false;18501851// For parameters, pick the newer one. This is either an error or (in1852// Objective-C) permitted as an extension.1853if (isa<ParmVarDecl>(this))1854return true;18551856// Inline namespaces can give us two declarations with the same1857// name and kind in the same scope but different contexts; we should1858// keep both declarations in this case.1859if (!this->getDeclContext()->getRedeclContext()->Equals(1860OldD->getDeclContext()->getRedeclContext()))1861return false;18621863// Using declarations can be replaced if they import the same name from the1864// same context.1865if (const auto *UD = dyn_cast<UsingDecl>(this)) {1866ASTContext &Context = getASTContext();1867return Context.getCanonicalNestedNameSpecifier(UD->getQualifier()) ==1868Context.getCanonicalNestedNameSpecifier(1869cast<UsingDecl>(OldD)->getQualifier());1870}1871if (const auto *UUVD = dyn_cast<UnresolvedUsingValueDecl>(this)) {1872ASTContext &Context = getASTContext();1873return Context.getCanonicalNestedNameSpecifier(UUVD->getQualifier()) ==1874Context.getCanonicalNestedNameSpecifier(1875cast<UnresolvedUsingValueDecl>(OldD)->getQualifier());1876}18771878if (isRedeclarable(getKind())) {1879if (getCanonicalDecl() != OldD->getCanonicalDecl())1880return false;18811882if (IsKnownNewer)1883return true;18841885// Check whether this is actually newer than OldD. We want to keep the1886// newer declaration. This loop will usually only iterate once, because1887// OldD is usually the previous declaration.1888for (const auto *D : redecls()) {1889if (D == OldD)1890break;18911892// If we reach the canonical declaration, then OldD is not actually older1893// than this one.1894//1895// FIXME: In this case, we should not add this decl to the lookup table.1896if (D->isCanonicalDecl())1897return false;1898}18991900// It's a newer declaration of the same kind of declaration in the same1901// scope: we want this decl instead of the existing one.1902return true;1903}19041905// In all other cases, we need to keep both declarations in case they have1906// different visibility. Any attempt to use the name will result in an1907// ambiguity if more than one is visible.1908return false;1909}19101911bool NamedDecl::hasLinkage() const {1912switch (getFormalLinkage()) {1913case Linkage::Invalid:1914llvm_unreachable("Linkage hasn't been computed!");1915case Linkage::None:1916return false;1917case Linkage::Internal:1918return true;1919case Linkage::UniqueExternal:1920case Linkage::VisibleNone:1921llvm_unreachable("Non-formal linkage is not allowed here!");1922case Linkage::Module:1923case Linkage::External:1924return true;1925}1926llvm_unreachable("Unhandled Linkage enum");1927}19281929NamedDecl *NamedDecl::getUnderlyingDeclImpl() {1930NamedDecl *ND = this;1931if (auto *UD = dyn_cast<UsingShadowDecl>(ND))1932ND = UD->getTargetDecl();19331934if (auto *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND))1935return AD->getClassInterface();19361937if (auto *AD = dyn_cast<NamespaceAliasDecl>(ND))1938return AD->getNamespace();19391940return ND;1941}19421943bool NamedDecl::isCXXInstanceMember() const {1944if (!isCXXClassMember())1945return false;19461947const NamedDecl *D = this;1948if (isa<UsingShadowDecl>(D))1949D = cast<UsingShadowDecl>(D)->getTargetDecl();19501951if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<MSPropertyDecl>(D))1952return true;1953if (const auto *MD = dyn_cast_if_present<CXXMethodDecl>(D->getAsFunction()))1954return MD->isInstance();1955return false;1956}19571958//===----------------------------------------------------------------------===//1959// DeclaratorDecl Implementation1960//===----------------------------------------------------------------------===//19611962template <typename DeclT>1963static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {1964if (decl->getNumTemplateParameterLists() > 0)1965return decl->getTemplateParameterList(0)->getTemplateLoc();1966return decl->getInnerLocStart();1967}19681969SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {1970TypeSourceInfo *TSI = getTypeSourceInfo();1971if (TSI) return TSI->getTypeLoc().getBeginLoc();1972return SourceLocation();1973}19741975SourceLocation DeclaratorDecl::getTypeSpecEndLoc() const {1976TypeSourceInfo *TSI = getTypeSourceInfo();1977if (TSI) return TSI->getTypeLoc().getEndLoc();1978return SourceLocation();1979}19801981void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {1982if (QualifierLoc) {1983// Make sure the extended decl info is allocated.1984if (!hasExtInfo()) {1985// Save (non-extended) type source info pointer.1986auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();1987// Allocate external info struct.1988DeclInfo = new (getASTContext()) ExtInfo;1989// Restore savedTInfo into (extended) decl info.1990getExtInfo()->TInfo = savedTInfo;1991}1992// Set qualifier info.1993getExtInfo()->QualifierLoc = QualifierLoc;1994} else if (hasExtInfo()) {1995// Here Qualifier == 0, i.e., we are removing the qualifier (if any).1996getExtInfo()->QualifierLoc = QualifierLoc;1997}1998}19992000void DeclaratorDecl::setTrailingRequiresClause(Expr *TrailingRequiresClause) {2001assert(TrailingRequiresClause);2002// Make sure the extended decl info is allocated.2003if (!hasExtInfo()) {2004// Save (non-extended) type source info pointer.2005auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();2006// Allocate external info struct.2007DeclInfo = new (getASTContext()) ExtInfo;2008// Restore savedTInfo into (extended) decl info.2009getExtInfo()->TInfo = savedTInfo;2010}2011// Set requires clause info.2012getExtInfo()->TrailingRequiresClause = TrailingRequiresClause;2013}20142015void DeclaratorDecl::setTemplateParameterListsInfo(2016ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {2017assert(!TPLists.empty());2018// Make sure the extended decl info is allocated.2019if (!hasExtInfo()) {2020// Save (non-extended) type source info pointer.2021auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();2022// Allocate external info struct.2023DeclInfo = new (getASTContext()) ExtInfo;2024// Restore savedTInfo into (extended) decl info.2025getExtInfo()->TInfo = savedTInfo;2026}2027// Set the template parameter lists info.2028getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);2029}20302031SourceLocation DeclaratorDecl::getOuterLocStart() const {2032return getTemplateOrInnerLocStart(this);2033}20342035// Helper function: returns true if QT is or contains a type2036// having a postfix component.2037static bool typeIsPostfix(QualType QT) {2038while (true) {2039const Type* T = QT.getTypePtr();2040switch (T->getTypeClass()) {2041default:2042return false;2043case Type::Pointer:2044QT = cast<PointerType>(T)->getPointeeType();2045break;2046case Type::BlockPointer:2047QT = cast<BlockPointerType>(T)->getPointeeType();2048break;2049case Type::MemberPointer:2050QT = cast<MemberPointerType>(T)->getPointeeType();2051break;2052case Type::LValueReference:2053case Type::RValueReference:2054QT = cast<ReferenceType>(T)->getPointeeType();2055break;2056case Type::PackExpansion:2057QT = cast<PackExpansionType>(T)->getPattern();2058break;2059case Type::Paren:2060case Type::ConstantArray:2061case Type::DependentSizedArray:2062case Type::IncompleteArray:2063case Type::VariableArray:2064case Type::FunctionProto:2065case Type::FunctionNoProto:2066return true;2067}2068}2069}20702071SourceRange DeclaratorDecl::getSourceRange() const {2072SourceLocation RangeEnd = getLocation();2073if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {2074// If the declaration has no name or the type extends past the name take the2075// end location of the type.2076if (!getDeclName() || typeIsPostfix(TInfo->getType()))2077RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();2078}2079return SourceRange(getOuterLocStart(), RangeEnd);2080}20812082void QualifierInfo::setTemplateParameterListsInfo(2083ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {2084// Free previous template parameters (if any).2085if (NumTemplParamLists > 0) {2086Context.Deallocate(TemplParamLists);2087TemplParamLists = nullptr;2088NumTemplParamLists = 0;2089}2090// Set info on matched template parameter lists (if any).2091if (!TPLists.empty()) {2092TemplParamLists = new (Context) TemplateParameterList *[TPLists.size()];2093NumTemplParamLists = TPLists.size();2094std::copy(TPLists.begin(), TPLists.end(), TemplParamLists);2095}2096}20972098//===----------------------------------------------------------------------===//2099// VarDecl Implementation2100//===----------------------------------------------------------------------===//21012102const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {2103switch (SC) {2104case SC_None: break;2105case SC_Auto: return "auto";2106case SC_Extern: return "extern";2107case SC_PrivateExtern: return "__private_extern__";2108case SC_Register: return "register";2109case SC_Static: return "static";2110}21112112llvm_unreachable("Invalid storage class");2113}21142115VarDecl::VarDecl(Kind DK, ASTContext &C, DeclContext *DC,2116SourceLocation StartLoc, SourceLocation IdLoc,2117const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,2118StorageClass SC)2119: DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),2120redeclarable_base(C) {2121static_assert(sizeof(VarDeclBitfields) <= sizeof(unsigned),2122"VarDeclBitfields too large!");2123static_assert(sizeof(ParmVarDeclBitfields) <= sizeof(unsigned),2124"ParmVarDeclBitfields too large!");2125static_assert(sizeof(NonParmVarDeclBitfields) <= sizeof(unsigned),2126"NonParmVarDeclBitfields too large!");2127AllBits = 0;2128VarDeclBits.SClass = SC;2129// Everything else is implicitly initialized to false.2130}21312132VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation StartL,2133SourceLocation IdL, const IdentifierInfo *Id,2134QualType T, TypeSourceInfo *TInfo, StorageClass S) {2135return new (C, DC) VarDecl(Var, C, DC, StartL, IdL, Id, T, TInfo, S);2136}21372138VarDecl *VarDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) {2139return new (C, ID)2140VarDecl(Var, C, nullptr, SourceLocation(), SourceLocation(), nullptr,2141QualType(), nullptr, SC_None);2142}21432144void VarDecl::setStorageClass(StorageClass SC) {2145assert(isLegalForVariable(SC));2146VarDeclBits.SClass = SC;2147}21482149VarDecl::TLSKind VarDecl::getTLSKind() const {2150switch (VarDeclBits.TSCSpec) {2151case TSCS_unspecified:2152if (!hasAttr<ThreadAttr>() &&2153!(getASTContext().getLangOpts().OpenMPUseTLS &&2154getASTContext().getTargetInfo().isTLSSupported() &&2155hasAttr<OMPThreadPrivateDeclAttr>()))2156return TLS_None;2157return ((getASTContext().getLangOpts().isCompatibleWithMSVC(2158LangOptions::MSVC2015)) ||2159hasAttr<OMPThreadPrivateDeclAttr>())2160? TLS_Dynamic2161: TLS_Static;2162case TSCS___thread: // Fall through.2163case TSCS__Thread_local:2164return TLS_Static;2165case TSCS_thread_local:2166return TLS_Dynamic;2167}2168llvm_unreachable("Unknown thread storage class specifier!");2169}21702171SourceRange VarDecl::getSourceRange() const {2172if (const Expr *Init = getInit()) {2173SourceLocation InitEnd = Init->getEndLoc();2174// If Init is implicit, ignore its source range and fallback on2175// DeclaratorDecl::getSourceRange() to handle postfix elements.2176if (InitEnd.isValid() && InitEnd != getLocation())2177return SourceRange(getOuterLocStart(), InitEnd);2178}2179return DeclaratorDecl::getSourceRange();2180}21812182template<typename T>2183static LanguageLinkage getDeclLanguageLinkage(const T &D) {2184// C++ [dcl.link]p1: All function types, function names with external linkage,2185// and variable names with external linkage have a language linkage.2186if (!D.hasExternalFormalLinkage())2187return NoLanguageLinkage;21882189// Language linkage is a C++ concept, but saying that everything else in C has2190// C language linkage fits the implementation nicely.2191if (!D.getASTContext().getLangOpts().CPlusPlus)2192return CLanguageLinkage;21932194// C++ [dcl.link]p4: A C language linkage is ignored in determining the2195// language linkage of the names of class members and the function type of2196// class member functions.2197const DeclContext *DC = D.getDeclContext();2198if (DC->isRecord())2199return CXXLanguageLinkage;22002201// If the first decl is in an extern "C" context, any other redeclaration2202// will have C language linkage. If the first one is not in an extern "C"2203// context, we would have reported an error for any other decl being in one.2204if (isFirstInExternCContext(&D))2205return CLanguageLinkage;2206return CXXLanguageLinkage;2207}22082209template<typename T>2210static bool isDeclExternC(const T &D) {2211// Since the context is ignored for class members, they can only have C++2212// language linkage or no language linkage.2213const DeclContext *DC = D.getDeclContext();2214if (DC->isRecord()) {2215assert(D.getASTContext().getLangOpts().CPlusPlus);2216return false;2217}22182219return D.getLanguageLinkage() == CLanguageLinkage;2220}22212222LanguageLinkage VarDecl::getLanguageLinkage() const {2223return getDeclLanguageLinkage(*this);2224}22252226bool VarDecl::isExternC() const {2227return isDeclExternC(*this);2228}22292230bool VarDecl::isInExternCContext() const {2231return getLexicalDeclContext()->isExternCContext();2232}22332234bool VarDecl::isInExternCXXContext() const {2235return getLexicalDeclContext()->isExternCXXContext();2236}22372238VarDecl *VarDecl::getCanonicalDecl() { return getFirstDecl(); }22392240VarDecl::DefinitionKind2241VarDecl::isThisDeclarationADefinition(ASTContext &C) const {2242if (isThisDeclarationADemotedDefinition())2243return DeclarationOnly;22442245// C++ [basic.def]p2:2246// A declaration is a definition unless [...] it contains the 'extern'2247// specifier or a linkage-specification and neither an initializer [...],2248// it declares a non-inline static data member in a class declaration [...],2249// it declares a static data member outside a class definition and the variable2250// was defined within the class with the constexpr specifier [...],2251// C++1y [temp.expl.spec]p15:2252// An explicit specialization of a static data member or an explicit2253// specialization of a static data member template is a definition if the2254// declaration includes an initializer; otherwise, it is a declaration.2255//2256// FIXME: How do you declare (but not define) a partial specialization of2257// a static data member template outside the containing class?2258if (isStaticDataMember()) {2259if (isOutOfLine() &&2260!(getCanonicalDecl()->isInline() &&2261getCanonicalDecl()->isConstexpr()) &&2262(hasInit() ||2263// If the first declaration is out-of-line, this may be an2264// instantiation of an out-of-line partial specialization of a variable2265// template for which we have not yet instantiated the initializer.2266(getFirstDecl()->isOutOfLine()2267? getTemplateSpecializationKind() == TSK_Undeclared2268: getTemplateSpecializationKind() !=2269TSK_ExplicitSpecialization) ||2270isa<VarTemplatePartialSpecializationDecl>(this)))2271return Definition;2272if (!isOutOfLine() && isInline())2273return Definition;2274return DeclarationOnly;2275}2276// C99 6.7p5:2277// A definition of an identifier is a declaration for that identifier that2278// [...] causes storage to be reserved for that object.2279// Note: that applies for all non-file-scope objects.2280// C99 6.9.2p1:2281// If the declaration of an identifier for an object has file scope and an2282// initializer, the declaration is an external definition for the identifier2283if (hasInit())2284return Definition;22852286if (hasDefiningAttr())2287return Definition;22882289if (const auto *SAA = getAttr<SelectAnyAttr>())2290if (!SAA->isInherited())2291return Definition;22922293// A variable template specialization (other than a static data member2294// template or an explicit specialization) is a declaration until we2295// instantiate its initializer.2296if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(this)) {2297if (VTSD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization &&2298!isa<VarTemplatePartialSpecializationDecl>(VTSD) &&2299!VTSD->IsCompleteDefinition)2300return DeclarationOnly;2301}23022303if (hasExternalStorage())2304return DeclarationOnly;23052306// [dcl.link] p7:2307// A declaration directly contained in a linkage-specification is treated2308// as if it contains the extern specifier for the purpose of determining2309// the linkage of the declared name and whether it is a definition.2310if (isSingleLineLanguageLinkage(*this))2311return DeclarationOnly;23122313// C99 6.9.2p2:2314// A declaration of an object that has file scope without an initializer,2315// and without a storage class specifier or the scs 'static', constitutes2316// a tentative definition.2317// No such thing in C++.2318if (!C.getLangOpts().CPlusPlus && isFileVarDecl())2319return TentativeDefinition;23202321// What's left is (in C, block-scope) declarations without initializers or2322// external storage. These are definitions.2323return Definition;2324}23252326VarDecl *VarDecl::getActingDefinition() {2327DefinitionKind Kind = isThisDeclarationADefinition();2328if (Kind != TentativeDefinition)2329return nullptr;23302331VarDecl *LastTentative = nullptr;23322333// Loop through the declaration chain, starting with the most recent.2334for (VarDecl *Decl = getMostRecentDecl(); Decl;2335Decl = Decl->getPreviousDecl()) {2336Kind = Decl->isThisDeclarationADefinition();2337if (Kind == Definition)2338return nullptr;2339// Record the first (most recent) TentativeDefinition that is encountered.2340if (Kind == TentativeDefinition && !LastTentative)2341LastTentative = Decl;2342}23432344return LastTentative;2345}23462347VarDecl *VarDecl::getDefinition(ASTContext &C) {2348VarDecl *First = getFirstDecl();2349for (auto *I : First->redecls()) {2350if (I->isThisDeclarationADefinition(C) == Definition)2351return I;2352}2353return nullptr;2354}23552356VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const {2357DefinitionKind Kind = DeclarationOnly;23582359const VarDecl *First = getFirstDecl();2360for (auto *I : First->redecls()) {2361Kind = std::max(Kind, I->isThisDeclarationADefinition(C));2362if (Kind == Definition)2363break;2364}23652366return Kind;2367}23682369const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {2370for (auto *I : redecls()) {2371if (auto Expr = I->getInit()) {2372D = I;2373return Expr;2374}2375}2376return nullptr;2377}23782379bool VarDecl::hasInit() const {2380if (auto *P = dyn_cast<ParmVarDecl>(this))2381if (P->hasUnparsedDefaultArg() || P->hasUninstantiatedDefaultArg())2382return false;23832384if (auto *Eval = getEvaluatedStmt())2385return Eval->Value.isValid();23862387return !Init.isNull();2388}23892390Expr *VarDecl::getInit() {2391if (!hasInit())2392return nullptr;23932394if (auto *S = Init.dyn_cast<Stmt *>())2395return cast<Expr>(S);23962397auto *Eval = getEvaluatedStmt();23982399return cast<Expr>(Eval->Value.get(2400Eval->Value.isOffset() ? getASTContext().getExternalSource() : nullptr));2401}24022403Stmt **VarDecl::getInitAddress() {2404if (auto *ES = Init.dyn_cast<EvaluatedStmt *>())2405return ES->Value.getAddressOfPointer(getASTContext().getExternalSource());24062407return Init.getAddrOfPtr1();2408}24092410VarDecl *VarDecl::getInitializingDeclaration() {2411VarDecl *Def = nullptr;2412for (auto *I : redecls()) {2413if (I->hasInit())2414return I;24152416if (I->isThisDeclarationADefinition()) {2417if (isStaticDataMember())2418return I;2419Def = I;2420}2421}2422return Def;2423}24242425bool VarDecl::isOutOfLine() const {2426if (Decl::isOutOfLine())2427return true;24282429if (!isStaticDataMember())2430return false;24312432// If this static data member was instantiated from a static data member of2433// a class template, check whether that static data member was defined2434// out-of-line.2435if (VarDecl *VD = getInstantiatedFromStaticDataMember())2436return VD->isOutOfLine();24372438return false;2439}24402441void VarDecl::setInit(Expr *I) {2442if (auto *Eval = Init.dyn_cast<EvaluatedStmt *>()) {2443Eval->~EvaluatedStmt();2444getASTContext().Deallocate(Eval);2445}24462447Init = I;2448}24492450bool VarDecl::mightBeUsableInConstantExpressions(const ASTContext &C) const {2451const LangOptions &Lang = C.getLangOpts();24522453// OpenCL permits const integral variables to be used in constant2454// expressions, like in C++98.2455if (!Lang.CPlusPlus && !Lang.OpenCL && !Lang.C23)2456return false;24572458// Function parameters are never usable in constant expressions.2459if (isa<ParmVarDecl>(this))2460return false;24612462// The values of weak variables are never usable in constant expressions.2463if (isWeak())2464return false;24652466// In C++11, any variable of reference type can be used in a constant2467// expression if it is initialized by a constant expression.2468if (Lang.CPlusPlus11 && getType()->isReferenceType())2469return true;24702471// Only const objects can be used in constant expressions in C++. C++98 does2472// not require the variable to be non-volatile, but we consider this to be a2473// defect.2474if (!getType().isConstant(C) || getType().isVolatileQualified())2475return false;24762477// In C++, but not in C, const, non-volatile variables of integral or2478// enumeration types can be used in constant expressions.2479if (getType()->isIntegralOrEnumerationType() && !Lang.C23)2480return true;24812482// C23 6.6p7: An identifier that is:2483// ...2484// - declared with storage-class specifier constexpr and has an object type,2485// is a named constant, ... such a named constant is a constant expression2486// with the type and value of the declared object.2487// Additionally, in C++11, non-volatile constexpr variables can be used in2488// constant expressions.2489return (Lang.CPlusPlus11 || Lang.C23) && isConstexpr();2490}24912492bool VarDecl::isUsableInConstantExpressions(const ASTContext &Context) const {2493// C++2a [expr.const]p3:2494// A variable is usable in constant expressions after its initializing2495// declaration is encountered...2496const VarDecl *DefVD = nullptr;2497const Expr *Init = getAnyInitializer(DefVD);2498if (!Init || Init->isValueDependent() || getType()->isDependentType())2499return false;2500// ... if it is a constexpr variable, or it is of reference type or of2501// const-qualified integral or enumeration type, ...2502if (!DefVD->mightBeUsableInConstantExpressions(Context))2503return false;2504// ... and its initializer is a constant initializer.2505if ((Context.getLangOpts().CPlusPlus || getLangOpts().C23) &&2506!DefVD->hasConstantInitialization())2507return false;2508// C++98 [expr.const]p1:2509// An integral constant-expression can involve only [...] const variables2510// or static data members of integral or enumeration types initialized with2511// [integer] constant expressions (dcl.init)2512if ((Context.getLangOpts().CPlusPlus || Context.getLangOpts().OpenCL) &&2513!Context.getLangOpts().CPlusPlus11 && !DefVD->hasICEInitializer(Context))2514return false;2515return true;2516}25172518/// Convert the initializer for this declaration to the elaborated EvaluatedStmt2519/// form, which contains extra information on the evaluated value of the2520/// initializer.2521EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const {2522auto *Eval = Init.dyn_cast<EvaluatedStmt *>();2523if (!Eval) {2524// Note: EvaluatedStmt contains an APValue, which usually holds2525// resources not allocated from the ASTContext. We need to do some2526// work to avoid leaking those, but we do so in VarDecl::evaluateValue2527// where we can detect whether there's anything to clean up or not.2528Eval = new (getASTContext()) EvaluatedStmt;2529Eval->Value = Init.get<Stmt *>();2530Init = Eval;2531}2532return Eval;2533}25342535EvaluatedStmt *VarDecl::getEvaluatedStmt() const {2536return Init.dyn_cast<EvaluatedStmt *>();2537}25382539APValue *VarDecl::evaluateValue() const {2540SmallVector<PartialDiagnosticAt, 8> Notes;2541return evaluateValueImpl(Notes, hasConstantInitialization());2542}25432544APValue *VarDecl::evaluateValueImpl(SmallVectorImpl<PartialDiagnosticAt> &Notes,2545bool IsConstantInitialization) const {2546EvaluatedStmt *Eval = ensureEvaluatedStmt();25472548const auto *Init = getInit();2549assert(!Init->isValueDependent());25502551// We only produce notes indicating why an initializer is non-constant the2552// first time it is evaluated. FIXME: The notes won't always be emitted the2553// first time we try evaluation, so might not be produced at all.2554if (Eval->WasEvaluated)2555return Eval->Evaluated.isAbsent() ? nullptr : &Eval->Evaluated;25562557if (Eval->IsEvaluating) {2558// FIXME: Produce a diagnostic for self-initialization.2559return nullptr;2560}25612562Eval->IsEvaluating = true;25632564ASTContext &Ctx = getASTContext();2565bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, Ctx, this, Notes,2566IsConstantInitialization);25672568// In C++, or in C23 if we're initialising a 'constexpr' variable, this isn't2569// a constant initializer if we produced notes. In that case, we can't keep2570// the result, because it may only be correct under the assumption that the2571// initializer is a constant context.2572if (IsConstantInitialization &&2573(Ctx.getLangOpts().CPlusPlus ||2574(isConstexpr() && Ctx.getLangOpts().C23)) &&2575!Notes.empty())2576Result = false;25772578// Ensure the computed APValue is cleaned up later if evaluation succeeded,2579// or that it's empty (so that there's nothing to clean up) if evaluation2580// failed.2581if (!Result)2582Eval->Evaluated = APValue();2583else if (Eval->Evaluated.needsCleanup())2584Ctx.addDestruction(&Eval->Evaluated);25852586Eval->IsEvaluating = false;2587Eval->WasEvaluated = true;25882589return Result ? &Eval->Evaluated : nullptr;2590}25912592APValue *VarDecl::getEvaluatedValue() const {2593if (EvaluatedStmt *Eval = getEvaluatedStmt())2594if (Eval->WasEvaluated)2595return &Eval->Evaluated;25962597return nullptr;2598}25992600bool VarDecl::hasICEInitializer(const ASTContext &Context) const {2601const Expr *Init = getInit();2602assert(Init && "no initializer");26032604EvaluatedStmt *Eval = ensureEvaluatedStmt();2605if (!Eval->CheckedForICEInit) {2606Eval->CheckedForICEInit = true;2607Eval->HasICEInit = Init->isIntegerConstantExpr(Context);2608}2609return Eval->HasICEInit;2610}26112612bool VarDecl::hasConstantInitialization() const {2613// In C, all globals and constexpr variables should have constant2614// initialization. For constexpr variables in C check that initializer is a2615// constant initializer because they can be used in constant expressions.2616if (hasGlobalStorage() && !getASTContext().getLangOpts().CPlusPlus &&2617!isConstexpr())2618return true;26192620// In C++, it depends on whether the evaluation at the point of definition2621// was evaluatable as a constant initializer.2622if (EvaluatedStmt *Eval = getEvaluatedStmt())2623return Eval->HasConstantInitialization;26242625return false;2626}26272628bool VarDecl::checkForConstantInitialization(2629SmallVectorImpl<PartialDiagnosticAt> &Notes) const {2630EvaluatedStmt *Eval = ensureEvaluatedStmt();2631// If we ask for the value before we know whether we have a constant2632// initializer, we can compute the wrong value (for example, due to2633// std::is_constant_evaluated()).2634assert(!Eval->WasEvaluated &&2635"already evaluated var value before checking for constant init");2636assert((getASTContext().getLangOpts().CPlusPlus ||2637getASTContext().getLangOpts().C23) &&2638"only meaningful in C++/C23");26392640assert(!getInit()->isValueDependent());26412642// Evaluate the initializer to check whether it's a constant expression.2643Eval->HasConstantInitialization =2644evaluateValueImpl(Notes, true) && Notes.empty();26452646// If evaluation as a constant initializer failed, allow re-evaluation as a2647// non-constant initializer if we later find we want the value.2648if (!Eval->HasConstantInitialization)2649Eval->WasEvaluated = false;26502651return Eval->HasConstantInitialization;2652}26532654bool VarDecl::isParameterPack() const {2655return isa<PackExpansionType>(getType());2656}26572658template<typename DeclT>2659static DeclT *getDefinitionOrSelf(DeclT *D) {2660assert(D);2661if (auto *Def = D->getDefinition())2662return Def;2663return D;2664}26652666bool VarDecl::isEscapingByref() const {2667return hasAttr<BlocksAttr>() && NonParmVarDeclBits.EscapingByref;2668}26692670bool VarDecl::isNonEscapingByref() const {2671return hasAttr<BlocksAttr>() && !NonParmVarDeclBits.EscapingByref;2672}26732674bool VarDecl::hasDependentAlignment() const {2675QualType T = getType();2676return T->isDependentType() || T->isUndeducedType() ||2677llvm::any_of(specific_attrs<AlignedAttr>(), [](const AlignedAttr *AA) {2678return AA->isAlignmentDependent();2679});2680}26812682VarDecl *VarDecl::getTemplateInstantiationPattern() const {2683const VarDecl *VD = this;26842685// If this is an instantiated member, walk back to the template from which2686// it was instantiated.2687if (MemberSpecializationInfo *MSInfo = VD->getMemberSpecializationInfo()) {2688if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) {2689VD = VD->getInstantiatedFromStaticDataMember();2690while (auto *NewVD = VD->getInstantiatedFromStaticDataMember())2691VD = NewVD;2692}2693}26942695// If it's an instantiated variable template specialization, find the2696// template or partial specialization from which it was instantiated.2697if (auto *VDTemplSpec = dyn_cast<VarTemplateSpecializationDecl>(VD)) {2698if (isTemplateInstantiation(VDTemplSpec->getTemplateSpecializationKind())) {2699auto From = VDTemplSpec->getInstantiatedFrom();2700if (auto *VTD = From.dyn_cast<VarTemplateDecl *>()) {2701while (!VTD->isMemberSpecialization()) {2702auto *NewVTD = VTD->getInstantiatedFromMemberTemplate();2703if (!NewVTD)2704break;2705VTD = NewVTD;2706}2707return getDefinitionOrSelf(VTD->getTemplatedDecl());2708}2709if (auto *VTPSD =2710From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {2711while (!VTPSD->isMemberSpecialization()) {2712auto *NewVTPSD = VTPSD->getInstantiatedFromMember();2713if (!NewVTPSD)2714break;2715VTPSD = NewVTPSD;2716}2717return getDefinitionOrSelf<VarDecl>(VTPSD);2718}2719}2720}27212722// If this is the pattern of a variable template, find where it was2723// instantiated from. FIXME: Is this necessary?2724if (VarTemplateDecl *VarTemplate = VD->getDescribedVarTemplate()) {2725while (!VarTemplate->isMemberSpecialization()) {2726auto *NewVT = VarTemplate->getInstantiatedFromMemberTemplate();2727if (!NewVT)2728break;2729VarTemplate = NewVT;2730}27312732return getDefinitionOrSelf(VarTemplate->getTemplatedDecl());2733}27342735if (VD == this)2736return nullptr;2737return getDefinitionOrSelf(const_cast<VarDecl*>(VD));2738}27392740VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {2741if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())2742return cast<VarDecl>(MSI->getInstantiatedFrom());27432744return nullptr;2745}27462747TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {2748if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))2749return Spec->getSpecializationKind();27502751if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())2752return MSI->getTemplateSpecializationKind();27532754return TSK_Undeclared;2755}27562757TemplateSpecializationKind2758VarDecl::getTemplateSpecializationKindForInstantiation() const {2759if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())2760return MSI->getTemplateSpecializationKind();27612762if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))2763return Spec->getSpecializationKind();27642765return TSK_Undeclared;2766}27672768SourceLocation VarDecl::getPointOfInstantiation() const {2769if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))2770return Spec->getPointOfInstantiation();27712772if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())2773return MSI->getPointOfInstantiation();27742775return SourceLocation();2776}27772778VarTemplateDecl *VarDecl::getDescribedVarTemplate() const {2779return getASTContext().getTemplateOrSpecializationInfo(this)2780.dyn_cast<VarTemplateDecl *>();2781}27822783void VarDecl::setDescribedVarTemplate(VarTemplateDecl *Template) {2784getASTContext().setTemplateOrSpecializationInfo(this, Template);2785}27862787bool VarDecl::isKnownToBeDefined() const {2788const auto &LangOpts = getASTContext().getLangOpts();2789// In CUDA mode without relocatable device code, variables of form 'extern2790// __shared__ Foo foo[]' are pointers to the base of the GPU core's shared2791// memory pool. These are never undefined variables, even if they appear2792// inside of an anon namespace or static function.2793//2794// With CUDA relocatable device code enabled, these variables don't get2795// special handling; they're treated like regular extern variables.2796if (LangOpts.CUDA && !LangOpts.GPURelocatableDeviceCode &&2797hasExternalStorage() && hasAttr<CUDASharedAttr>() &&2798isa<IncompleteArrayType>(getType()))2799return true;28002801return hasDefinition();2802}28032804bool VarDecl::isNoDestroy(const ASTContext &Ctx) const {2805return hasGlobalStorage() && (hasAttr<NoDestroyAttr>() ||2806(!Ctx.getLangOpts().RegisterStaticDestructors &&2807!hasAttr<AlwaysDestroyAttr>()));2808}28092810QualType::DestructionKind2811VarDecl::needsDestruction(const ASTContext &Ctx) const {2812if (EvaluatedStmt *Eval = getEvaluatedStmt())2813if (Eval->HasConstantDestruction)2814return QualType::DK_none;28152816if (isNoDestroy(Ctx))2817return QualType::DK_none;28182819return getType().isDestructedType();2820}28212822bool VarDecl::hasFlexibleArrayInit(const ASTContext &Ctx) const {2823assert(hasInit() && "Expect initializer to check for flexible array init");2824auto *Ty = getType()->getAs<RecordType>();2825if (!Ty || !Ty->getDecl()->hasFlexibleArrayMember())2826return false;2827auto *List = dyn_cast<InitListExpr>(getInit()->IgnoreParens());2828if (!List)2829return false;2830const Expr *FlexibleInit = List->getInit(List->getNumInits() - 1);2831auto InitTy = Ctx.getAsConstantArrayType(FlexibleInit->getType());2832if (!InitTy)2833return false;2834return !InitTy->isZeroSize();2835}28362837CharUnits VarDecl::getFlexibleArrayInitChars(const ASTContext &Ctx) const {2838assert(hasInit() && "Expect initializer to check for flexible array init");2839auto *Ty = getType()->getAs<RecordType>();2840if (!Ty || !Ty->getDecl()->hasFlexibleArrayMember())2841return CharUnits::Zero();2842auto *List = dyn_cast<InitListExpr>(getInit()->IgnoreParens());2843if (!List || List->getNumInits() == 0)2844return CharUnits::Zero();2845const Expr *FlexibleInit = List->getInit(List->getNumInits() - 1);2846auto InitTy = Ctx.getAsConstantArrayType(FlexibleInit->getType());2847if (!InitTy)2848return CharUnits::Zero();2849CharUnits FlexibleArraySize = Ctx.getTypeSizeInChars(InitTy);2850const ASTRecordLayout &RL = Ctx.getASTRecordLayout(Ty->getDecl());2851CharUnits FlexibleArrayOffset =2852Ctx.toCharUnitsFromBits(RL.getFieldOffset(RL.getFieldCount() - 1));2853if (FlexibleArrayOffset + FlexibleArraySize < RL.getSize())2854return CharUnits::Zero();2855return FlexibleArrayOffset + FlexibleArraySize - RL.getSize();2856}28572858MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {2859if (isStaticDataMember())2860// FIXME: Remove ?2861// return getASTContext().getInstantiatedFromStaticDataMember(this);2862return getASTContext().getTemplateOrSpecializationInfo(this)2863.dyn_cast<MemberSpecializationInfo *>();2864return nullptr;2865}28662867void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,2868SourceLocation PointOfInstantiation) {2869assert((isa<VarTemplateSpecializationDecl>(this) ||2870getMemberSpecializationInfo()) &&2871"not a variable or static data member template specialization");28722873if (VarTemplateSpecializationDecl *Spec =2874dyn_cast<VarTemplateSpecializationDecl>(this)) {2875Spec->setSpecializationKind(TSK);2876if (TSK != TSK_ExplicitSpecialization &&2877PointOfInstantiation.isValid() &&2878Spec->getPointOfInstantiation().isInvalid()) {2879Spec->setPointOfInstantiation(PointOfInstantiation);2880if (ASTMutationListener *L = getASTContext().getASTMutationListener())2881L->InstantiationRequested(this);2882}2883} else if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) {2884MSI->setTemplateSpecializationKind(TSK);2885if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&2886MSI->getPointOfInstantiation().isInvalid()) {2887MSI->setPointOfInstantiation(PointOfInstantiation);2888if (ASTMutationListener *L = getASTContext().getASTMutationListener())2889L->InstantiationRequested(this);2890}2891}2892}28932894void2895VarDecl::setInstantiationOfStaticDataMember(VarDecl *VD,2896TemplateSpecializationKind TSK) {2897assert(getASTContext().getTemplateOrSpecializationInfo(this).isNull() &&2898"Previous template or instantiation?");2899getASTContext().setInstantiatedFromStaticDataMember(this, VD, TSK);2900}29012902//===----------------------------------------------------------------------===//2903// ParmVarDecl Implementation2904//===----------------------------------------------------------------------===//29052906ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,2907SourceLocation StartLoc, SourceLocation IdLoc,2908const IdentifierInfo *Id, QualType T,2909TypeSourceInfo *TInfo, StorageClass S,2910Expr *DefArg) {2911return new (C, DC) ParmVarDecl(ParmVar, C, DC, StartLoc, IdLoc, Id, T, TInfo,2912S, DefArg);2913}29142915QualType ParmVarDecl::getOriginalType() const {2916TypeSourceInfo *TSI = getTypeSourceInfo();2917QualType T = TSI ? TSI->getType() : getType();2918if (const auto *DT = dyn_cast<DecayedType>(T))2919return DT->getOriginalType();2920return T;2921}29222923ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) {2924return new (C, ID)2925ParmVarDecl(ParmVar, C, nullptr, SourceLocation(), SourceLocation(),2926nullptr, QualType(), nullptr, SC_None, nullptr);2927}29282929SourceRange ParmVarDecl::getSourceRange() const {2930if (!hasInheritedDefaultArg()) {2931SourceRange ArgRange = getDefaultArgRange();2932if (ArgRange.isValid())2933return SourceRange(getOuterLocStart(), ArgRange.getEnd());2934}29352936// DeclaratorDecl considers the range of postfix types as overlapping with the2937// declaration name, but this is not the case with parameters in ObjC methods.2938if (isa<ObjCMethodDecl>(getDeclContext()))2939return SourceRange(DeclaratorDecl::getBeginLoc(), getLocation());29402941return DeclaratorDecl::getSourceRange();2942}29432944bool ParmVarDecl::isDestroyedInCallee() const {2945// ns_consumed only affects code generation in ARC2946if (hasAttr<NSConsumedAttr>())2947return getASTContext().getLangOpts().ObjCAutoRefCount;29482949// FIXME: isParamDestroyedInCallee() should probably imply2950// isDestructedType()2951const auto *RT = getType()->getAs<RecordType>();2952if (RT && RT->getDecl()->isParamDestroyedInCallee() &&2953getType().isDestructedType())2954return true;29552956return false;2957}29582959Expr *ParmVarDecl::getDefaultArg() {2960assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");2961assert(!hasUninstantiatedDefaultArg() &&2962"Default argument is not yet instantiated!");29632964Expr *Arg = getInit();2965if (auto *E = dyn_cast_if_present<FullExpr>(Arg))2966return E->getSubExpr();29672968return Arg;2969}29702971void ParmVarDecl::setDefaultArg(Expr *defarg) {2972ParmVarDeclBits.DefaultArgKind = DAK_Normal;2973Init = defarg;2974}29752976SourceRange ParmVarDecl::getDefaultArgRange() const {2977switch (ParmVarDeclBits.DefaultArgKind) {2978case DAK_None:2979case DAK_Unparsed:2980// Nothing we can do here.2981return SourceRange();29822983case DAK_Uninstantiated:2984return getUninstantiatedDefaultArg()->getSourceRange();29852986case DAK_Normal:2987if (const Expr *E = getInit())2988return E->getSourceRange();29892990// Missing an actual expression, may be invalid.2991return SourceRange();2992}2993llvm_unreachable("Invalid default argument kind.");2994}29952996void ParmVarDecl::setUninstantiatedDefaultArg(Expr *arg) {2997ParmVarDeclBits.DefaultArgKind = DAK_Uninstantiated;2998Init = arg;2999}30003001Expr *ParmVarDecl::getUninstantiatedDefaultArg() {3002assert(hasUninstantiatedDefaultArg() &&3003"Wrong kind of initialization expression!");3004return cast_if_present<Expr>(Init.get<Stmt *>());3005}30063007bool ParmVarDecl::hasDefaultArg() const {3008// FIXME: We should just return false for DAK_None here once callers are3009// prepared for the case that we encountered an invalid default argument and3010// were unable to even build an invalid expression.3011return hasUnparsedDefaultArg() || hasUninstantiatedDefaultArg() ||3012!Init.isNull();3013}30143015void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {3016getASTContext().setParameterIndex(this, parameterIndex);3017ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;3018}30193020unsigned ParmVarDecl::getParameterIndexLarge() const {3021return getASTContext().getParameterIndex(this);3022}30233024//===----------------------------------------------------------------------===//3025// FunctionDecl Implementation3026//===----------------------------------------------------------------------===//30273028FunctionDecl::FunctionDecl(Kind DK, ASTContext &C, DeclContext *DC,3029SourceLocation StartLoc,3030const DeclarationNameInfo &NameInfo, QualType T,3031TypeSourceInfo *TInfo, StorageClass S,3032bool UsesFPIntrin, bool isInlineSpecified,3033ConstexprSpecKind ConstexprKind,3034Expr *TrailingRequiresClause)3035: DeclaratorDecl(DK, DC, NameInfo.getLoc(), NameInfo.getName(), T, TInfo,3036StartLoc),3037DeclContext(DK), redeclarable_base(C), Body(), ODRHash(0),3038EndRangeLoc(NameInfo.getEndLoc()), DNLoc(NameInfo.getInfo()) {3039assert(T.isNull() || T->isFunctionType());3040FunctionDeclBits.SClass = S;3041FunctionDeclBits.IsInline = isInlineSpecified;3042FunctionDeclBits.IsInlineSpecified = isInlineSpecified;3043FunctionDeclBits.IsVirtualAsWritten = false;3044FunctionDeclBits.IsPureVirtual = false;3045FunctionDeclBits.HasInheritedPrototype = false;3046FunctionDeclBits.HasWrittenPrototype = true;3047FunctionDeclBits.IsDeleted = false;3048FunctionDeclBits.IsTrivial = false;3049FunctionDeclBits.IsTrivialForCall = false;3050FunctionDeclBits.IsDefaulted = false;3051FunctionDeclBits.IsExplicitlyDefaulted = false;3052FunctionDeclBits.HasDefaultedOrDeletedInfo = false;3053FunctionDeclBits.IsIneligibleOrNotSelected = false;3054FunctionDeclBits.HasImplicitReturnZero = false;3055FunctionDeclBits.IsLateTemplateParsed = false;3056FunctionDeclBits.ConstexprKind = static_cast<uint64_t>(ConstexprKind);3057FunctionDeclBits.BodyContainsImmediateEscalatingExpression = false;3058FunctionDeclBits.InstantiationIsPending = false;3059FunctionDeclBits.UsesSEHTry = false;3060FunctionDeclBits.UsesFPIntrin = UsesFPIntrin;3061FunctionDeclBits.HasSkippedBody = false;3062FunctionDeclBits.WillHaveBody = false;3063FunctionDeclBits.IsMultiVersion = false;3064FunctionDeclBits.DeductionCandidateKind =3065static_cast<unsigned char>(DeductionCandidate::Normal);3066FunctionDeclBits.HasODRHash = false;3067FunctionDeclBits.FriendConstraintRefersToEnclosingTemplate = false;3068if (TrailingRequiresClause)3069setTrailingRequiresClause(TrailingRequiresClause);3070}30713072void FunctionDecl::getNameForDiagnostic(3073raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const {3074NamedDecl::getNameForDiagnostic(OS, Policy, Qualified);3075const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();3076if (TemplateArgs)3077printTemplateArgumentList(OS, TemplateArgs->asArray(), Policy);3078}30793080bool FunctionDecl::isVariadic() const {3081if (const auto *FT = getType()->getAs<FunctionProtoType>())3082return FT->isVariadic();3083return false;3084}30853086FunctionDecl::DefaultedOrDeletedFunctionInfo *3087FunctionDecl::DefaultedOrDeletedFunctionInfo::Create(3088ASTContext &Context, ArrayRef<DeclAccessPair> Lookups,3089StringLiteral *DeletedMessage) {3090static constexpr size_t Alignment =3091std::max({alignof(DefaultedOrDeletedFunctionInfo),3092alignof(DeclAccessPair), alignof(StringLiteral *)});3093size_t Size = totalSizeToAlloc<DeclAccessPair, StringLiteral *>(3094Lookups.size(), DeletedMessage != nullptr);30953096DefaultedOrDeletedFunctionInfo *Info =3097new (Context.Allocate(Size, Alignment)) DefaultedOrDeletedFunctionInfo;3098Info->NumLookups = Lookups.size();3099Info->HasDeletedMessage = DeletedMessage != nullptr;31003101std::uninitialized_copy(Lookups.begin(), Lookups.end(),3102Info->getTrailingObjects<DeclAccessPair>());3103if (DeletedMessage)3104*Info->getTrailingObjects<StringLiteral *>() = DeletedMessage;3105return Info;3106}31073108void FunctionDecl::setDefaultedOrDeletedInfo(3109DefaultedOrDeletedFunctionInfo *Info) {3110assert(!FunctionDeclBits.HasDefaultedOrDeletedInfo && "already have this");3111assert(!Body && "can't replace function body with defaulted function info");31123113FunctionDeclBits.HasDefaultedOrDeletedInfo = true;3114DefaultedOrDeletedInfo = Info;3115}31163117void FunctionDecl::setDeletedAsWritten(bool D, StringLiteral *Message) {3118FunctionDeclBits.IsDeleted = D;31193120if (Message) {3121assert(isDeletedAsWritten() && "Function must be deleted");3122if (FunctionDeclBits.HasDefaultedOrDeletedInfo)3123DefaultedOrDeletedInfo->setDeletedMessage(Message);3124else3125setDefaultedOrDeletedInfo(DefaultedOrDeletedFunctionInfo::Create(3126getASTContext(), /*Lookups=*/{}, Message));3127}3128}31293130void FunctionDecl::DefaultedOrDeletedFunctionInfo::setDeletedMessage(3131StringLiteral *Message) {3132// We should never get here with the DefaultedOrDeletedInfo populated, but3133// no space allocated for the deleted message, since that would require3134// recreating this, but setDefaultedOrDeletedInfo() disallows overwriting3135// an already existing DefaultedOrDeletedFunctionInfo.3136assert(HasDeletedMessage &&3137"No space to store a delete message in this DefaultedOrDeletedInfo");3138*getTrailingObjects<StringLiteral *>() = Message;3139}31403141FunctionDecl::DefaultedOrDeletedFunctionInfo *3142FunctionDecl::getDefalutedOrDeletedInfo() const {3143return FunctionDeclBits.HasDefaultedOrDeletedInfo ? DefaultedOrDeletedInfo3144: nullptr;3145}31463147bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {3148for (const auto *I : redecls()) {3149if (I->doesThisDeclarationHaveABody()) {3150Definition = I;3151return true;3152}3153}31543155return false;3156}31573158bool FunctionDecl::hasTrivialBody() const {3159const Stmt *S = getBody();3160if (!S) {3161// Since we don't have a body for this function, we don't know if it's3162// trivial or not.3163return false;3164}31653166if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())3167return true;3168return false;3169}31703171bool FunctionDecl::isThisDeclarationInstantiatedFromAFriendDefinition() const {3172if (!getFriendObjectKind())3173return false;31743175// Check for a friend function instantiated from a friend function3176// definition in a templated class.3177if (const FunctionDecl *InstantiatedFrom =3178getInstantiatedFromMemberFunction())3179return InstantiatedFrom->getFriendObjectKind() &&3180InstantiatedFrom->isThisDeclarationADefinition();31813182// Check for a friend function template instantiated from a friend3183// function template definition in a templated class.3184if (const FunctionTemplateDecl *Template = getDescribedFunctionTemplate()) {3185if (const FunctionTemplateDecl *InstantiatedFrom =3186Template->getInstantiatedFromMemberTemplate())3187return InstantiatedFrom->getFriendObjectKind() &&3188InstantiatedFrom->isThisDeclarationADefinition();3189}31903191return false;3192}31933194bool FunctionDecl::isDefined(const FunctionDecl *&Definition,3195bool CheckForPendingFriendDefinition) const {3196for (const FunctionDecl *FD : redecls()) {3197if (FD->isThisDeclarationADefinition()) {3198Definition = FD;3199return true;3200}32013202// If this is a friend function defined in a class template, it does not3203// have a body until it is used, nevertheless it is a definition, see3204// [temp.inst]p2:3205//3206// ... for the purpose of determining whether an instantiated redeclaration3207// is valid according to [basic.def.odr] and [class.mem], a declaration that3208// corresponds to a definition in the template is considered to be a3209// definition.3210//3211// The following code must produce redefinition error:3212//3213// template<typename T> struct C20 { friend void func_20() {} };3214// C20<int> c20i;3215// void func_20() {}3216//3217if (CheckForPendingFriendDefinition &&3218FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {3219Definition = FD;3220return true;3221}3222}32233224return false;3225}32263227Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {3228if (!hasBody(Definition))3229return nullptr;32303231assert(!Definition->FunctionDeclBits.HasDefaultedOrDeletedInfo &&3232"definition should not have a body");3233if (Definition->Body)3234return Definition->Body.get(getASTContext().getExternalSource());32353236return nullptr;3237}32383239void FunctionDecl::setBody(Stmt *B) {3240FunctionDeclBits.HasDefaultedOrDeletedInfo = false;3241Body = LazyDeclStmtPtr(B);3242if (B)3243EndRangeLoc = B->getEndLoc();3244}32453246void FunctionDecl::setIsPureVirtual(bool P) {3247FunctionDeclBits.IsPureVirtual = P;3248if (P)3249if (auto *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))3250Parent->markedVirtualFunctionPure();3251}32523253template<std::size_t Len>3254static bool isNamed(const NamedDecl *ND, const char (&Str)[Len]) {3255const IdentifierInfo *II = ND->getIdentifier();3256return II && II->isStr(Str);3257}32583259bool FunctionDecl::isImmediateEscalating() const {3260// C++23 [expr.const]/p173261// An immediate-escalating function is3262// - the call operator of a lambda that is not declared with the consteval3263// specifier,3264if (isLambdaCallOperator(this) && !isConsteval())3265return true;3266// - a defaulted special member function that is not declared with the3267// consteval specifier,3268if (isDefaulted() && !isConsteval())3269return true;3270// - a function that results from the instantiation of a templated entity3271// defined with the constexpr specifier.3272TemplatedKind TK = getTemplatedKind();3273if (TK != TK_NonTemplate && TK != TK_DependentNonTemplate &&3274isConstexprSpecified())3275return true;3276return false;3277}32783279bool FunctionDecl::isImmediateFunction() const {3280// C++23 [expr.const]/p183281// An immediate function is a function or constructor that is3282// - declared with the consteval specifier3283if (isConsteval())3284return true;3285// - an immediate-escalating function F whose function body contains an3286// immediate-escalating expression3287if (isImmediateEscalating() && BodyContainsImmediateEscalatingExpressions())3288return true;32893290if (const auto *MD = dyn_cast<CXXMethodDecl>(this);3291MD && MD->isLambdaStaticInvoker())3292return MD->getParent()->getLambdaCallOperator()->isImmediateFunction();32933294return false;3295}32963297bool FunctionDecl::isMain() const {3298const TranslationUnitDecl *tunit =3299dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());3300return tunit &&3301!tunit->getASTContext().getLangOpts().Freestanding &&3302isNamed(this, "main");3303}33043305bool FunctionDecl::isMSVCRTEntryPoint() const {3306const TranslationUnitDecl *TUnit =3307dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());3308if (!TUnit)3309return false;33103311// Even though we aren't really targeting MSVCRT if we are freestanding,3312// semantic analysis for these functions remains the same.33133314// MSVCRT entry points only exist on MSVCRT targets.3315if (!TUnit->getASTContext().getTargetInfo().getTriple().isOSMSVCRT())3316return false;33173318// Nameless functions like constructors cannot be entry points.3319if (!getIdentifier())3320return false;33213322return llvm::StringSwitch<bool>(getName())3323.Cases("main", // an ANSI console app3324"wmain", // a Unicode console App3325"WinMain", // an ANSI GUI app3326"wWinMain", // a Unicode GUI app3327"DllMain", // a DLL3328true)3329.Default(false);3330}33313332bool FunctionDecl::isReservedGlobalPlacementOperator() const {3333if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName)3334return false;3335if (getDeclName().getCXXOverloadedOperator() != OO_New &&3336getDeclName().getCXXOverloadedOperator() != OO_Delete &&3337getDeclName().getCXXOverloadedOperator() != OO_Array_New &&3338getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)3339return false;33403341if (!getDeclContext()->getRedeclContext()->isTranslationUnit())3342return false;33433344const auto *proto = getType()->castAs<FunctionProtoType>();3345if (proto->getNumParams() != 2 || proto->isVariadic())3346return false;33473348const ASTContext &Context =3349cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())3350->getASTContext();33513352// The result type and first argument type are constant across all3353// these operators. The second argument must be exactly void*.3354return (proto->getParamType(1).getCanonicalType() == Context.VoidPtrTy);3355}33563357bool FunctionDecl::isReplaceableGlobalAllocationFunction(3358std::optional<unsigned> *AlignmentParam, bool *IsNothrow) const {3359if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName)3360return false;3361if (getDeclName().getCXXOverloadedOperator() != OO_New &&3362getDeclName().getCXXOverloadedOperator() != OO_Delete &&3363getDeclName().getCXXOverloadedOperator() != OO_Array_New &&3364getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)3365return false;33663367if (isa<CXXRecordDecl>(getDeclContext()))3368return false;33693370// This can only fail for an invalid 'operator new' declaration.3371if (!getDeclContext()->getRedeclContext()->isTranslationUnit())3372return false;33733374const auto *FPT = getType()->castAs<FunctionProtoType>();3375if (FPT->getNumParams() == 0 || FPT->getNumParams() > 4 || FPT->isVariadic())3376return false;33773378// If this is a single-parameter function, it must be a replaceable global3379// allocation or deallocation function.3380if (FPT->getNumParams() == 1)3381return true;33823383unsigned Params = 1;3384QualType Ty = FPT->getParamType(Params);3385const ASTContext &Ctx = getASTContext();33863387auto Consume = [&] {3388++Params;3389Ty = Params < FPT->getNumParams() ? FPT->getParamType(Params) : QualType();3390};33913392// In C++14, the next parameter can be a 'std::size_t' for sized delete.3393bool IsSizedDelete = false;3394if (Ctx.getLangOpts().SizedDeallocation &&3395(getDeclName().getCXXOverloadedOperator() == OO_Delete ||3396getDeclName().getCXXOverloadedOperator() == OO_Array_Delete) &&3397Ctx.hasSameType(Ty, Ctx.getSizeType())) {3398IsSizedDelete = true;3399Consume();3400}34013402// In C++17, the next parameter can be a 'std::align_val_t' for aligned3403// new/delete.3404if (Ctx.getLangOpts().AlignedAllocation && !Ty.isNull() && Ty->isAlignValT()) {3405Consume();3406if (AlignmentParam)3407*AlignmentParam = Params;3408}34093410// If this is not a sized delete, the next parameter can be a3411// 'const std::nothrow_t&'.3412if (!IsSizedDelete && !Ty.isNull() && Ty->isReferenceType()) {3413Ty = Ty->getPointeeType();3414if (Ty.getCVRQualifiers() != Qualifiers::Const)3415return false;3416if (Ty->isNothrowT()) {3417if (IsNothrow)3418*IsNothrow = true;3419Consume();3420}3421}34223423// Finally, recognize the not yet standard versions of new that take a3424// hot/cold allocation hint (__hot_cold_t). These are currently supported by3425// tcmalloc (see3426// https://github.com/google/tcmalloc/blob/220043886d4e2efff7a5702d5172cb8065253664/tcmalloc/malloc_extension.h#L53).3427if (!IsSizedDelete && !Ty.isNull() && Ty->isEnumeralType()) {3428QualType T = Ty;3429while (const auto *TD = T->getAs<TypedefType>())3430T = TD->getDecl()->getUnderlyingType();3431const IdentifierInfo *II =3432T->castAs<EnumType>()->getDecl()->getIdentifier();3433if (II && II->isStr("__hot_cold_t"))3434Consume();3435}34363437return Params == FPT->getNumParams();3438}34393440bool FunctionDecl::isInlineBuiltinDeclaration() const {3441if (!getBuiltinID())3442return false;34433444const FunctionDecl *Definition;3445if (!hasBody(Definition))3446return false;34473448if (!Definition->isInlineSpecified() ||3449!Definition->hasAttr<AlwaysInlineAttr>())3450return false;34513452ASTContext &Context = getASTContext();3453switch (Context.GetGVALinkageForFunction(Definition)) {3454case GVA_Internal:3455case GVA_DiscardableODR:3456case GVA_StrongODR:3457return false;3458case GVA_AvailableExternally:3459case GVA_StrongExternal:3460return true;3461}3462llvm_unreachable("Unknown GVALinkage");3463}34643465bool FunctionDecl::isDestroyingOperatorDelete() const {3466// C++ P0722:3467// Within a class C, a single object deallocation function with signature3468// (T, std::destroying_delete_t, <more params>)3469// is a destroying operator delete.3470if (!isa<CXXMethodDecl>(this) || getOverloadedOperator() != OO_Delete ||3471getNumParams() < 2)3472return false;34733474auto *RD = getParamDecl(1)->getType()->getAsCXXRecordDecl();3475return RD && RD->isInStdNamespace() && RD->getIdentifier() &&3476RD->getIdentifier()->isStr("destroying_delete_t");3477}34783479LanguageLinkage FunctionDecl::getLanguageLinkage() const {3480return getDeclLanguageLinkage(*this);3481}34823483bool FunctionDecl::isExternC() const {3484return isDeclExternC(*this);3485}34863487bool FunctionDecl::isInExternCContext() const {3488if (hasAttr<OpenCLKernelAttr>())3489return true;3490return getLexicalDeclContext()->isExternCContext();3491}34923493bool FunctionDecl::isInExternCXXContext() const {3494return getLexicalDeclContext()->isExternCXXContext();3495}34963497bool FunctionDecl::isGlobal() const {3498if (const auto *Method = dyn_cast<CXXMethodDecl>(this))3499return Method->isStatic();35003501if (getCanonicalDecl()->getStorageClass() == SC_Static)3502return false;35033504for (const DeclContext *DC = getDeclContext();3505DC->isNamespace();3506DC = DC->getParent()) {3507if (const auto *Namespace = cast<NamespaceDecl>(DC)) {3508if (!Namespace->getDeclName())3509return false;3510}3511}35123513return true;3514}35153516bool FunctionDecl::isNoReturn() const {3517if (hasAttr<NoReturnAttr>() || hasAttr<CXX11NoReturnAttr>() ||3518hasAttr<C11NoReturnAttr>())3519return true;35203521if (auto *FnTy = getType()->getAs<FunctionType>())3522return FnTy->getNoReturnAttr();35233524return false;3525}35263527bool FunctionDecl::isMemberLikeConstrainedFriend() const {3528// C++20 [temp.friend]p9:3529// A non-template friend declaration with a requires-clause [or]3530// a friend function template with a constraint that depends on a template3531// parameter from an enclosing template [...] does not declare the same3532// function or function template as a declaration in any other scope.35333534// If this isn't a friend then it's not a member-like constrained friend.3535if (!getFriendObjectKind()) {3536return false;3537}35383539if (!getDescribedFunctionTemplate()) {3540// If these friends don't have constraints, they aren't constrained, and3541// thus don't fall under temp.friend p9. Else the simple presence of a3542// constraint makes them unique.3543return getTrailingRequiresClause();3544}35453546return FriendConstraintRefersToEnclosingTemplate();3547}35483549MultiVersionKind FunctionDecl::getMultiVersionKind() const {3550if (hasAttr<TargetAttr>())3551return MultiVersionKind::Target;3552if (hasAttr<TargetVersionAttr>())3553return MultiVersionKind::TargetVersion;3554if (hasAttr<CPUDispatchAttr>())3555return MultiVersionKind::CPUDispatch;3556if (hasAttr<CPUSpecificAttr>())3557return MultiVersionKind::CPUSpecific;3558if (hasAttr<TargetClonesAttr>())3559return MultiVersionKind::TargetClones;3560return MultiVersionKind::None;3561}35623563bool FunctionDecl::isCPUDispatchMultiVersion() const {3564return isMultiVersion() && hasAttr<CPUDispatchAttr>();3565}35663567bool FunctionDecl::isCPUSpecificMultiVersion() const {3568return isMultiVersion() && hasAttr<CPUSpecificAttr>();3569}35703571bool FunctionDecl::isTargetMultiVersion() const {3572return isMultiVersion() &&3573(hasAttr<TargetAttr>() || hasAttr<TargetVersionAttr>());3574}35753576bool FunctionDecl::isTargetMultiVersionDefault() const {3577if (!isMultiVersion())3578return false;3579if (hasAttr<TargetAttr>())3580return getAttr<TargetAttr>()->isDefaultVersion();3581return hasAttr<TargetVersionAttr>() &&3582getAttr<TargetVersionAttr>()->isDefaultVersion();3583}35843585bool FunctionDecl::isTargetClonesMultiVersion() const {3586return isMultiVersion() && hasAttr<TargetClonesAttr>();3587}35883589bool FunctionDecl::isTargetVersionMultiVersion() const {3590return isMultiVersion() && hasAttr<TargetVersionAttr>();3591}35923593void3594FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {3595redeclarable_base::setPreviousDecl(PrevDecl);35963597if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {3598FunctionTemplateDecl *PrevFunTmpl3599= PrevDecl? PrevDecl->getDescribedFunctionTemplate() : nullptr;3600assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");3601FunTmpl->setPreviousDecl(PrevFunTmpl);3602}36033604if (PrevDecl && PrevDecl->isInlined())3605setImplicitlyInline(true);3606}36073608FunctionDecl *FunctionDecl::getCanonicalDecl() { return getFirstDecl(); }36093610/// Returns a value indicating whether this function corresponds to a builtin3611/// function.3612///3613/// The function corresponds to a built-in function if it is declared at3614/// translation scope or within an extern "C" block and its name matches with3615/// the name of a builtin. The returned value will be 0 for functions that do3616/// not correspond to a builtin, a value of type \c Builtin::ID if in the3617/// target-independent range \c [1,Builtin::First), or a target-specific builtin3618/// value.3619///3620/// \param ConsiderWrapperFunctions If true, we should consider wrapper3621/// functions as their wrapped builtins. This shouldn't be done in general, but3622/// it's useful in Sema to diagnose calls to wrappers based on their semantics.3623unsigned FunctionDecl::getBuiltinID(bool ConsiderWrapperFunctions) const {3624unsigned BuiltinID = 0;36253626if (const auto *ABAA = getAttr<ArmBuiltinAliasAttr>()) {3627BuiltinID = ABAA->getBuiltinName()->getBuiltinID();3628} else if (const auto *BAA = getAttr<BuiltinAliasAttr>()) {3629BuiltinID = BAA->getBuiltinName()->getBuiltinID();3630} else if (const auto *A = getAttr<BuiltinAttr>()) {3631BuiltinID = A->getID();3632}36333634if (!BuiltinID)3635return 0;36363637// If the function is marked "overloadable", it has a different mangled name3638// and is not the C library function.3639if (!ConsiderWrapperFunctions && hasAttr<OverloadableAttr>() &&3640(!hasAttr<ArmBuiltinAliasAttr>() && !hasAttr<BuiltinAliasAttr>()))3641return 0;36423643const ASTContext &Context = getASTContext();3644if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))3645return BuiltinID;36463647// This function has the name of a known C library3648// function. Determine whether it actually refers to the C library3649// function or whether it just has the same name.36503651// If this is a static function, it's not a builtin.3652if (!ConsiderWrapperFunctions && getStorageClass() == SC_Static)3653return 0;36543655// OpenCL v1.2 s6.9.f - The library functions defined in3656// the C99 standard headers are not available.3657if (Context.getLangOpts().OpenCL &&3658Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))3659return 0;36603661// CUDA does not have device-side standard library. printf and malloc are the3662// only special cases that are supported by device-side runtime.3663if (Context.getLangOpts().CUDA && hasAttr<CUDADeviceAttr>() &&3664!hasAttr<CUDAHostAttr>() &&3665!(BuiltinID == Builtin::BIprintf || BuiltinID == Builtin::BImalloc))3666return 0;36673668// As AMDGCN implementation of OpenMP does not have a device-side standard3669// library, none of the predefined library functions except printf and malloc3670// should be treated as a builtin i.e. 0 should be returned for them.3671if (Context.getTargetInfo().getTriple().isAMDGCN() &&3672Context.getLangOpts().OpenMPIsTargetDevice &&3673Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&3674!(BuiltinID == Builtin::BIprintf || BuiltinID == Builtin::BImalloc))3675return 0;36763677return BuiltinID;3678}36793680/// getNumParams - Return the number of parameters this function must have3681/// based on its FunctionType. This is the length of the ParamInfo array3682/// after it has been created.3683unsigned FunctionDecl::getNumParams() const {3684const auto *FPT = getType()->getAs<FunctionProtoType>();3685return FPT ? FPT->getNumParams() : 0;3686}36873688void FunctionDecl::setParams(ASTContext &C,3689ArrayRef<ParmVarDecl *> NewParamInfo) {3690assert(!ParamInfo && "Already has param info!");3691assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");36923693// Zero params -> null pointer.3694if (!NewParamInfo.empty()) {3695ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];3696std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);3697}3698}36993700/// getMinRequiredArguments - Returns the minimum number of arguments3701/// needed to call this function. This may be fewer than the number of3702/// function parameters, if some of the parameters have default3703/// arguments (in C++) or are parameter packs (C++11).3704unsigned FunctionDecl::getMinRequiredArguments() const {3705if (!getASTContext().getLangOpts().CPlusPlus)3706return getNumParams();37073708// Note that it is possible for a parameter with no default argument to3709// follow a parameter with a default argument.3710unsigned NumRequiredArgs = 0;3711unsigned MinParamsSoFar = 0;3712for (auto *Param : parameters()) {3713if (!Param->isParameterPack()) {3714++MinParamsSoFar;3715if (!Param->hasDefaultArg())3716NumRequiredArgs = MinParamsSoFar;3717}3718}3719return NumRequiredArgs;3720}37213722bool FunctionDecl::hasCXXExplicitFunctionObjectParameter() const {3723return getNumParams() != 0 && getParamDecl(0)->isExplicitObjectParameter();3724}37253726unsigned FunctionDecl::getNumNonObjectParams() const {3727return getNumParams() -3728static_cast<unsigned>(hasCXXExplicitFunctionObjectParameter());3729}37303731unsigned FunctionDecl::getMinRequiredExplicitArguments() const {3732return getMinRequiredArguments() -3733static_cast<unsigned>(hasCXXExplicitFunctionObjectParameter());3734}37353736bool FunctionDecl::hasOneParamOrDefaultArgs() const {3737return getNumParams() == 1 ||3738(getNumParams() > 1 &&3739llvm::all_of(llvm::drop_begin(parameters()),3740[](ParmVarDecl *P) { return P->hasDefaultArg(); }));3741}37423743/// The combination of the extern and inline keywords under MSVC forces3744/// the function to be required.3745///3746/// Note: This function assumes that we will only get called when isInlined()3747/// would return true for this FunctionDecl.3748bool FunctionDecl::isMSExternInline() const {3749assert(isInlined() && "expected to get called on an inlined function!");37503751const ASTContext &Context = getASTContext();3752if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&3753!hasAttr<DLLExportAttr>())3754return false;37553756for (const FunctionDecl *FD = getMostRecentDecl(); FD;3757FD = FD->getPreviousDecl())3758if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)3759return true;37603761return false;3762}37633764static bool redeclForcesDefMSVC(const FunctionDecl *Redecl) {3765if (Redecl->getStorageClass() != SC_Extern)3766return false;37673768for (const FunctionDecl *FD = Redecl->getPreviousDecl(); FD;3769FD = FD->getPreviousDecl())3770if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)3771return false;37723773return true;3774}37753776static bool RedeclForcesDefC99(const FunctionDecl *Redecl) {3777// Only consider file-scope declarations in this test.3778if (!Redecl->getLexicalDeclContext()->isTranslationUnit())3779return false;37803781// Only consider explicit declarations; the presence of a builtin for a3782// libcall shouldn't affect whether a definition is externally visible.3783if (Redecl->isImplicit())3784return false;37853786if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)3787return true; // Not an inline definition37883789return false;3790}37913792/// For a function declaration in C or C++, determine whether this3793/// declaration causes the definition to be externally visible.3794///3795/// For instance, this determines if adding the current declaration to the set3796/// of redeclarations of the given functions causes3797/// isInlineDefinitionExternallyVisible to change from false to true.3798bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const {3799assert(!doesThisDeclarationHaveABody() &&3800"Must have a declaration without a body.");38013802const ASTContext &Context = getASTContext();38033804if (Context.getLangOpts().MSVCCompat) {3805const FunctionDecl *Definition;3806if (hasBody(Definition) && Definition->isInlined() &&3807redeclForcesDefMSVC(this))3808return true;3809}38103811if (Context.getLangOpts().CPlusPlus)3812return false;38133814if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {3815// With GNU inlining, a declaration with 'inline' but not 'extern', forces3816// an externally visible definition.3817//3818// FIXME: What happens if gnu_inline gets added on after the first3819// declaration?3820if (!isInlineSpecified() || getStorageClass() == SC_Extern)3821return false;38223823const FunctionDecl *Prev = this;3824bool FoundBody = false;3825while ((Prev = Prev->getPreviousDecl())) {3826FoundBody |= Prev->doesThisDeclarationHaveABody();38273828if (Prev->doesThisDeclarationHaveABody()) {3829// If it's not the case that both 'inline' and 'extern' are3830// specified on the definition, then it is always externally visible.3831if (!Prev->isInlineSpecified() ||3832Prev->getStorageClass() != SC_Extern)3833return false;3834} else if (Prev->isInlineSpecified() &&3835Prev->getStorageClass() != SC_Extern) {3836return false;3837}3838}3839return FoundBody;3840}38413842// C99 6.7.4p6:3843// [...] If all of the file scope declarations for a function in a3844// translation unit include the inline function specifier without extern,3845// then the definition in that translation unit is an inline definition.3846if (isInlineSpecified() && getStorageClass() != SC_Extern)3847return false;3848const FunctionDecl *Prev = this;3849bool FoundBody = false;3850while ((Prev = Prev->getPreviousDecl())) {3851FoundBody |= Prev->doesThisDeclarationHaveABody();3852if (RedeclForcesDefC99(Prev))3853return false;3854}3855return FoundBody;3856}38573858FunctionTypeLoc FunctionDecl::getFunctionTypeLoc() const {3859const TypeSourceInfo *TSI = getTypeSourceInfo();3860return TSI ? TSI->getTypeLoc().IgnoreParens().getAs<FunctionTypeLoc>()3861: FunctionTypeLoc();3862}38633864SourceRange FunctionDecl::getReturnTypeSourceRange() const {3865FunctionTypeLoc FTL = getFunctionTypeLoc();3866if (!FTL)3867return SourceRange();38683869// Skip self-referential return types.3870const SourceManager &SM = getASTContext().getSourceManager();3871SourceRange RTRange = FTL.getReturnLoc().getSourceRange();3872SourceLocation Boundary = getNameInfo().getBeginLoc();3873if (RTRange.isInvalid() || Boundary.isInvalid() ||3874!SM.isBeforeInTranslationUnit(RTRange.getEnd(), Boundary))3875return SourceRange();38763877return RTRange;3878}38793880SourceRange FunctionDecl::getParametersSourceRange() const {3881unsigned NP = getNumParams();3882SourceLocation EllipsisLoc = getEllipsisLoc();38833884if (NP == 0 && EllipsisLoc.isInvalid())3885return SourceRange();38863887SourceLocation Begin =3888NP > 0 ? ParamInfo[0]->getSourceRange().getBegin() : EllipsisLoc;3889SourceLocation End = EllipsisLoc.isValid()3890? EllipsisLoc3891: ParamInfo[NP - 1]->getSourceRange().getEnd();38923893return SourceRange(Begin, End);3894}38953896SourceRange FunctionDecl::getExceptionSpecSourceRange() const {3897FunctionTypeLoc FTL = getFunctionTypeLoc();3898return FTL ? FTL.getExceptionSpecRange() : SourceRange();3899}39003901/// For an inline function definition in C, or for a gnu_inline function3902/// in C++, determine whether the definition will be externally visible.3903///3904/// Inline function definitions are always available for inlining optimizations.3905/// However, depending on the language dialect, declaration specifiers, and3906/// attributes, the definition of an inline function may or may not be3907/// "externally" visible to other translation units in the program.3908///3909/// In C99, inline definitions are not externally visible by default. However,3910/// if even one of the global-scope declarations is marked "extern inline", the3911/// inline definition becomes externally visible (C99 6.7.4p6).3912///3913/// In GNU89 mode, or if the gnu_inline attribute is attached to the function3914/// definition, we use the GNU semantics for inline, which are nearly the3915/// opposite of C99 semantics. In particular, "inline" by itself will create3916/// an externally visible symbol, but "extern inline" will not create an3917/// externally visible symbol.3918bool FunctionDecl::isInlineDefinitionExternallyVisible() const {3919assert((doesThisDeclarationHaveABody() || willHaveBody() ||3920hasAttr<AliasAttr>()) &&3921"Must be a function definition");3922assert(isInlined() && "Function must be inline");3923ASTContext &Context = getASTContext();39243925if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {3926// Note: If you change the logic here, please change3927// doesDeclarationForceExternallyVisibleDefinition as well.3928//3929// If it's not the case that both 'inline' and 'extern' are3930// specified on the definition, then this inline definition is3931// externally visible.3932if (Context.getLangOpts().CPlusPlus)3933return false;3934if (!(isInlineSpecified() && getStorageClass() == SC_Extern))3935return true;39363937// If any declaration is 'inline' but not 'extern', then this definition3938// is externally visible.3939for (auto *Redecl : redecls()) {3940if (Redecl->isInlineSpecified() &&3941Redecl->getStorageClass() != SC_Extern)3942return true;3943}39443945return false;3946}39473948// The rest of this function is C-only.3949assert(!Context.getLangOpts().CPlusPlus &&3950"should not use C inline rules in C++");39513952// C99 6.7.4p6:3953// [...] If all of the file scope declarations for a function in a3954// translation unit include the inline function specifier without extern,3955// then the definition in that translation unit is an inline definition.3956for (auto *Redecl : redecls()) {3957if (RedeclForcesDefC99(Redecl))3958return true;3959}39603961// C99 6.7.4p6:3962// An inline definition does not provide an external definition for the3963// function, and does not forbid an external definition in another3964// translation unit.3965return false;3966}39673968/// getOverloadedOperator - Which C++ overloaded operator this3969/// function represents, if any.3970OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {3971if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)3972return getDeclName().getCXXOverloadedOperator();3973return OO_None;3974}39753976/// getLiteralIdentifier - The literal suffix identifier this function3977/// represents, if any.3978const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {3979if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)3980return getDeclName().getCXXLiteralIdentifier();3981return nullptr;3982}39833984FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {3985if (TemplateOrSpecialization.isNull())3986return TK_NonTemplate;3987if (const auto *ND = TemplateOrSpecialization.dyn_cast<NamedDecl *>()) {3988if (isa<FunctionDecl>(ND))3989return TK_DependentNonTemplate;3990assert(isa<FunctionTemplateDecl>(ND) &&3991"No other valid types in NamedDecl");3992return TK_FunctionTemplate;3993}3994if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())3995return TK_MemberSpecialization;3996if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())3997return TK_FunctionTemplateSpecialization;3998if (TemplateOrSpecialization.is3999<DependentFunctionTemplateSpecializationInfo*>())4000return TK_DependentFunctionTemplateSpecialization;40014002llvm_unreachable("Did we miss a TemplateOrSpecialization type?");4003}40044005FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {4006if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())4007return cast<FunctionDecl>(Info->getInstantiatedFrom());40084009return nullptr;4010}40114012MemberSpecializationInfo *FunctionDecl::getMemberSpecializationInfo() const {4013if (auto *MSI =4014TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>())4015return MSI;4016if (auto *FTSI = TemplateOrSpecialization4017.dyn_cast<FunctionTemplateSpecializationInfo *>())4018return FTSI->getMemberSpecializationInfo();4019return nullptr;4020}40214022void4023FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,4024FunctionDecl *FD,4025TemplateSpecializationKind TSK) {4026assert(TemplateOrSpecialization.isNull() &&4027"Member function is already a specialization");4028MemberSpecializationInfo *Info4029= new (C) MemberSpecializationInfo(FD, TSK);4030TemplateOrSpecialization = Info;4031}40324033FunctionTemplateDecl *FunctionDecl::getDescribedFunctionTemplate() const {4034return dyn_cast_if_present<FunctionTemplateDecl>(4035TemplateOrSpecialization.dyn_cast<NamedDecl *>());4036}40374038void FunctionDecl::setDescribedFunctionTemplate(4039FunctionTemplateDecl *Template) {4040assert(TemplateOrSpecialization.isNull() &&4041"Member function is already a specialization");4042TemplateOrSpecialization = Template;4043}40444045bool FunctionDecl::isFunctionTemplateSpecialization() const {4046return TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>() ||4047TemplateOrSpecialization4048.is<DependentFunctionTemplateSpecializationInfo *>();4049}40504051void FunctionDecl::setInstantiatedFromDecl(FunctionDecl *FD) {4052assert(TemplateOrSpecialization.isNull() &&4053"Function is already a specialization");4054TemplateOrSpecialization = FD;4055}40564057FunctionDecl *FunctionDecl::getInstantiatedFromDecl() const {4058return dyn_cast_if_present<FunctionDecl>(4059TemplateOrSpecialization.dyn_cast<NamedDecl *>());4060}40614062bool FunctionDecl::isImplicitlyInstantiable() const {4063// If the function is invalid, it can't be implicitly instantiated.4064if (isInvalidDecl())4065return false;40664067switch (getTemplateSpecializationKindForInstantiation()) {4068case TSK_Undeclared:4069case TSK_ExplicitInstantiationDefinition:4070case TSK_ExplicitSpecialization:4071return false;40724073case TSK_ImplicitInstantiation:4074return true;40754076case TSK_ExplicitInstantiationDeclaration:4077// Handled below.4078break;4079}40804081// Find the actual template from which we will instantiate.4082const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();4083bool HasPattern = false;4084if (PatternDecl)4085HasPattern = PatternDecl->hasBody(PatternDecl);40864087// C++0x [temp.explicit]p9:4088// Except for inline functions, other explicit instantiation declarations4089// have the effect of suppressing the implicit instantiation of the entity4090// to which they refer.4091if (!HasPattern || !PatternDecl)4092return true;40934094return PatternDecl->isInlined();4095}40964097bool FunctionDecl::isTemplateInstantiation() const {4098// FIXME: Remove this, it's not clear what it means. (Which template4099// specialization kind?)4100return clang::isTemplateInstantiation(getTemplateSpecializationKind());4101}41024103FunctionDecl *4104FunctionDecl::getTemplateInstantiationPattern(bool ForDefinition) const {4105// If this is a generic lambda call operator specialization, its4106// instantiation pattern is always its primary template's pattern4107// even if its primary template was instantiated from another4108// member template (which happens with nested generic lambdas).4109// Since a lambda's call operator's body is transformed eagerly,4110// we don't have to go hunting for a prototype definition template4111// (i.e. instantiated-from-member-template) to use as an instantiation4112// pattern.41134114if (isGenericLambdaCallOperatorSpecialization(4115dyn_cast<CXXMethodDecl>(this))) {4116assert(getPrimaryTemplate() && "not a generic lambda call operator?");4117return getDefinitionOrSelf(getPrimaryTemplate()->getTemplatedDecl());4118}41194120// Check for a declaration of this function that was instantiated from a4121// friend definition.4122const FunctionDecl *FD = nullptr;4123if (!isDefined(FD, /*CheckForPendingFriendDefinition=*/true))4124FD = this;41254126if (MemberSpecializationInfo *Info = FD->getMemberSpecializationInfo()) {4127if (ForDefinition &&4128!clang::isTemplateInstantiation(Info->getTemplateSpecializationKind()))4129return nullptr;4130return getDefinitionOrSelf(cast<FunctionDecl>(Info->getInstantiatedFrom()));4131}41324133if (ForDefinition &&4134!clang::isTemplateInstantiation(getTemplateSpecializationKind()))4135return nullptr;41364137if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {4138// If we hit a point where the user provided a specialization of this4139// template, we're done looking.4140while (!ForDefinition || !Primary->isMemberSpecialization()) {4141auto *NewPrimary = Primary->getInstantiatedFromMemberTemplate();4142if (!NewPrimary)4143break;4144Primary = NewPrimary;4145}41464147return getDefinitionOrSelf(Primary->getTemplatedDecl());4148}41494150return nullptr;4151}41524153FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {4154if (FunctionTemplateSpecializationInfo *Info4155= TemplateOrSpecialization4156.dyn_cast<FunctionTemplateSpecializationInfo*>()) {4157return Info->getTemplate();4158}4159return nullptr;4160}41614162FunctionTemplateSpecializationInfo *4163FunctionDecl::getTemplateSpecializationInfo() const {4164return TemplateOrSpecialization4165.dyn_cast<FunctionTemplateSpecializationInfo *>();4166}41674168const TemplateArgumentList *4169FunctionDecl::getTemplateSpecializationArgs() const {4170if (FunctionTemplateSpecializationInfo *Info4171= TemplateOrSpecialization4172.dyn_cast<FunctionTemplateSpecializationInfo*>()) {4173return Info->TemplateArguments;4174}4175return nullptr;4176}41774178const ASTTemplateArgumentListInfo *4179FunctionDecl::getTemplateSpecializationArgsAsWritten() const {4180if (FunctionTemplateSpecializationInfo *Info4181= TemplateOrSpecialization4182.dyn_cast<FunctionTemplateSpecializationInfo*>()) {4183return Info->TemplateArgumentsAsWritten;4184}4185if (DependentFunctionTemplateSpecializationInfo *Info =4186TemplateOrSpecialization4187.dyn_cast<DependentFunctionTemplateSpecializationInfo *>()) {4188return Info->TemplateArgumentsAsWritten;4189}4190return nullptr;4191}41924193void FunctionDecl::setFunctionTemplateSpecialization(4194ASTContext &C, FunctionTemplateDecl *Template,4195TemplateArgumentList *TemplateArgs, void *InsertPos,4196TemplateSpecializationKind TSK,4197const TemplateArgumentListInfo *TemplateArgsAsWritten,4198SourceLocation PointOfInstantiation) {4199assert((TemplateOrSpecialization.isNull() ||4200TemplateOrSpecialization.is<MemberSpecializationInfo *>()) &&4201"Member function is already a specialization");4202assert(TSK != TSK_Undeclared &&4203"Must specify the type of function template specialization");4204assert((TemplateOrSpecialization.isNull() ||4205getFriendObjectKind() != FOK_None ||4206TSK == TSK_ExplicitSpecialization) &&4207"Member specialization must be an explicit specialization");4208FunctionTemplateSpecializationInfo *Info =4209FunctionTemplateSpecializationInfo::Create(4210C, this, Template, TSK, TemplateArgs, TemplateArgsAsWritten,4211PointOfInstantiation,4212TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>());4213TemplateOrSpecialization = Info;4214Template->addSpecialization(Info, InsertPos);4215}42164217void FunctionDecl::setDependentTemplateSpecialization(4218ASTContext &Context, const UnresolvedSetImpl &Templates,4219const TemplateArgumentListInfo *TemplateArgs) {4220assert(TemplateOrSpecialization.isNull());4221DependentFunctionTemplateSpecializationInfo *Info =4222DependentFunctionTemplateSpecializationInfo::Create(Context, Templates,4223TemplateArgs);4224TemplateOrSpecialization = Info;4225}42264227DependentFunctionTemplateSpecializationInfo *4228FunctionDecl::getDependentSpecializationInfo() const {4229return TemplateOrSpecialization4230.dyn_cast<DependentFunctionTemplateSpecializationInfo *>();4231}42324233DependentFunctionTemplateSpecializationInfo *4234DependentFunctionTemplateSpecializationInfo::Create(4235ASTContext &Context, const UnresolvedSetImpl &Candidates,4236const TemplateArgumentListInfo *TArgs) {4237const auto *TArgsWritten =4238TArgs ? ASTTemplateArgumentListInfo::Create(Context, *TArgs) : nullptr;4239return new (Context.Allocate(4240totalSizeToAlloc<FunctionTemplateDecl *>(Candidates.size())))4241DependentFunctionTemplateSpecializationInfo(Candidates, TArgsWritten);4242}42434244DependentFunctionTemplateSpecializationInfo::4245DependentFunctionTemplateSpecializationInfo(4246const UnresolvedSetImpl &Candidates,4247const ASTTemplateArgumentListInfo *TemplateArgsWritten)4248: NumCandidates(Candidates.size()),4249TemplateArgumentsAsWritten(TemplateArgsWritten) {4250std::transform(Candidates.begin(), Candidates.end(),4251getTrailingObjects<FunctionTemplateDecl *>(),4252[](NamedDecl *ND) {4253return cast<FunctionTemplateDecl>(ND->getUnderlyingDecl());4254});4255}42564257TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {4258// For a function template specialization, query the specialization4259// information object.4260if (FunctionTemplateSpecializationInfo *FTSInfo =4261TemplateOrSpecialization4262.dyn_cast<FunctionTemplateSpecializationInfo *>())4263return FTSInfo->getTemplateSpecializationKind();42644265if (MemberSpecializationInfo *MSInfo =4266TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>())4267return MSInfo->getTemplateSpecializationKind();42684269// A dependent function template specialization is an explicit specialization,4270// except when it's a friend declaration.4271if (TemplateOrSpecialization4272.is<DependentFunctionTemplateSpecializationInfo *>() &&4273getFriendObjectKind() == FOK_None)4274return TSK_ExplicitSpecialization;42754276return TSK_Undeclared;4277}42784279TemplateSpecializationKind4280FunctionDecl::getTemplateSpecializationKindForInstantiation() const {4281// This is the same as getTemplateSpecializationKind(), except that for a4282// function that is both a function template specialization and a member4283// specialization, we prefer the member specialization information. Eg:4284//4285// template<typename T> struct A {4286// template<typename U> void f() {}4287// template<> void f<int>() {}4288// };4289//4290// Within the templated CXXRecordDecl, A<T>::f<int> is a dependent function4291// template specialization; both getTemplateSpecializationKind() and4292// getTemplateSpecializationKindForInstantiation() will return4293// TSK_ExplicitSpecialization.4294//4295// For A<int>::f<int>():4296// * getTemplateSpecializationKind() will return TSK_ExplicitSpecialization4297// * getTemplateSpecializationKindForInstantiation() will return4298// TSK_ImplicitInstantiation4299//4300// This reflects the facts that A<int>::f<int> is an explicit specialization4301// of A<int>::f, and that A<int>::f<int> should be implicitly instantiated4302// from A::f<int> if a definition is needed.4303if (FunctionTemplateSpecializationInfo *FTSInfo =4304TemplateOrSpecialization4305.dyn_cast<FunctionTemplateSpecializationInfo *>()) {4306if (auto *MSInfo = FTSInfo->getMemberSpecializationInfo())4307return MSInfo->getTemplateSpecializationKind();4308return FTSInfo->getTemplateSpecializationKind();4309}43104311if (MemberSpecializationInfo *MSInfo =4312TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>())4313return MSInfo->getTemplateSpecializationKind();43144315if (TemplateOrSpecialization4316.is<DependentFunctionTemplateSpecializationInfo *>() &&4317getFriendObjectKind() == FOK_None)4318return TSK_ExplicitSpecialization;43194320return TSK_Undeclared;4321}43224323void4324FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,4325SourceLocation PointOfInstantiation) {4326if (FunctionTemplateSpecializationInfo *FTSInfo4327= TemplateOrSpecialization.dyn_cast<4328FunctionTemplateSpecializationInfo*>()) {4329FTSInfo->setTemplateSpecializationKind(TSK);4330if (TSK != TSK_ExplicitSpecialization &&4331PointOfInstantiation.isValid() &&4332FTSInfo->getPointOfInstantiation().isInvalid()) {4333FTSInfo->setPointOfInstantiation(PointOfInstantiation);4334if (ASTMutationListener *L = getASTContext().getASTMutationListener())4335L->InstantiationRequested(this);4336}4337} else if (MemberSpecializationInfo *MSInfo4338= TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {4339MSInfo->setTemplateSpecializationKind(TSK);4340if (TSK != TSK_ExplicitSpecialization &&4341PointOfInstantiation.isValid() &&4342MSInfo->getPointOfInstantiation().isInvalid()) {4343MSInfo->setPointOfInstantiation(PointOfInstantiation);4344if (ASTMutationListener *L = getASTContext().getASTMutationListener())4345L->InstantiationRequested(this);4346}4347} else4348llvm_unreachable("Function cannot have a template specialization kind");4349}43504351SourceLocation FunctionDecl::getPointOfInstantiation() const {4352if (FunctionTemplateSpecializationInfo *FTSInfo4353= TemplateOrSpecialization.dyn_cast<4354FunctionTemplateSpecializationInfo*>())4355return FTSInfo->getPointOfInstantiation();4356if (MemberSpecializationInfo *MSInfo =4357TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>())4358return MSInfo->getPointOfInstantiation();43594360return SourceLocation();4361}43624363bool FunctionDecl::isOutOfLine() const {4364if (Decl::isOutOfLine())4365return true;43664367// If this function was instantiated from a member function of a4368// class template, check whether that member function was defined out-of-line.4369if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {4370const FunctionDecl *Definition;4371if (FD->hasBody(Definition))4372return Definition->isOutOfLine();4373}43744375// If this function was instantiated from a function template,4376// check whether that function template was defined out-of-line.4377if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {4378const FunctionDecl *Definition;4379if (FunTmpl->getTemplatedDecl()->hasBody(Definition))4380return Definition->isOutOfLine();4381}43824383return false;4384}43854386SourceRange FunctionDecl::getSourceRange() const {4387return SourceRange(getOuterLocStart(), EndRangeLoc);4388}43894390unsigned FunctionDecl::getMemoryFunctionKind() const {4391IdentifierInfo *FnInfo = getIdentifier();43924393if (!FnInfo)4394return 0;43954396// Builtin handling.4397switch (getBuiltinID()) {4398case Builtin::BI__builtin_memset:4399case Builtin::BI__builtin___memset_chk:4400case Builtin::BImemset:4401return Builtin::BImemset;44024403case Builtin::BI__builtin_memcpy:4404case Builtin::BI__builtin___memcpy_chk:4405case Builtin::BImemcpy:4406return Builtin::BImemcpy;44074408case Builtin::BI__builtin_mempcpy:4409case Builtin::BI__builtin___mempcpy_chk:4410case Builtin::BImempcpy:4411return Builtin::BImempcpy;44124413case Builtin::BI__builtin_memmove:4414case Builtin::BI__builtin___memmove_chk:4415case Builtin::BImemmove:4416return Builtin::BImemmove;44174418case Builtin::BIstrlcpy:4419case Builtin::BI__builtin___strlcpy_chk:4420return Builtin::BIstrlcpy;44214422case Builtin::BIstrlcat:4423case Builtin::BI__builtin___strlcat_chk:4424return Builtin::BIstrlcat;44254426case Builtin::BI__builtin_memcmp:4427case Builtin::BImemcmp:4428return Builtin::BImemcmp;44294430case Builtin::BI__builtin_bcmp:4431case Builtin::BIbcmp:4432return Builtin::BIbcmp;44334434case Builtin::BI__builtin_strncpy:4435case Builtin::BI__builtin___strncpy_chk:4436case Builtin::BIstrncpy:4437return Builtin::BIstrncpy;44384439case Builtin::BI__builtin_strncmp:4440case Builtin::BIstrncmp:4441return Builtin::BIstrncmp;44424443case Builtin::BI__builtin_strncasecmp:4444case Builtin::BIstrncasecmp:4445return Builtin::BIstrncasecmp;44464447case Builtin::BI__builtin_strncat:4448case Builtin::BI__builtin___strncat_chk:4449case Builtin::BIstrncat:4450return Builtin::BIstrncat;44514452case Builtin::BI__builtin_strndup:4453case Builtin::BIstrndup:4454return Builtin::BIstrndup;44554456case Builtin::BI__builtin_strlen:4457case Builtin::BIstrlen:4458return Builtin::BIstrlen;44594460case Builtin::BI__builtin_bzero:4461case Builtin::BIbzero:4462return Builtin::BIbzero;44634464case Builtin::BI__builtin_bcopy:4465case Builtin::BIbcopy:4466return Builtin::BIbcopy;44674468case Builtin::BIfree:4469return Builtin::BIfree;44704471default:4472if (isExternC()) {4473if (FnInfo->isStr("memset"))4474return Builtin::BImemset;4475if (FnInfo->isStr("memcpy"))4476return Builtin::BImemcpy;4477if (FnInfo->isStr("mempcpy"))4478return Builtin::BImempcpy;4479if (FnInfo->isStr("memmove"))4480return Builtin::BImemmove;4481if (FnInfo->isStr("memcmp"))4482return Builtin::BImemcmp;4483if (FnInfo->isStr("bcmp"))4484return Builtin::BIbcmp;4485if (FnInfo->isStr("strncpy"))4486return Builtin::BIstrncpy;4487if (FnInfo->isStr("strncmp"))4488return Builtin::BIstrncmp;4489if (FnInfo->isStr("strncasecmp"))4490return Builtin::BIstrncasecmp;4491if (FnInfo->isStr("strncat"))4492return Builtin::BIstrncat;4493if (FnInfo->isStr("strndup"))4494return Builtin::BIstrndup;4495if (FnInfo->isStr("strlen"))4496return Builtin::BIstrlen;4497if (FnInfo->isStr("bzero"))4498return Builtin::BIbzero;4499if (FnInfo->isStr("bcopy"))4500return Builtin::BIbcopy;4501} else if (isInStdNamespace()) {4502if (FnInfo->isStr("free"))4503return Builtin::BIfree;4504}4505break;4506}4507return 0;4508}45094510unsigned FunctionDecl::getODRHash() const {4511assert(hasODRHash());4512return ODRHash;4513}45144515unsigned FunctionDecl::getODRHash() {4516if (hasODRHash())4517return ODRHash;45184519if (auto *FT = getInstantiatedFromMemberFunction()) {4520setHasODRHash(true);4521ODRHash = FT->getODRHash();4522return ODRHash;4523}45244525class ODRHash Hash;4526Hash.AddFunctionDecl(this);4527setHasODRHash(true);4528ODRHash = Hash.CalculateHash();4529return ODRHash;4530}45314532//===----------------------------------------------------------------------===//4533// FieldDecl Implementation4534//===----------------------------------------------------------------------===//45354536FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC,4537SourceLocation StartLoc, SourceLocation IdLoc,4538const IdentifierInfo *Id, QualType T,4539TypeSourceInfo *TInfo, Expr *BW, bool Mutable,4540InClassInitStyle InitStyle) {4541return new (C, DC) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,4542BW, Mutable, InitStyle);4543}45444545FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) {4546return new (C, ID) FieldDecl(Field, nullptr, SourceLocation(),4547SourceLocation(), nullptr, QualType(), nullptr,4548nullptr, false, ICIS_NoInit);4549}45504551bool FieldDecl::isAnonymousStructOrUnion() const {4552if (!isImplicit() || getDeclName())4553return false;45544555if (const auto *Record = getType()->getAs<RecordType>())4556return Record->getDecl()->isAnonymousStructOrUnion();45574558return false;4559}45604561Expr *FieldDecl::getInClassInitializer() const {4562if (!hasInClassInitializer())4563return nullptr;45644565LazyDeclStmtPtr InitPtr = BitField ? InitAndBitWidth->Init : Init;4566return cast_if_present<Expr>(4567InitPtr.isOffset() ? InitPtr.get(getASTContext().getExternalSource())4568: InitPtr.get(nullptr));4569}45704571void FieldDecl::setInClassInitializer(Expr *NewInit) {4572setLazyInClassInitializer(LazyDeclStmtPtr(NewInit));4573}45744575void FieldDecl::setLazyInClassInitializer(LazyDeclStmtPtr NewInit) {4576assert(hasInClassInitializer() && !getInClassInitializer());4577if (BitField)4578InitAndBitWidth->Init = NewInit;4579else4580Init = NewInit;4581}45824583unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const {4584assert(isBitField() && "not a bitfield");4585return getBitWidth()->EvaluateKnownConstInt(Ctx).getZExtValue();4586}45874588bool FieldDecl::isZeroLengthBitField(const ASTContext &Ctx) const {4589return isUnnamedBitField() && !getBitWidth()->isValueDependent() &&4590getBitWidthValue(Ctx) == 0;4591}45924593bool FieldDecl::isZeroSize(const ASTContext &Ctx) const {4594if (isZeroLengthBitField(Ctx))4595return true;45964597// C++2a [intro.object]p7:4598// An object has nonzero size if it4599// -- is not a potentially-overlapping subobject, or4600if (!hasAttr<NoUniqueAddressAttr>())4601return false;46024603// -- is not of class type, or4604const auto *RT = getType()->getAs<RecordType>();4605if (!RT)4606return false;4607const RecordDecl *RD = RT->getDecl()->getDefinition();4608if (!RD) {4609assert(isInvalidDecl() && "valid field has incomplete type");4610return false;4611}46124613// -- [has] virtual member functions or virtual base classes, or4614// -- has subobjects of nonzero size or bit-fields of nonzero length4615const auto *CXXRD = cast<CXXRecordDecl>(RD);4616if (!CXXRD->isEmpty())4617return false;46184619// Otherwise, [...] the circumstances under which the object has zero size4620// are implementation-defined.4621if (!Ctx.getTargetInfo().getCXXABI().isMicrosoft())4622return true;46234624// MS ABI: has nonzero size if it is a class type with class type fields,4625// whether or not they have nonzero size4626return !llvm::any_of(CXXRD->fields(), [](const FieldDecl *Field) {4627return Field->getType()->getAs<RecordType>();4628});4629}46304631bool FieldDecl::isPotentiallyOverlapping() const {4632return hasAttr<NoUniqueAddressAttr>() && getType()->getAsCXXRecordDecl();4633}46344635unsigned FieldDecl::getFieldIndex() const {4636const FieldDecl *Canonical = getCanonicalDecl();4637if (Canonical != this)4638return Canonical->getFieldIndex();46394640if (CachedFieldIndex) return CachedFieldIndex - 1;46414642unsigned Index = 0;4643const RecordDecl *RD = getParent()->getDefinition();4644assert(RD && "requested index for field of struct with no definition");46454646for (auto *Field : RD->fields()) {4647Field->getCanonicalDecl()->CachedFieldIndex = Index + 1;4648assert(Field->getCanonicalDecl()->CachedFieldIndex == Index + 1 &&4649"overflow in field numbering");4650++Index;4651}46524653assert(CachedFieldIndex && "failed to find field in parent");4654return CachedFieldIndex - 1;4655}46564657SourceRange FieldDecl::getSourceRange() const {4658const Expr *FinalExpr = getInClassInitializer();4659if (!FinalExpr)4660FinalExpr = getBitWidth();4661if (FinalExpr)4662return SourceRange(getInnerLocStart(), FinalExpr->getEndLoc());4663return DeclaratorDecl::getSourceRange();4664}46654666void FieldDecl::setCapturedVLAType(const VariableArrayType *VLAType) {4667assert((getParent()->isLambda() || getParent()->isCapturedRecord()) &&4668"capturing type in non-lambda or captured record.");4669assert(StorageKind == ISK_NoInit && !BitField &&4670"bit-field or field with default member initializer cannot capture "4671"VLA type");4672StorageKind = ISK_CapturedVLAType;4673CapturedVLAType = VLAType;4674}46754676void FieldDecl::printName(raw_ostream &OS, const PrintingPolicy &Policy) const {4677// Print unnamed members using name of their type.4678if (isAnonymousStructOrUnion()) {4679this->getType().print(OS, Policy);4680return;4681}4682// Otherwise, do the normal printing.4683DeclaratorDecl::printName(OS, Policy);4684}46854686//===----------------------------------------------------------------------===//4687// TagDecl Implementation4688//===----------------------------------------------------------------------===//46894690TagDecl::TagDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC,4691SourceLocation L, IdentifierInfo *Id, TagDecl *PrevDecl,4692SourceLocation StartL)4693: TypeDecl(DK, DC, L, Id, StartL), DeclContext(DK), redeclarable_base(C),4694TypedefNameDeclOrQualifier((TypedefNameDecl *)nullptr) {4695assert((DK != Enum || TK == TagTypeKind::Enum) &&4696"EnumDecl not matched with TagTypeKind::Enum");4697setPreviousDecl(PrevDecl);4698setTagKind(TK);4699setCompleteDefinition(false);4700setBeingDefined(false);4701setEmbeddedInDeclarator(false);4702setFreeStanding(false);4703setCompleteDefinitionRequired(false);4704TagDeclBits.IsThisDeclarationADemotedDefinition = false;4705}47064707SourceLocation TagDecl::getOuterLocStart() const {4708return getTemplateOrInnerLocStart(this);4709}47104711SourceRange TagDecl::getSourceRange() const {4712SourceLocation RBraceLoc = BraceRange.getEnd();4713SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();4714return SourceRange(getOuterLocStart(), E);4715}47164717TagDecl *TagDecl::getCanonicalDecl() { return getFirstDecl(); }47184719void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) {4720TypedefNameDeclOrQualifier = TDD;4721if (const Type *T = getTypeForDecl()) {4722(void)T;4723assert(T->isLinkageValid());4724}4725assert(isLinkageValid());4726}47274728void TagDecl::startDefinition() {4729setBeingDefined(true);47304731if (auto *D = dyn_cast<CXXRecordDecl>(this)) {4732struct CXXRecordDecl::DefinitionData *Data =4733new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);4734for (auto *I : redecls())4735cast<CXXRecordDecl>(I)->DefinitionData = Data;4736}4737}47384739void TagDecl::completeDefinition() {4740assert((!isa<CXXRecordDecl>(this) ||4741cast<CXXRecordDecl>(this)->hasDefinition()) &&4742"definition completed but not started");47434744setCompleteDefinition(true);4745setBeingDefined(false);47464747if (ASTMutationListener *L = getASTMutationListener())4748L->CompletedTagDefinition(this);4749}47504751TagDecl *TagDecl::getDefinition() const {4752if (isCompleteDefinition())4753return const_cast<TagDecl *>(this);47544755// If it's possible for us to have an out-of-date definition, check now.4756if (mayHaveOutOfDateDef()) {4757if (IdentifierInfo *II = getIdentifier()) {4758if (II->isOutOfDate()) {4759updateOutOfDate(*II);4760}4761}4762}47634764if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(this))4765return CXXRD->getDefinition();47664767for (auto *R : redecls())4768if (R->isCompleteDefinition())4769return R;47704771return nullptr;4772}47734774void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {4775if (QualifierLoc) {4776// Make sure the extended qualifier info is allocated.4777if (!hasExtInfo())4778TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;4779// Set qualifier info.4780getExtInfo()->QualifierLoc = QualifierLoc;4781} else {4782// Here Qualifier == 0, i.e., we are removing the qualifier (if any).4783if (hasExtInfo()) {4784if (getExtInfo()->NumTemplParamLists == 0) {4785getASTContext().Deallocate(getExtInfo());4786TypedefNameDeclOrQualifier = (TypedefNameDecl *)nullptr;4787}4788else4789getExtInfo()->QualifierLoc = QualifierLoc;4790}4791}4792}47934794void TagDecl::printName(raw_ostream &OS, const PrintingPolicy &Policy) const {4795DeclarationName Name = getDeclName();4796// If the name is supposed to have an identifier but does not have one, then4797// the tag is anonymous and we should print it differently.4798if (Name.isIdentifier() && !Name.getAsIdentifierInfo()) {4799// If the caller wanted to print a qualified name, they've already printed4800// the scope. And if the caller doesn't want that, the scope information4801// is already printed as part of the type.4802PrintingPolicy Copy(Policy);4803Copy.SuppressScope = true;4804getASTContext().getTagDeclType(this).print(OS, Copy);4805return;4806}4807// Otherwise, do the normal printing.4808Name.print(OS, Policy);4809}48104811void TagDecl::setTemplateParameterListsInfo(4812ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {4813assert(!TPLists.empty());4814// Make sure the extended decl info is allocated.4815if (!hasExtInfo())4816// Allocate external info struct.4817TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;4818// Set the template parameter lists info.4819getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);4820}48214822//===----------------------------------------------------------------------===//4823// EnumDecl Implementation4824//===----------------------------------------------------------------------===//48254826EnumDecl::EnumDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,4827SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl,4828bool Scoped, bool ScopedUsingClassTag, bool Fixed)4829: TagDecl(Enum, TagTypeKind::Enum, C, DC, IdLoc, Id, PrevDecl, StartLoc) {4830assert(Scoped || !ScopedUsingClassTag);4831IntegerType = nullptr;4832setNumPositiveBits(0);4833setNumNegativeBits(0);4834setScoped(Scoped);4835setScopedUsingClassTag(ScopedUsingClassTag);4836setFixed(Fixed);4837setHasODRHash(false);4838ODRHash = 0;4839}48404841void EnumDecl::anchor() {}48424843EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC,4844SourceLocation StartLoc, SourceLocation IdLoc,4845IdentifierInfo *Id,4846EnumDecl *PrevDecl, bool IsScoped,4847bool IsScopedUsingClassTag, bool IsFixed) {4848auto *Enum = new (C, DC) EnumDecl(C, DC, StartLoc, IdLoc, Id, PrevDecl,4849IsScoped, IsScopedUsingClassTag, IsFixed);4850Enum->setMayHaveOutOfDateDef(C.getLangOpts().Modules);4851C.getTypeDeclType(Enum, PrevDecl);4852return Enum;4853}48544855EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) {4856EnumDecl *Enum =4857new (C, ID) EnumDecl(C, nullptr, SourceLocation(), SourceLocation(),4858nullptr, nullptr, false, false, false);4859Enum->setMayHaveOutOfDateDef(C.getLangOpts().Modules);4860return Enum;4861}48624863SourceRange EnumDecl::getIntegerTypeRange() const {4864if (const TypeSourceInfo *TI = getIntegerTypeSourceInfo())4865return TI->getTypeLoc().getSourceRange();4866return SourceRange();4867}48684869void EnumDecl::completeDefinition(QualType NewType,4870QualType NewPromotionType,4871unsigned NumPositiveBits,4872unsigned NumNegativeBits) {4873assert(!isCompleteDefinition() && "Cannot redefine enums!");4874if (!IntegerType)4875IntegerType = NewType.getTypePtr();4876PromotionType = NewPromotionType;4877setNumPositiveBits(NumPositiveBits);4878setNumNegativeBits(NumNegativeBits);4879TagDecl::completeDefinition();4880}48814882bool EnumDecl::isClosed() const {4883if (const auto *A = getAttr<EnumExtensibilityAttr>())4884return A->getExtensibility() == EnumExtensibilityAttr::Closed;4885return true;4886}48874888bool EnumDecl::isClosedFlag() const {4889return isClosed() && hasAttr<FlagEnumAttr>();4890}48914892bool EnumDecl::isClosedNonFlag() const {4893return isClosed() && !hasAttr<FlagEnumAttr>();4894}48954896TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const {4897if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())4898return MSI->getTemplateSpecializationKind();48994900return TSK_Undeclared;4901}49024903void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,4904SourceLocation PointOfInstantiation) {4905MemberSpecializationInfo *MSI = getMemberSpecializationInfo();4906assert(MSI && "Not an instantiated member enumeration?");4907MSI->setTemplateSpecializationKind(TSK);4908if (TSK != TSK_ExplicitSpecialization &&4909PointOfInstantiation.isValid() &&4910MSI->getPointOfInstantiation().isInvalid())4911MSI->setPointOfInstantiation(PointOfInstantiation);4912}49134914EnumDecl *EnumDecl::getTemplateInstantiationPattern() const {4915if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) {4916if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) {4917EnumDecl *ED = getInstantiatedFromMemberEnum();4918while (auto *NewED = ED->getInstantiatedFromMemberEnum())4919ED = NewED;4920return getDefinitionOrSelf(ED);4921}4922}49234924assert(!isTemplateInstantiation(getTemplateSpecializationKind()) &&4925"couldn't find pattern for enum instantiation");4926return nullptr;4927}49284929EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const {4930if (SpecializationInfo)4931return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom());49324933return nullptr;4934}49354936void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,4937TemplateSpecializationKind TSK) {4938assert(!SpecializationInfo && "Member enum is already a specialization");4939SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK);4940}49414942unsigned EnumDecl::getODRHash() {4943if (hasODRHash())4944return ODRHash;49454946class ODRHash Hash;4947Hash.AddEnumDecl(this);4948setHasODRHash(true);4949ODRHash = Hash.CalculateHash();4950return ODRHash;4951}49524953SourceRange EnumDecl::getSourceRange() const {4954auto Res = TagDecl::getSourceRange();4955// Set end-point to enum-base, e.g. enum foo : ^bar4956if (auto *TSI = getIntegerTypeSourceInfo()) {4957// TagDecl doesn't know about the enum base.4958if (!getBraceRange().getEnd().isValid())4959Res.setEnd(TSI->getTypeLoc().getEndLoc());4960}4961return Res;4962}49634964void EnumDecl::getValueRange(llvm::APInt &Max, llvm::APInt &Min) const {4965unsigned Bitwidth = getASTContext().getIntWidth(getIntegerType());4966unsigned NumNegativeBits = getNumNegativeBits();4967unsigned NumPositiveBits = getNumPositiveBits();49684969if (NumNegativeBits) {4970unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1);4971Max = llvm::APInt(Bitwidth, 1) << (NumBits - 1);4972Min = -Max;4973} else {4974Max = llvm::APInt(Bitwidth, 1) << NumPositiveBits;4975Min = llvm::APInt::getZero(Bitwidth);4976}4977}49784979//===----------------------------------------------------------------------===//4980// RecordDecl Implementation4981//===----------------------------------------------------------------------===//49824983RecordDecl::RecordDecl(Kind DK, TagKind TK, const ASTContext &C,4984DeclContext *DC, SourceLocation StartLoc,4985SourceLocation IdLoc, IdentifierInfo *Id,4986RecordDecl *PrevDecl)4987: TagDecl(DK, TK, C, DC, IdLoc, Id, PrevDecl, StartLoc) {4988assert(classof(static_cast<Decl *>(this)) && "Invalid Kind!");4989setHasFlexibleArrayMember(false);4990setAnonymousStructOrUnion(false);4991setHasObjectMember(false);4992setHasVolatileMember(false);4993setHasLoadedFieldsFromExternalStorage(false);4994setNonTrivialToPrimitiveDefaultInitialize(false);4995setNonTrivialToPrimitiveCopy(false);4996setNonTrivialToPrimitiveDestroy(false);4997setHasNonTrivialToPrimitiveDefaultInitializeCUnion(false);4998setHasNonTrivialToPrimitiveDestructCUnion(false);4999setHasNonTrivialToPrimitiveCopyCUnion(false);5000setParamDestroyedInCallee(false);5001setArgPassingRestrictions(RecordArgPassingKind::CanPassInRegs);5002setIsRandomized(false);5003setODRHash(0);5004}50055006RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC,5007SourceLocation StartLoc, SourceLocation IdLoc,5008IdentifierInfo *Id, RecordDecl* PrevDecl) {5009RecordDecl *R = new (C, DC) RecordDecl(Record, TK, C, DC,5010StartLoc, IdLoc, Id, PrevDecl);5011R->setMayHaveOutOfDateDef(C.getLangOpts().Modules);50125013C.getTypeDeclType(R, PrevDecl);5014return R;5015}50165017RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C,5018GlobalDeclID ID) {5019RecordDecl *R = new (C, ID)5020RecordDecl(Record, TagTypeKind::Struct, C, nullptr, SourceLocation(),5021SourceLocation(), nullptr, nullptr);5022R->setMayHaveOutOfDateDef(C.getLangOpts().Modules);5023return R;5024}50255026bool RecordDecl::isInjectedClassName() const {5027return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&5028cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();5029}50305031bool RecordDecl::isLambda() const {5032if (auto RD = dyn_cast<CXXRecordDecl>(this))5033return RD->isLambda();5034return false;5035}50365037bool RecordDecl::isCapturedRecord() const {5038return hasAttr<CapturedRecordAttr>();5039}50405041void RecordDecl::setCapturedRecord() {5042addAttr(CapturedRecordAttr::CreateImplicit(getASTContext()));5043}50445045bool RecordDecl::isOrContainsUnion() const {5046if (isUnion())5047return true;50485049if (const RecordDecl *Def = getDefinition()) {5050for (const FieldDecl *FD : Def->fields()) {5051const RecordType *RT = FD->getType()->getAs<RecordType>();5052if (RT && RT->getDecl()->isOrContainsUnion())5053return true;5054}5055}50565057return false;5058}50595060RecordDecl::field_iterator RecordDecl::field_begin() const {5061if (hasExternalLexicalStorage() && !hasLoadedFieldsFromExternalStorage())5062LoadFieldsFromExternalStorage();5063// This is necessary for correctness for C++ with modules.5064// FIXME: Come up with a test case that breaks without definition.5065if (RecordDecl *D = getDefinition(); D && D != this)5066return D->field_begin();5067return field_iterator(decl_iterator(FirstDecl));5068}50695070/// completeDefinition - Notes that the definition of this type is now5071/// complete.5072void RecordDecl::completeDefinition() {5073assert(!isCompleteDefinition() && "Cannot redefine record!");5074TagDecl::completeDefinition();50755076ASTContext &Ctx = getASTContext();50775078// Layouts are dumped when computed, so if we are dumping for all complete5079// types, we need to force usage to get types that wouldn't be used elsewhere.5080//5081// If the type is dependent, then we can't compute its layout because there5082// is no way for us to know the size or alignment of a dependent type. Also5083// ignore declarations marked as invalid since 'getASTRecordLayout()' asserts5084// on that.5085if (Ctx.getLangOpts().DumpRecordLayoutsComplete && !isDependentType() &&5086!isInvalidDecl())5087(void)Ctx.getASTRecordLayout(this);5088}50895090/// isMsStruct - Get whether or not this record uses ms_struct layout.5091/// This which can be turned on with an attribute, pragma, or the5092/// -mms-bitfields command-line option.5093bool RecordDecl::isMsStruct(const ASTContext &C) const {5094return hasAttr<MSStructAttr>() || C.getLangOpts().MSBitfields == 1;5095}50965097void RecordDecl::reorderDecls(const SmallVectorImpl<Decl *> &Decls) {5098std::tie(FirstDecl, LastDecl) = DeclContext::BuildDeclChain(Decls, false);5099LastDecl->NextInContextAndBits.setPointer(nullptr);5100setIsRandomized(true);5101}51025103void RecordDecl::LoadFieldsFromExternalStorage() const {5104ExternalASTSource *Source = getASTContext().getExternalSource();5105assert(hasExternalLexicalStorage() && Source && "No external storage?");51065107// Notify that we have a RecordDecl doing some initialization.5108ExternalASTSource::Deserializing TheFields(Source);51095110SmallVector<Decl*, 64> Decls;5111setHasLoadedFieldsFromExternalStorage(true);5112Source->FindExternalLexicalDecls(this, [](Decl::Kind K) {5113return FieldDecl::classofKind(K) || IndirectFieldDecl::classofKind(K);5114}, Decls);51155116#ifndef NDEBUG5117// Check that all decls we got were FieldDecls.5118for (unsigned i=0, e=Decls.size(); i != e; ++i)5119assert(isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>(Decls[i]));5120#endif51215122if (Decls.empty())5123return;51245125auto [ExternalFirst, ExternalLast] =5126BuildDeclChain(Decls,5127/*FieldsAlreadyLoaded=*/false);5128ExternalLast->NextInContextAndBits.setPointer(FirstDecl);5129FirstDecl = ExternalFirst;5130if (!LastDecl)5131LastDecl = ExternalLast;5132}51335134bool RecordDecl::mayInsertExtraPadding(bool EmitRemark) const {5135ASTContext &Context = getASTContext();5136const SanitizerMask EnabledAsanMask = Context.getLangOpts().Sanitize.Mask &5137(SanitizerKind::Address | SanitizerKind::KernelAddress);5138if (!EnabledAsanMask || !Context.getLangOpts().SanitizeAddressFieldPadding)5139return false;5140const auto &NoSanitizeList = Context.getNoSanitizeList();5141const auto *CXXRD = dyn_cast<CXXRecordDecl>(this);5142// We may be able to relax some of these requirements.5143int ReasonToReject = -1;5144if (!CXXRD || CXXRD->isExternCContext())5145ReasonToReject = 0; // is not C++.5146else if (CXXRD->hasAttr<PackedAttr>())5147ReasonToReject = 1; // is packed.5148else if (CXXRD->isUnion())5149ReasonToReject = 2; // is a union.5150else if (CXXRD->isTriviallyCopyable())5151ReasonToReject = 3; // is trivially copyable.5152else if (CXXRD->hasTrivialDestructor())5153ReasonToReject = 4; // has trivial destructor.5154else if (CXXRD->isStandardLayout())5155ReasonToReject = 5; // is standard layout.5156else if (NoSanitizeList.containsLocation(EnabledAsanMask, getLocation(),5157"field-padding"))5158ReasonToReject = 6; // is in an excluded file.5159else if (NoSanitizeList.containsType(5160EnabledAsanMask, getQualifiedNameAsString(), "field-padding"))5161ReasonToReject = 7; // The type is excluded.51625163if (EmitRemark) {5164if (ReasonToReject >= 0)5165Context.getDiagnostics().Report(5166getLocation(),5167diag::remark_sanitize_address_insert_extra_padding_rejected)5168<< getQualifiedNameAsString() << ReasonToReject;5169else5170Context.getDiagnostics().Report(5171getLocation(),5172diag::remark_sanitize_address_insert_extra_padding_accepted)5173<< getQualifiedNameAsString();5174}5175return ReasonToReject < 0;5176}51775178const FieldDecl *RecordDecl::findFirstNamedDataMember() const {5179for (const auto *I : fields()) {5180if (I->getIdentifier())5181return I;51825183if (const auto *RT = I->getType()->getAs<RecordType>())5184if (const FieldDecl *NamedDataMember =5185RT->getDecl()->findFirstNamedDataMember())5186return NamedDataMember;5187}51885189// We didn't find a named data member.5190return nullptr;5191}51925193unsigned RecordDecl::getODRHash() {5194if (hasODRHash())5195return RecordDeclBits.ODRHash;51965197// Only calculate hash on first call of getODRHash per record.5198ODRHash Hash;5199Hash.AddRecordDecl(this);5200// For RecordDecl the ODRHash is stored in the remaining 265201// bit of RecordDeclBits, adjust the hash to accomodate.5202setODRHash(Hash.CalculateHash() >> 6);5203return RecordDeclBits.ODRHash;5204}52055206//===----------------------------------------------------------------------===//5207// BlockDecl Implementation5208//===----------------------------------------------------------------------===//52095210BlockDecl::BlockDecl(DeclContext *DC, SourceLocation CaretLoc)5211: Decl(Block, DC, CaretLoc), DeclContext(Block) {5212setIsVariadic(false);5213setCapturesCXXThis(false);5214setBlockMissingReturnType(true);5215setIsConversionFromLambda(false);5216setDoesNotEscape(false);5217setCanAvoidCopyToHeap(false);5218}52195220void BlockDecl::setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {5221assert(!ParamInfo && "Already has param info!");52225223// Zero params -> null pointer.5224if (!NewParamInfo.empty()) {5225NumParams = NewParamInfo.size();5226ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];5227std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);5228}5229}52305231void BlockDecl::setCaptures(ASTContext &Context, ArrayRef<Capture> Captures,5232bool CapturesCXXThis) {5233this->setCapturesCXXThis(CapturesCXXThis);5234this->NumCaptures = Captures.size();52355236if (Captures.empty()) {5237this->Captures = nullptr;5238return;5239}52405241this->Captures = Captures.copy(Context).data();5242}52435244bool BlockDecl::capturesVariable(const VarDecl *variable) const {5245for (const auto &I : captures())5246// Only auto vars can be captured, so no redeclaration worries.5247if (I.getVariable() == variable)5248return true;52495250return false;5251}52525253SourceRange BlockDecl::getSourceRange() const {5254return SourceRange(getLocation(), Body ? Body->getEndLoc() : getLocation());5255}52565257//===----------------------------------------------------------------------===//5258// Other Decl Allocation/Deallocation Method Implementations5259//===----------------------------------------------------------------------===//52605261void TranslationUnitDecl::anchor() {}52625263TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {5264return new (C, (DeclContext *)nullptr) TranslationUnitDecl(C);5265}52665267void TranslationUnitDecl::setAnonymousNamespace(NamespaceDecl *D) {5268AnonymousNamespace = D;52695270if (ASTMutationListener *Listener = Ctx.getASTMutationListener())5271Listener->AddedAnonymousNamespace(this, D);5272}52735274void PragmaCommentDecl::anchor() {}52755276PragmaCommentDecl *PragmaCommentDecl::Create(const ASTContext &C,5277TranslationUnitDecl *DC,5278SourceLocation CommentLoc,5279PragmaMSCommentKind CommentKind,5280StringRef Arg) {5281PragmaCommentDecl *PCD =5282new (C, DC, additionalSizeToAlloc<char>(Arg.size() + 1))5283PragmaCommentDecl(DC, CommentLoc, CommentKind);5284memcpy(PCD->getTrailingObjects<char>(), Arg.data(), Arg.size());5285PCD->getTrailingObjects<char>()[Arg.size()] = '\0';5286return PCD;5287}52885289PragmaCommentDecl *PragmaCommentDecl::CreateDeserialized(ASTContext &C,5290GlobalDeclID ID,5291unsigned ArgSize) {5292return new (C, ID, additionalSizeToAlloc<char>(ArgSize + 1))5293PragmaCommentDecl(nullptr, SourceLocation(), PCK_Unknown);5294}52955296void PragmaDetectMismatchDecl::anchor() {}52975298PragmaDetectMismatchDecl *5299PragmaDetectMismatchDecl::Create(const ASTContext &C, TranslationUnitDecl *DC,5300SourceLocation Loc, StringRef Name,5301StringRef Value) {5302size_t ValueStart = Name.size() + 1;5303PragmaDetectMismatchDecl *PDMD =5304new (C, DC, additionalSizeToAlloc<char>(ValueStart + Value.size() + 1))5305PragmaDetectMismatchDecl(DC, Loc, ValueStart);5306memcpy(PDMD->getTrailingObjects<char>(), Name.data(), Name.size());5307PDMD->getTrailingObjects<char>()[Name.size()] = '\0';5308memcpy(PDMD->getTrailingObjects<char>() + ValueStart, Value.data(),5309Value.size());5310PDMD->getTrailingObjects<char>()[ValueStart + Value.size()] = '\0';5311return PDMD;5312}53135314PragmaDetectMismatchDecl *5315PragmaDetectMismatchDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID,5316unsigned NameValueSize) {5317return new (C, ID, additionalSizeToAlloc<char>(NameValueSize + 1))5318PragmaDetectMismatchDecl(nullptr, SourceLocation(), 0);5319}53205321void ExternCContextDecl::anchor() {}53225323ExternCContextDecl *ExternCContextDecl::Create(const ASTContext &C,5324TranslationUnitDecl *DC) {5325return new (C, DC) ExternCContextDecl(DC);5326}53275328void LabelDecl::anchor() {}53295330LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,5331SourceLocation IdentL, IdentifierInfo *II) {5332return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, IdentL);5333}53345335LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,5336SourceLocation IdentL, IdentifierInfo *II,5337SourceLocation GnuLabelL) {5338assert(GnuLabelL != IdentL && "Use this only for GNU local labels");5339return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, GnuLabelL);5340}53415342LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) {5343return new (C, ID) LabelDecl(nullptr, SourceLocation(), nullptr, nullptr,5344SourceLocation());5345}53465347void LabelDecl::setMSAsmLabel(StringRef Name) {5348char *Buffer = new (getASTContext(), 1) char[Name.size() + 1];5349memcpy(Buffer, Name.data(), Name.size());5350Buffer[Name.size()] = '\0';5351MSAsmName = Buffer;5352}53535354void ValueDecl::anchor() {}53555356bool ValueDecl::isWeak() const {5357auto *MostRecent = getMostRecentDecl();5358return MostRecent->hasAttr<WeakAttr>() ||5359MostRecent->hasAttr<WeakRefAttr>() || isWeakImported();5360}53615362bool ValueDecl::isInitCapture() const {5363if (auto *Var = llvm::dyn_cast<VarDecl>(this))5364return Var->isInitCapture();5365return false;5366}53675368void ImplicitParamDecl::anchor() {}53695370ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,5371SourceLocation IdLoc,5372IdentifierInfo *Id, QualType Type,5373ImplicitParamKind ParamKind) {5374return new (C, DC) ImplicitParamDecl(C, DC, IdLoc, Id, Type, ParamKind);5375}53765377ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, QualType Type,5378ImplicitParamKind ParamKind) {5379return new (C, nullptr) ImplicitParamDecl(C, Type, ParamKind);5380}53815382ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C,5383GlobalDeclID ID) {5384return new (C, ID) ImplicitParamDecl(C, QualType(), ImplicitParamKind::Other);5385}53865387FunctionDecl *5388FunctionDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,5389const DeclarationNameInfo &NameInfo, QualType T,5390TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin,5391bool isInlineSpecified, bool hasWrittenPrototype,5392ConstexprSpecKind ConstexprKind,5393Expr *TrailingRequiresClause) {5394FunctionDecl *New = new (C, DC) FunctionDecl(5395Function, C, DC, StartLoc, NameInfo, T, TInfo, SC, UsesFPIntrin,5396isInlineSpecified, ConstexprKind, TrailingRequiresClause);5397New->setHasWrittenPrototype(hasWrittenPrototype);5398return New;5399}54005401FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) {5402return new (C, ID) FunctionDecl(5403Function, C, nullptr, SourceLocation(), DeclarationNameInfo(), QualType(),5404nullptr, SC_None, false, false, ConstexprSpecKind::Unspecified, nullptr);5405}54065407BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {5408return new (C, DC) BlockDecl(DC, L);5409}54105411BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) {5412return new (C, ID) BlockDecl(nullptr, SourceLocation());5413}54145415CapturedDecl::CapturedDecl(DeclContext *DC, unsigned NumParams)5416: Decl(Captured, DC, SourceLocation()), DeclContext(Captured),5417NumParams(NumParams), ContextParam(0), BodyAndNothrow(nullptr, false) {}54185419CapturedDecl *CapturedDecl::Create(ASTContext &C, DeclContext *DC,5420unsigned NumParams) {5421return new (C, DC, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))5422CapturedDecl(DC, NumParams);5423}54245425CapturedDecl *CapturedDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID,5426unsigned NumParams) {5427return new (C, ID, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))5428CapturedDecl(nullptr, NumParams);5429}54305431Stmt *CapturedDecl::getBody() const { return BodyAndNothrow.getPointer(); }5432void CapturedDecl::setBody(Stmt *B) { BodyAndNothrow.setPointer(B); }54335434bool CapturedDecl::isNothrow() const { return BodyAndNothrow.getInt(); }5435void CapturedDecl::setNothrow(bool Nothrow) { BodyAndNothrow.setInt(Nothrow); }54365437EnumConstantDecl::EnumConstantDecl(const ASTContext &C, DeclContext *DC,5438SourceLocation L, IdentifierInfo *Id,5439QualType T, Expr *E, const llvm::APSInt &V)5440: ValueDecl(EnumConstant, DC, L, Id, T), Init((Stmt *)E) {5441setInitVal(C, V);5442}54435444EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,5445SourceLocation L,5446IdentifierInfo *Id, QualType T,5447Expr *E, const llvm::APSInt &V) {5448return new (C, CD) EnumConstantDecl(C, CD, L, Id, T, E, V);5449}54505451EnumConstantDecl *EnumConstantDecl::CreateDeserialized(ASTContext &C,5452GlobalDeclID ID) {5453return new (C, ID) EnumConstantDecl(C, nullptr, SourceLocation(), nullptr,5454QualType(), nullptr, llvm::APSInt());5455}54565457void IndirectFieldDecl::anchor() {}54585459IndirectFieldDecl::IndirectFieldDecl(ASTContext &C, DeclContext *DC,5460SourceLocation L, DeclarationName N,5461QualType T,5462MutableArrayRef<NamedDecl *> CH)5463: ValueDecl(IndirectField, DC, L, N, T), Chaining(CH.data()),5464ChainingSize(CH.size()) {5465// In C++, indirect field declarations conflict with tag declarations in the5466// same scope, so add them to IDNS_Tag so that tag redeclaration finds them.5467if (C.getLangOpts().CPlusPlus)5468IdentifierNamespace |= IDNS_Tag;5469}54705471IndirectFieldDecl *5472IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,5473const IdentifierInfo *Id, QualType T,5474llvm::MutableArrayRef<NamedDecl *> CH) {5475return new (C, DC) IndirectFieldDecl(C, DC, L, Id, T, CH);5476}54775478IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C,5479GlobalDeclID ID) {5480return new (C, ID)5481IndirectFieldDecl(C, nullptr, SourceLocation(), DeclarationName(),5482QualType(), std::nullopt);5483}54845485SourceRange EnumConstantDecl::getSourceRange() const {5486SourceLocation End = getLocation();5487if (Init)5488End = Init->getEndLoc();5489return SourceRange(getLocation(), End);5490}54915492void TypeDecl::anchor() {}54935494TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,5495SourceLocation StartLoc, SourceLocation IdLoc,5496const IdentifierInfo *Id,5497TypeSourceInfo *TInfo) {5498return new (C, DC) TypedefDecl(C, DC, StartLoc, IdLoc, Id, TInfo);5499}55005501void TypedefNameDecl::anchor() {}55025503TagDecl *TypedefNameDecl::getAnonDeclWithTypedefName(bool AnyRedecl) const {5504if (auto *TT = getTypeSourceInfo()->getType()->getAs<TagType>()) {5505auto *OwningTypedef = TT->getDecl()->getTypedefNameForAnonDecl();5506auto *ThisTypedef = this;5507if (AnyRedecl && OwningTypedef) {5508OwningTypedef = OwningTypedef->getCanonicalDecl();5509ThisTypedef = ThisTypedef->getCanonicalDecl();5510}5511if (OwningTypedef == ThisTypedef)5512return TT->getDecl();5513}55145515return nullptr;5516}55175518bool TypedefNameDecl::isTransparentTagSlow() const {5519auto determineIsTransparent = [&]() {5520if (auto *TT = getUnderlyingType()->getAs<TagType>()) {5521if (auto *TD = TT->getDecl()) {5522if (TD->getName() != getName())5523return false;5524SourceLocation TTLoc = getLocation();5525SourceLocation TDLoc = TD->getLocation();5526if (!TTLoc.isMacroID() || !TDLoc.isMacroID())5527return false;5528SourceManager &SM = getASTContext().getSourceManager();5529return SM.getSpellingLoc(TTLoc) == SM.getSpellingLoc(TDLoc);5530}5531}5532return false;5533};55345535bool isTransparent = determineIsTransparent();5536MaybeModedTInfo.setInt((isTransparent << 1) | 1);5537return isTransparent;5538}55395540TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) {5541return new (C, ID) TypedefDecl(C, nullptr, SourceLocation(), SourceLocation(),5542nullptr, nullptr);5543}55445545TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC,5546SourceLocation StartLoc,5547SourceLocation IdLoc,5548const IdentifierInfo *Id,5549TypeSourceInfo *TInfo) {5550return new (C, DC) TypeAliasDecl(C, DC, StartLoc, IdLoc, Id, TInfo);5551}55525553TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C,5554GlobalDeclID ID) {5555return new (C, ID) TypeAliasDecl(C, nullptr, SourceLocation(),5556SourceLocation(), nullptr, nullptr);5557}55585559SourceRange TypedefDecl::getSourceRange() const {5560SourceLocation RangeEnd = getLocation();5561if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {5562if (typeIsPostfix(TInfo->getType()))5563RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();5564}5565return SourceRange(getBeginLoc(), RangeEnd);5566}55675568SourceRange TypeAliasDecl::getSourceRange() const {5569SourceLocation RangeEnd = getBeginLoc();5570if (TypeSourceInfo *TInfo = getTypeSourceInfo())5571RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();5572return SourceRange(getBeginLoc(), RangeEnd);5573}55745575void FileScopeAsmDecl::anchor() {}55765577FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,5578StringLiteral *Str,5579SourceLocation AsmLoc,5580SourceLocation RParenLoc) {5581return new (C, DC) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);5582}55835584FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C,5585GlobalDeclID ID) {5586return new (C, ID) FileScopeAsmDecl(nullptr, nullptr, SourceLocation(),5587SourceLocation());5588}55895590void TopLevelStmtDecl::anchor() {}55915592TopLevelStmtDecl *TopLevelStmtDecl::Create(ASTContext &C, Stmt *Statement) {5593assert(C.getLangOpts().IncrementalExtensions &&5594"Must be used only in incremental mode");55955596SourceLocation Loc = Statement ? Statement->getBeginLoc() : SourceLocation();5597DeclContext *DC = C.getTranslationUnitDecl();55985599return new (C, DC) TopLevelStmtDecl(DC, Loc, Statement);5600}56015602TopLevelStmtDecl *TopLevelStmtDecl::CreateDeserialized(ASTContext &C,5603GlobalDeclID ID) {5604return new (C, ID)5605TopLevelStmtDecl(/*DC=*/nullptr, SourceLocation(), /*S=*/nullptr);5606}56075608SourceRange TopLevelStmtDecl::getSourceRange() const {5609return SourceRange(getLocation(), Statement->getEndLoc());5610}56115612void TopLevelStmtDecl::setStmt(Stmt *S) {5613assert(S);5614Statement = S;5615setLocation(Statement->getBeginLoc());5616}56175618void EmptyDecl::anchor() {}56195620EmptyDecl *EmptyDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {5621return new (C, DC) EmptyDecl(DC, L);5622}56235624EmptyDecl *EmptyDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) {5625return new (C, ID) EmptyDecl(nullptr, SourceLocation());5626}56275628HLSLBufferDecl::HLSLBufferDecl(DeclContext *DC, bool CBuffer,5629SourceLocation KwLoc, IdentifierInfo *ID,5630SourceLocation IDLoc, SourceLocation LBrace)5631: NamedDecl(Decl::Kind::HLSLBuffer, DC, IDLoc, DeclarationName(ID)),5632DeclContext(Decl::Kind::HLSLBuffer), LBraceLoc(LBrace), KwLoc(KwLoc),5633IsCBuffer(CBuffer) {}56345635HLSLBufferDecl *HLSLBufferDecl::Create(ASTContext &C,5636DeclContext *LexicalParent, bool CBuffer,5637SourceLocation KwLoc, IdentifierInfo *ID,5638SourceLocation IDLoc,5639SourceLocation LBrace) {5640// For hlsl like this5641// cbuffer A {5642// cbuffer B {5643// }5644// }5645// compiler should treat it as5646// cbuffer A {5647// }5648// cbuffer B {5649// }5650// FIXME: support nested buffers if required for back-compat.5651DeclContext *DC = LexicalParent;5652HLSLBufferDecl *Result =5653new (C, DC) HLSLBufferDecl(DC, CBuffer, KwLoc, ID, IDLoc, LBrace);5654return Result;5655}56565657HLSLBufferDecl *HLSLBufferDecl::CreateDeserialized(ASTContext &C,5658GlobalDeclID ID) {5659return new (C, ID) HLSLBufferDecl(nullptr, false, SourceLocation(), nullptr,5660SourceLocation(), SourceLocation());5661}56625663//===----------------------------------------------------------------------===//5664// ImportDecl Implementation5665//===----------------------------------------------------------------------===//56665667/// Retrieve the number of module identifiers needed to name the given5668/// module.5669static unsigned getNumModuleIdentifiers(Module *Mod) {5670unsigned Result = 1;5671while (Mod->Parent) {5672Mod = Mod->Parent;5673++Result;5674}5675return Result;5676}56775678ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,5679Module *Imported,5680ArrayRef<SourceLocation> IdentifierLocs)5681: Decl(Import, DC, StartLoc), ImportedModule(Imported),5682NextLocalImportAndComplete(nullptr, true) {5683assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size());5684auto *StoredLocs = getTrailingObjects<SourceLocation>();5685std::uninitialized_copy(IdentifierLocs.begin(), IdentifierLocs.end(),5686StoredLocs);5687}56885689ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,5690Module *Imported, SourceLocation EndLoc)5691: Decl(Import, DC, StartLoc), ImportedModule(Imported),5692NextLocalImportAndComplete(nullptr, false) {5693*getTrailingObjects<SourceLocation>() = EndLoc;5694}56955696ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC,5697SourceLocation StartLoc, Module *Imported,5698ArrayRef<SourceLocation> IdentifierLocs) {5699return new (C, DC,5700additionalSizeToAlloc<SourceLocation>(IdentifierLocs.size()))5701ImportDecl(DC, StartLoc, Imported, IdentifierLocs);5702}57035704ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC,5705SourceLocation StartLoc,5706Module *Imported,5707SourceLocation EndLoc) {5708ImportDecl *Import = new (C, DC, additionalSizeToAlloc<SourceLocation>(1))5709ImportDecl(DC, StartLoc, Imported, EndLoc);5710Import->setImplicit();5711return Import;5712}57135714ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID,5715unsigned NumLocations) {5716return new (C, ID, additionalSizeToAlloc<SourceLocation>(NumLocations))5717ImportDecl(EmptyShell());5718}57195720ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const {5721if (!isImportComplete())5722return std::nullopt;57235724const auto *StoredLocs = getTrailingObjects<SourceLocation>();5725return llvm::ArrayRef(StoredLocs,5726getNumModuleIdentifiers(getImportedModule()));5727}57285729SourceRange ImportDecl::getSourceRange() const {5730if (!isImportComplete())5731return SourceRange(getLocation(), *getTrailingObjects<SourceLocation>());57325733return SourceRange(getLocation(), getIdentifierLocs().back());5734}57355736//===----------------------------------------------------------------------===//5737// ExportDecl Implementation5738//===----------------------------------------------------------------------===//57395740void ExportDecl::anchor() {}57415742ExportDecl *ExportDecl::Create(ASTContext &C, DeclContext *DC,5743SourceLocation ExportLoc) {5744return new (C, DC) ExportDecl(DC, ExportLoc);5745}57465747ExportDecl *ExportDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) {5748return new (C, ID) ExportDecl(nullptr, SourceLocation());5749}57505751bool clang::IsArmStreamingFunction(const FunctionDecl *FD,5752bool IncludeLocallyStreaming) {5753if (IncludeLocallyStreaming)5754if (FD->hasAttr<ArmLocallyStreamingAttr>())5755return true;57565757if (const Type *Ty = FD->getType().getTypePtrOrNull())5758if (const auto *FPT = Ty->getAs<FunctionProtoType>())5759if (FPT->getAArch64SMEAttributes() &5760FunctionType::SME_PStateSMEnabledMask)5761return true;57625763return false;5764}576557665767